Root: D:/projects/mfiles/gilgen2020/phase5 - apk-customizer/ - contrib/ - xml2axml.jar - src/ - ch/ - mfiles/ - kolibri/ - tools/ - ZipExtender.java - staging/ - assets/ - raw/ - ssm 11.wav - build.gradle.kts - build.number - build.xml - keystore-v2.p12 - keystore.p12 - settings.properties - buildSrc/ - src/ - main/ - kotlin/ - ch.mfiles.kolibri-application.gradle.kts - build.gradle.kts - settings.gradle.kts - common/ - data/ - fixed-master-data.txt - i18n/ - ch/ - mfiles/ - kaba/ - kolibri/ - common/ - Messages.java - messages.properties - Messages.txt - messages_de.properties - messages_fr.properties - messages_it.properties - javatest/ - ch/ - mfiles/ - kaba/ - kolibri/ - common/ - businessobjects/ - types/ - JobStatusTest.java - forms/ - adapters/ - SpinnerTextStyleTest.java - util/ - ReportMaterialInsertPolicyTest.java - lib/ - commons-logging-1.2.jar - hamcrest-core-1.3.jar - jacocoant.jar - junit-4.12.jar - sonar-ant-task-2.3.jar - src/ - ch/ - mfiles/ - kaba/ - kolibri/ - common/ - businessobjects/ - enums/ - AddressType.java - InvoiceCode.java - JobPriority.java - JobStatusName.java - JobType.java - LocalizedTextEnum.java - LoginMessage.java - MessageRecipient.java - Month.java - NoSignatureReason.java - ReportSendType.java - Titel.java - VariousExpens.java - types/ - CalendarStatus.java - DeliveryStatus.java - ExpenseValidation.java - FormItemType.java - FormType.java - JobStatus.java - JobType.java - ReportStatus.java - SpecificFunctionType.java - TimesheetStatus.java - TimesheetValidation.java - Warehouse.java - AbsenceNotification.java - AbsenceType.java - Address.java - BaseEntity.java - Billing.java - CalendarTimeSheet.java - Checklist.java - DeliveryList.java - Drive.java - Email.java - Employee.java - ErrorCode.java - Expenses.java - Form.java - FormDependency.java - FormInstance.java - FormItem.java - FormValueList.java - History.java - Incident.java - InternalWorkType.java - Inventory.java - Invoice.java - Job.java - JobFile.java - JobFormDesc.java - JobMessage.java - JobMonText.java - JobNoForm.java - JobReportTime.java - JobReturnReason.java - Material.java - MaterialMovement.java - MaterialPerson.java - NextIntervention.java - Order.java - OrderMaterial.java - Person.java - PhoneBookEntry.java - Progress.java - Reason.java - ReceiptOfGoods.java - Report.java - ReportMaterial.java - ReportMeasurement.java - ReportMessage.java - ServerJob.java - ServiceRefused.java - ShortMessage.java - StateOfInstallation.java - TimeSheet.java - VariousExpenseFile.java - VariousExpenses.java - VehicleInventory.java - WorkType.java - db/ - CALENDAR.java - FORM.java - FORMDEPENDENCY.java - FORMINSTANCE.java - FORMITEM.java - FORMVALUELIST.java - LocalizedTexts.java - SIGNPIC.java - ZARBEITSART.java - ZFCODE.java - ZKDCSTORC.java - ZKDHIST.java - ZKDMAABSENCE.java - ZKDMAESPNSPICS.java - ZKDMAEXPNS.java - ZKDMAEXPNSDIV.java - ZKDMAMAT.java - ZKDMATIME.java - ZKDMATORD.java - ZKDMOB.java - ZKDMOBABSC.java - ZKDMOBADR.java - ZKDMOBANTRTYP.java - ZKDMOBARBA.java - ZKDMOBBEGRSAV.java - ZKDMOBBTRBZUST.java - ZKDMOBCHKLIST.java - ZKDMOBDELVRYLIST.java - ZKDMOBFLGVRG.java - ZKDMOBFORMDESC.java - ZKDMOBFZGMBEW.java - ZKDMOBFZLG.java - ZKDMOBFZLGSYNC.java - ZKDMOBMA.java - ZKDMOBMAT.java - ZKDMOBMATPERS.java - ZKDMOBMC.java - ZKDMOBMEAS.java - ZKDMOBMONSTK.java - ZKDMOBMONTXT.java - ZKDMOBMSG.java - ZKDMOBMSGC.java - ZKDMOBMV.java - ZKDMOBMVCASE.java - ZKDMOBNOFORM.java - ZKDMOBREP.java - ZKDMOBRETURN.java - ZKDMOBRTIM.java - ZKDMOBSTORC.java - ZKDMOBVERRC.java - ZKDMOBVRCINT.java - ZKDMOBWERET.java - ZKDSMOBEMAIL.java - ZKDSMOBMA.java - ZKSMABEST.java - ZSHORTMSG.java - forms/ - adapters/ - CustomArrayAdapter.java - CustomAutoCompleteItemAdapter.java - CustomSpinnerAdapter.java - CustomSpinnerItem.java - SpinnerTextStyle.java - StepAdapter.java - dlg/ - DialogForm.java - widgets/ - inputmasks/ - ExpenseMaskWatcher.java - MaterialNumberMaskWatcher.java - VehicleMaskWatcher.java - Watcher.java - lists/ - CheckBoxListWidget.java - CheckBoxListWidgetAdapter.java - CheckBoxListWidgetItem.java - DefaultListWidget.java - DefaultListWidgetAdapter.java - DefaultListWidgetItem.java - DetailListWidget.java - DetailListWidgetAdapter.java - DetailListWidgetItem.java - ImageListWidget.java - ImageListWidgetAdapter.java - ImageListWidgetItem.java - ListWidget.java - ListWidgetAdapter.java - MaterialListWidget.java - MaterialListWidgetAdapter.java - MaterialListWidgetItem.java - RadioButtonListWidget.java - RadioButtonListWidgetAdapter.java - RadioButtonListWidgetItem.java - StatusListWidget.java - StatusListWidgetAdapter.java - StatusListWidgetItem.java - TimeListWidget.java - TimeListWidgetAdapter.java - TimeListWidgetItem.java - AmountEditText.java - CommissionNumberLayout.java - CommissionNumberText.java - DividerView.java - ExpenseMaskEditText.java - MaterialSearchView.java - MDAutoComplete.java - MDCalendar.java - MDCheckBox.java - MDDialog.java - MDEditText.java - MDRadioButton.java - MDSpinner.java - ReportContentWidget.java - TimeEditText.java - ViewPageAdapter.java - CommonUtilForm.java - MaterialSearchForm.java - Navigation.java - NavigationForm.java - SuperForm.java - net/ - CommSetupHelper.java - MasterDataDBHandler.java - PresenceState.java - RemoteTransactionHandler.java - RemoteTransactionResult.java - util/ - ActionUtil.java - BackupHandler.java - BitmapConverterUtil.java - BitmapLoadUtils.java - CommonConstants.java - DatabaseUtil.java - DateTimeConverter.jpage - DateTimeUtil.java - DbConstants.java - DeviceMirrorringHandler.java - EnumUtil.java - EvalTimeGenerator.jpage - FileUtils.java - FormUtil.java - GuidGenerator.java - HTMLEncode.java - HtmlUtil.java - ImageHeaderParser.java - ImagesUtil.java - KeyboardUtil.java - LayoutUtils.java - Messages.java - MessageUtil.java - Notifications.java - PropertiesFileConverter.java - RegistryUtil.java - ResetEval.jpage - ResetEvalPeriod.sql - RunOnUIThread.java - SoundUtil.java - SQLFileConverter.java - StepUtil.java - StringUtil.java - TimeUtil.java - TranslationFileConverter.java - CommonApplication.java - NotificationTestMessage.java - images/ - call.png - ic_absence_black_24dp.png - ic_add_black_24dp.png - ic_add_disabled_white_24dp.png - ic_add_photo_black_32dp.png - ic_add_white_24dp.png - ic_alarm_black_24dp.png - ic_alarm_red_24dp.png - ic_arrow_back_white_48dp.png - ic_arrow_back_white_disabled_48dp.png - ic_arrow_forward_disabled_black_24dp.png - ic_assignment_ind_black_24dp.png - ic_assignment_ind_disabled_black_24dp.png - ic_assignment_turned_in_black_24dp.png - ic_assignment_turned_in_disabled_black_24dp.png - ic_camera_black_24dp.png - ic_camera_disabled_black_24dp.png - ic_camera_disabled_white_24dp.png - ic_camera_white_24dp.png - ic_checkbox_checked_60dp.png - ic_checkbox_some_60dp.png - ic_checkbox_unchecked_60dp.png - ic_check_512dp.png - ic_check_white_512dp.png - ic_clear_white_48dp.png - ic_contact_phone_black_24dp.png - ic_delete_forever_black_24dp.png - ic_delete_forever_disabled_black_24dp.png - ic_delete_forever_disabled_white_24dp.png - ic_delete_forever_white_24dp.png - ic_done_black_24db.png - ic_done_white_24db.png - ic_download_error_512dp.png - ic_download_success_512dp.png - ic_email_black_24dp.png - ic_email_disabled_black_24dp.png - ic_exit_to_app_black_24dp.png - ic_exit_to_app_disabled_black_24dp.png - ic_file_download_black_24dp.png - ic_file_download_disabled_black_24dp.png - ic_file_download_white_48dp.png - ic_gesture_black_24dp.png - ic_gesture_disabled_black_24dp.png - ic_gesture_white_24dp.png - ic_help_black_24dp.png - ic_help_disabled_black_24dp.png - ic_info_black_24dp.png - ic_info_disabled_black_24dp.png - ic_info_outline_black_24dp.png - ic_info_outline_disabled_black_24dp.png - ic_info_outline_white_24dp.png - ic_info_white_24dp.png - ic_list_black_24dp.png - ic_list_disabled_black_24dp.png - ic_mode_edit_black_24dp.png - ic_offline_share_black_24dp.png - ic_pageview_black_24dp.png - ic_pageview_disabled_black_24dp.png - ic_pageview_white_24dp.png - ic_perm_device_information_black_24dp.png - ic_perm_device_information_disabled_black_24dp.png - ic_phone_black_24dp.png - ic_phone_disabled_black_24dp.png - ic_photo_library_black_24dp.png - ic_picture_as_pdf_black_24dp.png - ic_play_arrow_black_24dp.png - ic_play_arrow_disabled_black_24dp.png - ic_play_circle_outline_black_24dp.png - ic_remote_black_24dp.png - ic_restore_page_black_24dp.png - ic_restore_page_white_24dp.png - ic_save_black_24dp.png - ic_save_disabled_black_24dp.png - ic_save_disabled_white_24dp.png - ic_save_white_48dp.png - ic_schedule_black_24dp.png - ic_schedule_disabled_black_24dp.png - ic_search_file_black_72dp.png - ic_search_file_disabled_72dp.png - ic_search_white_24dp.png - ic_send_black_24dp.png - ic_send_disabled_black_24dp.png - ic_send_disabled_white_24dp.png - ic_send_white_24dp.png - ic_settings_applications_black_24dp.png - ic_settings_applications_disabled_black_24dp.png - ic_settings_black_24dp.png - ic_settings_disabled_black_24dp.png - ic_shopping_cart_add_black_128dp.png - ic_shopping_cart_add_disabled_white_128dp.png - ic_shopping_cart_add_white_128dp.png - ic_shopping_cart_black_128dp.png - ic_shopping_cart_disabled_white_128dp.png - ic_shopping_cart_white_128dp.png - ic_stop_black_24dp.png - ic_stop_disabled_black_24dp.png - ic_supervisor_account_black_24dp.png - ic_supervisor_account_disabled_black_24dp.png - ic_system_update_black_24dp.png - ic_system_update_disabled_black_24dp.png - ic_truck_black_128dp.png - ic_truck_white_128dp.png - ic_update_black_24dp.png - ic_update_disabled_black_24dp.png - ic_update_white_24dp.png - ic_wrench_black_72dp.png - ic_wrench_disabled_black_72dp.png - ic_youtube_searched_for_black_24dp.png - ic_youtube_searched_for_white_24dp.png - menu.png - menu_white.png - video-play-3-72 (1).png - test/ - ch/ - mfiles/ - kaba/ - kolibri/ - common/ - util/ - DateTimeUtilTest.java - StringUtilTest.java - AndroidManifest.xml - application.dtd - application.xml - build.gradle.kts - build.xml - project.properties - sonar.xml - gradle/ - wrapper/ - gradle-wrapper.jar - gradle-wrapper.properties - login/ - i18n/ - ch/ - mfiles/ - kaba/ - kolibri/ - login/ - LoginMessages.java - messages.properties - Messages.txt - messages_de.properties - messages_fr.properties - messages_it.properties - lib/ - sonar-ant-task-2.3.jar - src/ - ch/ - mfiles/ - kaba/ - kolibri/ - login/ - forms/ - KolibriIdForm.java - LoginForm.java - LoginNavigationForm.java - LoginApplication.java - util/ - LoginConstants.java - images/ - button_ok.png - button_ok_LoginDisabled.png - header.jpg - header.png - kaba.png - login.png - AndroidManifest.xml - application.dtd - application.xml - build.gradle.kts - build.xml - project.properties - sonar.xml - material/ - i18n/ - ch/ - mfiles/ - kaba/ - kolibri/ - material/ - MaterialMessages.java - Messages.properties - Messages_de.properties - Messages_fr.properties - Messages_it.properties - lib/ - sonar-ant-task-2.3.jar - src/ - ch/ - mfiles/ - kaba/ - kolibri/ - material/ - forms/ - OrderListForm.java - OrderMaterialForm.java - OrderMaterialNewEditForm.java - SuperForm.java - MaterialApplication.java - images/ - kaba.png - AndroidManifest.xml - application.dtd - application.xml - build.gradle.kts - build.xml - project.properties - sonar.xml - service/ - i18n/ - ch/ - mfiles/ - kaba/ - kolibri/ - service/ - messages.properties - messages_de.properties - messages_fr.properties - messages_it.properties - ServiceMessages.java - lib/ - commons-logging-1.2.jar - hamcrest-core-1.3.jar - jacocoant.jar - junit-4.12.jar - sonar-ant-task-2.3.jar - src/ - ch/ - mfiles/ - kaba/ - kolibri/ - service/ - forms/ - AbsenceNotificationListForm.java - AbsenceNotificationNewEditForm.java - AddressEditSuperForm.java - ArticleDetailForm.java - ArticleIncomningForm.java - ArticleListForm.java - ArticleOutgoingForm.java - ArticleOutgoingListForm.java - ArticleSearchForm.java - EmployeeListForm.java - InventoryInformationsForm.java - InventoryStockForm.java - JobDeleteForm.java - JobDetailAddressEditForm.java - JobDetailAddressForm.java - JobDetailForm.java - JobDetailHistoryForm.java - JobDetailInfoCommissionNumberForm.java - JobDetailInfoForm.java - JobDetailInfoInstallationTypeForm.java - JobDetailReportForm.java - JobDownloadResultForm.java - JobEditForm.java - JobForwardForm.java - JobListForm.java - JobNewForm.java - JobSearchForm.java - JobSearchListForm.java - ReportChecklistForm.java - ReportDocumentAttachmentsListForm.java - ReportDocumentAttachmentsNewEditForm.java - ReportDocumentDetailForm.java - ReportEditForm.java - ReportFormListForm.java - ReportFormNewEditForm.java - ReportGuaranteeForm.java - ReportImageAttachmentsListForm.java - ReportImageAttachmentsNewEditForm.java - ReportMaterialListForm.java - ReportMaterialNewEditForm.java - ReportMeasurementForm.java - ReportMessageNewEditForm.java - ReportSummaryForm.java - ReportTimeListForm.java - ReportTimeNewEditForm.java - RescheduleJobForm.java - ServiceNavigationForm.java - ShortMessageForm.java - ShortMessageListForm.java - SignatureBundleListForm.java - SignatureForm.java - SuperForm.java - test/ - LongTaskForm.java - SampleCallingForm.java - SampleDialogForm.java - SampleNavigationViewForm.java - SampleTabForm.java - ui/ - widgets/ - FormImageLayout.java - FormListItemWidget.java - GridLayoutForm.java - MeasurementListItemWidget.java - MeasurementTable.java - util/ - ReportUtil.java - ServiceConstants.java - ServiceFormUtil.java - ServiceJobUtil.java - SignatureUtil.java - NotificationTestMessage.java - ServiceApplication.java - images/ - active.png - finalized.png - inProgress.png - kaba.png - test/ - ch/ - mfiles/ - kaba/ - kolibri/ - service/ - forms/ - util/ - ReportDeletionStateTest.java - ReportTest.java - ServiceJobUtilTest.java - AndroidManifest.xml - application.dtd - application.xml - build.gradle.kts - build.xml - project.properties - report.html - sonar.xml - timeSheet/ - i18n/ - ch/ - mfiles/ - kaba/ - kolibri/ - timesheet/ - Messages.properties - Messages_de.properties - Messages_fr.properties - Messages_it.properties - TimeSheetMessages.java - lib/ - commons-logging-1.2.jar - hamcrest-core-1.3.jar - junit-4.12.jar - sonar-ant-task-2.3.jar - src/ - ch/ - mfiles/ - kaba/ - kolibri/ - timesheet/ - forms/ - CalendarOverviewForm.java - SuperForm.java - TimeSheetDetailForm.java - TimeSheetForm.java - VariousExpensesImageNewEditForm.java - util/ - CalendarDateRange.java - CalendarDateSelection.java - CalendarListWindow.java - CalendarMonthHeaderPolicy.java - CalendarMonthScroll.java - CalendarMonthTitleState.java - CalendarScrollTrigger.java - CalendarTimeSheetCache.java - CalendarToolbarTitleText.java - TimesheetDateUtils.java - TimeSheetApplication.java - images/ - Error.png - kaba.png - report.png - reportDisabled.png - Success.png - Warning.png - test/ - ch/ - mfiles/ - kaba/ - kolibri/ - timesheet/ - forms/ - ExpenseCurrencyValueTest.java - ExpensesCompensationTest.java - TestDateCorrectness.java - TimeSheetDetailFormSavePolicyTest.java - TimeSheetValidatorTest.java - util/ - CalendarDateRangeTest.java - CalendarDateSelectionTest.java - CalendarListWindowTest.java - CalendarMonthHeaderPolicyTest.java - CalendarMonthScrollTest.java - CalendarMonthTitleStateTest.java - CalendarScrollTriggerTest.java - CalendarTimeSheetCacheTest.java - CalendarToolbarTitleTextTest.java - AndroidManifest.xml - application.dtd - application.xml - build.gradle.kts - build.xml - project.properties - sonar.xml - gradlew.bat - phase5-summary_082326_1420.txt - Screenshot_25-8-2026_84146_dev.mfiles.ch.jpeg - settings.gradle.kts     apk-customizer/build.gradle.kts:   import java.io.FileInputStream import java.net.URI import java.util.Properties plugins { base `maven-publish` } // the Kolibri runtime version to use (-> settings.properties) val props = Properties() props.load(FileInputStream(project.file("settings.properties"))) val runtimeVersion = props["runtimeVersion"] // inject the signature key pwd (i.e. set env-variable ORG_GRADLE_PROJECT_signatureKeyPwd) var signatureKeyPwd : String = if (project.hasProperty("signatureKeyPwd")) project.property("signatureKeyPwd").toString() else "" // inject an api token for publishing to the MFiles maven repository of project gilgen2020 var publicationApiToken : String = if (project.hasProperty("publicationApiToken")) project.property("publicationApiToken").toString() else "" // inject a job token for publishing to the MFiles maven repository of project gilgen2020 var publicationJobToken : String = if (project.hasProperty("publicationJobToken")) project.property("publicationJobToken").toString() else "" // publication url var publicationUrl = "https://dev.mfiles.ch/gitlab/api/v4/projects/19/packages/maven" //"gilgen/gilgen2020" // extract app version from common/application.xml fun parseApplicationDescriptor(): Map { val xmlFile = File(project.rootDir, "common/application.xml") val xmlInput = org.xml.sax.InputSource(java.io.StringReader(xmlFile.readText())) val docBuilder = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder() docBuilder.setEntityResolver { _, _ -> org.xml.sax.InputSource(java.io.FileReader(project.rootDir.path + "/common/application.dtd")) } val doc = docBuilder.parse(xmlInput) val xPath = javax.xml.xpath.XPathFactory.newInstance().newXPath() val result = HashMap() result["appClass"] = xPath.evaluate("/application/@class", doc) result["versionMajor"] = xPath.evaluate("/application/version/@major", doc) result["versionMinor"] = xPath.evaluate("/application/version/@minor", doc) result["versionBuild"] = xPath.evaluate("/application/version/@build", doc) return result } val ad = parseApplicationDescriptor() val appVersion = ad["versionMajor"] + "." + ad["versionMinor"] + "." + ad["versionBuild"] val versionText = "${appVersion}-${runtimeVersion}" // define configuration to hold all jars of all Kolibri apps val kolibriJars: Configuration by configurations.creating { isCanBeConsumed = false isCanBeResolved = true } dependencies { // add dependencies to all Kolibri applications to configuration kolibriJars listOf(":common", ":login", ":material", ":service", ":timeSheet").forEach { kolibriJars(project(mapOf("path" to it, "configuration" to "kolibriJars"))) } } /** * Task for copying the Kolibri jars to the apk customizer's staging folder 'deploy' */ tasks.register("deployKolibriJars", Copy::class) { from(kolibriJars) into("staging/assets/deploy") } /** * Task for building a ZIP output of the customized APK and all contributed Kolibri app jars */ tasks.register("distributionZip", Zip::class) { group = "build" dependsOn("ANT-build-apk") from(kolibriJars) { into("deploy") } from("build/runtime-android-customized.apk") { this.rename { "${rootProject.name}-customized-$versionText.apk"} } } // import ant build ant.importBuild("build.xml") { "ANT-$it" } // inject ant properties (i.e. values of settings.properties) if (signatureKeyPwd != "") ant.properties["pwd"] = signatureKeyPwd ant.properties["runtimeVersion"] = runtimeVersion ant.properties["appVersion"] = appVersion tasks.named("ANT-merge-apk") { dependsOn("deployKolibriJars") } // append our tasks to base lifecycle tasks tasks.named("assemble") { dependsOn("ANT-build-apk") } tasks.named("clean") { dependsOn("ANT-clean") doLast { delete(fileTree("staging/assets/deploy") { include("**.jar") }) } } publishing { publications { create("distribution") { groupId = "ch.gilgen.kolibri" artifactId = "gilgen2020-distro" version = versionText artifact(tasks.named("distributionZip")) { extension = "zip" } } } repositories { maven { name = "MFilesGitLAB" url = URI(publicationUrl) credentials(HttpHeaderCredentials::class) { name = if (publicationApiToken != "") "Private-Token" else "Job-Token" value = if (publicationApiToken != "") publicationApiToken else publicationJobToken } authentication { create("header") } } } }     apk-customizer/build.number:   #Build Number for ANT. Do not edit! #Sat Feb 12 18:58:05 CET 2022 build.number=13     apk-customizer/build.xml:   Build file helping to customize a Kolibri runtime apk file. Creating custom-apk-version due to existing deployments     apk-customizer/settings.properties:   runtimeVersion=1.8.1p202512091754 appVersion=5.0.3     apk-customizer/src/ch/mfiles/kolibri/tools/ZipExtender.java:   package ch.mfiles.kolibri.tools; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * Zips a folder using compression settings from a reference ZIP file. Files not found in the * reference ZIP file are added uncompressed. * * @author Joerg * */ public class ZipExtender { private static String sourceFolder = "apk"; private static String referenceZip = "reference.apk"; private static String targetZip = "tmp.apk"; public static void main(String[] args) { // get hashmap of zip entries with compressed-Flag HashMap compressed = new HashMap<>(); try { System.out.println("Reading reference APK file..."); ZipInputStream refZipIn = new ZipInputStream(new FileInputStream(referenceZip)); for (ZipEntry entry = refZipIn.getNextEntry(); entry != null; entry = refZipIn.getNextEntry()) { compressed.put(entry.getName(), entry.getMethod()); } refZipIn.close(); } catch (IOException ex) { System.out.println("Exception caught while reading reference ZIP file..."); ex.printStackTrace(); return; } try { System.out.println("Creating target APK file with mixed compression settings..."); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(targetZip)); Path sourcePath = Paths.get(sourceFolder); Files.walkFileTree(sourcePath, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String entryName = sourcePath.relativize(file).toString().replace('\\', '/'); ZipEntry entry = new ZipEntry(entryName); int method = compressed.get(entryName) != null ? compressed.get(entryName) : ZipEntry.STORED; entry.setMethod(method); if (method == ZipEntry.STORED) { entry.setSize(attrs.size()); entry.setCrc(getCrc(file)); } zipOut.putNextEntry(entry); Files.copy(file, zipOut); zipOut.closeEntry(); return FileVisitResult.CONTINUE; } private long getCrc(Path file) throws IOException { CRC32 crc = new CRC32(); crc.update(Files.readAllBytes(file)); return crc.getValue(); } }); zipOut.close(); } catch (IOException ex) { System.out.println("Exception caught while writing target ZIP file..."); ex.printStackTrace(); return; } } }     buildSrc/build.gradle.kts:   plugins { `kotlin-dsl` } repositories { mavenCentral() }     buildSrc/settings.gradle.kts:   val androidSDK = "bubu"     buildSrc/src/main/kotlin/ch.mfiles.kolibri-application.gradle.kts:   import org.apache.tools.ant.taskdefs.condition.Os import org.xml.sax.InputSource import java.io.FileReader import java.io.StringReader import javax.xml.parsers.DocumentBuilderFactory import javax.xml.xpath.XPathFactory plugins { java } /** Path to Android SDK */ var androidSDK: String = System.getenv("ANDROID_HOME") /** Path to Android build tools */ var androidBT: String = "$androidSDK/build-tools/23.0.1" /** Path to Kolibri deploy folder on Android device */ var deployPath: String = "/sdcard/Android/data/ch.mfiles.kolibri/files/deploy" /** API token to access the MFiles Kolibri Maven repository */ var mFilesGitLABMavenToken = "glpat-KfpFM7pLtvszBABr58SK" java { sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 } sourceSets { main { java { srcDir("src") srcDir("i18n") } resources { srcDir("src") srcDir("i18n") } } } repositories { maven { name = "MFilesGitLAB" url = uri("https://dev.mfiles.ch/gitlab/api/v4/groups/repository/-/packages/maven") } } dependencies { implementation(files("$androidSDK/platforms/android-23/android.jar")) implementation("ch.mfiles.kolibri:android-kolibri:1.8.1p202503161504") implementation("ch.mfiles.kolibri:android-contrib:1.8.1p202503161504") implementation("ch.mfiles.kolibri:android-support-annotations:25.3.1") implementation("ch.mfiles.kolibri:android-aurelhubert-ahbottomnavigation:2.0.4") implementation("ch.mfiles.kolibri:android-support-animated-vector-drawable:25.3.1") implementation("ch.mfiles.kolibri:android-support-compat:25.3.1") implementation("ch.mfiles.kolibri:android-support-core-ui:25.3.1") implementation("ch.mfiles.kolibri:android-support-core-utils:25.3.1") implementation("ch.mfiles.kolibri:android-support-design:25.3.1") implementation("ch.mfiles.kolibri:android-support-fragment:25.3.1") implementation("ch.mfiles.kolibri:android-support-media-compat:25.3.1") implementation("ch.mfiles.kolibri:android-support-transition:25.3.1") implementation("ch.mfiles.kolibri:android-support-v4:25.3.1") implementation("ch.mfiles.kolibri:android-support-v7-appcompat:25.3.1") implementation("ch.mfiles.kolibri:android-support-v7-cardview:25.3.1") implementation("ch.mfiles.kolibri:android-support-v7-gridlayout:25.3.1") implementation("ch.mfiles.kolibri:android-support-v7-preference:25.3.1") implementation("ch.mfiles.kolibri:android-support-v7-recyclerview:25.3.1") implementation("ch.mfiles.kolibri:android-support-vector-drawable:25.3.1") implementation("ch.mfiles.kolibri:android-stepstone-material-stepper:3.3.0") } /** * Include application.xml on project root in resources. */ tasks.named("processResources", Copy::class).configure { from("application.xml") } /** * Helper function for parsing the application descriptor for class and version data. */ fun parseApplicationDescriptor(): Map { val xmlFile = File(project.projectDir.path + "/application.xml") val xmlInput = InputSource(StringReader(xmlFile.readText())) val docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder() docBuilder.setEntityResolver { _, _ -> InputSource(FileReader(project.projectDir.path + "/application.dtd")) } val doc = docBuilder.parse(xmlInput) val xPath = XPathFactory.newInstance().newXPath() val result = HashMap() result["appClass"] = xPath.evaluate("/application/@class", doc) result["versionMajor"] = xPath.evaluate("/application/version/@major", doc) result["versionMinor"] = xPath.evaluate("/application/version/@minor", doc) result["versionBuild"] = xPath.evaluate("/application/version/@build", doc) return result } /** * Create a dex-ed version of the java jar artifact in the kolibri folder */ val kolibriJar by tasks.registering(DefaultTask::class) { group = "build" // input is result from jar task inputs.files(tasks.named("jar").get().outputs) val ad = parseApplicationDescriptor() val kolibriJarFile = File( project.buildDir, "/kolibri/" + ad["appClass"] + "-" + "${ad["versionMajor"]}.${ad["versionMinor"]}.${ad["versionBuild"]}.jar" ) outputs.file(kolibriJarFile) doLast { val jarFile = inputs.files.singleFile logger.info("DEXing $jarFile") // make sure the output folder exists kolibriJarFile.parentFile.mkdirs() exec { if (Os.isFamily(Os.FAMILY_WINDOWS)) { //windows executable = "cmd" args = listOf( "/c", "$androidBT/dx.bat", "--dex", "--output=${kolibriJarFile.absolutePath}", "--min-sdk-version=23", jarFile.absolutePath ) } else { //linux executable = "$androidBT/dx" args = listOf( "--dex", "--output=${kolibriJarFile.absolutePath}", "--min-sdk-version=23", jarFile.absolutePath ) } } } } // create outgoing variant for consuming the Kolibri jar generated by the kolibriJar task val kolibriJars: Configuration by configurations.creating { isCanBeConsumed = true isCanBeResolved = false } artifacts { add("kolibriJars", kolibriJar.get().outputs.files.singleFile) { builtBy(kolibriJar) } } tasks.register("deploy", Exec::class) { group = "publishing" // input is result from kolibriJar task inputs.files(kolibriJar.get().outputs) // no output (pushed to connected device...) // set working dir to project dir workingDir(project.projectDir) // call adb push to push the project's jar to the Kolibri deploy folder val kolibriJar = inputs.files.singleFile executable = "${androidSDK}/platform-tools/adb" args("push") args(kolibriJar.relativeTo(project.projectDir)) args("$deployPath/${kolibriJar.name}") } tasks.register("checkVersion") { group = "verification" val appVersionProperty = "kolibriAppVersion" onlyIf { // run only if the app version was provided on the command line (project.hasProperty(appVersionProperty) && project.property(appVersionProperty) != "") || (rootProject.hasProperty(appVersionProperty) && rootProject.property(appVersionProperty) != "") } doLast { // check app version against the one given by kolibriAppVersion val targetVersion = if (project.hasProperty(appVersionProperty)) project.property(appVersionProperty) else rootProject.property(appVersionProperty) val ad = parseApplicationDescriptor() val appVersion = ad["versionMajor"] + "." + ad["versionMinor"] + "." + ad["versionBuild"] if (appVersion != targetVersion) throw GradleException("Kolibri app version $appVersion differs from requested $appVersionProperty $targetVersion") } } tasks.named("check") { dependsOn("checkVersion") }     common/AndroidManifest.xml:       common/application.dtd:       common/application.xml:  
    common/build.gradle.kts:   plugins { id("ch.mfiles.kolibri-application") } tasks.named("processResources", Copy::class).configure { from("data") { this.into("data") } } sourceSets { test { java { srcDir("javatest") } } } repositories { mavenCentral() } // Create separate configuration for JUnit dependencies in order to put them 1st on the test compile/runtime classpath. // If we don't do this, the android.jar is placed before junit.jar which breaks JUnit tests with a // "RuntimeException Stub!" val junitConfiguration: Configuration by configurations.creating dependencies { junitConfiguration("junit:junit:4.12") junitConfiguration("commons-logging:commons-logging:1.2") testImplementation(junitConfiguration) } tasks.named("test", Test::class).configure { classpath = junitConfiguration + classpath }     common/build.xml:       common/data/fixed-master-data.txt:   INSERT INTO localizedTexts VALUES ("0","D","Bitte wählen..","1") INSERT INTO localizedTexts VALUES ("1","D","SAV","1") INSERT INTO localizedTexts VALUES ("2","D","MON","1") INSERT INTO localizedTexts VALUES ("3","D","REP","1") INSERT INTO localizedTexts VALUES ("0","F","Choisir..","1") INSERT INTO localizedTexts VALUES ("1","F","SAV","1") INSERT INTO localizedTexts VALUES ("2","F","MON","1") INSERT INTO localizedTexts VALUES ("3","F","REP","1") INSERT INTO localizedTexts VALUES ("01","D","NEU","2") INSERT INTO localizedTexts VALUES ("02","D","ANGENOMMEN","2") INSERT INTO localizedTexts VALUES ("03","D","ABGELEHNT","2") INSERT INTO localizedTexts VALUES ("04","D","WEITERGELEITET","2") INSERT INTO localizedTexts VALUES ("05","D","IN ARBEIT","2") INSERT INTO localizedTexts VALUES ("06","D","ABGESCHLOSSEN","2") INSERT INTO localizedTexts VALUES ("07","D","TEILERLEDIGT","2") INSERT INTO localizedTexts VALUES ("01","F","NOUVEAU","2") INSERT INTO localizedTexts VALUES ("02","F","ADMIS","2") INSERT INTO localizedTexts VALUES ("03","F","REJETÉ","2") INSERT INTO localizedTexts VALUES ("04","F","TRANSMIS","2") INSERT INTO localizedTexts VALUES ("05","F","EN TRAVAIL","2") INSERT INTO localizedTexts VALUES ("06","F","RéPARATION FINALE","2") INSERT INTO localizedTexts VALUES ("07","F","RéPARATION PARTIELLE","2") INSERT INTO localizedTexts VALUES ("1","D","HOCH","3") INSERT INTO localizedTexts VALUES ("2","D","MITTEL","3") INSERT INTO localizedTexts VALUES ("3","D","NIEDRIG","3") INSERT INTO localizedTexts VALUES ("1","F","URGENT","3") INSERT INTO localizedTexts VALUES ("2","F","MOYEN","3") INSERT INTO localizedTexts VALUES ("3","F","FAIBLEMENT","3") INSERT INTO localizedTexts VALUES ("0000","D","Bitte wählen..","4") INSERT INTO localizedTexts VALUES ("0001","D","Frau","4") INSERT INTO localizedTexts VALUES ("0002","D","Herr","4") INSERT INTO localizedTexts VALUES ("0003","D","Firma","4") INSERT INTO localizedTexts VALUES ("0004","D","Herr und Frau","4") INSERT INTO localizedTexts VALUES ("0005","D","Familie","4") INSERT INTO localizedTexts VALUES ("0000","E","Please select","4") INSERT INTO localizedTexts VALUES ("0001","E","Mrs","4") INSERT INTO localizedTexts VALUES ("0002","E","Sir","4") INSERT INTO localizedTexts VALUES ("0003","E","Company","4") INSERT INTO localizedTexts VALUES ("0004","E","Mr. and Mrs","4") INSERT INTO localizedTexts VALUES ("0005","E","family", "4") INSERT INTO localizedTexts VALUES ("0000","F","Choisir..","4") INSERT INTO localizedTexts VALUES ("0001","F","Madame","4") INSERT INTO localizedTexts VALUES ("0002","F","Monsieur","4") INSERT INTO localizedTexts VALUES ("0003","F","Entreprise","4") INSERT INTO localizedTexts VALUES ("0004","F","Monsieur et Madame","4") INSERT INTO localizedTexts VALUES ("0005","F","Famille","4") INSERT INTO localizedTexts VALUES ("01","D","Objekt","5") INSERT INTO localizedTexts VALUES ("02","D","Kunde","5") INSERT INTO localizedTexts VALUES ("03","D","Auftraggeber","5") INSERT INTO localizedTexts VALUES ("04","D","Eigentümer","5") INSERT INTO localizedTexts VALUES ("05","D","Verwaltung","5") INSERT INTO localizedTexts VALUES ("06","D","Ansprechpartner Anlage","5") INSERT INTO localizedTexts VALUES ("07","D","Warenempfänger","5") INSERT INTO localizedTexts VALUES ("01","F","Objet","5") INSERT INTO localizedTexts VALUES ("02","F","Client","5") INSERT INTO localizedTexts VALUES ("03","F","Donneur d'ordre","5") INSERT INTO localizedTexts VALUES ("04","F","Propriétaire","5") INSERT INTO localizedTexts VALUES ("05","F","Administration","5") INSERT INTO localizedTexts VALUES ("06","F","Partenaire","5") INSERT INTO localizedTexts VALUES ("07","F","Destinataire","5") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","6") INSERT INTO localizedTexts VALUES ("01","D","Niemand auf Platz ","6") INSERT INTO localizedTexts VALUES ("02","D","Unterschrift verweigert ","6") INSERT INTO localizedTexts VALUES ("03","D","Rapport in Briefkasten / bei Anlage ","6") INSERT INTO localizedTexts VALUES ("04","D","Aus Hygienegründen keine Unterschrift","6") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","6") INSERT INTO localizedTexts VALUES ("01","F","Personne sur place ","6") INSERT INTO localizedTexts VALUES ("02","F","Signature refuse ","6") INSERT INTO localizedTexts VALUES ("03","F","Rapport dans boîte aux lettres ","6") INSERT INTO localizedTexts VALUES ("04","F","Pas de signature pour des raisons d'hygi�ne ","6") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","7") INSERT INTO localizedTexts VALUES ("01","D","Fax","7") INSERT INTO localizedTexts VALUES ("02","D","eMail","7") INSERT INTO localizedTexts VALUES ("03","D","Formular","7") INSERT INTO localizedTexts VALUES ("04","D","Verzicht","7") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","7") INSERT INTO localizedTexts VALUES ("01","F","Fax","7") INSERT INTO localizedTexts VALUES ("02","F","eMail","7") INSERT INTO localizedTexts VALUES ("03","F","Formulaire","7") INSERT INTO localizedTexts VALUES ("04","F","Pas de rapport","7") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","8") INSERT INTO localizedTexts VALUES ("01","D","Tor CL 2021","8") INSERT INTO localizedTexts VALUES ("02","D","Tor CL 2022","8") INSERT INTO localizedTexts VALUES ("03","D","STW CL 2023","8") INSERT INTO localizedTexts VALUES ("04","D","Barriere CL 2022","8") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","8") INSERT INTO localizedTexts VALUES ("01","F","Porte CL 2021","8") INSERT INTO localizedTexts VALUES ("02","F","Portail CL 2022","8") INSERT INTO localizedTexts VALUES ("03","F","STW CL 2023","8") INSERT INTO localizedTexts VALUES ("04","F","Barrière CL 2022","8") INSERT INTO localizedTexts VALUES ("00","D","Monat","9") INSERT INTO localizedTexts VALUES ("01","D","Januar","9") INSERT INTO localizedTexts VALUES ("02","D","Februar","9") INSERT INTO localizedTexts VALUES ("03","D","März","9") INSERT INTO localizedTexts VALUES ("04","D","April","9") INSERT INTO localizedTexts VALUES ("05","D","Mai","9") INSERT INTO localizedTexts VALUES ("06","D","Juni","9") INSERT INTO localizedTexts VALUES ("07","D","Juli","9") INSERT INTO localizedTexts VALUES ("08","D","August","9") INSERT INTO localizedTexts VALUES ("09","D","September","9") INSERT INTO localizedTexts VALUES ("10","D","Oktober","9") INSERT INTO localizedTexts VALUES ("11","D","November","9") INSERT INTO localizedTexts VALUES ("12","D","Dezember","9") INSERT INTO localizedTexts VALUES ("00","E","Month","9") INSERT INTO localizedTexts VALUES ("01","E","January","9") INSERT INTO localizedTexts VALUES ("02","E","February","9") INSERT INTO localizedTexts VALUES ("03","E","March","9") INSERT INTO localizedTexts VALUES ("04","E","April","9") INSERT INTO localizedTexts VALUES ("05","E","May","9") INSERT INTO localizedTexts VALUES ("06","E","June","9") INSERT INTO localizedTexts VALUES ("07","E","July","9") INSERT INTO localizedTexts VALUES ("08","E","August","9") INSERT INTO localizedTexts VALUES ("09","E","September","9") INSERT INTO localizedTexts VALUES ("10","E","October","9") INSERT INTO localizedTexts VALUES ("11","E","November","9") INSERT INTO localizedTexts VALUES ("12","E","December","9") INSERT INTO localizedTexts VALUES ("00","F","Mois","9") INSERT INTO localizedTexts VALUES ("01","F","Janvier","9") INSERT INTO localizedTexts VALUES ("02","F","Février","9") INSERT INTO localizedTexts VALUES ("03","F","Mars","9") INSERT INTO localizedTexts VALUES ("04","F","Avril","9") INSERT INTO localizedTexts VALUES ("05","F","Mai","9") INSERT INTO localizedTexts VALUES ("06","F","Juin","9") INSERT INTO localizedTexts VALUES ("07","F","Juillet","9") INSERT INTO localizedTexts VALUES ("08","F","Août","9") INSERT INTO localizedTexts VALUES ("09","F","Septembre","9") INSERT INTO localizedTexts VALUES ("10","F","Octobre","9") INSERT INTO localizedTexts VALUES ("11","F","Novembre","9") INSERT INTO localizedTexts VALUES ("12","F","Décembre","9") INSERT INTO localizedTexts VALUES ("01","D","Vorgesetzter","10") INSERT INTO localizedTexts VALUES ("02","D","Kunde","10") INSERT INTO localizedTexts VALUES ("03","D","1. Rapportnachricht","10") INSERT INTO localizedTexts VALUES ("04","D","2. Rapportnachricht","10") INSERT INTO localizedTexts VALUES ("05","D","Interne Nachricht","10") INSERT INTO localizedTexts VALUES ("06","D","Projektverantwortlicher","10") INSERT INTO localizedTexts VALUES ("07","D","Disposition","10") INSERT INTO localizedTexts VALUES ("01","F","Supérieur","10") INSERT INTO localizedTexts VALUES ("02","F","Client","10") INSERT INTO localizedTexts VALUES ("03","F","1er message du rapport","10") INSERT INTO localizedTexts VALUES ("04","F","2éme message du rapprt","10") INSERT INTO localizedTexts VALUES ("05","F","Message interne","10") INSERT INTO localizedTexts VALUES ("06","F","Responsable de projet","10") INSERT INTO localizedTexts VALUES ("07","F","Disposition","10") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","11") INSERT INTO localizedTexts VALUES ("01","D","Diverses..","11") INSERT INTO localizedTexts VALUES ("02","D","Fahrzeugwasch","11") INSERT INTO localizedTexts VALUES ("03","D","Fahrzeugverlad","11") INSERT INTO localizedTexts VALUES ("04","D","Parkinggebühren","11") INSERT INTO localizedTexts VALUES ("05","D","Einkauf Werkzeug","11") INSERT INTO localizedTexts VALUES ("06","D","Einkauf Verbrauchsmittel","11") INSERT INTO localizedTexts VALUES ("07","D","Benzinzahlung bar","11") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","11") INSERT INTO localizedTexts VALUES ("01","F","divers..","11") INSERT INTO localizedTexts VALUES ("02","F","laver la voiture","11") INSERT INTO localizedTexts VALUES ("03","F","expédier du véhicule","11") INSERT INTO localizedTexts VALUES ("04","F","parking impôt","11") INSERT INTO localizedTexts VALUES ("05","F","achat des outils","11") INSERT INTO localizedTexts VALUES ("06","F","matériel consommations","11") INSERT INTO localizedTexts VALUES ("07","F","essence","11") INSERT INTO localizedTexts VALUES ("00","D","Standard","12") INSERT INTO localizedTexts VALUES ("04","D","Garantie","12") INSERT INTO localizedTexts VALUES ("05","D","Kulanz","12") INSERT INTO localizedTexts VALUES ("06","D","Auftrag","12") INSERT INTO localizedTexts VALUES ("00","F","Standard","12") INSERT INTO localizedTexts VALUES ("04","F","Garantie","12") INSERT INTO localizedTexts VALUES ("05","F","Pas de facturation","12") INSERT INTO localizedTexts VALUES ("06","F","Offre","12") INSERT INTO localizedTexts VALUES ("00","D","Arbeit/Fahrt","13") INSERT INTO localizedTexts VALUES ("01","D","Praxisausbildung","13") INSERT INTO localizedTexts VALUES ("02","D","Intern","13") INSERT INTO localizedTexts VALUES ("03","D","Fahrzeug","13") INSERT INTO localizedTexts VALUES ("04","D","Lager","13") INSERT INTO localizedTexts VALUES ("05","D","Transport","13") INSERT INTO localizedTexts VALUES ("06","D","Konferenzen","13") INSERT INTO localizedTexts VALUES ("07","D","Objektabklärung","13") INSERT INTO localizedTexts VALUES ("08","D","Externe Ganztagesschulung","13") INSERT INTO localizedTexts VALUES ("00","F","Travail, en route","13") INSERT INTO localizedTexts VALUES ("01","F","Stage pratique","13") INSERT INTO localizedTexts VALUES ("02","F","Interne","13") INSERT INTO localizedTexts VALUES ("03","F","Véhicule","13") INSERT INTO localizedTexts VALUES ("04","F","Dépôt","13") INSERT INTO localizedTexts VALUES ("05","F","Transport","13") INSERT INTO localizedTexts VALUES ("06","F","Conférences","13") INSERT INTO localizedTexts VALUES ("07","F","Recherche objet","13") INSERT INTO localizedTexts VALUES ("08","F","Journée de formation continue externe","13") INSERT INTO localizedTexts VALUES ("01","D","Erfolgreich angemeldet","14") INSERT INTO localizedTexts VALUES ("02","D","Passwort falsch","14") INSERT INTO localizedTexts VALUES ("03","D","Benutzer gesperrt","14") INSERT INTO localizedTexts VALUES ("04","D","Benutzer ist nicht registriert","14") INSERT INTO localizedTexts VALUES ("01","F","annoncé avec succès","14") INSERT INTO localizedTexts VALUES ("02","F","mot de passe faux","14") INSERT INTO localizedTexts VALUES ("03","F","utilisateur fermè","14") INSERT INTO localizedTexts VALUES ("04","F","utilisateur n'enregistre pas","14")     common/i18n/ch/mfiles/kaba/kolibri/common/Messages.java:   package ch.mfiles.kaba.kolibri.common; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.common.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }     common/i18n/ch/mfiles/kaba/kolibri/common/messages.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) ArtNr = Art. Nr. BackupHandler_11 = Scheduled next backup run for {0} BackupHandler_13 = Daily backup run BackupHandler_15 = Backup failed: {0} BackupHandler_19 = The last (automatic) backup run is more than 24 hours past. BackupHandler_21 = There is no runtime backup. A new backup will be triggered now. BackupHandler_23 = The last successful backup is older than 2 days. A new backup will be triggered now. BackupHandler_5 = Restart the application to activate the periodic backup of application data. BackupHandler_6 = Application restart Containersize = Container size DeviceMirrorringHandler.0 = Encoded restore point must start with 'SNAPSHOT~' and contain exactly 5 segments separated by '~'! DeviceMirrorringHandler.1 = Activating device... DeviceMirrorringHandler.10 = Unable to create and request the personal push token. Retry later. DeviceMirrorringHandler.11 = User ''{0}'' is already registered on device ''{1}''! Trigger a device migration on the other device. DeviceMirrorringHandler.13 = Could not reconstruct restore point for data migration from other device! DeviceMirrorringHandler.14 = Update to the most current application release and use the previously released device in the meantime. DeviceMirrorringHandler.15 = Local application data will be replaced with the data from the switching user. DeviceMirrorringHandler.16 = Continue? DeviceMirrorringHandler.17 = Assigning personal push token... DeviceMirrorringHandler.18 = Unable to request the personal push token. Retry later. DeviceMirrorringHandler.19 = Some applications are not installed with the required version. DeviceMirrorringHandler.2 = Synchronizing push tokens... DeviceMirrorringHandler.20 = Unable to prepare device for push notifications. Could not synchronize push tokens. DeviceMirrorringHandler.23 = Exception caught while loading the personal push token attributes. Retry later. DeviceMirrorringHandler.24 = Multiple personal push tokens are already assigned for user {0}!? Contact IT support. DeviceMirrorringHandler.26 = Device is currently assigned to user {0} but was not fully activated. Log in as user {0} first to complete the process! DeviceMirrorringHandler.27 = Unable to create and request the personal push token. Retry later. DeviceMirrorringHandler.28 = Reading token attributes... DeviceMirrorringHandler.29 = Cause: DeviceMirrorringHandler.3 = Unable to prepare device for push notifications. Could not synchronize push tokens. DeviceMirrorringHandler.30 = Could not reconstruct restore point for data migration from other device! DeviceMirrorringHandler.31 = Creating personal push token... DeviceMirrorringHandler.34 = Could not prepare to restore migrated application data from other device! DeviceMirrorringHandler.35 = User is already registered on device ''{0}''! Trigger a device migration on the other device first. DeviceMirrorringHandler.37 = Unable to request the personal push token. Retry later. DeviceMirrorringHandler.39 = The application data will be replaced with the state of the source device due to a device migration. Source device: ''{0}'', backup time: {1} DeviceMirrorringHandler.4 = Activate application... DeviceMirrorringHandler.41 = Assigning personal push token... DeviceMirrorringHandler.42 = Restoring the state of the source device failed. DeviceMirrorringHandler.44 = Unable to check prerequisites. Could not synchronize push tokens. DeviceMirrorringHandler.46 = Not all required applications are installed. Please carry out an update to the latest application version and use in the meantime the previously handed over device. DeviceMirrorringHandler.47 = Some applications are not at the required version. Please carry out un update to the latest version and use in the meantime the previously handed over device. DeviceMirrorringHandler.48 = Unable to release the personal push token. DeviceMirrorringHandler.5 = Reading token attributes... DeviceMirrorringHandler.50 = Restored source device state DeviceMirrorringHandler.51 = The application was not activated for the logged in user ''{0}'' but for user ''{1}''. DeviceMirrorringHandler.52 = Backup of application data failed. DeviceMirrorringHandler.53 = Release the device for user ''{1}'' and continue the device activation with user ''{0}''? DeviceMirrorringHandler.55 = Releasing device... DeviceMirrorringHandler.56 = Synchronizing push tokens... DeviceMirrorringHandler.58 = Release application... DeviceMirrorringHandler.59 = The logged in user ''{0}'' has no personal push token assigned! DeviceMirrorringHandler.6 = Cause: DeviceMirrorringHandler.60 = There are multiple personal push tokens assigned! Contact IT support. DeviceMirrorringHandler.62 = Creating runtime restore point... DeviceMirrorringHandler.63 = Releasing push tokens... DeviceMirrorringHandler.66 = The application data of user ''{0}'' will be backed up to be migrated to another device later. DeviceMirrorringHandler.68 = Continue? DeviceMirrorringHandler.7 = Exception caught while loading the personal push token attributes. Retry later. DeviceMirrorringHandler.72 = Backup complete DeviceMirrorringHandler.73 = Application not activated for any user. DeviceMirrorringHandler.8 = Creating personal push token... DeviceMirrorringHandler.9 = Not all required applications are currently installed. Done = Done FileUtils_0 = File {0} not present in classpath!? FormatMailAddress = Format of the mail address: address@server.xy HTMLEncode_0 = Error invoking 1.4 URLEncoder.encode with reflection: InvalidFileName = Invalid file name: NumbersUpToSixDigitsAreAllowed = Numbers up to six digits are allowed PhoneBookEntry_1 = No company name Planed = Planed PropertiesFileConverter.0 = Not a directory: RemoteTransactionHandler.0 = Internal error: method must be called on the AM thread only! RemoteTransactionHandler.1 = Refreshing masterdata.. RemoteTransactionHandler.2 = Refresh flag updated. RemoteTransactionHandler.3 = Masterdata downloaded. RemoteTransactionHandler.4 = Obsolete data deleted. RemoteTransactionHandler.5 = Deleting firmware files.. RemoteTransactionHandler.6 = Firmware file deleted. RemoteTransactionHandler.7 = No firmware file received from server ReservedForFutureUse = Not used. Reserved for future use. SAPError = SAP error SAPErrorMessage = SAP error message: Service = Service StartEndLessThan3MinutesApart = Start/End is less than 3 minutes apart TimeIsOverlapping = Time is overlapping with {0} - {1}\n WorkTimeRecordingWasStartedYesterday. = Working time recording was started yesterday. WouldYouLikeToCall = Would you like to call {0}? WrongFormArgument = Wrong form argument class found in form WrongFormat = Wrong format ({0}) WrongFormatXX-XXXX-XXX/XX = Wrong format (XX-XXXX-XXX/XX) abort = Abort aborted = aborted... all = All billing = Billing camera = Camera cancelled = Cancelled characters = characters checkList = Check list commNo = Comm-No. communicationError = Communication error communicationErrorWithColon = Communication error: confirmToDeleteMaterial = Do you want to delete this material from the Database! costumerReport = Costumer report deliveryListDownloaded = Delivery list downloaded designation = Bez. destinationAddressIsInvalid = The pointer to the destination address is not valid, is NULL, or the destination address string is too long. doYouWantToStopTimesheet = Do you want to stop Timesheet? documents = Documents duplicatedMaterialNumber = There is MaterialNumber {0} duplicated {1} can not insert. employee = Employee error = Error errorWithParam = Error {0} exit = Exit failure = Failure firstName = First name foundErrorsInTimesheetsOnDate = Errors in timesheets have been found on the following dates: {0}. Please correct and send them. from = From gallery = Gallery image = Image images = Images information = Information insertComplete = Insert complete. insertingMasterData = Inserting MasterData... installationError = Installation error invalidNotificationInterval = Invalid value for 'NotificationInterval' setting found invalidUsernameOrPassword = invalid username or password invalidVolume = Invalid value for 'Volume' setting found jobState = Job State loadCALENDARObjectWithDatetime = Try to load a CALENDAR object with a datetime value ( location = Location material = Material materialList = MaterialList materialName = Material name materialNumber = Material number measurement = Force measurement messages = Messages name = Name newJob = New Job! newJobReceived = New job received. newMessage = New Message!\n newVehicleInventoryReceived = New Vehicle Inventory received. newShortMessageReceived = New short message received. noDocumentsRecorded = No document attached noImagesRecorded = No image recorded noMaterialRecorded = No material recorded noMeasurementsRecorded = No measurement available noMessagesRecorded = No message recorded noPartsFound = no parts found matching the criteria. noRecipientApplication = No recipient application is available to handle the request. noReportRecorded = No report recorded noTimesRecorded = No times recorded noUserActive = No user active! REGISTER_USER not called / corrupt data in table ZKDMOBMA? noValueForNotificationIntervalFound = No value for notification interval found noVolumeSettingFound = No volume setting found number = Number onlyNumberAndSpacesAllowedForTelephoneNumber = Only numbers and spaces are allowed for phone numbers (max. 30 char) orderDate = Order Date orderNo = Order No orderWillBeForwardedTo = {0}-Order {1} will be forwarded to {2} overHoursInOneDay = "{0}" is over hours in one day. overlapping = {0} is overlapping {1} partFound = part found pleaseSelect = Please select... pleaseSelectValue = Please select a value! pleaseProvideValue = Please provide a value! pointerReferenceToInvalidMemoryLocation = A pointer does not reference a valid memory location. One or more of the pointers lpszDestAddress, lpszAppName, lpszCalledParty, or lpszComment have been specified but are invalid. receive = Receive recipientApplicationIsActive = The recipient application is active, but its request queue is full or there is insufficient memory to expand the queue. The calling application should try again later. replacement = Replacement reportCannotContainTimesMoreThanOneDay = The report can not contain times form more than one day. There are already entries from {0} reports = Reports reportsFrom = Reports from reset = Reset saveCALENDARObjectWithDatetime = Try to save a CALENDAR object with a datetime value ( search = Search select = Select... shortNews = Short news signature = Signature subject = Subject timeStopped = Time stopped times = Times timesFrom = Times from timesheetCannotBeStartet = Timesheet can not be startet. It's already sent. to = To total = Total typeOfJob = Type of job updatingDeliveryList = Updating delivery list userIsNotRegistred = User is not registered userLocked = User locked validationError = Validation error. \nPlease type all required information. valueMustNotBeLongerThen = Value must not be longer then warning = Warning! workTimeCapturingStartet = Work time capturing startet workTimeCapturingStartetBeforeYesterday = Work time capturing was startet before yesterday wrongFormArgument = Wrong form argument class found in form     common/i18n/ch/mfiles/kaba/kolibri/common/Messages.txt:   CommonApplication.5 new short message received Neue Kurznachricht erhalten     common/i18n/ch/mfiles/kaba/kolibri/common/messages_de.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface ArtNr = Art. Nr. BackupHandler_11 = N\u00E4chste Sicherung eingeplant am {0} BackupHandler_13 = T\u00E4glicher Sicherungslauf BackupHandler_15 = Sicherung fehlgeschlagen: {0} BackupHandler_19 = Der letzte (automatische) Sicherungslauf ist \u00E4lter als 24 Stunden. BackupHandler_21 = Es gibt noch keine Sicherung. Eine neue Sicherung wird jetzt gestartet. BackupHandler_23 = Die letzte erfolgreiche Sicherung liegt l\u00E4nger als 2 Tage zur\u00FCck. Eine neue Sicherung wird jetzt gestartet. BackupHandler_5 = Die Anwendung wird neu gestartet, um die regelm\u00E4\u00DFige Sicherung der Anwendungsdaten zu aktivieren. BackupHandler_6 = Neustart der Anwendung Containersize = Verpackungsgr\u00F6sse DeviceMirrorringHandler.0 = Codierter Sicherungspunkt muss mit 'SNAPSHOT~' beginnen und genau 5 durch '~' getrennte Segmente beinhalten! DeviceMirrorringHandler.1 = Aktiviere Ger\u00E4t... DeviceMirrorringHandler.10 = Der pers\u00F6nliche Push-Token kann nicht erzeugt und angefordert werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.11 = Benutzer ''{0}'' ist bereits auf Ger\u00E4t ''{1}'' registriert! Starten Sie eine Ger\u00E4temigration auf dem anderen Ger\u00E4t. DeviceMirrorringHandler.13 = Der Sicherungspunkt aus der Datenmigration von einem anderen Ger\u00E4t konnte nicht wiederhergestellt werden! DeviceMirrorringHandler.14 = Aktualisieren Sie auf die aktuellste Anwendungsversion and verwenden Sie in der Zwischenzeit das zuvor freigegebene Ger\u00E4t. DeviceMirrorringHandler.15 = Die lokalen Anwendungsdaten werden durch die Daten des \u00FCbernehmenden Benutzers ersetzt. DeviceMirrorringHandler.16 = Fortsetzen? DeviceMirrorringHandler.17 = Pers\u00F6nlichen Push-Token zuordnen... DeviceMirrorringHandler.18 = Der pers\u00F6nliche Push-Token konnte nicht angefordert werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.19 = Einige Anwendungen haben nicht die erforderliche Version. DeviceMirrorringHandler.2 = Synchronisierung der Push-Token... DeviceMirrorringHandler.20 = Das Ger\u00E4t konnte nicht f\u00FCr Push-Benachrichtigung vorbereitet werden. Push-Token konnten nicht synchronisiert werden. DeviceMirrorringHandler.23 = Beim Zugriff auf Attribute des pers\u00F6nlichen Push-Tokens ist ein Fehler aufgetreten. Sp\u00E4ter versuchen. DeviceMirrorringHandler.24 = Dem Benutzer {0} sind mehrere pers\u00F6nliche Push-Token zugeordnet!? Informieren Sie den IT-Support. DeviceMirrorringHandler.26 = Das Ger\u00E4t ist derzeit dem Benutzer {0} zugeordnet, die Ger\u00E4teaktivierung wurde aber nicht vollst\u00E4ndig abgeschlossen. Melden Sie sich als Benutzer {} an, um den Vorgang abzuschlie\u00DFen! DeviceMirrorringHandler.27 = Das pers\u00F6nliche Push-Token konnte nicht angelegt und zugeordnet werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.28 = Lese Token-Attribute... DeviceMirrorringHandler.29 = Ursache: DeviceMirrorringHandler.3 = Ger\u00E4t konnte nicht f\u00FCr den Empfang von Push-Benachrichtigungen vorbereitet werden. Push-Token konnten nicht synchronisiert werden. DeviceMirrorringHandler.30 = Die Sicherung zur Daten\u00FCbernahme vom anderen Ger\u00E4t konnte nicht wiederhergestellt werden! DeviceMirrorringHandler.31 = Erstelle pers\u00F6nliches Push-Token... DeviceMirrorringHandler.34 = Die Wiederherstellung der Sicherungsdaten vom anderen Ger\u00E4t konnte nicht vorbereitet werden! DeviceMirrorringHandler.35 = Der Benutzer ist bereits auf Ger\u00E4t ''{0}'' registriert! Starten Sie zun\u00E4chst den Ger\u00E4tewechsel auf dem anderen Ger\u00E4t. DeviceMirrorringHandler.37 = Das pers\u00F6nliche Push-Token konnte nicht angefordert werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.39 = Die Anwendungsdaten werden ersetzt mit den Daten vom Quellger\u00E4t aufgrund eines Ger\u00E4tewechsels. Quellger\u00E4t: ''{0}'', Sicherungszeit: {1} DeviceMirrorringHandler.4 = Aktiviere Anwendung... DeviceMirrorringHandler.41 = Pers\u00F6nliches Push-Token zuweisen... DeviceMirrorringHandler.42 = Wiederherstellung der Sicherungsdaten vom Quellger\u00E4t schlug fehl. DeviceMirrorringHandler.44 = Voraussetzungen konnten nicht gepr\u00FCft werden. Push-Token konnten nicht synchronisiert werden. DeviceMirrorringHandler.46 = Es sind nicht alle erforderlichen Anwendungen installiert. F\u00FChren Sie ein Update auf die aktuellste Anwendungsversion durch und verwenden Sie zwischenzeitlich das zuvor abgegebene Ger\u00E4t. DeviceMirrorringHandler.47 = Einige Anwendungen sind nicht auf der erforderlichen Version. F\u00FChren Sie ein Update auf die aktuellste Anwendungsversion durch und verwenden Sie zwischenzeitlich das zuvor abgegebene Ger\u00E4t. DeviceMirrorringHandler.48 = Das pers\u00F6nliche Push-Token konnte nicht freigegeben werden. DeviceMirrorringHandler.5 = Lese Token-Attribute... DeviceMirrorringHandler.50 = Quellger\u00E4te-Zustand wiederherstellen DeviceMirrorringHandler.51 = Die Anwendung wurde nicht f\u00FCr den angemeldeten Benutzer ''{0}'' aktiviert, sondern f\u00FCr Benutzer ''{1}''. DeviceMirrorringHandler.52 = Sicherung der Anwendungsdaten fehlgeschlagen. DeviceMirrorringHandler.53 = Ger\u00E4t f\u00FCr Benutzer ''{1}'' freigeben und mit der Ger\u00E4teaktivierung f\u00FCr den Benutzer ''{0}'' fortfahren? DeviceMirrorringHandler.55 = Ger\u00E4t freigeben... DeviceMirrorringHandler.56 = Synchronisiere Push-Token... DeviceMirrorringHandler.58 = Anwendung freigeben... DeviceMirrorringHandler.59 = Der angemeldete Benutzer ''{0}'' hat kein zugeordnetes pers\u00F6nliches Push-Token! DeviceMirrorringHandler.6 = Ursache: DeviceMirrorringHandler.60 = Es sind mehrere pers\u00F6nliche Push-Token zugeordnet! IT-Support kontaktieren. DeviceMirrorringHandler.62 = Erstelle Laufzeit-Wiederherstellungspunkt... DeviceMirrorringHandler.63 = Push-Token freigeben... DeviceMirrorringHandler.66 = Die Anwendungsdaten des Benutzers ''{0}'' werden gesichert, um sie sp\u00E4ter auf ein anderes Ger\u00E4t zu \u00FCbernehmen. DeviceMirrorringHandler.68 = Fortsetzen? DeviceMirrorringHandler.7 = Beim Laden der Attribute des pers\u00F6nlichen Push-Tokens ist ein Fehler aufgetreten. Sp\u00E4ter versuchen. DeviceMirrorringHandler.72 = Sicherung erstellt DeviceMirrorringHandler.73 = Anwendung f\u00FCr keinen Benutzer aktiviert. DeviceMirrorringHandler.8 = Erstelle pers\u00F6nliches Push-Token... DeviceMirrorringHandler.9 = Nicht alle erforderlichen Anwendungen sind derzeit installiert. Done = Erledigt FileUtils_0 = Datei {0} nicht vorhanden im Klassenpfad!? FormatMailAddress = Zul\u00E4ssiges Format: address@server.xy HTMLEncode_0 = Fehler bez\u00FCglich 1.4URLEncoder. Codieren mit Reflexion: InvalidFileName = Ung\u00FCltiger Dateiname: NumbersUpToSixDigitsAreAllowed = Zahlen bis zu 6 Stellen zul\u00E4ssig. PhoneBookEntry_1 = Kein Firmenname Planed = Geplant PropertiesFileConverter.0 = Kein Verzeichnis: RemoteTransactionHandler.0 = Interner Fehler: Die Methode darf nur auf dem AM Thread aufgerufen werden! RemoteTransactionHandler.1 = Stammdaten aktualisieren. RemoteTransactionHandler.2 = Aktualisierungs-Flag erneuert RemoteTransactionHandler.3 = Stammdaten heruntergeladen. RemoteTransactionHandler.4 = Veraltete Daten gel\u00F6scht. RemoteTransactionHandler.5 = Firmware-Dateien werden gel\u00F6scht. RemoteTransactionHandler.6 = Firmware-Datei wird gel\u00F6scht. RemoteTransactionHandler.7 = Keine Firmware-Datei vom Server erhalten. ReservedForFutureUse = Nicht verwendet. Reserviert f\u00FCr zuk\u00FCnfige Verwendung. SAPError = SAP-Fehler SAPErrorMessage = SAP Fehlermeldung: Service = Service StartEndLessThan3MinutesApart = Von/Bis ist weniger als 3 Minuten auseinander. TimeIsOverlapping = Zeit \u00FCberlappt mit {0} - {1}.\n WorkTimeRecordingWasStartedYesterday. = Arbeitszeiterfassung wurde bereits gestern gestartet. WouldYouLikeToCall = {0} anrufen? WrongFormArgument = Falsche Form Argumentklasse in Form gefunden. WrongFormat = Falsches Format ({0}) WrongFormatXX-XXXX-XXX/XX = Falsches Format (XX-XXXX-XXX/XX). abort = Abbrechen aborted = abgebrochen\u2026 all = Alle billing = Verrechnung camera = Kamera cancelled = Abgebrochen characters = Zeichen checkList = Checkliste commNo = Komm.-Nr. communicationError = Kommunikationsfehler communicationErrorWithColon = Kommunikationsfehler: confirmToDeleteMaterial = Artikel aus Datenbank l\u00F6schen? costumerReport = Kundenrapport deliveryListDownloaded = Artikelliste heruntergeladen. designation = Bezeichnung destinationAddressIsInvalid = Die Zieladresse ist ung\u00FCltig, NULL oder zu lange. doYouWantToStopTimesheet = Pers\u00F6nliche Arbeitszeit stoppen? documents = Dokumente duplicatedMaterialNumber = Artikel {0} schon verhanden {1} kann nicht hinzugef\u00FCgt werden. employee = Mitarbeiter error = Fehler errorWithParam = Fehler {0} exit = Beenden failure = St\u00F6rung firstName = Vorname foundErrorsInTimesheetsOnDate = An folgenden Daten wurden fehlerhafte Timesheets gefunden: {0}. Bitte korrigieren und senden. from = Von gallery = Galerie image = Bild images = Bilder information = Information insertComplete = Daten eingef\u00FCgt. insertingMasterData = Stammdaten laden... installationError = Anlagenfehler invalidNotificationInterval = Ung\u00FCltiger Wert f\u00FCr das Benachrichtigungsintervall gefunden. invalidUsernameOrPassword = Benutzername oder Passwort falsch. invalidVolume = Ung\u00FCltiger Wert f\u00FCr die Lautst\u00E4rke gefunden. jobState = Auftragsstatus loadCALENDARObjectWithDatetime = Laden eines Kalender-Objektes mit Datum ( location = Anlage material = Material materialList = Materialliste materialName = Artikelbezeichnung materialNumber = Artikelnummer measurement = Kraftmessung messages = Mitteilungen name = Name newJob = Neuer Auftrag! newJobReceived = Neuer Auftrag erhalten. newMessage = Neue Nachricht!\n newVehicleInventoryReceived = Neuer Wareneingang. newShortMessageReceived = Neue Kurznachricht erhalten. noDocumentsRecorded = Keine Dokumente vorhanden. noImagesRecorded = Keine Bilder vorhanden. noMaterialRecorded = Noch kein Material erfasst. noMeasurementsRecorded = Keine Messung vorhanden noMessagesRecorded = Noch keine Mitteilungen erfasst. noPartsFound = Keine Ersatzteile f\u00FCr diese Suchkriterien gefunden noRecipientApplication = Die gesuchte Anwendung konnte nicht gefunden werden. noReportRecorded = Noch kein Rapport erstellt. noTimesRecorded = Noch keine Zeiten erfasst. noUserActive = Kein aktiver Benutzer gefunden! REGISTER_USER noch nicht aufgerufen / defekte Daten in ZKDMOBMA? noValueForNotificationIntervalFound = Kein Wert f\u00FCr das Benachrichtigungsintervall gefunden noVolumeSettingFound = Kein Wert f\u00FCr die Lautst\u00E4rke gefunden number = Anzahl onlyNumberAndSpacesAllowedForTelephoneNumber = Nur Ziffern und Leerzeichen zul\u00E4ssig bei Telefonnummern. orderDate = Auftragsdatum orderNo = Auftragsnummer orderWillBeForwardedTo = Der {0}-Auftrag {1} wird an {2} weitergeleitet. overHoursInOneDay = "{0}" ist > 24h. overlapping = {0} \u00FCberlappt {1} partFound = Artikel gefunden. pleaseSelect = Bitte w\u00E4hlen... pleaseSelectValue = Bitte w\u00E4hlen Sie einen Wert aus! pleaseProvideValue = Bitte Wert eingeben! pointerReferenceToInvalidMemoryLocation = Ein Pointer zeigt auf einen ung\u00FCltigen Speicherbereich. Ein oder mehrer Pointer lpszDestAddress, lpszAppName, lpszCalledParty, oder lpszComment wurde sezifiziert, sind aber ung\u00FCltig. receive = Erhalten recipientApplicationIsActive = Die gesuchte Anwendung wurde gefunden. Jedoch ist die Request-Queue voll oder hat zu wenig Speicher zur Verf\u00FCgung. replacement = Ersatz reportCannotContainTimesMoreThanOneDay = Der Rapport kann nicht Zeiten von mehreren Tagen enthalten. Es gibt bereits Eintr\u00E4ge vom {0}. reports = Rapport reportsFrom = Rapport vom reset = Zur\u00FCcksetzen saveCALENDARObjectWithDatetime = Sichern eines Kalender-Objektes mit Datum ( search = Suchen select = W\u00E4hlen... shortNews = Kurznachrichten signature = Unterschrift subject = Betreff timeStopped = Zeit gestoppt times = Zeiten timesFrom = Zeiten vom timesheetCannotBeStartet = Zeiterfassung kann nicht gestartet werden. Das Timesheet wurde bereits gesendet. to = Bis total = Total typeOfJob = Arbeitsart updatingDeliveryList = Update Artikelliste userIsNotRegistred = Benutzer ist nicht registriert userLocked = Benutzer gesperrt. validationError = Validierungsfehler.\nBitte vervollst\u00E4ndigen Sie den Rapport. valueMustNotBeLongerThen = Text darf nicht l\u00E4nger sein als warning = Warnung! workTimeCapturingStartet = Arbeitszeit gestartet. workTimeCapturingStartetBeforeYesterday = Arbeitszeiterfassung wurde bereits vor mehreren Tagen gestartet. wrongFormArgument = Falscher Form\u00FCbergabeparameter.     common/i18n/ch/mfiles/kaba/kolibri/common/messages_fr.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface ArtNr = No d'art. BackupHandler_11 = Prochaine sauvegarde des donn\u00E9es pr\u00E9vue pour le {0} BackupHandler_13 = Sauvegarde quotidienne BackupHandler_15 = La sauvegarde a \u00E9chou\u00E9: {0} BackupHandler_19 = La derni\u00E8re ex\u00E9cution de la sauvegarde (automatique) date de plus de 24 heures. BackupHandler_21 = Il n\u2019y a pas encore de sauvegarde. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_23 = La derni\u00E8re sauvegarde r\u00E9ussie remonte \u00E0 plus de 2 jours. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_5 = L\u2019application est red\u00E9marr\u00E9e pour activer la sauvegarde r\u00E9guli\u00E8re des donn\u00E9es de l\u2019application. BackupHandler_6 = Red\u00E9marrage de l\u2018application Containersize = Dimensions d'emballage DeviceMirrorringHandler.0 = Le point de restaurantion cod\u00E9 doit commencer par 'SNAPSHOT~' et comprendre pr\u00E9cis\u00E9ment 5 segments s\u00E9par\u00E9s par '~'! DeviceMirrorringHandler.1 = Activer l'appareil... DeviceMirrorringHandler.10 = Impossible de cr\u00E9er et demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.11 = L'utilisateur ''{0}'' est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{1}'' ! D\u00E9marrez une migration de l'appareil sur l'autre appareil. DeviceMirrorringHandler.13 = Impossible de r\u00E9tablir le point de restauration de la migration de donn\u00E9es \u00E0 partir d'un autre appareil! DeviceMirrorringHandler.14 = Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment partag\u00E9. DeviceMirrorringHandler.15 = Les donn\u00E9es d\u2019application locales sont remplac\u00E9es par les donn\u00E9es de l\u2019utilisateur reprenant. DeviceMirrorringHandler.16 = Continuer? DeviceMirrorringHandler.17 = Attribuer le Push-Token personnel... DeviceMirrorringHandler.18 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.19 = Quelques applications n'ont pas la version n\u00E9cessaire. DeviceMirrorringHandler.2 = Synchronisation des Push-Token... DeviceMirrorringHandler.20 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.23 = Une erreur est survenue en acc\u00E9dant les attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.24 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.26 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.27 = Impossible de cr\u00E9er et attribuer le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.28 = Attributs Token de lecture... DeviceMirrorringHandler.29 = Cause: DeviceMirrorringHandler.3 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour recevoir les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.30 = Impossible de r\u00E9tablir la sauvegarde pour la reprise de donn\u00E9es de l\u2019autre appareil! DeviceMirrorringHandler.31 = Cr\u00E9ation d'un Push-Token personnel... DeviceMirrorringHandler.34 = Impossible de pr\u00E9parer le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019autre appareil! DeviceMirrorringHandler.35 = L'utilisateur est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{0}''! D\u00E9marrez d'abord le changement d'appareil sur un autre appareil. DeviceMirrorringHandler.37 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.39 = Les donn\u00E9es d\u2019application sont remplac\u00E9es par les donn\u00E9es de l\u2019appareil source en raison d\u2019un changement d\u2019\u00E9quipement. Appareil source: ''{0}'', temps de sauvegarde: {1} DeviceMirrorringHandler.4 = Activer l'application... DeviceMirrorringHandler.41 = Attribuer les Push-Token personnels... DeviceMirrorringHandler.42 = Le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019appareil source a \u00E9chou\u00E9. DeviceMirrorringHandler.44 = Les conditions pr\u00E9alables n'ont pas pu \u00EAtre v\u00E9rifi\u00E9es. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.46 = Pas toutes les applications n\u00E9cessaires sont install\u00E9es. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.47 = Certaines des applications ne se trouvent pas dans la version requise. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.48 = Le Push-Token personnel n'a pas pu \u00EAtre lib\u00E9r\u00E9. DeviceMirrorringHandler.5 = Attributs Token de lecture... DeviceMirrorringHandler.50 = R\u00E9tablir l\u2019\u00E9tat de l\u2019appareil source DeviceMirrorringHandler.51 = L'application n'a pas \u00E9t\u00E9 activ\u00E9e pour l'utilisateur ''{0}'' enregistr\u00E9, mais pour l'utilisateur ''{1}''. DeviceMirrorringHandler.52 = La sauvegarde des donn\u00E9es d\u2019application a \u00E9chou\u00E9. DeviceMirrorringHandler.53 = Lib\u00E9rer l'appareil pour l'utilisateur ''{1}'' et continuer avec l'activation de l'appareil pour l'utilisateur ''{0}'' ? DeviceMirrorringHandler.55 = Lib\u00E9rer l'apparail... DeviceMirrorringHandler.56 = Synchronisation du Push-Token... DeviceMirrorringHandler.58 = Lib\u00E9rer l'application... DeviceMirrorringHandler.59 = L'utilisateur ''{0}'' enregistr\u00E9 n'a pas de Push-Token personnel attribu\u00E9! DeviceMirrorringHandler.6 = Cause: DeviceMirrorringHandler.60 = Plusieurs Push-Token personnels sont d\u00E9j\u00E0 attribu\u00E9s! Veuillez contacter le support informatique. DeviceMirrorringHandler.62 = Cr\u00E9ez un point de restauration de la dur\u00E9e d\u2019ex\u00E9cution. DeviceMirrorringHandler.63 = Lib\u00E9rer Push-Token ... DeviceMirrorringHandler.66 = Les donn\u00E9es d'application de l'utilisateur ''{0}'' sont sauvegard\u00E9es afin d'\u00EAtre transfer\u00E9es ult\u00E9rieurement sur un autre appareil. DeviceMirrorringHandler.68 = Continuer? DeviceMirrorringHandler.7 = Une erreur est survenue lors du chargement des attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.72 = Sauvegarde \u00E9tablie. DeviceMirrorringHandler.73 = L\u2019application n\u2019est activ\u00E9e pour aucun utilisateur. DeviceMirrorringHandler.8 = Cr\u00E9er un Push-Token personnel... DeviceMirrorringHandler.9 = Actuellement, pas toutes les applications sont install\u00E9es. Done = Fini FileUtils_0 = Fichier {0} pas pr\u00E9sent dans classpath!? FormatMailAddress = Format admissible: address@server.xy HTMLEncode_0 = Erreur invoquant 1.4 URLEncodeur.encoder avec r\u00E9flexion: InvalidFileName = Nom de fichier invalide: NumbersUpToSixDigitsAreAllowed = Jusqu'\u00E0 six chiffres admissibles. PhoneBookEntry_1 = Aucun nom d'entreprise Planed = Pr\u00E9vu PropertiesFileConverter.0 = Pas un r\u00E9pertoire: RemoteTransactionHandler.0 = Erreur interne: la m\u00E9thode ne doit \u00EAtre appel\u00E9e que sur le thread AM! RemoteTransactionHandler.1 = Actualiser donn\u00E9es de base. RemoteTransactionHandler.2 = Flag d'actualisation mis \u00E0 jour. RemoteTransactionHandler.3 = Donn\u00E9es de base t\u00E9l\u00E9charg\u00E9es. RemoteTransactionHandler.4 = Donn\u00E9es obsol\u00E8tes effac\u00E9es. RemoteTransactionHandler.5 = Fichiers du logiciel r\u00E9sident sont effac\u00E9s. RemoteTransactionHandler.6 = Fichier du logiciel r\u00E9sident est effac\u00E9. RemoteTransactionHandler.7 = Aucun fichier du logiciel r\u00E9sident re\u00E7u par le ser ReservedForFutureUse = Pas appliqu\u00E9, r\u00E9serv\u00E9 pour application \u00E0 l'avenir. SAPError = SAP erreur SAPErrorMessage = SAP erreur: Service = Service StartEndLessThan3MinutesApart = de/\u00E0 diff\u00E9re moins de 3 minutes. TimeIsOverlapping = Temps chevauchent par {0} - {1}.\n WorkTimeRecordingWasStartedYesterday. = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e hier. WouldYouLikeToCall = T\u00E9l\u00E9phoner {0} ? WrongFormArgument = Param\u00E8tre de remise de la forme incorrect. WrongFormat = Format incorrect ({0}) WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). abort = Annuler aborted = annul\u00E9\u2026 all = Tous billing = Facturation camera = Camera cancelled = Annul\u00E9 characters = Caract\u00E9res checkList = Check-list commNo = No com. communicationError = Erreur de communication communicationErrorWithColon = Erreur de communication: confirmToDeleteMaterial = Effacer l'article de la base de donn\u00E9es? costumerReport = Rapport clients deliveryListDownloaded = Articles t\u00E9l\u00E9charg\u00E9es. designation = D\u00E9signation destinationAddressIsInvalid = L'adresse cible est invalide, ZERO ou trop long. doYouWantToStopTimesheet = Arr\u00E9ter le temps de travail personnel? documents = Documents duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur error = Erreur errorWithParam = Erreur {0} exit = Terminer failure = D\u00E9faillance firstName = Pr\u00E9nom foundErrorsInTimesheetsOnDate = Des Timesheet (fiches horaires) fautives ont \u00E9t\u00E9 trouv\u00E8res pour les dates suivantes: {0}. Veuillez s'il vous pla\u00EEt les corriger et envoyer. from = de gallery = Galerie image = Image images = Images information = Information insertComplete = Ajout\u00E9es des donn\u00E9es. insertingMasterData = Ins\u00E9rer des donn\u00E9es de base... installationError = Erreur d'installation invalidNotificationInterval = Valeur invalide trouv\u00E9 pour l'intervalle d'avertissement. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect invalidVolume = Valeur invalide trouv\u00E9 pour l'intensit\u00E9 du son. jobState = \u00C9tat de commande loadCALENDARObjectWithDatetime = Charger un objet calendrier avec date ( location = Installation material = Mat\u00E9riel materialList = Liste de mat\u00E9riel materialName = Nom d'article materialNumber = No. d'article measurement = Mesure de la force messages = Messages name = Nom newJob = Nouvel ordre! newJobReceived = Nouveau travail re\u00E7u. newMessage = Nouveau Message!\n newVehicleInventoryReceived = Nouveau Entrep\u00F4t de v\u00E8hicules re\u00E7u. newShortMessageReceived = Nouveau message court re\u00E7u. noDocumentsRecorded = Aucun documents disponible. noImagesRecorded = Aucun images disponible. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMeasurementsRecorded = Aucune meseure n'est disponible noMessagesRecorded = Aucun message enregistr\u00E9 noPartsFound = Pas de pi\u00E8ce de rechange trouv\u00E8res pour ces crit\u00E8r noRecipientApplication = Impossible de trouver l'application cherch\u00E9e. noReportRecorded = Aucun rapport enregistr\u00E9 noTimesRecorded = Aucune heure enregistr\u00E9e noUserActive = Aucun utilisateur actif n'est trouv\u00E9! Pas encore appel\u00E9 le REGISTER_USER / donn\u00E9es d\u00E9fectueuses dans ZKDMOBMA? noValueForNotificationIntervalFound = Aucune valeur trouv\u00E9 pour l'intervalle d'avertisse noVolumeSettingFound = Aucune valeur trouv\u00E9 pour l'intensit\u00E9 du son. number = Quantit\u00E9 onlyNumberAndSpacesAllowedForTelephoneNumber = Uniquement chiffres et espaces admissibles pour les num\u00E9ros de t\u00E9l. orderDate = Date de commande orderNo = No de commande orderWillBeForwardedTo = La commande {0} {1} sera transmise \u00E0 {2}. overHoursInOneDay = "{0}" est > 24h. overlapping = {0} chevauchent {1} partFound = Article trouv\u00E9. pleaseSelect = Choisir... pleaseSelectValue = S\u00E9lectionnez une valeur! pleaseProvideValue = Veuillez fournir une valeur! pointerReferenceToInvalidMemoryLocation = Un pointeur montre une zone de m\u00E9moire invalide. Un ou plusieurs pointeurs lpszDestAddress, lpszAppName, lpszCalledParty, ou lpszComment ont \u00E9t\u00E9 sp\u00E9cifi\u00E9s, mais sont invalides. receive = Re\u00E7u recipientApplicationIsActive = Impossible de trouver l'application cherch\u00E9e, mais la file de demande est bond\u00E9e ou capacit\u00E9 du m\u00E9moire insuffisante. replacement = Remplacement reportCannotContainTimesMoreThanOneDay = Le rapport ne peut pas contenir des temps de plusieurs jours. Des donn\u00E9es sont d\u00E9j\u00E0 existantes du {0}. reports = Rapports reportsFrom = Rapports de reset = Rappel saveCALENDARObjectWithDatetime = M\u00E9moriser un objet calendrier avec date ( search = Recherche select = S\u00E9lectionner... shortNews = Flash d'informations signature = Signature subject = Concerne timeStopped = Le temps est arr\u00E9t\u00E9 times = Temps timesFrom = Temps de timesheetCannotBeStartet = Impossible de d\u00E9marrer la saisie de temps. Le Timesheet a \u00E9t\u00E9 d\u00E9j\u00E0 envoy\u00E9. to = jusqu'\u00E0 total = Total typeOfJob = Type de travail updatingDeliveryList = Mettre \u00E0 jour la liste des articles userIsNotRegistred = Utilisateur n'enregistre pas. userLocked = Utilisateur ferm\u00E9. validationError = Erreur de validation.\nS.v.p. entrez toutes les donn\u00E9es. valueMustNotBeLongerThen = Longueur du texte pas plus que warning = Avertissement! workTimeCapturingStartet = La saisie des heures de travail d\u00E9marr\u00E9. workTimeCapturingStartetBeforeYesterday = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e il y a plusieurs jours. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect.     common/i18n/ch/mfiles/kaba/kolibri/common/messages_it.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface ArtNr = No d'art. BackupHandler_11 = Prochaine sauvegarde des donn\u00E9es pr\u00E9vue pour le {0} BackupHandler_13 = Sauvegarde quotidienne BackupHandler_15 = La sauvegarde a \u00E9chou\u00E9: {0} BackupHandler_19 = La derni\u00E8re ex\u00E9cution de la sauvegarde (automatique) date de plus de 24 heures. BackupHandler_21 = Il n\u2019y a pas encore de sauvegarde. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_23 = La derni\u00E8re sauvegarde r\u00E9ussie remonte \u00E0 plus de 2 jours. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_5 = L\u2019application est red\u00E9marr\u00E9e pour activer la sauvegarde r\u00E9guli\u00E8re des donn\u00E9es de l\u2019application. BackupHandler_6 = Red\u00E9marrage de l\u2018application Containersize = Dimensions d'emballage DeviceMirrorringHandler.0 = Le point de restaurantion cod\u00E9 doit commencer par 'SNAPSHOT~' et comprendre pr\u00E9cis\u00E9ment 5 segments s\u00E9par\u00E9s par '~'! DeviceMirrorringHandler.1 = Activer l'appareil... DeviceMirrorringHandler.10 = Impossible de cr\u00E9er et demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.11 = L'utilisateur ''{0}'' est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{1}'' ! D\u00E9marrez une migration de l'appareil sur l'autre appareil. DeviceMirrorringHandler.13 = Impossible de r\u00E9tablir le point de restauration de la migration de donn\u00E9es \u00E0 partir d'un autre appareil! DeviceMirrorringHandler.14 = Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment partag\u00E9. DeviceMirrorringHandler.15 = Les donn\u00E9es d\u2019application locales sont remplac\u00E9es par les donn\u00E9es de l\u2019utilisateur reprenant. DeviceMirrorringHandler.16 = Continuer? DeviceMirrorringHandler.17 = Attribuer le Push-Token personnel... DeviceMirrorringHandler.18 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.19 = Quelques applications n'ont pas la version n\u00E9cessaire. DeviceMirrorringHandler.2 = Synchronisation des Push-Token... DeviceMirrorringHandler.20 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.23 = Une erreur est survenue en acc\u00E9dant les attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.24 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.26 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.27 = Impossible de cr\u00E9er et attribuer le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.28 = Attributs Token de lecture... DeviceMirrorringHandler.29 = Cause: DeviceMirrorringHandler.3 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour recevoir les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.30 = Impossible de r\u00E9tablir la sauvegarde pour la reprise de donn\u00E9es de l\u2019autre appareil! DeviceMirrorringHandler.31 = Cr\u00E9ation d'un Push-Token personnel... DeviceMirrorringHandler.34 = Impossible de pr\u00E9parer le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019autre appareil! DeviceMirrorringHandler.35 = L'utilisateur est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{0}''! D\u00E9marrez d'abord le changement d'appareil sur un autre appareil. DeviceMirrorringHandler.37 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.39 = Les donn\u00E9es d\u2019application sont remplac\u00E9es par les donn\u00E9es de l\u2019appareil source en raison d\u2019un changement d\u2019\u00E9quipement. Appareil source: ''{0}'', temps de sauvegarde: {1} DeviceMirrorringHandler.4 = Activer l'application... DeviceMirrorringHandler.41 = Attribuer les Push-Token personnels... DeviceMirrorringHandler.42 = Le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019appareil source a \u00E9chou\u00E9. DeviceMirrorringHandler.44 = Les conditions pr\u00E9alables n'ont pas pu \u00EAtre v\u00E9rifi\u00E9es. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.46 = Pas toutes les applications n\u00E9cessaires sont install\u00E9es. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.47 = Certaines des applications ne se trouvent pas dans la version requise. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.48 = Le Push-Token personnel n'a pas pu \u00EAtre lib\u00E9r\u00E9. DeviceMirrorringHandler.5 = Attributs Token de lecture... DeviceMirrorringHandler.50 = R\u00E9tablir l\u2019\u00E9tat de l\u2019appareil source DeviceMirrorringHandler.51 = L'application n'a pas \u00E9t\u00E9 activ\u00E9e pour l'utilisateur ''{0}'' enregistr\u00E9, mais pour l'utilisateur ''{1}''. DeviceMirrorringHandler.52 = La sauvegarde des donn\u00E9es d\u2019application a \u00E9chou\u00E9. DeviceMirrorringHandler.53 = Lib\u00E9rer l'appareil pour l'utilisateur ''{1}'' et continuer avec l'activation de l'appareil pour l'utilisateur ''{0}'' ? DeviceMirrorringHandler.55 = Lib\u00E9rer l'apparail... DeviceMirrorringHandler.56 = Synchronisation du Push-Token... DeviceMirrorringHandler.58 = Lib\u00E9rer l'application... DeviceMirrorringHandler.59 = L'utilisateur ''{0}'' enregistr\u00E9 n'a pas de Push-Token personnel attribu\u00E9! DeviceMirrorringHandler.6 = Cause: DeviceMirrorringHandler.60 = Plusieurs Push-Token personnels sont d\u00E9j\u00E0 attribu\u00E9s! Veuillez contacter le support informatique. DeviceMirrorringHandler.62 = Cr\u00E9ez un point de restauration de la dur\u00E9e d\u2019ex\u00E9cution. DeviceMirrorringHandler.63 = Lib\u00E9rer Push-Token ... DeviceMirrorringHandler.66 = Les donn\u00E9es d'application de l'utilisateur ''{0}'' sont sauvegard\u00E9es afin d'\u00EAtre transfer\u00E9es ult\u00E9rieurement sur un autre appareil. DeviceMirrorringHandler.68 = Continuer? DeviceMirrorringHandler.7 = Une erreur est survenue lors du chargement des attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.72 = Sauvegarde \u00E9tablie. DeviceMirrorringHandler.73 = L\u2019application n\u2019est activ\u00E9e pour aucun utilisateur. DeviceMirrorringHandler.8 = Cr\u00E9er un Push-Token personnel... DeviceMirrorringHandler.9 = Actuellement, pas toutes les applications sont install\u00E9es. Done = Fini FileUtils_0 = Fichier {0} pas pr\u00E9sent dans classpath!? FormatMailAddress = Format admissible: address@server.xy HTMLEncode_0 = Erreur invoquant 1.4 URLEncodeur.encoder avec r\u00E9flexion: InvalidFileName = Nom de fichier invalide: NumbersUpToSixDigitsAreAllowed = Jusqu'\u00E0 six chiffres admissibles. PhoneBookEntry_1 = Aucun nom d'entreprise Planed = Pr\u00E9vu PropertiesFileConverter.0 = Pas un r\u00E9pertoire: RemoteTransactionHandler.0 = Erreur interne: la m\u00E9thode ne doit \u00EAtre appel\u00E9e que sur le thread AM! RemoteTransactionHandler.1 = Actualiser donn\u00E9es de base. RemoteTransactionHandler.2 = Flag d'actualisation mis \u00E0 jour. RemoteTransactionHandler.3 = Donn\u00E9es de base t\u00E9l\u00E9charg\u00E9es. RemoteTransactionHandler.4 = Donn\u00E9es obsol\u00E8tes effac\u00E9es. RemoteTransactionHandler.5 = Fichiers du logiciel r\u00E9sident sont effac\u00E9s. RemoteTransactionHandler.6 = Fichier du logiciel r\u00E9sident est effac\u00E9. RemoteTransactionHandler.7 = Aucun fichier du logiciel r\u00E9sident re\u00E7u par le ser ReservedForFutureUse = Pas appliqu\u00E9, r\u00E9serv\u00E9 pour application \u00E0 l'avenir. SAPError = SAP erreur SAPErrorMessage = SAP erreur: Service = Service StartEndLessThan3MinutesApart = de/\u00E0 diff\u00E9re moins de 3 minutes. TimeIsOverlapping = Temps chevauchent par {0} - {1}.\n WorkTimeRecordingWasStartedYesterday. = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e hier. WouldYouLikeToCall = T\u00E9l\u00E9phoner {0} ? WrongFormArgument = Param\u00E8tre de remise de la forme incorrect. WrongFormat = Format incorrect ({0}) WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). abort = Annuler aborted = annul\u00E9\u2026 all = Tous billing = Facturation camera = Camera cancelled = Annul\u00E9 characters = Caract\u00E9res checkList = Check-list commNo = No com. communicationError = Erreur de communication communicationErrorWithColon = Erreur de communication: confirmToDeleteMaterial = Effacer l'article de la base de donn\u00E9es? costumerReport = Rapport clients deliveryListDownloaded = Aggiorna t\u00E9l\u00E9charg\u00E9es. designation = D\u00E9signation destinationAddressIsInvalid = L'adresse cible est invalide, ZERO ou trop long. doYouWantToStopTimesheet = Arr\u00E9ter le temps de travail personnel? documents = Documents duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur error = Erreur errorWithParam = Erreur {0} exit = Terminer failure = D\u00E9faillance firstName = Pr\u00E9nom foundErrorsInTimesheetsOnDate = Des Timesheet (fiches horaires) fautives ont \u00E9t\u00E9 trouv\u00E8res pour les dates suivantes: {0}. Veuillez s'il vous pla\u00EEt les corriger et envoyer. from = de gallery = Galerie image = Image images = Images information = Information insertComplete = Ajout\u00E9es des donn\u00E9es. insertingMasterData = Ins\u00E9rer des donn\u00E9es de base... installationError = Erreur d'installation invalidNotificationInterval = Valeur invalide trouv\u00E9 pour l'intervalle d'avertissement. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect invalidVolume = Valeur invalide trouv\u00E9 pour l'intensit\u00E9 du son. jobState = \u00C9tat de commande loadCALENDARObjectWithDatetime = Charger un objet calendrier avec date ( location = Installation material = Mat\u00E9riel materialList = Liste de mat\u00E9riel materialName = Nom d'article materialNumber = No. d'article measurement = Mesure de la force messages = Messages name = Nom newJob = Nouvel ordre! newJobReceived = Nouveau travail re\u00E7u. newMessage = Nouveau Message!\n newVehicleInventoryReceived = Nouveau Magazzino veicoli re\u00E7u. newShortMessageReceived = Nouveau message court re\u00E7u. noDocumentsRecorded = Aucun documents disponible. noImagesRecorded = Aucun images disponible. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMeasurementsRecorded = Aucune meseure n'est disponible noMessagesRecorded = Aucun message enregistr\u00E9 noPartsFound = Pas de pi\u00E8ce de rechange trouv\u00E8res pour ces crit\u00E8r noRecipientApplication = Impossible de trouver l'application cherch\u00E9e. noReportRecorded = Aucun rapport enregistr\u00E9 noTimesRecorded = Aucune heure enregistr\u00E9e noUserActive = Aucun utilisateur actif n'est trouv\u00E9! Pas encore appel\u00E9 le REGISTER_USER / donn\u00E9es d\u00E9fectueuses dans ZKDMOBMA? noValueForNotificationIntervalFound = Aucune valeur trouv\u00E9 pour l'intervalle d'avertisse noVolumeSettingFound = Aucune valeur trouv\u00E9 pour l'intensit\u00E9 du son. number = Quantit\u00E9 onlyNumberAndSpacesAllowedForTelephoneNumber = Uniquement chiffres et espaces admissibles pour les num\u00E9ros de t\u00E9l. orderDate = Date de commande orderNo = No de commande orderWillBeForwardedTo = La commande {0} {1} sera transmise \u00E0 {2}. overHoursInOneDay = "{0}" est > 24h. overlapping = {0} chevauchent {1} partFound = Article trouv\u00E9. pleaseSelect = Choisir... pleaseSelectValue = S\u00E9lectionnez une valeur! pleaseProvideValue = Veuillez fournir une valeur! pointerReferenceToInvalidMemoryLocation = Un pointeur montre une zone de m\u00E9moire invalide. Un ou plusieurs pointeurs lpszDestAddress, lpszAppName, lpszCalledParty, ou lpszComment ont \u00E9t\u00E9 sp\u00E9cifi\u00E9s, mais sont invalides. receive = Re\u00E7u recipientApplicationIsActive = Impossible de trouver l'application cherch\u00E9e, mais la file de demande est bond\u00E9e ou capacit\u00E9 du m\u00E9moire insuffisante. replacement = Remplacement reportCannotContainTimesMoreThanOneDay = Le rapport ne peut pas contenir des temps de plusieurs jours. Des donn\u00E9es sont d\u00E9j\u00E0 existantes du {0}. reports = Rapports reportsFrom = Rapports de reset = Rappel saveCALENDARObjectWithDatetime = M\u00E9moriser un objet calendrier avec date ( search = Recherche select = S\u00E9lectionner... shortNews = Flash d'informations signature = Signature subject = Concerne timeStopped = Le temps est arr\u00E9t\u00E9 times = Temps timesFrom = Temps de timesheetCannotBeStartet = Impossible de d\u00E9marrer la saisie de temps. Le Timesheet a \u00E9t\u00E9 d\u00E9j\u00E0 envoy\u00E9. to = jusqu'\u00E0 total = Total typeOfJob = Type de travail updatingDeliveryList = Aggiorna l'elenco degli articoli userIsNotRegistred = Utilisateur n'enregistre pas. userLocked = Utilisateur ferm\u00E9. validationError = Erreur de validation.\nS.v.p. entrez toutes les donn\u00E9es. valueMustNotBeLongerThen = Longueur du texte pas plus que warning = Avertissement! workTimeCapturingStartet = La saisie des heures de travail d\u00E9marr\u00E9. workTimeCapturingStartetBeforeYesterday = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e il y a plusieurs jours. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect.     common/javatest/ch/mfiles/kaba/kolibri/common/businessobjects/types/JobStatusTest.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; import org.junit.Test; import junit.framework.TestCase; public class JobStatusTest extends TestCase { @Test public void testReportTimeStartedUsesLocalInProgressAndBackend5a() { JobStatus localStatus = new JobStatus("05"); //$NON-NLS-1$ assertTrue(localStatus.isInProgress()); assertEquals("05", JobStatus.IN_PROGRESS); //$NON-NLS-1$ assertEquals("5a", JobStatus.SAP_InProgress); //$NON-NLS-1$ } }     common/javatest/ch/mfiles/kaba/kolibri/common/forms/adapters/SpinnerTextStyleTest.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; import junit.framework.TestCase; public class SpinnerTextStyleTest extends TestCase { public void testNoneDoesNotApplyCustomClosedViewStyle() { assertFalse(SpinnerTextStyle.none().isCustom()); } public void testCustomStyleKeepsValuesForClosedSpinnerView() { SpinnerTextStyle style = SpinnerTextStyle.custom(7, null, 2, 20); assertTrue(style.isCustom()); assertEquals(7, style.getTextColor()); assertNull(style.getTypeface()); assertEquals(2, style.getTextSizeUnit()); assertEquals(20, style.getTextSize()); } }     common/javatest/ch/mfiles/kaba/kolibri/common/util/ReportMaterialInsertPolicyTest.java:   package ch.mfiles.kaba.kolibri.common.util; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import junit.framework.TestCase; public class ReportMaterialInsertPolicyTest extends TestCase { public ReportMaterialInsertPolicyTest(String name) { super(name); } @Test public void testNextIdxDoesNotReuseExistingIdxZero() { ReportMaterial maxReportMaterial = new ReportMaterial(); maxReportMaterial.setIdx(0); assertEquals(1, DatabaseUtil.getNextReportMaterialIdx(0, maxReportMaterial)); } @Test public void testNextIdxKeepsNewIdxWhenNoMaterialExists() { assertEquals(0, DatabaseUtil.getNextReportMaterialIdx(0, null)); } @Test public void testNextIdxKeepsRequestedIdxAboveCurrentMax() { ReportMaterial maxReportMaterial = new ReportMaterial(); maxReportMaterial.setIdx(1); assertEquals(3, DatabaseUtil.getNextReportMaterialIdx(3, maxReportMaterial)); } }     common/project.properties:   # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23     common/sonar.xml:       common/src/ch/mfiles/kaba/kolibri/common/businessobjects/AbsenceNotification.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAABSENCE */ public class AbsenceNotification { private String guId = ""; private Date absenceDate; private int personalNumber = 0; private String absenceType; private Date dateFrom; private Date dateTo; private Date timeFrom; private Date timeTo; private String text; public AbsenceNotification() { // constructor } public AbsenceNotification(RecordSet rs) { this.setGuid(rs.getString(DbConstants.AbsenceNotification.GUID)); this.setAbsenceDate(rs.getDate(DbConstants.AbsenceNotification.DATE)); this.setPersonalNumber(rs.getInt(DbConstants.AbsenceNotification.PERSONAL_NUMBER)); this.setAbsenceType(rs.getString(DbConstants.AbsenceNotification.ABSENCE_TYPE)); this.setDateFrom(rs.getDate(DbConstants.AbsenceNotification.DATE_FROM)); this.setDateTo(rs.getDate(DbConstants.AbsenceNotification.DATE_TO)); this.setTimeFrom(rs.getDate(DbConstants.AbsenceNotification.TIME_FROM)); this.setTimeTo(rs.getDate(DbConstants.AbsenceNotification.TIME_TO)); this.setText(rs.getString(DbConstants.AbsenceNotification.TEXT)); } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public Date getAbsenceDate() { return absenceDate; } public void setAbsenceDate(Date absenceDate) { this.absenceDate = absenceDate; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getAbsenceType() { return absenceType; } public void setAbsenceType(String absenceType) { this.absenceType = absenceType; } public Date getDateFrom() { return dateFrom; } public void setDateFrom(Date dateFrom) { this.dateFrom = dateFrom; } public Date getDateTo() { return dateTo; } public void setDateTo(Date dateTo) { this.dateTo = dateTo; } public Date getTimeFrom() { return timeFrom; } public void setTimeFrom(Date timeFrom) { this.timeFrom = timeFrom; } public Date getTimeTo() { return timeTo; } public void setTimeTo(Date timeTo) { this.timeTo = timeTo; } public String getText() { return text; } public void setText(String text) { this.text = text; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/AbsenceType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBABSC */ public class AbsenceType { private String absenceType = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ AbsenceType() { } public AbsenceType(RecordSet rs) { this.setAbsenceType((rs.getString(DbConstants.AbsenceType.ABWGRND))); this.setLanguage(rs.getString(DbConstants.AbsenceType.LANGUAGE)); this.setText(rs.getString(DbConstants.AbsenceType.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.AbsenceType.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getAbsenceType() { return this.absenceType; } public void setAbsenceType(String absenceType) { this.absenceType = absenceType; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Address.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDMOBADR * */ public class Address { public static final Log log = LogFactory.getLog(Job.class); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String type = ""; //$NON-NLS-1$ private String partnerNummer = ""; //$NON-NLS-1$ private String commissionNumber = ""; //$NON-NLS-1$ private String customerNumber = ""; //$NON-NLS-1$ private String title = ""; //$NON-NLS-1$ private String name1 = ""; //$NON-NLS-1$ private String name2 = ""; //$NON-NLS-1$ private String name3 = ""; //$NON-NLS-1$ private String location = ""; //$NON-NLS-1$ private String street = ""; //$NON-NLS-1$ private String city = ""; //$NON-NLS-1$ private String postalCode = ""; //$NON-NLS-1$ private String telNumber1 = ""; //$NON-NLS-1$ private String telNumber2 = ""; //$NON-NLS-1$ private String faxNumber = ""; //$NON-NLS-1$ private String email = ""; //$NON-NLS-1$ private String changeFlag = ""; //$NON-NLS-1$ private String dirtyFlag = ""; //$NON-NLS-1$ public Address() { } public Address(RecordSet rs) { this.setType(rs.getString(DbConstants.Address.TYPE)); this.setJobType(rs.getString(DbConstants.Address.JOB_TYPE)); this.setCity(rs.getString(DbConstants.Address.CITY)); this.setDirtyFlag(rs.getString(DbConstants.Address.DIRTY_FLAG)); this.setEmail(rs.getString(DbConstants.Address.EMAIL)); this.setFaxNumber(rs.getString(DbConstants.Address.FAX)); this.setCustomerNumber(rs.getString(DbConstants.Address.CUSTOMER_NUMBER)); this.setJobNumber(rs.getString(DbConstants.Address.JOB_NUMBER)); this.setName1(rs.getString(DbConstants.Address.NAME1)); this.setName2(rs.getString(DbConstants.Address.NAME2)); this.setName3(rs.getString(DbConstants.Address.NAME3)); this.setLocation(rs.getString(DbConstants.Address.LOCATION)); this.setPartnerNummer(rs.getString(DbConstants.Address.PARTNER_NUMBER)); this.setPostalCode(rs.getString(DbConstants.Address.PASTAL_CODE)); this.setStreet(rs.getString(DbConstants.Address.STREET)); this.setTelNumber1(rs.getString(DbConstants.Address.PHONE_1)); this.setTelNumber2(rs.getString(DbConstants.Address.PHONE_2)); this.setTitle(rs.getString(DbConstants.Address.TITLE)); this.setChangeFlag(rs.getString(DbConstants.Address.CHANGE_FLAG)); this.setCommissionNumber(rs.getString(DbConstants.Address.COMMISSION_NUMBER)); } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getDirtyFlag() { return this.dirtyFlag; } public void setDirtyFlag(String dirtyflg) { this.dirtyFlag = dirtyflg; } public boolean isDirtyFlag() { return "X".equalsIgnoreCase(this.getDirtyFlag()); //$NON-NLS-1$ } public void setDIRTYFLG(boolean dirtyflg) { if (dirtyflg) { this.setDirtyFlag("X"); //$NON-NLS-1$ } else { this.setDirtyFlag(""); //$NON-NLS-1$ } } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getFaxNumber() { return this.faxNumber; } public void setFaxNumber(String faxNumber) { this.faxNumber = faxNumber; } public String getCustomerNumber() { return this.customerNumber; } public void setCustomerNumber(String kunnr) { this.customerNumber = kunnr; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getName1() { return this.name1; } public void setName1(String name1) { this.name1 = name1; } public String getName2() { return this.name2; } public void setName2(String name2) { this.name2 = name2; } public String getName3() { return this.name3; } public void setName3(String name3) { this.name3 = name3; } public String getLocation() { return this.location; } public void setLocation(String name4) { this.location = name4; } public String getPartnerNummer() { return this.partnerNummer; } public void setPartnerNummer(String parnr) { this.partnerNummer = parnr; } public String getPostalCode() { return this.postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public String getTelNumber1() { return this.telNumber1; } public void setTelNumber1(String telNumber1) { this.telNumber1 = telNumber1; } public String getTelNumber2() { return this.telNumber2; } public void setTelNumber2(String telNumber2) { this.telNumber2 = telNumber2; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getChangeFlag() { return this.changeFlag; } public void setChangeFlag(String upd) { this.changeFlag = upd; } public boolean isChangeFlag() { return "X".equalsIgnoreCase(this.getChangeFlag()); //$NON-NLS-1$ } public void setChangeFlag(boolean udp) { if (udp) { this.setChangeFlag("X"); //$NON-NLS-1$ } else { this.setChangeFlag(""); //$NON-NLS-1$ } } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isPrivate() { return "1".equalsIgnoreCase(this.getType()); //$NON-NLS-1$ } public void setPrivate(boolean isPrivate) { if (isPrivate) { this.setType("1"); //$NON-NLS-1$ } else { this.setType("2"); //$NON-NLS-1$ } } public boolean isInitial() { return this.partnerNummer == null; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Address.ADDRESS, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Address.ADDRESS, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/BaseEntity.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBException; import ch.mfiles.kolibri.db.DBSColumn; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; public abstract class BaseEntity { public static final Log log = LogFactory.getLog(BaseEntity.class); BaseEntity() { } /** * Writes a backup of all records of the table with tableName. Special characters in String fields are escaped with quote() function of sqlite. * @param tableName Name of the table to backup * @param app Current application object * @param folder Folder where to store the backup. * @return Number of backuped records. */ protected static int backup(String tableName, Application app, File folder) { int ret = 0; RecordSet rs = app.getDBSession().getRecordSet(); List columns = app.getApplicationDescriptor().getDbschema().getTable(tableName).getColumns(); String attrbuteList = ""; //$NON-NLS-1$ String attrbuteLine = ""; //$NON-NLS-1$ Iterator itr = columns.iterator(); while (itr.hasNext()) { DBSColumn col = (DBSColumn) itr.next(); attrbuteLine = attrbuteLine.concat(col.getName()).concat(","); //$NON-NLS-1$ if (col.getType() == DBSColumn.TYPE_STRING) attrbuteList = attrbuteList.concat("quote(" + col.getName() + ") AS " + col.getName() + ","); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else attrbuteList = attrbuteList.concat(col.getName()).concat(","); //$NON-NLS-1$ } // remove the last comma attrbuteLine = attrbuteLine.substring(0, attrbuteLine.length() - 1); attrbuteList = attrbuteList.substring(0, attrbuteList.length() - 1); String sql = "SELECT " + attrbuteList + " FROM " + tableName; //$NON-NLS-1$ //$NON-NLS-2$ FileWriter fw = null; try { rs.setQuery(sql); ret = rs.getCount(); File file = new File(folder, "\\" + tableName); //$NON-NLS-1$ if (file.exists() && file.delete()) { // file deleted. } fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write(attrbuteLine); out.newLine(); String line = ""; //$NON-NLS-1$ while (rs.moveNext()) { line = ""; //$NON-NLS-1$ itr = columns.iterator(); while (itr.hasNext()) { DBSColumn col = (DBSColumn) itr.next(); line = line.concat(rs.getString(col.getName())).concat(","); //$NON-NLS-1$ } // remove line separators line = line.replace(System.getProperty("line.separator").charAt(0), ' '); //$NON-NLS-1$ if (System.getProperty("line.separator").length() > 1) //$NON-NLS-1$ line = line.replace(System.getProperty("line.separator").charAt(1), ' '); //$NON-NLS-1$ // remove the last comma out.write(line.substring(0, line.length() - 1)); out.newLine(); } out.close(); fw.close(); } catch (IOException e) { log.error("Error while writing " + tableName + " records to " + folder + "\\" + tableName); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(e); } catch (DBException e) { log.error("Error while selecting " + tableName + " records for backup"); //$NON-NLS-1$ //$NON-NLS-2$ log.error(e); } finally { rs.dispose(); try { if (fw != null) fw.close(); } catch (IOException e) { log.error(e); } } return ret; } /** * Restore function for table backup created with backup(). * Reads the records from the file (filename = tablename) from the folder * folder an writes them into the database. In case of an SQL * error, the record will be ignored (INSERT OR IGNORE INTO * )without any error message. * * @param tableName * @param db * @param folder */ protected static void restore(String tableName, DBSession db, File folder) { if (!folder.exists()) { log.info("Error while reading " + tableName + ": folder " + folder.getName() + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ return; } File file = new File(folder, "\\" + tableName); //$NON-NLS-1$ if (!file.exists()) { log.info("Error while reading " + tableName + ": backup file '" + file.getAbsolutePath() + "' not found"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return; } readFileAndExecuteSql(tableName, db, file); } private static void readFileAndExecuteSql(String tableName, DBSession db, File file) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String columnNames = br.readLine(); String columns[] = columnNames.split(","); List columnNoFoundInDb = new ArrayList(); for (int j = 0; j < columns.length; j++) { // adds all column name from file columnNoFoundInDb.add(columns[j]); } List columnToRemoveList = new ArrayList(); List dbColumns = db.getDBSchema().getTable(tableName).getColumns(); List columnToAddList = new ArrayList(); // default as column from db, will remove later. columnToAddList.addAll(dbColumns); for (int i = 0; i < columns.length; i++) { if (isColumnExistInDb(dbColumns, columns[i])) { // found the same column name between file and DB, so remove columnNoFoundInDb.remove(columns[i]); } for (DBSColumn dbsColumn : dbColumns) { if (dbsColumn.getName().equalsIgnoreCase(columns[i])) { // found the same column name between file and DB, so remove columnToAddList.remove(dbsColumn); } } } for (String column : columnNoFoundInDb) { log.info("column to be removed " + column); for (int i = 0; i < columns.length; i++) { if (column.equalsIgnoreCase(columns[i])) { // found column index to remove columnToRemoveList.add(i); } } } StringBuffer columnBuffer = new StringBuffer(); for (int i = 0; i < columns.length; i++) { if (!columnToRemoveList.contains(i)) { if (i > 0) { columnBuffer.append(","); } columnBuffer.append(columns[i]); } } String sql = "INSERT OR IGNORE INTO " + tableName + " (" + columnBuffer.toString() ; if (!columnToAddList.isEmpty()) { for (DBSColumn dbsColumn : columnToAddList) { log.info("column to be added " + dbsColumn.getName()); sql += "," + dbsColumn.getName(); } } sql += ") VALUES "; String line; while ((line = br.readLine()) != null) { log.info("line " + line); String dataLine[] = line.split(","); StringBuffer buffer = new StringBuffer(); if (columnNoFoundInDb.size() > 0) { for (int i = 0; i < dataLine.length; i++) { if (!columnToRemoveList.contains(i)) { if (i > 0) { buffer.append(","); } buffer.append(dataLine[i]); } } line = buffer.toString(); } if (!columnToAddList.isEmpty()) { for (DBSColumn dbsColumn : columnToAddList) { String defaultValue = dbsColumn.getDefaultValue() == null ? "" : dbsColumn.getDefaultValue(); if (dbsColumn.getType() == DBSColumn.TYPE_STRING) { line += ",'" + defaultValue + "'"; } else if (dbsColumn.getType() == DBSColumn.TYPE_DATE) { line += ",0"; } else { line += "," + defaultValue; } } } log.info(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ int inserted = db.executeSql(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ log.info(inserted + " Records inserted with: " + sql + "(" + line + ")"); } } catch (IOException e) { log.error("Error while reading " + tableName + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ log.error(e); } finally { if (br != null) try { br.close(); } catch (IOException e) { } } } private static boolean isColumnExistInDb(List dbColumns, String columnName) { for (int i = 0; i < dbColumns.size(); i++) { for (DBSColumn dbsColumn : dbColumns) { if (dbsColumn.getName().equalsIgnoreCase(columnName)) { return true; } } } return false; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Billing.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> VERRECHNUNG */ public class Billing { private String text = ""; //$NON-NLS-1$ private String code = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String refreshFlag = ""; //$NON-NLS-1$ Billing() { } public Billing(RecordSet rs) { this.setText(rs.getString(DbConstants.Billing.TEXT)); this.setCode(rs.getString(DbConstants.Billing.CODE)); this.setJobType(rs.getString(DbConstants.Billing.JOB_TYPE)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public JobType getJobType() { return this.jobType; } public void setJobType(JobType jobType) { this.jobType = jobType; } public void setJobType(String jobType) { this.jobType = new JobType(jobType); } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/CalendarTimeSheet.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import java.util.Iterator; import java.util.TreeSet; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.util.DateUtils; /** * In the Database -> CALENDAR * */ public class CalendarTimeSheet { private Date date = DateUtils.getInitialDate(); private int personalNumber = 0; private CalendarStatus status = new CalendarStatus(); private String dateString = ""; //$NON-NLS-1$ private Expenses expense = new Expenses(new Date(), 0); private TreeSet timeSheets = new TreeSet(); protected CalendarTimeSheet() { } public CalendarTimeSheet(Date date, int personalNumber) { this.setDate(date); this.setDateString(DateTimeUtil.tableDate(date)); this.personalNumber = personalNumber; this.expense = new Expenses(date, personalNumber); } public CalendarTimeSheet(RecordSet rs) { this.setDate(rs.getDate(DbConstants.CalendarTimeSheet.DATE)); this.setPersonalNumber(rs.getInt(DbConstants.CalendarTimeSheet.PERSONAL_NUMBER)); this.setStatus(new CalendarStatus(rs.getString(DbConstants.CalendarTimeSheet.STATUS))); this.setDateString(rs.getString(DbConstants.CalendarTimeSheet.DATE_STRING)); } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public CalendarStatus getStatus() { return this.status; } public void setStatus(String status) { this.status.set(status); } public void setStatus(CalendarStatus status) { this.status = status; } public String getDateString() { return this.dateString; } public void setDateString(String datumTxt) { this.dateString = datumTxt; } public Expenses getExpense() { return this.expense; } public void setExpense(Expenses expense) { this.expense = expense; } public TreeSet getTimeSheets() { return this.timeSheets; } public void setTimeSheets(TreeSet timeSheets) { this.timeSheets = timeSheets; } public boolean isValid() { boolean valid = true; if (!this.expense.validate().isValid()) valid = false; if (this.timeSheets.isEmpty()) valid = false; else { Date temp = DateUtils.getInitialDateTime(); Iterator itr = this.timeSheets.iterator(); while (itr.hasNext()) { TimeSheet zkdmatime = itr.next(); if (!zkdmatime.validate().isValid()) valid = false; else { if (temp.compareTo(zkdmatime.getStartTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || zkdmatime.getStartTime().equals(DateUtils.getInitialDateTime())) temp = zkdmatime.getStartTime(); else valid = false; if (temp.compareTo(zkdmatime.getStopTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || zkdmatime.getStopTime().equals(DateUtils.getInitialDateTime())) temp = zkdmatime.getStopTime(); else valid = false; } } } return valid; } public boolean isTimeCapturing() { return getStartTimeCapturing() != null; } public Date getStartTimeCapturing() { Iterator itr = this.timeSheets.iterator(); while (itr.hasNext()) { TimeSheet zkdmatime = itr.next(); if (zkdmatime.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) return zkdmatime.getStartTime(); } return null; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Checklist.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBCHKLIST */ public class Checklist { private String checklistCode = ""; private String text = ""; private String refreshFlag = ""; Checklist() { } public Checklist(RecordSet rs) { this.setChecklistCode(rs.getString(DbConstants.Checklist.CODE)); this.setText(rs.getString(DbConstants.Checklist.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Checklist.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getChecklistCode() { return this.checklistCode; } public void setChecklistCode(String checklistCode) { this.checklistCode = checklistCode; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/DeliveryList.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.DeliveryStatus; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZGDELVRY */ public class DeliveryList { public static final Log log = LogFactory.getLog(DeliveryList.class); private String guid = ""; private int personalNumber; private String orderNumber = ""; private int orderPosition; private String materialNumber = ""; private String materialName = ""; private String from = ""; private String to = ""; private String warehouse = ""; private String entryCount = ""; private String entryUnit = ""; private Date date = new Date(0); private DeliveryStatus status = new DeliveryStatus(); public DeliveryList() { } public DeliveryList(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.DeliveryList.PERSONAL_NUMBER)); this.setGuid(rs.getString(DbConstants.DeliveryList.GUID)); this.setOrderNumber(rs.getString(DbConstants.DeliveryList.ORDER_NUMBER)); this.setOrderPosition(rs.getInt(DbConstants.DeliveryList.ORDER_POSITION)); this.setMaterialNumber(rs.getString(DbConstants.DeliveryList.MATERIAL_NUMBER)); this.setMaterialName(rs.getString(DbConstants.DeliveryList.MATERIAL_NAME)); this.setFrom(rs.getString(DbConstants.DeliveryList.FROM)); this.setTo(rs.getString(DbConstants.DeliveryList.TO)); this.setWarehouse(rs.getString(DbConstants.DeliveryList.WAREHOUSE)); this.setEntryCount(rs.getString(DbConstants.DeliveryList.ENTRY_COUNT)); this.setEntryUnit(rs.getString(DbConstants.DeliveryList.ENTRY_UNIT)); this.setDate(rs.getDate(DbConstants.DeliveryList.DATE)); this.setStatus(rs.getString(DbConstants.DeliveryList.STATUS)); } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getOrderPosition() { return orderPosition; } public void setOrderPosition(int orderPosition) { this.orderPosition = orderPosition; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getMaterialNumber() { return materialNumber; } public void setMaterialNumber(String materialNumber) { this.materialNumber = materialNumber; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getEntryCount() { return entryCount; } public void setEntryCount(String entryCount) { this.entryCount = entryCount; } public String getEntryUnit() { return entryUnit; } public void setEntryUnit(String entryUnit) { this.entryUnit = entryUnit; } public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } public String getWarehouse() { return warehouse; } public void setWarehouse(String warehouse) { this.warehouse = warehouse; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public DeliveryStatus getStatus() { return status; } public void setStatus(String status) { this.status = new DeliveryStatus(status); } public void setStatus(DeliveryStatus status) { this.status = status; } /** * = Color 900 blue grey O = Color 900 red T = Color 900 deep orange G = Color 900 light green * @return */ public int getStatusColor() { int result; if (getStatus().isOPEN()) { result = LayoutUtils.DEFAULT_RED; } else if (getStatus().isPART_DELIVERED()) { result = LayoutUtils.DEFAULT_ORANGE; } else if (getStatus().isDELIVERED()) { result = LayoutUtils.DEFAULT_GREEN; } else { result = LayoutUtils.DEFAULT_MATERIAL_COLOR; } return result; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Drive.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZANTRTYP */ public class Drive { private String code = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String longText = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Drive() { } public Drive(RecordSet rs) { this.setCode(rs.getString(DbConstants.Drive.CODE)); this.setText(rs.getString(DbConstants.Drive.TEXT)); this.setLongText(rs.getString(DbConstants.Drive.LONG_TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getLongText() { return this.longText; } public void setLongText(String longText) { this.longText = longText; } public boolean isLongText() { boolean result = false; if ("X".equalsIgnoreCase(this.getLongText())) { //$NON-NLS-1$ result = true; } return result; } public void setLongText(boolean longText) { if (longText) { this.setLongText("X"); //$NON-NLS-1$ } else { this.setLongText(""); //$NON-NLS-1$ } } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Email.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDSMOBEMAIL * */ public class Email { public static final Log log = LogFactory.getLog(Job.class); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String partnerNummer = ""; //$NON-NLS-1$ private String email = ""; //$NON-NLS-1$ public Email() { } public Email(RecordSet rs) { this.setJobType(rs.getString(DbConstants.Email.JOB_TYPE)); this.setEmail(rs.getString(DbConstants.Email.TEXT)); this.setJobNumber(rs.getString(DbConstants.Email.JOB_NUMBER)); this.setPartnerNummer(rs.getString(DbConstants.Email.PARTNER_NUMBER)); } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getPartnerNummer() { return this.partnerNummer; } public void setPartnerNummer(String parnr) { this.partnerNummer = parnr; } public boolean isInitial() { return this.partnerNummer == null; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Email.EMAIL, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Email.EMAIL, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Employee.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.SpecificFunctionType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDSMOBMA */ public class Employee { private int personalNumber = 0; private String lastName = ""; //$NON-NLS-1$ private String firstName = ""; //$NON-NLS-1$ private String initial = ""; //$NON-NLS-1$ private String personalNumberDeputy = ""; //$NON-NLS-1$ private String phoneNumber = ""; //$NON-NLS-1$ private String communicationNumber = ""; //$NON-NLS-1$ private String salesOffice = ""; //$NON-NLS-1$ private String absentFrom = ""; //$NON-NLS-1$ private String absentTo = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String deviceId; private String password; private String warehouseNumber = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ private SpecificFunctionType specificFunction; Employee() { } public Employee(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.Employee.PERSONAL_NUMBER)); this.setLastName(rs.getString(DbConstants.Employee.LAST_NAME)); this.setFirstName(rs.getString(DbConstants.Employee.FIRST_NAME)); this.setInitial(rs.getString(DbConstants.Employee.INITIAL)); this.setPersonalNumberDeputy(rs.getString(DbConstants.Employee.PERSONAL_NUMBER_DEPUTY)); this.setPhoneNumber(rs.getString(DbConstants.Employee.PHONE)); this.setCommunicationNumber(rs.getString(DbConstants.Employee.COMMUNICATION_NUMBER)); this.setSalesOffice(rs.getString(DbConstants.Employee.SALES_OFFICE)); this.setAbSentFrom(rs.getString(DbConstants.Employee.ABSENT_FROM)); this.setAbsentTo(rs.getString(DbConstants.Employee.ABSENT_TO)); this.setLanguage(rs.getString(DbConstants.Employee.LANGUAGE)); this.setDeviceId(rs.getString(DbConstants.Employee.DEVICE_ID)); this.setPassword(rs.getString(DbConstants.Employee.PASSOWRD)); this.setSpecificFunction(new SpecificFunctionType(rs.getString(DbConstants.Employee.SPECIFIC_FUNCTION))); this.setWarehouseNumber(rs.getString(DbConstants.Employee.WAREHOUSE_NUMBER)); this.setRefreshFlag(rs.getString(DbConstants.Employee.REFRESH_FLAG)); } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getLastName() { return this.lastName; } public void setLastName(String nachn) { this.lastName = nachn; } public String getFirstName() { return this.firstName; } public void setFirstName(String vorna) { this.firstName = vorna; } public String getInitial() { return this.initial; } public void setInitial(String inits) { this.initial = inits; } public String getPersonalNumberDeputy() { return this.personalNumberDeputy; } public void setPersonalNumberDeputy(String stvpernr) { this.personalNumberDeputy = stvpernr; } public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String telnr) { this.phoneNumber = telnr; } public String getCommunicationNumber() { return this.communicationNumber; } public void setCommunicationNumber(String num01) { this.communicationNumber = num01; } public String getSalesOffice() { return this.salesOffice; } public void setSalesOffice(String vkbur) { this.salesOffice = vkbur; } public String getAbsentFrom() { return this.absentFrom; } public void setAbSentFrom(String abwvon) { this.absentFrom = abwvon; } public String getAbsentTo() { return this.absentTo; } public void setAbsentTo(String abwbis) { this.absentTo = abwbis; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getDeviceId() { return this.deviceId; } public void setDeviceId(String gid) { this.deviceId = gid; } public String getPassword() { return this.password; } public void setPassword(String pwd) { this.password = pwd; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } public SpecificFunctionType getSpecificFunction() { return specificFunction; } public void setSpecificFunction(SpecificFunctionType specificFunction) { this.specificFunction = specificFunction; } public String getWarehouseNumber() { return warehouseNumber; } public void setWarehouseNumber(String warehouseNumber) { this.warehouseNumber = warehouseNumber; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/AddressType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 5 */ public class AddressType extends LocalizedTextEnum { protected AddressType() { } public AddressType(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.ADDRESS_TYPE); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/InvoiceCode.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for invoice codes (Verrechnungscodes) * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 12 */ public class InvoiceCode extends LocalizedTextEnum { protected InvoiceCode() { } public InvoiceCode(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.INVOICE); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/JobPriority.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 3 */ public class JobPriority extends LocalizedTextEnum { protected JobPriority() { } public JobPriority(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.JOB_PRIORITY); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/JobStatusName.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 2 */ public class JobStatusName extends LocalizedTextEnum { protected JobStatusName() { } public JobStatusName(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.JOB_STATUS); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/JobType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 1 */ public class JobType extends LocalizedTextEnum { protected JobType() { } public JobType(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.JOB_TYPE); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/LocalizedTextEnum.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.db.LocalizedTexts; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Base class for translated strings in the database * key: localizedTexts.Code * value: localizedTexts.Text * TextType 01: JobType ok * TextType 02: JobStatusName ok * TextType 03: JobPriority ok * TextType 04: Titel ok * TextType 05: AddressType ok * TextType 06: NoSignatureReason ok * TextType 07: ReportSendType ok * TextType 08: Checklist ok * TextType 09: Month ok * TextType 10: MessageRecipient ok * TextType 11: VariousExpens ok * TextType 12: InvoiceCode ok * TextType 13: InternalWorkType ok * TextType 14: LoginMessage ok */ public abstract class LocalizedTextEnum { private static Log log = LogFactory.getLog(LocalizedTextEnum.class); /** * localizedTexts.TextType */ protected String textType; protected TreeMap map = new TreeMap(); protected LocalizedTextEnum() { } protected LocalizedTextEnum(DatabaseUtil dbutil, String textType) { this.textType = textType; LocalizedTexts[] texts = dbutil.selectLocalizedTextsList(textType); //$NON-NLS-1$ for (int i = 0; i < texts.length; i++) { LocalizedTexts localizedText = texts[i]; map.put(localizedText.getCODE(), localizedText.getTEXT()); } } public boolean containsKey(String key) { return map.containsKey(key); } public boolean containsValue(String value) { return map.containsValue(value); } public String get(String key) { String value = ""; //$NON-NLS-1$ try { value = map.get(key); if (value == null) value = ""; //$NON-NLS-1$ } catch (Exception e) { log.error(e); } return value; } /** * @return An iterator for the entrySet of the inner HashMap */ public Iterator> iterator() { return map.entrySet().iterator(); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/LoginMessage.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 14 */ public class LoginMessage extends LocalizedTextEnum { protected LoginMessage() { } public LoginMessage(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.REGISTER_USER); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/MessageRecipient.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 10 */ public class MessageRecipient extends LocalizedTextEnum { protected MessageRecipient() { } public MessageRecipient(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.MESSAGE_ID); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/Month.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 9 */ public class Month extends LocalizedTextEnum { protected Month() { } public Month(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.MONTH); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/NoSignatureReason.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 6 */ public class NoSignatureReason extends LocalizedTextEnum { protected NoSignatureReason() { } public NoSignatureReason(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.REPORT_SIGNATURE); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/ReportSendType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 7 */ public class ReportSendType extends LocalizedTextEnum { protected ReportSendType() { } public ReportSendType(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.REPORT_CUSTOMER_SUPPORT); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/Titel.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 4 */ public class Titel extends LocalizedTextEnum { protected Titel() { } public Titel(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.ADDRESS_TITLE); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/enums/VariousExpens.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 11 */ public class VariousExpens extends LocalizedTextEnum { protected VariousExpens() { } public VariousExpens(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.VAREXP); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ErrorCode.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZFCODE */ public class ErrorCode { private String errorCode; private String text; ErrorCode() { } public ErrorCode(RecordSet rs) { this.setErrorCode(rs.getString(DbConstants.ErrorCode.CODE)); this.setText(rs.getString(DbConstants.ErrorCode.TEXT)); } public String getErrorCode() { return this.errorCode; } public void setErrorCode(String fc) { this.errorCode = fc; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Expenses.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ExpenseValidation; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAEXPNS */ public class Expenses { public static final String EXPENSE_COMPENSATION = "A"; //$NON-NLS-1$ private int personalNumber = 0; private Date date = new Date(); private Date expensesDate = new Date(); private String noExpenses = ""; //$NON-NLS-1$ private String dailyExpenses = ""; //$NON-NLS-1$ private String variousExpenses = ""; //$NON-NLS-1$ private String deduction = ""; //$NON-NLS-1$ private String expensesKey = ""; //$NON-NLS-1$ private String pikettExpenses = ""; //$NON-NLS-1$ private String expensesDescription = ""; //$NON-NLS-1$ private String operatingHoursOf = ""; //$NON-NLS-1$ private String operatingHoursUpTo = ""; //$NON-NLS-1$ private String operatingHoursTotal = ""; //$NON-NLS-1$ private String deductionDescription = ""; //$NON-NLS-1$ private String compensation = ""; //$NON-NLS-1$ Expenses() { } public Expenses(Date datum, int pernr) { this.setDate(datum); this.setPersonalNumber(pernr); this.setExpensesDate(datum); } public Expenses(RecordSet rs) { this.setDeduction(rs.getString(DbConstants.Expenses.DECUCTION)); this.setDeductionDescription(rs.getString(DbConstants.Expenses.DEDUCTION_DESCRIPTION)); this.setOperatingHoursUpTo(rs.getString(DbConstants.Expenses.OPERATION_HOURS_UP_TO)); this.setOperatingHoursTotal(rs.getString(DbConstants.Expenses.OPERATION_HOURS_TOTAL)); this.setOperatingHoursOf(rs.getString(DbConstants.Expenses.OPERATING_HOURS_OF)); this.setDate(rs.getDate(DbConstants.Expenses.DATE)); this.setNoExpenses(rs.getString(DbConstants.Expenses.NO_EXPENSES)); this.setPersonalNumber(rs.getInt(DbConstants.Expenses.PERSONAL_NUMBER)); this.setPikettExpenses(rs.getString(DbConstants.Expenses.PIKETT_EXPENSES)); this.setExpensesKey(rs.getString(DbConstants.Expenses.EXPENSES_KEY)); this.setVariousExpenses(rs.getString(DbConstants.Expenses.VARIOUS_EXPENSES)); this.setExpensesDescription(rs.getString(DbConstants.Expenses.EXPENSES_DESCRIPTION)); this.setExpensesDate(rs.getDate(DbConstants.Expenses.EXPENSES_DATE)); this.setDailyExpenses(rs.getString(DbConstants.Expenses.DAILY_EXPENSES)); this.setCompensation(rs.getString(DbConstants.Expenses.COMPENSTION)); } public boolean isInitial() { return ( getDailyExpenses().isEmpty() && getNoExpenses().isEmpty() && getExpensesDescription().isEmpty() && getPikettExpenses().isEmpty() && getVariousExpenses().isEmpty() && getDeduction().isEmpty() && getDeductionDescription().isEmpty() && getOperatingHoursOf().isEmpty() && getOperatingHoursUpTo().isEmpty() && getOperatingHoursTotal().isEmpty() && isCompensation() ); } public String getDeduction() { return this.deduction; } public void setDeduction(String abzg) { this.deduction = abzg; } public String getDeductionDescription() { return this.deductionDescription; } public void setDeductionDescription(String abzgtxt) { this.deductionDescription = abzgtxt; } public String getOperatingHoursUpTo() { return this.operatingHoursUpTo; } public void setOperatingHoursUpTo(String bbis) { this.operatingHoursUpTo = bbis; } public String getOperatingHoursTotal() { return this.operatingHoursTotal; } public void setOperatingHoursTotal(String btot) { this.operatingHoursTotal = btot; } public String getOperatingHoursOf() { return this.operatingHoursOf; } public void setOperatingHoursOf(String bvon) { this.operatingHoursOf = bvon; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getVariousExpenses() { return this.variousExpenses; } public void setVariousExpenses(String divspns) { this.variousExpenses = divspns; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getPikettExpenses() { return this.pikettExpenses; } public void setPikettExpenses(String pikett) { this.pikettExpenses = pikett; } public String getExpensesKey() { return this.expensesKey; } public void setExpensesKey(String spnskey) { this.expensesKey = spnskey; } public String getExpensesDescription() { return this.expensesDescription; } public void setExpensesDescription(String spnstxt) { this.expensesDescription = spnstxt; } public Date getExpensesDate() { return this.expensesDate; } public void setExpensesDate(Date expensesDate) { this.expensesDate = expensesDate; } public String getDailyExpenses() { return this.dailyExpenses; } public void setDailyExpenses(String tgspsn) { this.dailyExpenses = tgspsn; } public String getNoExpenses() { return this.noExpenses; } public void setNoExpenses(String noExpenses) { this.noExpenses = noExpenses; } public boolean isNoExpenses() { return "X".equalsIgnoreCase(this.getNoExpenses()); //$NON-NLS-1$ } public void setNoExpenses(boolean noExpenses) { if (noExpenses) { this.setNoExpenses("X"); //$NON-NLS-1$ } else { this.setNoExpenses(""); //$NON-NLS-1$ } } public String getCompensation() { return this.compensation; } public void setCompensation(String mverg) { this.compensation = mverg; } public boolean isCompensation() { return EXPENSE_COMPENSATION.equalsIgnoreCase(this.getCompensation()); } public void setExpenseCompensation() { this.setCompensation(EXPENSE_COMPENSATION); } public void setCompensation(boolean compensation) { this.setExpenseCompensation(); } public ExpenseValidation validate() { ExpenseValidation result = new ExpenseValidation(); // "Keine Spesen" nicht gew�hlt, jedoch weder einen Tages-, noch einen // Div.-Spesenbetrag eingegeben if ("".equalsIgnoreCase(getNoExpenses()) && "".equalsIgnoreCase(getDailyExpenses())) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ result.setValid(false); result.setTgSpesenError(true); result.setDivSpesenError(true); } // Abzug ausgef�llt, jedoch keinen Betrag eingegeben if (!"".equalsIgnoreCase(getDeductionDescription()) && "".equalsIgnoreCase(getDeduction())) { //$NON-NLS-1$ //$NON-NLS-2$ result.setValid(false); result.setAbzugError(true); } if (!isNoExpenses() && getOperatingHoursTotal().length() == 0 && (getOperatingHoursOf().length() == 0 || getOperatingHoursUpTo().length() == 0)) { if (getOperatingHoursTotal().length() == 0) { result.setValid(false); result.setBTotError(true); } if (getOperatingHoursOf().length() == 0) { result.setValid(false); result.setBVonError(true); } if (getOperatingHoursUpTo().length() == 0) { result.setValid(false); result.setBBisError(true); } try { if (Float.parseFloat(getOperatingHoursOf()) >= Float.parseFloat(getOperatingHoursUpTo())) { result.setValid(false); result.setBBisError(true); } } catch (NumberFormatException e) { result.setValid(false); result.setBVonError(true); result.setBBisError(true); } } return result; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Expenses.EXPENSES, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Expenses.EXPENSES, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Form.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORM */ public class Form { public static final Log log = LogFactory.getLog(Form.class); private String id = ""; private int version = 0; private String status = ""; private Date validFrom = new Date(0); private Date validTo = new Date(0); private String name = ""; private String description = ""; public Form() { } public Form(RecordSet rs) { this.setId(rs.getString(DbConstants.Form.ID)); this.setVersion(rs.getInt(DbConstants.Form.VERSION)); this.setStatus(rs.getString(DbConstants.Form.STATUS)); this.setValidFrom(rs.getDate(DbConstants.Form.VALID_FROM)); this.setValidTo(rs.getDate(DbConstants.Form.VALID_TO)); this.setName(rs.getString(DbConstants.Form.NAME)); this.setDescription(rs.getString(DbConstants.Form.DESCRIPTION)); } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public static Log getLog() { return log; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/FormDependency.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMDEPENDENCY */ public class FormDependency { public static final Log log = LogFactory.getLog(FormDependency.class); private String formId = ""; private int formVersion = 0; private String formItemId = ""; private int dependency = 0; private String checkBoxFormItemId = ""; private String valueListId = ""; private String valueId = ""; public FormDependency() { } public FormDependency(RecordSet rs) { this.setFormId(rs.getString(DbConstants.FormDependency.FORM_ID)); this.setFormVersion(rs.getInt(DbConstants.FormDependency.FORM_VERSION)); this.setFormItemId(rs.getString(DbConstants.FormDependency.FORM_ITEM_ID)); this.setDependency(rs.getInt(DbConstants.FormDependency.DEPENDENCY)); this.setCheckBoxFormItemId(rs.getString(DbConstants.FormDependency.CHECKBOX_FORM_ITEM_ID)); this.setValueListId(rs.getString(DbConstants.FormDependency.VALUE_LIST_ID)); this.setValueId(rs.getString(DbConstants.FormDependency.VALUE_ID)); } public String getFormId() { return formId; } public void setFormId(String formId) { this.formId = formId; } public int getFormVersion() { return formVersion; } public void setFormVersion(int formVersion) { this.formVersion = formVersion; } public String getFormItemId() { return formItemId; } public void setFormItemId(String formItemId) { this.formItemId = formItemId; } public int getDependency() { return dependency; } public void setDependency(int dependency) { this.dependency = dependency; } public String getCheckBoxFormItemId() { return checkBoxFormItemId; } public void setCheckBoxFormItemId(String checkBoxFormItemId) { this.checkBoxFormItemId = checkBoxFormItemId; } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getValueId() { return valueId; } public void setValueId(String valueId) { this.valueId = valueId; } public static Log getLog() { return log; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/FormInstance.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormItemType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMINSTANCE */ public class FormInstance { public static final Log log = LogFactory.getLog(FormInstance.class); private String guid = ""; private String formId = ""; private int formVersion = 0; private String formItemId = ""; private String valueListId = ""; private String valueId = ""; private FormItemType formItemType = new FormItemType(); private String stringValue = ""; private boolean booleanValue = false; private double floatValue = 0; private String attachmentValue = ""; public FormInstance() { } public FormInstance(RecordSet rs) { this.setGuid(rs.getString(DbConstants.FormInstance.GUID)); this.setFormId(rs.getString(DbConstants.FormInstance.FORM_ID)); this.setFormVersion(rs.getInt(DbConstants.FormItem.FORM_VERSION)); this.setFormItemId(rs.getString(DbConstants.FormInstance.FORM_ITEM_ID)); this.setValueListId(rs.getString(DbConstants.FormInstance.VALUE_LIST_ID)); this.setValueId(rs.getString(DbConstants.FormInstance.VALUE_ID)); this.setFormItemType(rs.getString(DbConstants.FormInstance.FORM_ITEM_TYPE)); this.setStringValue(rs.getString(DbConstants.FormInstance.STRING_VALUE)); this.setBooleanValue(rs.getBoolean(DbConstants.FormInstance.BOOLEAN_VALUE)); this.setFloatValue(rs.getDouble(DbConstants.FormInstance.FLOAT_VALUE)); this.setAttachmentValue(rs.getString(DbConstants.FormInstance.ATTACHMENT_VALUE)); } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getFormId() { return formId; } public void setFormId(String formId) { this.formId = formId; } public int getFormVersion() { return formVersion; } public void setFormVersion(int formVersion) { this.formVersion = formVersion; } public String getFormItemId() { return formItemId; } public void setFormItemId(String formItemId) { this.formItemId = formItemId; } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getValueId() { return valueId; } public void setValueId(String valueId) { this.valueId = valueId; } public FormItemType getFormItemType() { return formItemType; } public void setFormItemType(String formItemType) { this.formItemType = new FormItemType(formItemType); } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public void setBooleanValue(boolean booleanValue) { this.booleanValue = booleanValue; } public boolean isBooleanValue() { return booleanValue; } public double getFloatValue() { return floatValue; } public void setFloatValue(double floatValue) { this.floatValue = floatValue; } public String getAttachmentValue() { return attachmentValue; } public void setAttachmentValue(String attachmentValue) { this.attachmentValue = attachmentValue; } public static Log getLog() { return log; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/FormItem.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormItemType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMITEM */ public class FormItem { public static final Log log = LogFactory.getLog(FormItem.class); private String formId = ""; private int formVersion = 0; private String id = ""; private FormItemType formItemType = new FormItemType(); private int sequence = 0; private String label = ""; private boolean mandatory = false; private String cardName = ""; private boolean obsolete = false; private String valueListId = ""; private String emptyText = ""; private String groupName = ""; private int maxStringSize = 0; private String validationRegex = ""; private boolean multiLine = false; private String format = ""; private double minValue = 0; private double maxValue = 0; public FormItem() { } public FormItem(RecordSet rs) { this.setFormId(rs.getString(DbConstants.FormItem.FORM_ID)); this.setFormVersion(rs.getInt(DbConstants.FormItem.FORM_VERSION)); this.setId(rs.getString(DbConstants.FormItem.ID)); this.setFormItemType(rs.getString(DbConstants.FormItem.FORM_ITEM_TYPE)); this.setSequence(rs.getInt(DbConstants.FormItem.SEQUENCE)); this.setLabel(rs.getString(DbConstants.FormItem.LABEL)); this.setMandatory(rs.getBoolean(DbConstants.FormItem.MANDATORY)); this.setCardName(rs.getString(DbConstants.FormItem.CARD_NAME)); this.setObsolete(rs.getBoolean(DbConstants.FormItem.OBSOLETE)); this.setValueListId(rs.getString(DbConstants.FormItem.VALUE_LIST_ID)); this.setEmptyText(rs.getString(DbConstants.FormItem.EMPTY_TEXT)); this.setGroupName(rs.getString(DbConstants.FormItem.GROUP_NAME)); this.setMaxStringSize(rs.getInt(DbConstants.FormItem.MAX_STRING_SIZE)); this.setValidationRegex(rs.getString(DbConstants.FormItem.VALIDATION_REGEX)); this.setMultiLine(rs.getBoolean(DbConstants.FormItem.MULTILINE)); this.setFormat(rs.getString(DbConstants.FormItem.FORMAT)); this.setMinValue(rs.getDouble(DbConstants.FormItem.MIN_VALUE)); this.setMaxValue(rs.getDouble(DbConstants.FormItem.MAX_VALUE)); } public String getFormId() { return formId; } public void setFormId(String formId) { this.formId = formId; } public int getFormVersion() { return formVersion; } public void setFormVersion(int formVersion) { this.formVersion = formVersion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public FormItemType getFormItemType() { return formItemType; } public void setFormItemType(String formItemType) { this.formItemType = new FormItemType(formItemType); } public void setFormItemType(FormItemType formItemType) { this.formItemType = formItemType; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public boolean isMandatory() { return mandatory; } public void setMandatory(boolean mandatory) { this.mandatory = mandatory; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } public boolean isObsolete() { return obsolete; } public void setObsolete(boolean obsolete) { this.obsolete = obsolete; } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getEmptyText() { return emptyText; } public void setEmptyText(String emptyText) { this.emptyText = emptyText; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public int getMaxStringSize() { return maxStringSize; } public void setMaxStringSize(int maxStringSize) { this.maxStringSize = maxStringSize; } public String getValidationRegex() { return validationRegex; } public void setValidationRegex(String validationRegex) { this.validationRegex = validationRegex; } public boolean isMultiLine() { return multiLine; } public void setMultiLine(boolean multiLine) { this.multiLine = multiLine; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public double getMinValue() { return minValue; } public void setMinValue(double minValue) { this.minValue = minValue; } public double getMaxValue() { return maxValue; } public void setMaxValue(double maxValue) { this.maxValue = maxValue; } public static Log getLog() { return log; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/FormValueList.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMVALUELIST */ public class FormValueList { public static final Log log = LogFactory.getLog(FormValueList.class); private String valueListId = ""; private String valueId = ""; private int sequence = 0; private boolean defaultValue = false; private String value = ""; public FormValueList() { } public FormValueList(RecordSet rs) { this.setValueListId(rs.getString(DbConstants.FormValueList.VALUE_LIST_ID)); this.setValueId(rs.getString(DbConstants.FormValueList.VALUE_ID)); this.setSequence(rs.getInt(DbConstants.FormValueList.SEQUENCE)); this.setDefaultValue(rs.getBoolean(DbConstants.FormValueList.DEFAULT_VALUE)); this.setValue(rs.getString(DbConstants.FormValueList.VALUE)); } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getValueId() { return valueId; } public void setValueId(String valueId) { this.valueId = valueId; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public boolean isDefaultValue() { return defaultValue; } public void setDefaultValue(boolean defaultValue) { this.defaultValue = defaultValue; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static Log getLog() { return log; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/History.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDHIST */ public class History { private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private int idx = 0; private String text = ""; //$NON-NLS-1$ History() { } public History(RecordSet rs) { this.setIDX(rs.getInt(DbConstants.History.IDX)); this.setJobNumber(rs.getString(DbConstants.History.JOB_NUMBER)); this.setJobType(rs.getString(DbConstants.History.JOB_TYPE)); this.setText(rs.getString(DbConstants.History.Text)); } public int getIDX() { return this.idx; } public void setIDX(int index) { this.idx = index; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public JobType getJobType() { return this.jobType; } public void setJobType(String jobType) { this.jobType = new JobType(jobType); } public void setJobType(JobType jobType) { this.jobType = jobType; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Incident.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBSTORC */ public class Incident { private String errorCode = ""; //$NON-NLS-1$ private String fct = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Incident() { } public Incident(RecordSet rs) { this.setErrorCode(rs.getString(DbConstants.Incident.CODE)); this.setFct(rs.getString(DbConstants.Incident.FCT)); this.setText(rs.getString(DbConstants.Incident.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Incident.REFRESH_FLAG)); } public String getErrorCode() { return this.errorCode; } public void setErrorCode(String storc) { this.errorCode = storc; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } public String getFct() { return fct; } public void setFct(String fct) { this.fct = fct; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/InternalWorkType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZARBEITSART */ public class InternalWorkType { private String workTypeCode = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ InternalWorkType() { } public InternalWorkType(RecordSet rs) { this.setWorkTypeCode(rs.getString(DbConstants.InternalWorkType.CODE)); this.setText(rs.getString(DbConstants.InternalWorkType.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.InternalWorkType.REFRESH_FLAG)); } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Inventory.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.Warehouse; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZLG */ public class Inventory { private String warehouseNumber = ""; private int personalNumber = 0; private String name = ""; private Warehouse warehouse = new Warehouse(); private String refreshFlag = ""; public Inventory() { } public Inventory(RecordSet rs) { this.setWarehouseNumber(rs.getString(DbConstants.Inventory.WAREHOUSE_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.Inventory.PERSONAL_NUMBER)); this.setName(rs.getString(DbConstants.Inventory.NAME)); this.setWarehouse(new Warehouse(rs.getString(DbConstants.Inventory.WAREHOUSE))); this.setRefreshFlag(rs.getString(DbConstants.Inventory.REFRESH_FLAG)); } public String getWarehouseNumber() { return warehouseNumber; } public void setWarehouseNumber(String warehouseNumber) { this.warehouseNumber = warehouseNumber; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Warehouse getWarehouse() { return warehouse; } public void setWarehouse(Warehouse warehouse) { this.warehouse = warehouse; } public String getRefreshFlag() { return refreshFlag; } public void setRefreshFlag(String refreshFlag) { this.refreshFlag = refreshFlag; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Invoice.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBVERRC */ public class Invoice { private String code = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Invoice() { } public Invoice(RecordSet rs) { this.setCode(rs.getString(DbConstants.Invoice.CODE)); this.setText(rs.getString(DbConstants.Invoice.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Invoice.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobFile.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Bitmap; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMV; import ch.mfiles.kaba.kolibri.common.util.BitmapConverterUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMV */ public class JobFile { public static final Log log = LogFactory.getLog(Report.class); private String jobFileId = ""; //$NON-NLS-1$ private String guid = ""; //$NON-NLS-1$ private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String type = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ private boolean signpicAtSet = false; private String signpicAt = ""; //$NON-NLS-1$ private FormType formType = new FormType(); private String formDesc = ""; private Date sentDate = new Date(0); public JobFile() { } public JobFile(RecordSet rs) { this.setJobFileId(rs.getString(DbConstants.JobFile.IDX)); this.setGuid(rs.getString(DbConstants.JobFile.GUID)); this.setJobNumber(rs.getString(DbConstants.JobFile.JOB_NUMBER)); this.setJobType(rs.getString(DbConstants.JobFile.JOB_TYPE)); this.setType(rs.getString(DbConstants.JobFile.TYPE)); this.setDescription(rs.getString(DbConstants.JobFile.DESCRIPTION)); // lazy load file data to reduce memory footprint (MIG-988) //this.setSignPicAt(rs.getString(DbConstants.JobFile.SIGN_PIC_AT)); this.setSignPicAt(null); this.setFormType(new FormType(rs.getString(DbConstants.JobFile.FORM_TYPE))); this.setFormDesc(rs.getString(DbConstants.JobFile.FORM_DESC)); this.setSentDate(rs.getDate(DbConstants.JobFile.SENT_DATE)); } public String getJobFileId() { return jobFileId; } public void setJobFileId(String jobFileId) { this.jobFileId = jobFileId; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public JobType getJobType() { return jobType; } public void setJobType(JobType jobType) { this.jobType = jobType; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSignpicAt() { // lazy load file data from db without keeping it into heap memory (MIG-988) if (signpicAtSet) return signpicAt; DBSession db = Runtime.getApplicationManager().getDBSession(); ZKDMOBMV dbMobmv = ZKDMOBMV.getByPrimaryKey(db, getJobFileId()); return dbMobmv != null ? dbMobmv.getSIGNPIC_AT() : ""; } public void setSignPicAt(String signpicAt) { this.signpicAt = signpicAt; signpicAtSet = signpicAt != null && !signpicAt.isEmpty(); } public void setJobType(String auart) { this.jobType = new JobType(auart); } public Bitmap getSignPicBitmap() { return BitmapConverterUtil.stringToBitMap(getSignpicAt()); } public void setSignPicBitmap(Bitmap bitmap) { setSignPicAt(BitmapConverterUtil.bitMapToString(bitmap)); } public FormType getFormType() { return formType; } public void setFormType(FormType formType) { this.formType = formType; } public String getFormDesc() { return formDesc; } public void setFormDesc(String formDesc) { this.formDesc = formDesc; } public Date getSentDate() { return sentDate; } public void setSentDate(Date sentDate) { this.sentDate = sentDate; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.JobFile.JOB_FILE, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.JobFile.JOB_FILE, db, folder); } public boolean isValid() { boolean result = true; StringBuilder error = new StringBuilder(); error.append("\n"); if(equals(getGuid().trim().isEmpty())) { error.append("Guid required \n"); result = false; } if(getJobNumber().trim().isEmpty()) { error.append("JobNumber required \n" ); result = false; } if(getJobFileId().trim().isEmpty()) { error.append("FileId required \n" ); result = false; } if(getJobType().toString().isEmpty()) { error.append("JobType required \n" ); result = false; } if(getType().trim().isEmpty()) { error.append("Type required \n" ); result = false; } if(getType().trim().equalsIgnoreCase("F") && getFormType().isINITIAL()) { error.append("FormType required \n" ); result = false; } if(getSignpicAt().toString().trim().isEmpty()) { error.append("Signpic required \n" ); result = false; } log.info("is JobFile valid -> " + result + " " + error.toString()); return result; } public String getNoForm() { if (getJobFileId().contains("NO_FORM")) { return getJobFileId().split("NO_FORM")[1]; } return ""; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobFormDesc.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFORMDESC */ public class JobFormDesc { private String formDesc = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ JobFormDesc() { } public JobFormDesc(RecordSet rs) { this.setFormDesc((rs.getString(DbConstants.JobFormDesc.CODE))); this.setText(rs.getString(DbConstants.JobFormDesc.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobFormDesc.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getFormDesc() { return this.formDesc; } public void setFormDesc(String formDesc) { this.formDesc = formDesc; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobMessage.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMSG */ public class JobMessage extends BaseEntity { private String guId = ""; //$NON-NLS-1$ private String messageId = ""; //$NON-NLS-1$ private String messageCode = ""; //$NON-NLS-1$ private String messageCodeText = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String moreText = ""; //$NON-NLS-1$ public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.JobMessage.JOB_MESSAGE, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.JobMessage.JOB_MESSAGE, db, folder); } public JobMessage() { } public JobMessage(RecordSet rs) { this.setGuId(rs.getString(DbConstants.JobMessage.GUID)); this.setMessageId(rs.getString(DbConstants.JobMessage.MESSAGE_ID)); this.setMessageCode(rs.getString(DbConstants.JobMessage.MESSAGE_CODE)); this.setMessageCodeText(rs.getString(DbConstants.JobMessage.TEXT_1)); this.setText(rs.getString(DbConstants.JobMessage.TEXT_2)); this.setMoreText(rs.getString(DbConstants.JobMessage.MoreText)); } public String getMessageId() { return this.messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public String getGuId() { return this.guId; } public void setGuId(String guid) { this.guId = guid; } public String getMessageCode() { return this.messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } public String getMessageCodeText() { return this.messageCodeText; } public void setMessageCodeText(String messageCodeText) { this.messageCodeText = messageCodeText; } public String getFullText() { return this.text.concat(this.moreText); } public String geText() { return this.text; } public void setFullText(String text) { if (text.length() > 255) { this.text = text.substring(0, 255); this.moreText = text.substring(255); } else { this.text = text; this.moreText = ""; //$NON-NLS-1$ } } public void setText(String text) { this.text = text; } public String getMoreText() { return this.moreText; } public void setMoreText(String moreText) { this.moreText = moreText; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobMonText.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMONTXT */ public class JobMonText { private String monText = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ JobMonText() { } public JobMonText(RecordSet rs) { this.setMonText((rs.getString(DbConstants.JobMonText.CODE))); this.setLanguage(rs.getString(DbConstants.JobMonText.LANGUAGE)); this.setText(rs.getString(DbConstants.JobMonText.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getMonText() { return this.monText; } public void setMonText(String reasonText) { this.monText = reasonText; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobNoForm.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBNOFORM */ public class JobNoForm { private String noForm = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ JobNoForm() { } public JobNoForm(RecordSet rs) { this.setNoForm((rs.getString(DbConstants.JobNoForm.CODE))); this.setText(rs.getString(DbConstants.JobNoForm.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobNoForm.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getNoForm() { return this.noForm; } public void setNoForm(String noForm) { this.noForm = noForm; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobReportTime.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /** * Object representing working time spent on a job report. Implements Comparable * interface because the list of times of a certain day must be in the correct * order. * In the Database -> ZKDMOBRTIM * @author paulib * */ public class JobReportTime implements Comparable { private String guId = ""; //$NON-NLS-1$ private int idx = 0; private Date date = new Date(); private Date startTime = new Date(0); private Date stopTime = new Date(0); private String workTypeCode = ""; public JobReportTime() { } public JobReportTime(RecordSet rs) { this.setStopTime(rs.getDate(DbConstants.JobReportTime.STOP_TIME)); this.setGuid(rs.getString(DbConstants.JobReportTime.GUID)); this.setIdx(rs.getInt(DbConstants.JobReportTime.IDX)); this.setStartTime(rs.getDate(DbConstants.JobReportTime.START_TIME)); this.setDate(rs.getDate(DbConstants.JobReportTime.DATE)); this.setWorkTypeCode(rs.getString(DbConstants.JobReportTime.WORK_TYPE_CODE)); } public int compareTo(Object o) { JobReportTime jobReportTime = (JobReportTime) o; return this.getStartTime().compareTo(jobReportTime.getStartTime()); } public Date getStopTime() { return this.stopTime; } public void setStopTime(Date bis) { this.stopTime = bis; } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public Date getStartTime() { return this.startTime; } public void setStartTime(Date von) { this.startTime = von; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/JobReturnReason.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBRETURN */ public class JobReturnReason extends Reason{ JobReturnReason() { } public JobReturnReason(RecordSet rs) { this.setReasonText((rs.getString(DbConstants.JobReturnReason.CODE))); this.setLanguage(rs.getString(DbConstants.JobReturnReason.LANGUAGE)); this.setText(rs.getString(DbConstants.JobReturnReason.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobReturnReason.REFRESH_FLAG)); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Material.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMAT */ public class Material { private String materialNumber = ""; //$NON-NLS-1$ private String materialShortText = ""; //$NON-NLS-1$ private String customerServiceFlag = ""; //$NON-NLS-1$ private String mountingFlag = ""; //$NON-NLS-1$ private String unit = ""; //$NON-NLS-1$ private String size = ""; //$NON-NLS-1$ private String newPrice = ""; //$NON-NLS-1$ private String substitutePrice = ""; //$NON-NLS-1$ private String calculationNewPrice = ""; //$NON-NLS-1$ private String calculationSubstitutePrice = ""; //$NON-NLS-1$ private String unitNewPrice = ""; //$NON-NLS-1$ private String unitSubstitutePrice = ""; //$NON-NLS-1$ private String currencyNewPrice = ""; //$NON-NLS-1$ private String currencySubstitutePrice = ""; //$NON-NLS-1$ Material() { } public Material(RecordSet rs) { this.setMaterialShortText(rs.getString(DbConstants.Material.TEXT)); this.setMaterialNumber(rs.getString(DbConstants.Material.NUMBER)); this.setCustomerServiceFlag(rs.getString(DbConstants.Material.CUSTOMER_SERVICE_FLAG)); this.setMountingFlag(rs.getString(DbConstants.Material.MOUNTING_FLAG)); this.setUnit(rs.getString(DbConstants.Material.UNIT)); this.setSize(rs.getString(DbConstants.Material.SIZE)); this.setNewPrice(rs.getString(DbConstants.Material.NEW_PRICE)); this.setSubstitutePrice(rs.getString(DbConstants.Material.SUBSTITUE_PRICE)); this.setCalculationNewPrice(rs.getString(DbConstants.Material.CALCULATION_NEW_PRICE)); this.setCalculationSubstitutePrice(rs.getString(DbConstants.Material.CALCULATION_SUBSTITUE_PRICE)); this.setUnitNewPrice(rs.getString(DbConstants.Material.UNIT_NEW_PRICE)); this.setUnitSubstitutePrice(rs.getString(DbConstants.Material.UNIT_SUBSTITUE_PRICE)); this.setCurrencyNewPrice(rs.getString(DbConstants.Material.CURRENCY_NEW_PRICE)); this.setCurrencySubstitutePrice(rs.getString(DbConstants.Material.CURRENCY_SUBSTITUE_PRICE)); } public String getCustomerServiceFlag() { return this.customerServiceFlag; } public void setCustomerServiceFlag(String kdmat) { this.customerServiceFlag = kdmat; } public String getUnit() { return this.unit; } public void setUnit(String maunit) { this.unit = maunit; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getMountingFlag() { return this.mountingFlag; } public void setMountingFlag(String monmat) { this.mountingFlag = monmat; } public String getMaterialShortText() { return this.materialShortText; } public void setMaterialShortText(String maktx) { this.materialShortText = maktx; } public String getMaterialNumber() { return this.materialNumber; } public void setMaterialNumber(String matnr) { this.materialNumber = matnr; } public String getNewPrice() { return newPrice; } public void setNewPrice(String newPrice) { this.newPrice = newPrice; } public String getSubstitutePrice() { return substitutePrice; } public void setSubstitutePrice(String substitutePrice) { this.substitutePrice = substitutePrice; } public String getCalculationNewPrice() { return calculationNewPrice; } public void setCalculationNewPrice(String calculationNewPrice) { this.calculationNewPrice = calculationNewPrice; } public String getCalculationSubstitutePrice() { return calculationSubstitutePrice; } public void setCalculationSubstitutePrice(String calculationSubstitutePrice) { this.calculationSubstitutePrice = calculationSubstitutePrice; } public String getUnitNewPrice() { return unitNewPrice; } public void setUnitNewPrice(String unitNewPrice) { this.unitNewPrice = unitNewPrice; } public String getUnitSubstitutePrice() { return unitSubstitutePrice; } public void setUnitSubstitutePrice(String unitSubstitutePrice) { this.unitSubstitutePrice = unitSubstitutePrice; } public String getCurrencyNewPrice() { return currencyNewPrice; } public void setCurrencyNewPrice(String currencyNewPrice) { this.currencyNewPrice = currencyNewPrice; } public String getCurrencySubstitutePrice() { return currencySubstitutePrice; } public void setCurrencySubstitutePrice(String currencySubstitutePrice) { this.currencySubstitutePrice = currencySubstitutePrice; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/MaterialMovement.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZGMBEW */ public class MaterialMovement { public static final Log log = LogFactory.getLog(MaterialMovement.class); private String guid = ""; private String orderNumber = ""; private int orderPosition; private int personalNumber; private String materialNumber = ""; private String from = ""; private String to = ""; private String entryCount = ""; private String entryUnit = ""; private String receiptOfGoods = ""; private String barcode = ""; private String barcodeText = ""; private int personalNumberConfirmed; public MaterialMovement() { } public MaterialMovement(RecordSet rs) { this.setGuid(rs.getString(DbConstants.MaterialMovement.GUID)); this.setOrderNumber(rs.getString(DbConstants.MaterialMovement.ORDER_NUMBER)); this.setOrderPosition(rs.getInt(DbConstants.MaterialMovement.ORDER_POSITION)); this.setPersonalNumber(rs.getInt(DbConstants.MaterialMovement.PERSONAL_NUMBER)); this.setMaterialNumber(rs.getString(DbConstants.MaterialMovement.MATERIAL_NUMBER)); this.setFrom(rs.getString(DbConstants.MaterialMovement.FROM)); this.setTo(rs.getString(DbConstants.MaterialMovement.TO)); this.setEntryCount(rs.getString(DbConstants.MaterialMovement.ENTRY_COUNT)); this.setEntryUnit(rs.getString(DbConstants.MaterialMovement.ENTRY_UNIT)); this.setReceiptOfGoods(rs.getString(DbConstants.MaterialMovement.RECEIPT_OF_GOODS)); this.setBarcode(rs.getString(DbConstants.MaterialMovement.BARCODE)); this.setBarcodeText(rs.getString(DbConstants.MaterialMovement.BARCODE_TEXT)); this.setPersonalNumberConfirmed(rs.getInt(DbConstants.MaterialMovement.PERSONAL_NUMBER_CONFIRMED)); } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getOrderPosition() { return orderPosition; } public void setOrderPosition(int orderPosition) { this.orderPosition = orderPosition; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getMaterialNumber() { return materialNumber; } public void setMaterialNumber(String materialNumber) { this.materialNumber = materialNumber; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getEntryCount() { return entryCount; } public void setEntryCount(String entryCount) { this.entryCount = entryCount; } public String getEntryUnit() { return entryUnit; } public void setEntryUnit(String entryUnit) { this.entryUnit = entryUnit; } public String getReceiptOfGoods() { return receiptOfGoods; } public void setReceiptOfGoods(String receiptOfGoods) { this.receiptOfGoods = receiptOfGoods; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getBarcodeText() { return barcodeText; } public void setBarcodeText(String barcodeText) { this.barcodeText = barcodeText; } public int getPersonalNumberConfirmed() { return personalNumberConfirmed; } public void setPersonalNumberConfirmed(int personalNumberConfirmed) { this.personalNumberConfirmed = personalNumberConfirmed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/MaterialPerson.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDMOBMATPERS */ public class MaterialPerson { String materialNumber = ""; //$NON-NLS-1$ String materialShortText = ""; //$NON-NLS-1$ String customerServiceFlag = ""; //$NON-NLS-1$ String mountingFlag = ""; //$NON-NLS-1$ public MaterialPerson() { //constructor } public MaterialPerson(RecordSet rs) { this.setMaterialNumber(rs.getString(DbConstants.MaterialPerson.NUMBER)); this.setMaterialShortText(rs.getString(DbConstants.MaterialPerson.TEXT)); this.setCustomerServiceFlag(rs.getString(DbConstants.MaterialPerson.CUSTOMER_SERVICE_FLAG)); this.setMountingFlag(rs.getString(DbConstants.MaterialPerson.MOUNTING_FLAG)); } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.MaterialPerson.MATERIAL_PERSON, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.MaterialPerson.MATERIAL_PERSON, db, folder); } public String getMaterialNumber() { return this.materialNumber; } public void setMaterialNumber(String matnr) { this.materialNumber = matnr; } public String getMaterialShortText() { return this.materialShortText; } public void setMaterialShortText(String maktx) { this.materialShortText = maktx; } public String getCustomerServiceFlag() { return this.customerServiceFlag; } public void setCustomerServiceFlag(String kdmat) { this.customerServiceFlag = kdmat; } public String getMountingFlag() { return this.mountingFlag; } public void setMountingFlag(String monmat) { this.mountingFlag = monmat; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/NextIntervention.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFLGVRGT */ public class NextIntervention { private String code = ""; private String text = ""; private String refreshFlag = ""; NextIntervention() { } public NextIntervention(RecordSet rs) { this.setCode(rs.getString(DbConstants.NextIntervention.CODE)); this.setText(rs.getString(DbConstants.NextIntervention.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.NextIntervention.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Order.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKSMABEST */ public class Order { public static final Log log = LogFactory.getLog(Order.class); private int idx = 0; private int personalNumber = 0; private String status = ""; //$NON-NLS-1$ private String isNotUsed = ""; //$NON-NLS-1$ private Date createDate = new Date(); private Date sentDate = new Date(); public Order() { } public Order(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.Order.IDX)); this.setPersonalNumber(rs.getInt(DbConstants.Order.PERSONAL_NUMBER)); this.setStatus(rs.getString(DbConstants.Order.STATUS)); this.setANZ(rs.getString(DbConstants.Order.ANZ)); this.setCreateDate(rs.getDate(DbConstants.Order.CREATED_DATE)); this.setSentDate(rs.getDate(DbConstants.Order.SENT_DATE)); } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getANZ() { return this.isNotUsed; } public void setANZ(String anz) { this.isNotUsed = anz; } public Date getCreateDate() { return this.createDate; } public String getOrderCreateDate() { return DateTimeUtil.tableDate(this.getCreateDate()); } public void setCreateDate(Date erfasst) { this.createDate = erfasst; } public Date getSentDate() { return this.sentDate; } public String getOrderSentDate() { return DateTimeUtil.tableDate(this.getSentDate()); } public void setSentDate(Date gesendet) { this.sentDate = gesendet; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public boolean isNew() { return getStatus().equalsIgnoreCase(CommonConstants.Order.Status.NEW_ORDER); } public boolean isSent() { return getStatus().equalsIgnoreCase(CommonConstants.Order.Status.SENT_ORDER); } public int getStatusColor() { int result = 0; if (isNew()) { result = LayoutUtils.DEFAULT_RED; } else if (isSent()) { result = LayoutUtils.DEFAULT_DARK_GRAY; } return result; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Order.ORDER, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Order.ORDER, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/OrderMaterial.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAMAT */ public class OrderMaterial { private int personalNumber; private Date date; private String amount; private String materialNumber; private String expressFlag; private String variousMaterial; private String unit; private Date orderDate; public OrderMaterial() { } public OrderMaterial(RecordSet rs) { this.setDate(rs.getDate(DbConstants.OrderMaterial.DATE)); this.setExpressFlag(rs.getString(DbConstants.OrderMaterial.EXPRESS_FLAG)); this.setVariousMaterial(rs.getString(DbConstants.OrderMaterial.VARIOUS_MATERIAL)); this.setMaterialNumber(rs.getString(DbConstants.OrderMaterial.NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.OrderMaterial.PERSONAL_NUMBER)); this.setAmount(rs.getString(DbConstants.OrderMaterial.AMOUNT)); this.setUnit(rs.getString(DbConstants.OrderMaterial.UNIT)); this.setOrderDate(rs.getDate(DbConstants.OrderMaterial.ORDER_DATE)); } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getExpressFlag() { return this.expressFlag; } public boolean isExpressFlag() { return "X".equalsIgnoreCase(this.getExpressFlag()); //$NON-NLS-1$ } public void setExpressFlag(boolean expressFlag) { if (expressFlag) { this.setExpressFlag("X"); //$NON-NLS-1$ } else { this.setExpressFlag(""); //$NON-NLS-1$ } } public void setExpressFlag(String expr) { this.expressFlag = expr; } public String getVariousMaterial() { return this.variousMaterial; } public void setVariousMaterial(String maktx) { this.variousMaterial = maktx; } public String getMaterialNumber() { return this.materialNumber; } public void setMaterialNumber(String matnr) { this.materialNumber = matnr; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getAmount() { return this.amount; } public void setAmount(String stck) { this.amount = stck; } public String getUnit() { return this.unit; } public void setUnit(String maunit) { this.unit = maunit; } public void setOrderDate(Date bestdat) { this.orderDate = bestdat; } public Date getOrderDate() { return this.orderDate; } public int getStatusColor() { return LayoutUtils.DEFAULT_DARK_GRAY; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.OrderMaterial.ORDER_MATERIAL, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.OrderMaterial.ORDER_MATERIAL, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Person.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMA */ public class Person { private int personalNumber = 0; private String lastName = ""; //$NON-NLS-1$ private String firstName = ""; //$NON-NLS-1$ private String initial = ""; //$NON-NLS-1$ private String personalNumberDeputy = ""; //$NON-NLS-1$ private String phoneNumber = ""; //$NON-NLS-1$ private String communicationNumber = ""; //$NON-NLS-1$ private String salesOffice = ""; //$NON-NLS-1$ private String absentFrom = ""; //$NON-NLS-1$ private String absentTo = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String deviceId; private String password; private String refreshFlag = ""; private String warehouseNumber = ""; //$NON-NLS-1$ private String communicationNumberFormat = ""; private boolean expensesActive = false; private String profileText = ""; Person() { } public Person(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.Person.PERSONAL_NUMBER)); this.setLastName(rs.getString(DbConstants.Person.LAST_NAME)); this.setFirstName(rs.getString(DbConstants.Person.FIRST_NAME)); this.setInitial(rs.getString(DbConstants.Person.INITIAL)); this.setPersonalNumberDeputy(rs.getString(DbConstants.Person.PERSONAL_NUMBER_DEPUTY)); this.setPhoneNumber(rs.getString(DbConstants.Person.PHONE)); this.setNUM01(rs.getString(DbConstants.Person.NUM01)); this.setSalesOffice(rs.getString(DbConstants.Person.SALES_OFFICE)); this.setAbsentFrom(rs.getString(DbConstants.Person.ABSENT_FROM)); this.setAbsentTo(rs.getString(DbConstants.Person.ABSENT_TO)); this.setLanguage(rs.getString(DbConstants.Person.LANGUAGE)); this.setDeviceId(rs.getString(DbConstants.Person.DEVICE_ID)); this.setPassword(rs.getString(DbConstants.Person.PASSWORD)); this.setRefreshFlag(rs.getString(DbConstants.Person.REFRESH_FLAG)); this.setWarehouseNumber(rs.getString(DbConstants.Person.WAREHOUSE_NUMBER)); this.setCommunicationNumberFormat(rs.getString(DbConstants.Person.COMMISSION_NUMBER_FORMAT)); this.setExpensesActive(rs.getBoolean(DbConstants.Person.EXPENSES_ACTIVE)); this.setProfileText(rs.getString(DbConstants.Person.PROFILE_TEXT)); } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getInitial() { return this.initial; } public void setInitial(String inits) { this.initial = inits; } public String getLastName() { return this.lastName; } public void setLastName(String nachn) { this.lastName = nachn; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getPassword() { return this.password; } public void setPassword(String pwd) { this.password = pwd; } public String getPersonalNumberDeputy() { return this.personalNumberDeputy; } public void setPersonalNumberDeputy(String stvpernr) { this.personalNumberDeputy = stvpernr; } public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String telnr) { this.phoneNumber = telnr; } public String getSalesOffice() { return this.salesOffice; } public void setSalesOffice(String vkbur) { this.salesOffice = vkbur; } public String getFirstName() { return this.firstName; } public void setFirstName(String vorna) { this.firstName = vorna; } public String getNUM01() { return this.communicationNumber; } public void setNUM01(String num01) { this.communicationNumber = num01; } public String getAbsentFrom() { return this.absentFrom; } public void setAbsentFrom(String abwvon) { this.absentFrom = abwvon; } public String getAbsentTo() { return this.absentTo; } public void setAbsentTo(String abwbis) { this.absentTo = abwbis; } public String getDeviceId() { return this.deviceId; } public void setDeviceId(String gid) { this.deviceId = gid; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } public String getWarehouseNumber() { return warehouseNumber; } public void setWarehouseNumber(String warehouseNumber) { this.warehouseNumber = warehouseNumber; } public String getCommunicationNumberFormat() { return communicationNumberFormat; } public void setCommunicationNumberFormat(String communicationNumberFormat) { this.communicationNumberFormat = communicationNumberFormat; } public boolean getExpensesActive() { return expensesActive; } public void setExpensesActive(boolean expensesActive) { this.expensesActive = expensesActive; } public String getProfileText() { return profileText; } public void setProfileText(String profileText) { this.profileText = profileText; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/PhoneBookEntry.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class PhoneBookEntry { private static final String HTML_SPACE = " "; //$NON-NLS-1$ private static final String HTML_LINE_BREAK = "
"; //$NON-NLS-1$ private String mLabel1 = ""; //$NON-NLS-1$ private String mLabel2 = ""; //$NON-NLS-1$ private String mTitel = ""; //$NON-NLS-1$ private String mPosition = ""; //$NON-NLS-1$ private String mDetails = ""; //$NON-NLS-1$ private String mPhoneNumber1 = ""; //$NON-NLS-1$ private String mPhoneNumber2 = ""; //$NON-NLS-1$ private boolean mExistingPhoneNumber1 = false; private boolean mExistingPhoneNumber2 = false; public PhoneBookEntry(String label, String titel, String details, String position, String phoneNumber1) { mTitel = titel; mPosition = position; if (!"".equals(phoneNumber1)) { //$NON-NLS-1$ mExistingPhoneNumber1 = true; mPhoneNumber1 = StringUtil.removeLetters(phoneNumber1); if (!"".equals(position)) //$NON-NLS-1$ mLabel1 = mLabel1 + position + HTML_LINE_BREAK; if (!"".equals(mPhoneNumber1)) //$NON-NLS-1$ mLabel1 = mLabel1 + mPhoneNumber1; if (!"".equals(titel)) //$NON-NLS-1$ mDetails = mDetails + titel + HTML_SPACE; if (!"".equals(label)) //$NON-NLS-1$ mDetails = mDetails + label + HTML_LINE_BREAK; if (!"".equals(details)) //$NON-NLS-1$ mDetails = mDetails + details; } } public PhoneBookEntry(String titel, Address address, String position) { mTitel = titel; mPosition = position; extract(address); } private void extract(Address address) { String details = ""; //$NON-NLS-1$ if (address.isPrivate()) { if (!"".equals(address.getTitle())) //$NON-NLS-1$ mDetails = mDetails + mTitel + HTML_SPACE; if (!"".equals(address.getName1())) //$NON-NLS-1$ mDetails = mDetails + address.getName1() + HTML_SPACE; if (!"".equals(address.getName2())) //$NON-NLS-1$ mDetails = mDetails + address.getName2() + HTML_LINE_BREAK; if (!"".equals(address.getName3())) //$NON-NLS-1$ mDetails = mDetails + address.getName3() + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) { //$NON-NLS-1$ mExistingPhoneNumber1 = true; mPhoneNumber1 = StringUtil.removeLetters(address.getTelNumber1()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel1 = mLabel1 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) //$NON-NLS-1$ mLabel1 = mLabel1 + mPhoneNumber1; } if (!"".equals(address.getTelNumber2())) { //$NON-NLS-1$ mExistingPhoneNumber2 = true; mPhoneNumber2 = StringUtil.removeLetters(address.getTelNumber1()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel2 = mLabel2 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) //$NON-NLS-1$ mLabel2 = mLabel2 + mPhoneNumber2; } } else { if (!"".equals(address.getTitle())) //$NON-NLS-1$ details = details + mTitel + HTML_SPACE; if (!"".equals(address.getName1())) { //$NON-NLS-1$ details = details + address.getName1(); if (!"".equals(address.getName2())) //$NON-NLS-1$ details = details + address.getName2() + HTML_SPACE; } else if (!"".equals(address.getName2())) { //$NON-NLS-1$ details = details + address.getName2(); } else { details = details + Messages.getString("PhoneBookEntry_1"); //$NON-NLS-1$ } if (!"".equals(address.getName3())) //$NON-NLS-1$ details = details + address.getName3(); if (!"".equals(details)) //$NON-NLS-1$ mDetails = details + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) { //$NON-NLS-1$ mExistingPhoneNumber1 = true; mPhoneNumber1 = StringUtil.removeLetters(address.getTelNumber1()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel1 = mLabel1 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) //$NON-NLS-1$ mLabel1 = mLabel1 + mPhoneNumber1; } if (!"".equals(address.getTelNumber2())) { //$NON-NLS-1$ mExistingPhoneNumber2 = true; mPhoneNumber2 = StringUtil.removeLetters(address.getTelNumber2()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel2 = mLabel2 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber2())) //$NON-NLS-1$ mLabel2 = mLabel2 + mPhoneNumber2; } } } public String getLabel1() { return mLabel1; } public String getLabel2() { return mLabel2; } public String getPosition() { return mPosition; } public boolean hasPhoneNumber1() { return mExistingPhoneNumber1; } public String getDetails() { return mDetails; } public String getPhoneNumber1() { return mPhoneNumber1; } public boolean hasPhoneNumber2() { return mExistingPhoneNumber2; } public String getPhoneNumber2() { return mPhoneNumber2; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Progress.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMONSTK */ public class Progress { private String progressCode = ""; private String spras = ""; private String text = ""; private String refreshFlag = ""; Progress() { } public Progress(RecordSet rs) { this.setProgressCode(rs.getString(DbConstants.Progress.CODE)); this.setSpras(rs.getString(DbConstants.Progress.SPRAS)); this.setText(rs.getString(DbConstants.Progress.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Progress.REFRESH_FLAG)); } public String getProgressCode() { return this.progressCode; } public void setProgressCode(String progressCode) { this.progressCode = progressCode; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getSpras() { return spras; } public void setSpras(String spras) { this.spras = spras; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Reason.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> REASON */ public class Reason { private String reasonText = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Reason() { } public Reason(RecordSet rs) { this.setReasonText((rs.getString(DbConstants.Reason.CODE))); this.setLanguage(rs.getString(DbConstants.Reason.LANGUAGE)); this.setText(rs.getString(DbConstants.Reason.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Reason.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getReasonText() { return this.reasonText; } public void setReasonText(String reasonText) { this.reasonText = reasonText; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ReceiptOfGoods.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBWERET */ public class ReceiptOfGoods { private String code = ""; private String text = ""; private String refreshFlag = ""; ReceiptOfGoods() { } public ReceiptOfGoods(RecordSet rs) { this.setCode(rs.getString(DbConstants.ReceiptOfGoods.CODE)); this.setText(rs.getString(DbConstants.ReceiptOfGoods.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.ReceiptOfGoods.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/Report.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.util.DateUtils; /* * In the Database -> ZKDMOBREP */ public class Report extends BaseEntity { public static final Log log = LogFactory.getLog(Report.class); private int idx = 0; private String guId = ""; //$NON-NLS-1$ private Date createDate = new Date(); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String commissionNumber = ""; //$NON-NLS-1$ private int personalNumber = 0; private String partialRepair = ""; //$NON-NLS-1$ private String finalRepair = ""; //$NON-NLS-1$ private String reasoning = ""; //$NON-NLS-1$ private String incidentAB = ""; //$NON-NLS-1$ private String billing = ""; //$NON-NLS-1$ private String safetyReport = ""; //$NON-NLS-1$ private String customerSupport = ""; //$NON-NLS-1$ private String customerSupportText = ""; //$NON-NLS-1$ private String checklist = ""; //$NON-NLS-1$ private String errorId1 = ""; //$NON-NLS-1$ private String errorH1 = ""; //$NON-NLS-1$ private String errorFlag1 = ""; //$NON-NLS-1$ private String errorId2 = ""; //$NON-NLS-1$ private String errorH2 = ""; //$NON-NLS-1$ private String errorFlag2 = ""; //$NON-NLS-1$ private String errorId3 = ""; //$NON-NLS-1$ private String errorH3 = ""; //$NON-NLS-1$ private String errorFlag3 = ""; //$NON-NLS-1$ private String systemError = ""; //$NON-NLS-1$ private String distance = ""; //$NON-NLS-1$ private String expenses = ""; //$NON-NLS-1$ private String servicePlanMonth1 = ""; //$NON-NLS-1$ private String servicePlanMonth2 = ""; //$NON-NLS-1$ private String servicePlanMonth3 = ""; //$NON-NLS-1$ private String servicePlanMonth4 = ""; //$NON-NLS-1$ private String servicePlanMonth5 = ""; //$NON-NLS-1$ private String servicePlanMonth6 = ""; //$NON-NLS-1$ private String monthYear = ""; //$NON-NLS-1$ private String orderNumber = ""; //$NON-NLS-1$ private ReportStatus reportStatus = new ReportStatus(); private String signatureGuId = ""; //$NON-NLS-1$ private String signatureFlag = ""; //$NON-NLS-1$ private String signatureInfo = ""; //$NON-NLS-1$ private String signature = ""; //$NON-NLS-1$ private String workType = ""; //$NON-NLS-1$ private String collectively = ""; //$NON-NLS-1$ private String noMaterial = ""; //$NON-NLS-1$ private String cycleOfInstallation = ""; //$NON-NLS-1$ private String noForm1 = ""; private String noForm2 = ""; private String noForm3 = ""; private String serviceRefused = ""; private String openPending = ""; private String governmentReport = ""; private String checklistState = "U"; private String checklistSIA = "U"; private String checklistReady = "U"; private String checklistInstruction = "U"; private String checklistVKF = "U"; private String checklistTest = "U"; private String signatureName = ""; private String monStk = ""; private Date nextInterventionDate = new Date(); private String stateOfInstallation = ""; private String nextInterventionCode = ""; private List times = new ArrayList(); private List mats = new ArrayList(); private List messages = new ArrayList(); private List measurements = new ArrayList(); private List reportImageAttachments = new ArrayList(); private List reportDocumentAttachments = new ArrayList(); private List formInstances = new ArrayList(); private int currentTime; private boolean isCycleOfInstallationFlag; protected Report() { } public Report(String mldnr, JobType auart, String guid, int idx, boolean isCycleOfInstallationFlag) { this.setJobNumber(mldnr); this.setJobType(auart); this.setGuid(guid); this.setIdx(idx); this.isCycleOfInstallationFlag = isCycleOfInstallationFlag; } public Report(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.Report.IDX)); this.setJobType(rs.getString(DbConstants.Report.JOB_TYPE)); this.setCommissionNumber(rs.getString(DbConstants.Report.COMMISSION_NUMBER)); this.setChecklist(rs.getString(DbConstants.Report.CHECK_LIST)); this.setFinalRepair(rs.getString(DbConstants.Report.FINAL_REPAIR)); this.setCreateDate(rs.getDate(DbConstants.Report.CREATE_DATE)); this.setErrorFlag1(rs.getString(DbConstants.Report.ERROR_FLAG_1)); this.setErrorFlag2(rs.getString(DbConstants.Report.ERROR_FLAG_2)); this.setErrorFlag3(rs.getString(DbConstants.Report.ERROR_FLAG_3)); this.setSystemError(rs.getString(DbConstants.Report.SYSTEM_ERROR)); this.setErrorId1(rs.getString(DbConstants.Report.ERROR_ID_1)); this.setErrorId2(rs.getString(DbConstants.Report.ERROR_ID_2)); this.setErrorId3(rs.getString(DbConstants.Report.ERROR_ID_3)); this.setErrorH1(rs.getString(DbConstants.Report.ERROR_H_1)); this.setErrorH2(rs.getString(DbConstants.Report.ERROR_H_2)); this.setErrorH3(rs.getString(DbConstants.Report.ERROR_H_3)); this.setReasoning(rs.getString(DbConstants.Report.REASONING)); this.setGuid(rs.getString(DbConstants.Report.GUID)); this.setDistance(rs.getString(DbConstants.Report.DISTANCE)); this.setJobNumber(rs.getString(DbConstants.Report.JOB_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.Report.PERSONAL_NUMBER)); this.setCustomerSupport(rs.getString(DbConstants.Report.CUSTOMER_SUPPORT)); this.setCustomerSupportText(rs.getString(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT)); this.setReportStatus(new ReportStatus(rs.getString(DbConstants.Report.REPORT_STATUS))); this.setServicePlanMonth1(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_1)); this.setServicePlanMonth2(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_2)); this.setServicePlanMonth3(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_3)); this.setServicePlanMonth4(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_4)); this.setServicePlanMonth5(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_5)); this.setServicePlanMonth6(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_6)); this.setSafetyReport(rs.getString(DbConstants.Report.SAFETY_REPORT)); this.setMonthYear(rs.getString(DbConstants.Report.MONTH_YEAR)); this.setOrderNumber(rs.getString(DbConstants.Report.ORDER_NUMBER)); this.setSignatureGuId(rs.getString(DbConstants.Report.SIGNATURE_GUID)); this.setSignatureFlag(rs.getString(DbConstants.Report.SIGNATURE_FLAG)); this.setSignature(rs.getString(DbConstants.Report.SIGNATURE)); this.setSignatureInfo(rs.getString(DbConstants.Report.SIGNATURE_INFO)); this.setExpenses(rs.getString(DbConstants.Report.EXPENSES)); this.setIncidentAB(rs.getString(DbConstants.Report.INCIDENT_AB)); this.setPartialRepair(rs.getString(DbConstants.Report.PARTICAL_REPAIR)); this.setBilling(rs.getString(DbConstants.Report.BILLING)); this.setWorkType(rs.getString(DbConstants.Report.WORK_TYPE)); this.setCollectively(rs.getString(DbConstants.Report.COLLECTIVELY)); this.setNoMaterial(rs.getString(DbConstants.Report.NO_MATERIAL)); this.setCycleOfInstallation(rs.getString(DbConstants.Report.CYCLE_OF_INSTALLATION)); this.setNoForm1(rs.getString(DbConstants.Report.NO_FORM1)); this.setNoForm2(rs.getString(DbConstants.Report.NO_FORM2)); this.setNoForm3(rs.getString(DbConstants.Report.NO_FORM3)); this.setServiceRefused(rs.getString(DbConstants.Report.SERVICE_REFUSED)); this.setOpenPending(rs.getString(DbConstants.Report.OPEN_PENDING)); this.setGovernmentReport(rs.getString(DbConstants.Report.GOVERNMENT_REPORT)); this.setChecklistState(rs.getString(DbConstants.Report.CHECKLIST_STATE)); this.setChecklistSIA(rs.getString(DbConstants.Report.CHECKLIST_SIA)); this.setChecklistReady(rs.getString(DbConstants.Report.CHECKLIST_READY)); this.setChecklistInstruction(rs.getString(DbConstants.Report.CHECKLIST_INSTRUCTION)); this.setChecklistVKF(rs.getString(DbConstants.Report.CHECKLIST_VKF)); this.setChecklistTest(rs.getString(DbConstants.Report.CHECKLIST_TEST)); this.setSignatureName(rs.getString(DbConstants.Report.SIGNATURE_NAME)); this.setMonStk(rs.getString(DbConstants.Report.MON_STK)); this.setNextInterventionDate(rs.getDate(DbConstants.Report.NEXT_INTERVENTION_DATE)); this.setStateOfInstallation(rs.getString(DbConstants.Report.STATE_OF_INSTALLATION)); this.setNextInterventionCode(rs.getString(DbConstants.Report.NEXT_INTERVENTION_CODE)); } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Report.REPORT, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Report.REPORT, db, folder); } public JobType getJobType() { return this.jobType; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public void setJobType(JobType auart) { this.jobType = auart; } public String getChecklist() { return this.checklist; } public void setChecklist(String chckliste) { this.checklist = chckliste; } public String getFinalRepair() { return this.finalRepair; } public void setFinalRepair(String endrep) { this.finalRepair = endrep; } public boolean isFinalRepair() { return "X".equalsIgnoreCase(this.getFinalRepair()); //$NON-NLS-1$ } public void setFinalRepair(boolean endrep) { if (endrep) { this.setFinalRepair("X"); //$NON-NLS-1$ } else { this.setFinalRepair(""); //$NON-NLS-1$ } } public Date getCreateDate() { return this.createDate; } public void setCreateDate(Date erdat) { this.createDate = erdat; } public String getErrorFlag1() { return this.errorFlag1; } public void setErrorFlag1(String fm1) { this.errorFlag1 = fm1; } public String getErrorFlag2() { return this.errorFlag2; } public void setErrorFlag2(String fm2) { this.errorFlag2 = fm2; } public String getErrorFlag3() { return this.errorFlag3; } public void setErrorFlag3(String fm3) { this.errorFlag3 = fm3; } public String getSystemError() { return this.systemError; } public void setSystemError(String fmb) { this.systemError = fmb; } public boolean isErrorFlag1() { return "X".equalsIgnoreCase(this.getErrorFlag1()); //$NON-NLS-1$ } public void setErrorFlag1(boolean fm1) { if (fm1) { this.setErrorFlag1("X"); //$NON-NLS-1$ } else { this.setErrorFlag1(""); //$NON-NLS-1$ } } public String getErrorId1() { return this.errorId1; } public void setErrorId1(String fmc1) { this.errorId1 = fmc1; } public boolean isErrorFlag2() { return "X".equalsIgnoreCase(this.getErrorFlag2()); //$NON-NLS-1$ } public void setErrorFlag2(boolean fm2) { if (fm2) { this.setErrorFlag2("X"); //$NON-NLS-1$ } else { this.setErrorFlag2(""); //$NON-NLS-1$ } } public String getErrorId2() { return this.errorId2; } public void setErrorId2(String fmc2) { this.errorId2 = fmc2; } public boolean isErrorFlag3() { return "X".equalsIgnoreCase(this.getErrorFlag3()); //$NON-NLS-1$ } public void setErrorFlag3(boolean fm3) { if (fm3) { this.setErrorFlag3("X"); //$NON-NLS-1$ } else { this.setErrorFlag3(""); //$NON-NLS-1$ } } public String getErrorId3() { return this.errorId3; } public void setErrorId3(String fmc3) { this.errorId3 = fmc3; } public String getErrorH1() { return this.errorH1; } public void setErrorH1(String fmh1) { this.errorH1 = fmh1; } public String getErrorH2() { return this.errorH2; } public void setErrorH2(String fmh2) { this.errorH2 = fmh2; } public String getErrorH3() { return this.errorH3; } public void setErrorH3(String fmh3) { this.errorH3 = fmh3; } public String getReasoning() { return this.reasoning; } public void setReasoning(String folgerep) { this.reasoning = folgerep; } public boolean isReasoning() { return "X".equalsIgnoreCase(this.getReasoning()); //$NON-NLS-1$ } public void setReasoning(boolean folgerep) { if (folgerep) { this.setReasoning("X"); //$NON-NLS-1$ } else { this.setReasoning(""); //$NON-NLS-1$ } } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public String getDistance() { return this.distance; } public void setDistance(String km) { this.distance = km; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getCustomerSupport() { return this.customerSupport; } public void setCustomerSupport(String rapsend) { this.customerSupport = rapsend; } public String getCustomerSupportText() { return this.customerSupportText; } public void setCustomerSupportText(String rapsendcom) { this.customerSupportText = rapsendcom; } public ReportStatus getReportStatus() { return this.reportStatus; } public void setReportStatus(String reportstatus) { this.reportStatus.set(reportstatus); } public void setReportStatus(ReportStatus reportstatus) { this.reportStatus = reportstatus; } public String getServicePlanMonth1() { return this.servicePlanMonth1; } public void setServicePlanMonth1(String savlfd1) { this.servicePlanMonth1 = savlfd1; } public String getServicePlanMonth2() { return this.servicePlanMonth2; } public void setServicePlanMonth2(String savlfd2) { this.servicePlanMonth2 = savlfd2; } public String getServicePlanMonth3() { return this.servicePlanMonth3; } public void setServicePlanMonth3(String savlfd3) { this.servicePlanMonth3 = savlfd3; } public String getServicePlanMonth4() { return this.servicePlanMonth4; } public void setServicePlanMonth4(String savlfd4) { this.servicePlanMonth4 = savlfd4; } public String getServicePlanMonth5() { return this.servicePlanMonth5; } public void setServicePlanMonth5(String savlfd5) { this.servicePlanMonth5 = savlfd5; } public String getServicePlanMonth6() { return this.servicePlanMonth6; } public void setServicePlanMonth6(String savlfd6) { this.servicePlanMonth6 = savlfd6; } public String getSafetyReport() { return this.safetyReport; } public void setSafetyReport(String secrap) { this.safetyReport = secrap; } public boolean isSafetyReport() { return "X".equalsIgnoreCase(this.getSafetyReport()); //$NON-NLS-1$ } public void setSafetyReport(boolean secrap) { if (secrap) { this.setSafetyReport("X"); //$NON-NLS-1$ } else { this.setSafetyReport(""); //$NON-NLS-1$ } } public String getSignatureFlag() { return this.signatureFlag; } public void setSignatureFlag(String signflg) { this.signatureFlag = signflg; } public boolean isSignatureFlag() { return "X".equalsIgnoreCase(this.getSignatureFlag()); //$NON-NLS-1$ } public void setSignatureFlag(boolean signflg) { if (signflg) { this.setSignatureFlag("X"); //$NON-NLS-1$ } else { this.setSignatureFlag(""); //$NON-NLS-1$ } } public String getExpenses() { return this.expenses; } public void setExpenses(String spesen) { this.expenses = spesen; } public String getIncidentAB() { return this.incidentAB; } public void setIncidentAB(String storc) { this.incidentAB = storc; } public String getPartialRepair() { return this.partialRepair; } public void setPartialRepair(String teilrep) { this.partialRepair = teilrep; } public boolean isPartialRepair() { return "X".equalsIgnoreCase(this.getPartialRepair()); //$NON-NLS-1$ } public void setPartialRepair(boolean teilrep) { if (teilrep) { this.setPartialRepair("X"); //$NON-NLS-1$ } else { this.setPartialRepair(""); //$NON-NLS-1$ } } public String getBilling() { return this.billing; } public void setBilling(String verrc) { this.billing = verrc; } public String getSignatureInfo() { return this.signatureInfo; } public void setSignatureInfo(String signinfo) { this.signatureInfo = signinfo; } public boolean isSignatureInfo() { return !"".equalsIgnoreCase(this.getSignatureInfo()); //$NON-NLS-1$ } public String getMonthYear() { return this.monthYear; } public void setMonthYear(String saverl) { this.monthYear = saverl; } public String getOrderNumber() { return this.orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public String getSignatureGuId() { return this.signatureGuId; } public void setSignatureGuId(String signguid) { this.signatureGuId = signguid; } public String getSignature() { return this.signature; } public void setSignature(String signpic) { this.signature = signpic; } public String getWorkType() { return this.workType; } public void setWorkType(String arba) { this.workType = arba; } public String getCollectively() { return this.collectively; } public void setCollectively(String signbundle) { this.collectively = signbundle; } public void setCollectively(boolean signbundle) { if (signbundle) { this.setCollectively("X"); //$NON-NLS-1$ } else { this.setCollectively(""); //$NON-NLS-1$ } } public boolean isCollectively() { return "X".equalsIgnoreCase(getCollectively()); //$NON-NLS-1$ } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String anlnr) { this.commissionNumber = anlnr; } public String getNoMaterial() { return noMaterial; } public void setNoMaterial(String noMaterial) { this.noMaterial = noMaterial; } public void setNoMaterial(boolean noMaterial) { if (noMaterial) { this.setNoMaterial("X"); //$NON-NLS-1$ } else { this.setNoMaterial(""); //$NON-NLS-1$ } } public boolean isNoMaterial() { return "X".equalsIgnoreCase(getNoMaterial()); //$NON-NLS-1$ } public List getTimes() { return this.times; } public void setTimes(DatabaseUtil dbutil, List mTimes) { this.times = mTimes; this.currentTime = 0; dbutil.insertJobReportTimeList(this); } public String getCycleOfInstallation() { return cycleOfInstallation; } public void setCycleOfInstallation(String cycleOfInstallation) { this.cycleOfInstallation = cycleOfInstallation; } public String getNoForm1() { return noForm1; } public void setNoForm1(String noForm1) { this.noForm1 = noForm1; } public String getNoForm2() { return noForm2; } public void setNoForm2(String noForm2) { this.noForm2 = noForm2; } public String getNoForm3() { return noForm3; } public void setNoForm3(String noForm3) { this.noForm3 = noForm3; } public String getServiceRefused() { return serviceRefused; } public void setServiceRefused(String serviceRefused) { this.serviceRefused = serviceRefused; } public String getOpenPending() { return openPending; } public void setOpenPending(String openPending) { this.openPending = openPending; } public boolean isOpenPending() { return "X".equalsIgnoreCase(getOpenPending()); //$NON-NLS-1$ } public void setOpenPending(boolean isOpenPending) { if (isOpenPending) { this.setOpenPending("X"); //$NON-NLS-1$ } else { this.setOpenPending(""); //$NON-NLS-1$ } } public String getGovernmentReport() { return governmentReport; } public void setGovernmentReport(String governmentReport) { this.governmentReport = governmentReport; } public boolean isGovernmentReport() { return "X".equalsIgnoreCase(getGovernmentReport()); //$NON-NLS-1$ } public void setGovernmentReport(boolean isGovernmentReport) { if (isGovernmentReport) { this.setGovernmentReport("X"); //$NON-NLS-1$ } else { this.setGovernmentReport(""); //$NON-NLS-1$ } } public String getChecklistState() { return checklistState; } public void setChecklistState(String checklistState) { this.checklistState = checklistState; } public boolean isChecklistState() { return "X".equalsIgnoreCase(getChecklistState()); //$NON-NLS-1$ } public boolean isChecklistStateUnselected() { return "U".equalsIgnoreCase(getChecklistState()); //$NON-NLS-1$ } public void setChecklistState(boolean isChecklistState) { if (isChecklistState) { this.setChecklistState("X"); //$NON-NLS-1$ } else { this.setChecklistState(""); //$NON-NLS-1$ } } public String getChecklistSIA() { return checklistSIA; } public void setChecklistSIA(String checklistSIA) { this.checklistSIA = checklistSIA; } public boolean isChecklistSIA() { return "X".equalsIgnoreCase(getChecklistSIA()); //$NON-NLS-1$ } public boolean isChecklistSIAUnselected() { return "U".equalsIgnoreCase(getChecklistSIA()); //$NON-NLS-1$ } public void setChecklistSIA(boolean isChecklistSIA) { if (isChecklistSIA) { this.setChecklistSIA("X"); //$NON-NLS-1$ } else { this.setChecklistSIA(""); //$NON-NLS-1$ } } public String getChecklistReady() { return checklistReady; } public void setChecklistReady(String checklistReady) { this.checklistReady = checklistReady; } public boolean isChecklistReady() { return "X".equalsIgnoreCase(getChecklistReady()); //$NON-NLS-1$ } public boolean isChecklistReadyUnselected() { return "U".equalsIgnoreCase(getChecklistReady()); //$NON-NLS-1$ } public void setChecklistReady(boolean isChecklistReady) { if (isChecklistReady) { this.setChecklistReady("X"); //$NON-NLS-1$ } else { this.setChecklistReady(""); //$NON-NLS-1$ } } public String getChecklistInstruction() { return checklistInstruction; } public void setChecklistInstruction(String checklistInstruction) { this.checklistInstruction = checklistInstruction; } public boolean isChecklistInstruction() { return "X".equalsIgnoreCase(getChecklistInstruction()); //$NON-NLS-1$ } public boolean isChecklistInstructionUnselected() { return "U".equalsIgnoreCase(getChecklistInstruction()); //$NON-NLS-1$ } public void setChecklistInstruction(boolean isChecklistInstruction) { if (isChecklistInstruction) { this.setChecklistInstruction("X"); //$NON-NLS-1$ } else { this.setChecklistInstruction(""); //$NON-NLS-1$ } } public String getChecklistVKF() { return checklistVKF; } public void setChecklistVKF(String checklistVKF) { this.checklistVKF = checklistVKF; } public boolean isChecklistVKF() { return "X".equalsIgnoreCase(getChecklistVKF()); //$NON-NLS-1$ } public boolean isChecklistVKFUnselected() { return "U".equalsIgnoreCase(getChecklistVKF()); //$NON-NLS-1$ } public void setChecklistVKF(boolean isChecklistVKF) { if (isChecklistVKF) { this.setChecklistVKF("X"); //$NON-NLS-1$ } else { this.setChecklistVKF(""); //$NON-NLS-1$ } } public String getChecklistTest() { return checklistTest; } public void setChecklistTest(String checklistTest) { this.checklistTest = checklistTest; } public boolean isChecklistTest() { return "X".equalsIgnoreCase(getChecklistTest()); //$NON-NLS-1$ } public boolean isChecklistTestUnselected() { return "U".equalsIgnoreCase(getChecklistTest()); //$NON-NLS-1$ } public void setChecklistTest(boolean isChecklistTest) { if (isChecklistTest) { this.setChecklistTest("X"); //$NON-NLS-1$ } else { this.setChecklistTest(""); //$NON-NLS-1$ } } public String getSignatureName() { return this.signatureName; } public void setSignatureName(String signName) { this.signatureName = signName; } public boolean isSignatureName() { return !"".equalsIgnoreCase(this.getSignatureName()); //$NON-NLS-1$ } public String getMonStk() { return monStk; } public void setMonStk(String monStk) { this.monStk = monStk; } public Date getNextInterventionDate() { return this.nextInterventionDate; } public void setNextInterventionDate(Date nextInterventionDate) { this.nextInterventionDate = nextInterventionDate; } public String getStateOfInstallation() { return stateOfInstallation; } public void setStateOfInstallation(String stateOfInstallation) { this.stateOfInstallation = stateOfInstallation; } public String getNextInterventionCode() { return this.nextInterventionCode; } public void setNextInterventionCode(String nextInterventionCode) { this.nextInterventionCode = nextInterventionCode; } /** * The change of the type of work in report have to be assumed to all existing timestamps of the report. * This concerns only the job types REP and SAV. * @param arba * @param dbutil */ public void setTimesWorkType(String arba, DatabaseUtil dbutil) { this.workType = arba; if(getJobType().isREP() || getJobType().isSAV()) { if (getTimes().size() > 0 && !workType.equalsIgnoreCase(getTimes().get(0).getWorkTypeCode())) { for (int i = 0; i < getTimes().size(); i++) { getTimes().get(i).setWorkTypeCode(getWorkType());; } setTimes(dbutil, new ArrayList(getTimes())); } } } /** * @param dbutil * @return amount of reports loaded for this job */ public int loadTimes(DatabaseUtil dbutil) { this.times = dbutil.selectJobReportTimeListByReport(this); boolean isTimeUpdate = false; for (int i = 0; i < times.size(); i++) { JobReportTime jobReportTime = times.get(i); if(CommonConstants.PLEASE_SELECT.equalsIgnoreCase(jobReportTime.getWorkTypeCode()) && !this.jobType.isMON()) { // in case start capturing time from TimeSheet default arba is wrong. isTimeUpdate = true; times.get(i).setWorkTypeCode(dbutil.selectJobByJobIdAndJobType(this.jobNumber, this.jobType.getCode()).getDefaultJobTimeARBA()); } } if(isTimeUpdate) { setTimes(dbutil, times); } this.currentTime = 0; return this.times.size(); } /** * @return The report currently set in the list */ public JobReportTime getCurrentTime() { if (this.times.isEmpty()) return new JobReportTime(); else return this.times.get(this.currentTime); } public void checkIfTimeStartOverOndDay(DatabaseUtil dbutil) { // log.info("check if time started over one day."); loadTimes(dbutil); Iterator itr = times.iterator(); while (itr.hasNext()) { JobReportTime jobReportTime = itr.next(); if (jobReportTime.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) { Calendar latestTime = Calendar.getInstance(); latestTime.setTime(jobReportTime.getDate()); latestTime.set(latestTime.get(Calendar.YEAR), latestTime.get(Calendar.MONTH), latestTime.get(Calendar.DATE), 23, 59, 59); if(Calendar.getInstance().getTimeInMillis() > latestTime.getTimeInMillis()){ // now after start date 23.59 -> set stop time to 23.59. jobReportTime.setStopTime(latestTime.getTime()); setTimes(dbutil, new ArrayList(times)); Job job = dbutil.selectJobByGUID(guId); job.setStatus(JobStatus.RECEIVED); dbutil.updateJob(job); break; } } } } public boolean isChecklistCompleted() { return true; } public boolean isChedklistEdited() { if (isChecklistStateUnselected() && isChecklistSIAUnselected() && isChecklistReadyUnselected() && isChecklistInstructionUnselected() && isChecklistVKFUnselected() && isChecklistTestUnselected()) { return false; } return true; } public List getParts() { return this.mats; } /** * @param dbutil * @return amount of reports loaded for this job */ public int loadParts(DatabaseUtil dbutil) { this.mats = dbutil.selectReportMaterialList(getGuId()); return this.mats.size(); } public List getMessages() { return this.messages; } /** * @param dbutil * @return amount of messages loaded for this report */ public int loadMessages(DatabaseUtil dbutil) { this.messages = dbutil.selectJobMessageListByReport(this); return this.messages.size(); } public List getMeasurements() { return this.measurements; } /** * @param dbutil * @return amount of measurements loaded for this report */ public int loadMeasurements(DatabaseUtil dbutil) { this.measurements = dbutil.selectReportMeasurementListByReport(this); return this.measurements.size(); } /** * @return Latest (most up to date) report of this job (current report is * set to this one) */ public JobReportTime getLatestReport() { this.currentTime = 0; return getCurrentTime(); } public boolean hasNextTime() { return this.times.size() > this.currentTime + 1; } /** * @return Next report of this job (in chronological order) * @throws IndexOutOfBoundsException */ public JobReportTime getNextTime() throws IndexOutOfBoundsException { int location = this.currentTime + 1; JobReportTime time = this.times.get(location); this.currentTime = location; return time; } public boolean isValid() { boolean result = true; StringBuilder error = new StringBuilder(); error.append("\n"); if ("".equals(getCommissionNumber().trim())) { error.append("CommissionNumber required \n"); result = false; } if (!getJobType().isMON() && "".equals(getWorkType().trim())) { error.append("WorkType required \n" ); result = false; } // Arbeitsart 05: Vertragsservice // Checkliste 00: Bitte w�hlen.. (Initialwert) // SAV ausgef�hrt (Monat) 00: --- (Initialwert) // SAV ausgef�hrt (Jahr) 00: --- (Initialwert) if (CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT.equalsIgnoreCase(getWorkType()) && getMonthYear().isEmpty()) { error.append("WorkType & MonthYear required \n" ); result = false; } // or // if ("".equals(getChecklist().trim())) { if ((getJobType().isSAV() && !(getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA) || getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_MAINTENANCE_VONOVIA))) || getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT)) { error.append("Checklist required \n" ); result = false; } } if (!CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER.equalsIgnoreCase(getCustomerSupport()) && !getCustomerSupport().trim().isEmpty() && getCustomerSupportText().trim().isEmpty()) { error.append("CustomerSupport & CustomerSupportText required \n"); result = false; } if (isCycleOfInstallationFlag && getCycleOfInstallation().isEmpty()) { error.append("Cycle of installation required \n" ); result = false; } log.info("is report valid -> " + result + " " + error.toString()); return result; } public List getImageAttachments() { return this.reportImageAttachments; } /** * @param dbutil * @return amount of reportImageAttachments loaded for this report */ public int loadImageAttachments(DatabaseUtil dbutil) { this.reportImageAttachments = dbutil.selectReportJobFileImageListByReport(this); return this.reportImageAttachments.size(); } public List getDocumentAttachments() { return this.reportDocumentAttachments; } /** * @param dbutil * @return amount of reportDocumentAttachments loaded for this report */ public int loadDocumentAttachments(DatabaseUtil dbutil) { this.reportDocumentAttachments = dbutil.selectReportJobFileDocumentListByReport(this); return this.reportDocumentAttachments.size(); } public List getFormInstances() { return this.formInstances; } /** * @param dbutil * @return amount of formInstances loaded for this report */ public int loadFormInstances(DatabaseUtil dbutil) { this.formInstances = dbutil.selectFormInstanceListByGuid(getGuId()); return this.formInstances.size(); } public Map> getDocumentFormDescMap() { Map> documentFormDescMap = new HashMap>(); for (JobFile jobFile : getDocumentAttachments()) { if (!documentFormDescMap.containsKey(jobFile.getFormDesc())) { List documents = new ArrayList(); documents.add(jobFile); documentFormDescMap.put(jobFile.getFormDesc(), documents); } else { documentFormDescMap.get(jobFile.getFormDesc()).add(jobFile); } } return documentFormDescMap; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ReportMaterial.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMATORD */ public class ReportMaterial { private String guId = ""; //$NON-NLS-1$ private String sparePartNumber = ""; //$NON-NLS-1$ private int personalNumber = 0; private String commissionNumber = ""; //$NON-NLS-1$ private String amount = ""; //$NON-NLS-1$ private String delivery = ""; //$NON-NLS-1$ private String expressDelivery = ""; //$NON-NLS-1$ private String accountCode = ""; //$NON-NLS-1$ private String unit = ""; //$NON-NLS-1$ private int idx = 0; private String productName = ""; //$NON-NLS-1$ private String price = ""; //$NON-NLS-1$ private String barcode = ""; //$NON-NLS-1$ private String K14 = ""; //$NON-NLS-1$ private String explanationText = ""; private String otherTypeFlag = ""; public ReportMaterial() { // constructor } public ReportMaterial(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.ReportMaterial.IDX)); this.setExpressDelivery(rs.getString(DbConstants.ReportMaterial.EXPRESS_DELIVERY)); this.setGuid(rs.getString(DbConstants.ReportMaterial.GUID)); this.setSparePartNumber(rs.getString(DbConstants.ReportMaterial.NUMBER)); this.setDelivery(rs.getString(DbConstants.ReportMaterial.DELIVERY)); this.setPersonalNumber(rs.getInt(DbConstants.ReportMaterial.PERSONAL_NUMBER)); this.setAmount(rs.getString(DbConstants.ReportMaterial.AMOUNT)); this.setCommissionNumber(rs.getString(DbConstants.ReportMaterial.COMMISSION_NUMBER)); this.setAccountCode(rs.getString(DbConstants.ReportMaterial.ACCOUNT_CODE)); this.setUnit(rs.getString(DbConstants.ReportMaterial.UNIT)); this.setProductName(rs.getString(DbConstants.ReportMaterial.NAME)); this.setPrice(rs.getString(DbConstants.ReportMaterial.PRICE)); this.setBarcode(rs.getString(DbConstants.ReportMaterial.BARCODE)); this.setK14(rs.getString(DbConstants.ReportMaterial.K14)); this.setExplanationText(rs.getString(DbConstants.ReportMaterial.EXPLANATION_TEXT)); this.setOtherTypeFlag(rs.getString(DbConstants.ReportMaterial.OTHER_TYPE_FLAG)); } public String getExpressDelivery() { return this.expressDelivery; } public void setExpressDelivery(String expr) { this.expressDelivery = expr; } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public String getSparePartNumber() { return this.sparePartNumber; } public void setSparePartNumber(String matnr) { this.sparePartNumber = matnr; } public String getDelivery() { return this.delivery; } public void setDelivery(String mlif) { this.delivery = mlif; } public boolean isDelivery() { return "X".equalsIgnoreCase(this.getDelivery()); //$NON-NLS-1$ } public void setDelivery(boolean mlif) { if (mlif) { this.setDelivery("X"); //$NON-NLS-1$ } else { this.setDelivery(""); //$NON-NLS-1$ } } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getAmount() { return this.amount; } public void setAmount(String amount) { this.amount = amount; } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public String getAccountCode() { return this.accountCode; } public void setAccountCode(String verrc) { this.accountCode = verrc; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public String getUnit() { return this.unit; } public void setUnit(String maunit) { this.unit = maunit; } public String getProductName() { return this.productName; } public void setProductName(String maktx) { this.productName = maktx; } public String getPrice() { return this.price; } public void setPrice(String price) { this.price = price; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getK14() { return this.K14; } public void setK14(String k14) { this.K14 = k14; } public boolean isK14() { return "1".equalsIgnoreCase(this.getK14()); //$NON-NLS-1$ } public void setK14(boolean k14) { if (k14) { this.setK14("1"); //$NON-NLS-1$ } else { this.setK14("0"); //$NON-NLS-1$ } } public String getExplanationText() { return explanationText; } public void setExplanationText(String explanationText) { this.explanationText = explanationText; } public String getOtherTypeFlag() { return otherTypeFlag; } public void setOtherTypeFlag(String otherTypeFlag) { this.otherTypeFlag = otherTypeFlag; } public boolean isOtherType() { return "1".equalsIgnoreCase(this.getOtherTypeFlag()); //$NON-NLS-1$ } public void setOtherType(boolean otherType) { if (otherType) { this.setOtherTypeFlag("1"); //$NON-NLS-1$ } else { this.setOtherTypeFlag("0"); //$NON-NLS-1$ } } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ReportMeasurement.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMEAS */ public class ReportMeasurement { private String guId = ""; private String measurementPoint = ""; private int personalNumber = 0; private String commissionNumber = ""; private String neasurement = ""; private String dynamicPowerPeakValue = ""; private String dynamicTime = ""; private String staticEndPower = ""; private String deviceType = ""; private String sNOfDevice = ""; private Date calibrationDate = new Date(); public ReportMeasurement() { // constructor } public ReportMeasurement(RecordSet rs) { this.setGuid(rs.getString(DbConstants.ReportMeasurement.GUID)); this.setMeasurementPoint(rs.getString(DbConstants.ReportMeasurement.MEASURING_POINT)); this.setCommissionNumber(rs.getString(DbConstants.ReportMeasurement.COMMISSION_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.ReportMeasurement.PERSONAL_NUMBER)); this.setMeasurement(rs.getString(DbConstants.ReportMeasurement.MEASUREMENT)); this.setDynamicPowerPeakValue(rs.getString(DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE)); this.setDynamicTime(rs.getString(DbConstants.ReportMeasurement.DYNAMIC_TIME)); this.setStaticEndPower(rs.getString(DbConstants.ReportMeasurement.STATIC_END_POWER)); this.setDeviceType(rs.getString(DbConstants.ReportMeasurement.DEVICE_TYPE)); this.setSNOfDevice(rs.getString(DbConstants.ReportMeasurement.SN_OF_DEVICE)); this.setCalibrationDate(rs.getDate(DbConstants.ReportMeasurement.CALIBRATION_DATE)); } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getMeasurementPoint() { return measurementPoint; } public void setMeasurementPoint(String measurementPoint) { this.measurementPoint = measurementPoint; } public String getCommissionNumber() { return commissionNumber; } public void setCommissionNumber(String CommissionNumber) { this.commissionNumber = CommissionNumber; } public String getMeasurement() { return neasurement; } public void setMeasurement(String measurement) { neasurement = measurement; } public String getDynamicPowerPeakValue() { return dynamicPowerPeakValue; } public void setDynamicPowerPeakValue(String dynamicPowerPeakValue) { this.dynamicPowerPeakValue = dynamicPowerPeakValue; } public String getDynamicTime() { return dynamicTime; } public void setDynamicTime(String dynamicTime) { this.dynamicTime = dynamicTime; } public String getStaticEndPower() { return staticEndPower; } public void setStaticEndPower(String staticEndPower) { this.staticEndPower = staticEndPower; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getSNOfDevice() { return sNOfDevice; } public void setSNOfDevice(String sNOfDevice) { this.sNOfDevice = sNOfDevice; } public Date getCalibrationDate() { return this.calibrationDate; } public void setCalibrationDate(Date calibrationDate) { this.calibrationDate = calibrationDate; } public void setGuId(String guId) { this.guId = guId; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ReportMessage.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDCMSGC */ public class ReportMessage { private String messageCode; private String message; private String mKND; private String mKDZ; private String mABTL; private String refreshFlag = ""; //$NON-NLS-1$ ReportMessage() { } public ReportMessage(RecordSet rs) { this.setMessageCode(rs.getString(DbConstants.ReportMessage.CODE)); this.setMessage(rs.getString(DbConstants.ReportMessage.TEXT)); this.setKND(rs.getString(DbConstants.ReportMessage.KND)); this.setKDZ(rs.getString(DbConstants.ReportMessage.KDZ)); this.setABTL(rs.getString(DbConstants.ReportMessage.ABTL)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getMessageCode() { return this.messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getKND() { return this.mKND; } public void setKND(String knd) { this.mKND = knd; } public String getKDZ() { return this.mKDZ; } public void setKDZ(String kdz) { this.mKDZ = kdz; } public String getABTL() { return this.mABTL; } public void setABTL(String abtl) { this.mABTL = abtl; } public boolean isKND() { boolean result = false; if ("X".equalsIgnoreCase(this.getKND())) { //$NON-NLS-1$ result = true; } return result; } public void setKND(boolean isKND) { if (isKND) this.setKND("X"); //$NON-NLS-1$ } public boolean isKDZ() { boolean result = false; if ("X".equalsIgnoreCase(this.getKDZ())) { //$NON-NLS-1$ result = true; } return result; } public void setKDZ(boolean isKDZ) { if (isKDZ) { this.setKDZ("X"); //$NON-NLS-1$ } } public boolean isABTL() { boolean result = false; if ("X".equalsIgnoreCase(this.getABTL())) { //$NON-NLS-1$ result = true; } return result; } public void setABTL(boolean isABTL) { if (isABTL) this.setABTL("X"); //$NON-NLS-1$ } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ServerJob.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMC */ public class ServerJob { private String jobNumber; private JobType jobType; private String commissionNumber; private String street; private String city; private String postalCode; private String location; private String serviceContractType; private String monthYear; private String personalNumber; ServerJob() { } public ServerJob(RecordSet rs) { this.setJobType(rs.getString(DbConstants.ServerJob.JOB_TYPE)); this.setCity(rs.getString(DbConstants.ServerJob.CITY)); this.setJobNumber(rs.getString(DbConstants.ServerJob.JOB_NUMBER)); this.setLocation(rs.getString(DbConstants.ServerJob.LOCATION)); this.setPostalCode(rs.getString(DbConstants.ServerJob.PASTAL_CODE)); this.setServiceContractType(rs.getString(DbConstants.ServerJob.SERVICE_CONTRACT_TYPE)); this.setMonthYear(rs.getString(DbConstants.ServerJob.MONTH_YEAR)); this.setStreet(rs.getString(DbConstants.ServerJob.STREET)); this.setCommissionNumber(rs.getString(DbConstants.ServerJob.COMMISSION_NUMBER)); this.setPersonalNumber(rs.getString(DbConstants.ServerJob.PERSONAL_NUMBER)); } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getCity() { return this.city; } public void setCity(String city1) { this.city = city1; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getLocation() { return this.location; } public void setLocation(String name4) { this.location = name4; } public String getPostalCode() { return this.postalCode; } public void setPostalCode(String post_code1) { this.postalCode = post_code1; } public String getServiceContractType() { return this.serviceContractType; } public void setServiceContractType(String savc) { this.serviceContractType = savc; } public String getMonthYear() { return this.monthYear; } public void setMonthYear(String savoff) { this.monthYear = savoff; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public String getCommissionNumber() { return this.commissionNumber; } public String getcommissionNumberNoLeadingZero() { String vbeln = this.commissionNumber; while (vbeln.length() > 0 && vbeln.charAt(0) == '0') { vbeln = vbeln.substring(1); } return vbeln; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public void setPersonalNumber(String lkdpernr) { this.personalNumber = lkdpernr; } public String getPersonalNumber() { return this.personalNumber; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ServiceRefused.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBBEGRSAV */ public class ServiceRefused { private String code = ""; private String language = ""; private String text = ""; private String refreshFlag = ""; ServiceRefused() { } public ServiceRefused(RecordSet rs) { this.setCode((rs.getString(DbConstants.ServiceRefused.SAVRET))); this.setLanguage(rs.getString(DbConstants.ServiceRefused.LANGUAGE)); this.setText(rs.getString(DbConstants.ServiceRefused.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.ServiceRefused.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/ShortMessage.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZSHORTMSG */ public class ShortMessage { private int personalNumber = 0; private String messageKey = ""; //$NON-NLS-1$ private String subject = ""; //$NON-NLS-1$ private String confirm = ""; //$NON-NLS-1$ private String message = ""; //$NON-NLS-1$ private String status = ""; //$NON-NLS-1$ private String receiveDate = ""; //$NON-NLS-1$ private Date receiveTime = new Date(0); public ShortMessage() { // constructor } public ShortMessage(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.ShortMessage.PERSONAL_NUMBER)); this.setMessageKey(rs.getString(DbConstants.ShortMessage.MESSAGE_KEY)); this.setSubject(rs.getString(DbConstants.ShortMessage.SUBJECT)); this.setConfirm(rs.getString(DbConstants.ShortMessage.CONFIRM)); this.setMessage(rs.getString(DbConstants.ShortMessage.MESSAGE)); this.setStatus(rs.getString(DbConstants.ShortMessage.STATUS)); this.setReceiveDate(rs.getString(DbConstants.ShortMessage.RECEIVED_DATE)); this.setReceiveTime(rs.getDate(DbConstants.ShortMessage.RECEIVED_TIME)); } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getMessageKey() { return messageKey; } public void setMessageKey(String tdname) { this.messageKey = tdname; } public String getSubject() { return subject; } public void setSubject(String betreff) { this.subject = betreff; } public String getConfirm() { return confirm; } public boolean isConfirmed() { return "X".equalsIgnoreCase(this.getConfirm()); //$NON-NLS-1$ } public void isConfirmed(boolean isConfirmed) { if (isConfirmed) { this.setConfirm("X"); //$NON-NLS-1$ } else { this.setConfirm(""); //$NON-NLS-1$ } } public void setConfirm(String bestaetigt) { this.confirm = bestaetigt; } public String getMessage() { return message; } public void setMessage(String ltext) { this.message = ltext; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getReceiveDate() { return receiveDate; } public void setReceiveDate(String erhalten) { this.receiveDate = erhalten; } public Date getReceiveTime() { return receiveTime; } public void setReceiveTime(Date eingang) { this.receiveTime = eingang; } public int getStatusColor() { int result; if (getStatus().equalsIgnoreCase(CommonConstants.ShortMessage.Status.RECEIVED)) { result = LayoutUtils.DEFAULT_RED; } else if (getStatus().equalsIgnoreCase(CommonConstants.ShortMessage.Status.READ)) { result = LayoutUtils.DEFAULT_GREEN; } else { result = LayoutUtils.DEFAULT_DARK_GRAY; } return result; } public String getConfirmedMsg() { if (isConfirmed()) { return "!"; //$NON-NLS-1$ } return ""; //$NON-NLS-1$ } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/StateOfInstallation.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBBTRZUSTT */ public class StateOfInstallation { private String code = ""; private String text = ""; private String refreshFlag = ""; StateOfInstallation() { } public StateOfInstallation(RecordSet rs) { this.setCode(rs.getString(DbConstants.StateOfInstallation.CODE)); this.setText(rs.getString(DbConstants.StateOfInstallation.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.StateOfInstallation.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/TimeSheet.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Calendar; import java.util.Date; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.TimesheetValidation; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.util.DateUtils; /** * Object representing users working time. Implements Comparable interface * because the list of times of a certain day must be in the correct order. * In the Database -> ZKDMATIME * @author paulib * */ public class TimeSheet implements Comparable { private int idx = 0; private int personalNumber = 0; private Date date = Calendar.getInstance().getTime(); private Date startTime = DateUtils.getInitialDateTime(); private Date stopTime = DateUtils.getInitialDateTime(); private String commissionNumber = ""; //$NON-NLS-1$ private String costCenter = ""; //$NON-NLS-1$ private String workTypeCode = ""; //$NON-NLS-1$ private String callFlag = ""; //$NON-NLS-1$ protected TimeSheet() { } public TimeSheet(int pernr) { this.setPersonalNumber(pernr); } public TimeSheet(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.TimeSheet.IDX)); this.setPersonalNumber(rs.getInt(DbConstants.TimeSheet.PERSONAL_NUMBER)); this.setDate(rs.getDate(DbConstants.TimeSheet.DATE)); this.setStartTime(rs.getDate(DbConstants.TimeSheet.START_TIME)); this.setStopTime(rs.getDate(DbConstants.TimeSheet.STOP_TIME)); this.setCostCenter(rs.getString(DbConstants.TimeSheet.COST_CENTER)); this.setWorkTypeCode(rs.getString(DbConstants.TimeSheet.WORK_TYPE_CODE)); this.setCallFlag(rs.getString(DbConstants.TimeSheet.CALL_FLAG)); } @Override public int compareTo(Object o) { TimeSheet zkdmatime = (TimeSheet) o; return this.getStartTime().compareTo(zkdmatime.getStartTime()); } public Date getStopTime() { return this.stopTime; } public void setStopTime(Date bis) { this.stopTime = bis; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getCostCenter() { return this.costCenter; } public void setCostCenter(String kostl) { this.costCenter = kostl; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public boolean isCallFlag() { return "X".equalsIgnoreCase(this.getCallFlag()); //$NON-NLS-1$ } public void setCallFlag(boolean pikett) { if (pikett) { this.setCallFlag("X"); //$NON-NLS-1$ } else { this.setCallFlag(""); //$NON-NLS-1$ } } public String getCallFlag() { return this.callFlag; } public void setCallFlag(String pikett) { this.callFlag = pikett; } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String vbln) { this.commissionNumber = vbln; } public Date getStartTime() { return this.startTime; } public void setStartTime(Date von) { this.startTime = von; } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String arba) { this.workTypeCode = arba; } public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public TimesheetValidation validate() { TimesheetValidation result = new TimesheetValidation(); // No working type selected if ("".equalsIgnoreCase(getWorkTypeCode()) || "99".equalsIgnoreCase(getWorkTypeCode())) { //$NON-NLS-1$ //$NON-NLS-2$ result.setValid(false); result.setInitialArbaError(true); } // Initial value for VON is still set if (getStartTime().compareTo(DateUtils.getInitialDateTime()) == 0) { result.setValid(false); result.setInitialVonError(true); } // Initial value for BIS is still set if (getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) { result.setValid(false); result.setInitialBisError(true); } // Initial value for VON is still set if (getStartTime().compareTo(getStopTime()) > 0) { result.setValid(false); result.setVonBiggerBisError(true); } return result; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.TimeSheet.TIME_SHEET, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.TimeSheet.TIME_SHEET, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/CalendarStatus.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class CalendarStatus { /** * initial not a valid status, only used by the constructor */ public static final String INITIAL = "00"; //$NON-NLS-1$ /** * new */ public static final String SAVED = "01"; //$NON-NLS-1$ /** * sent */ public static final String SENT = "03"; //$NON-NLS-1$ private String code; public CalendarStatus() { set(INITIAL); } public CalendarStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isSAVED() { return this.code.equalsIgnoreCase(SAVED); } public boolean isSENT() { return this.code.equalsIgnoreCase(SENT); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/DeliveryStatus.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class DeliveryStatus { /** * initial not a valid status, only used by the constructor */ public static final String INITIAL = ""; public static final String OPEN = "O"; public static final String PART_DELIVERED = "T"; public static final String DELIVERED = "G"; private String code; public DeliveryStatus() { set(INITIAL); } public DeliveryStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isOPEN() { return this.code.equalsIgnoreCase(OPEN); } public boolean isPART_DELIVERED() { return this.code.equalsIgnoreCase(PART_DELIVERED); } public boolean isDELIVERED() { return this.code.equalsIgnoreCase(DELIVERED); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/ExpenseValidation.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class ExpenseValidation { // valid flag private boolean mValid = true; // Error indicator private boolean mTgSpesenError = false; private boolean mDivSpesenError = false; private boolean mAbzugError = false; private boolean mBVonError = false; private boolean mBBisError = false; private boolean mBTotError = false; public boolean isValid() { return mValid; } public void setValid(boolean valid) { this.mValid = valid; } public boolean isTgSpesenError() { return mTgSpesenError; } public void setTgSpesenError(boolean tgSpesenError) { this.mTgSpesenError = tgSpesenError; } public boolean isDivSpesenError() { return mDivSpesenError; } public void setDivSpesenError(boolean divSpesenError) { this.mDivSpesenError = divSpesenError; } public boolean isAbzugError() { return mAbzugError; } public void setAbzugError(boolean abzugError) { this.mAbzugError = abzugError; } public boolean isBVonError() { return mBVonError; } public void setBVonError(boolean bVonError) { this.mBVonError = bVonError; } public boolean isBBisError() { return mBBisError; } public void setBBisError(boolean bBisError) { this.mBBisError = bBisError; } public boolean isBTotError() { return mBTotError; } public void setBTotError(boolean bTotError) { this.mBTotError = bTotError; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/FormItemType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; /** * The type of item that should be shown on UI. FORMITEM.TYPE = rdbt radio button FORMITEM.TYPE = comb combo box FORMITEM.TYPE = chkb check box FORMITEM.TYPE = text text input FORMITEM.TYPE = numf numeric values FORMITEM.TYPE = sign signature FORMITEM.TYPE = titl header for better structure FORMITEM.TYPE = sepr separator (dividing line) for better structure * @author CYU * */ public class FormItemType { public static final String RDBT = "RDBT"; public static final String COMB = "COMB"; public static final String CHKB = "CHKB"; public static final String TEXT = "TEXT"; public static final String NUMF = "NUMF"; public static final String SIGN = "SIGN"; public static final String TITL = "TITL"; public static final String SEPR = "SEPR"; public static final String IMAG = "IMAG"; private String code; public FormItemType() { set(TEXT); } public FormItemType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isRDBT() { return this.code.equalsIgnoreCase(RDBT); } public boolean isCOMB() { return this.code.equalsIgnoreCase(COMB); } public boolean isCHKB() { return this.code.equalsIgnoreCase(CHKB); } public boolean isTEXT() { return this.code.equalsIgnoreCase(TEXT); } public boolean isNUMF() { return this.code.equalsIgnoreCase(NUMF); } public boolean isSIGN() { return this.code.equalsIgnoreCase(SIGN); } public boolean isTITL() { return this.code.equalsIgnoreCase(TITL); } public boolean isSEPR() { return this.code.equalsIgnoreCase(SEPR); } public boolean isIMAG() { return this.code.equalsIgnoreCase(IMAG); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/FormType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class FormType { public static final String INITIAL = ""; public static final String JPG = "JPG"; //Service-Check //$NON-NLS-1$ public static final String PDF = "PDF"; //Installation //$NON-NLS-1$ private String code; public FormType() { set(INITIAL); } public FormType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isJPG() { return this.code.equalsIgnoreCase(JPG); } public boolean isPDF() { return this.code.equalsIgnoreCase(PDF); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/JobStatus.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class JobStatus { /** * initial * no valid JobStatus, only used by the constructor */ public static final String INITIAL = "00"; //$NON-NLS-1$ /** * new */ public static final String NEW = "01"; //$NON-NLS-1$ /** * received */ public static final String RECEIVED = "02"; //$NON-NLS-1$ /** * rejected */ public static final String REJECTED = "03"; //$NON-NLS-1$ /** * forwarded */ public static final String FORWARDED = "04"; //$NON-NLS-1$ /** * in progress */ public static final String IN_PROGRESS = "05"; //$NON-NLS-1$ /** * finalized (finished) */ public static final String FINALIZED = "06"; //$NON-NLS-1$ /** * partly done */ public static final String PARLTY_DONE = "07"; //$NON-NLS-1$ /** * removed */ public static final String DELETED = "08"; //$NON-NLS-1$ // the states reported to SAP /** * confirmed by client(SAP) */ public static final String SAP_Confirmed = "5"; //$NON-NLS-1$ /** * report time started (SAP) */ public static final String SAP_InProgress = "5a"; //$NON-NLS-1$ /** * finalized (finished)(SAP) */ public static final String SAP_Finished = "12"; //$NON-NLS-1$ /** * forwarded(SAP) */ public static final String SAP_Forwarded = "15"; //$NON-NLS-1$ /** * deleted(SAP) */ public static final String SAP_Deleted = "16"; //$NON-NLS-1$ private String code; // private String value; public JobStatus() { set(INITIAL); } public JobStatus(String code) { set(code); } public String getCode() { return code; } // public String getValue() { // return value; // } public void set(String code) { this.code = code; // this.value = loadLocalizedStatus(code); } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isNew() { return this.code.equalsIgnoreCase(NEW); } public boolean isReceived() { return this.code.equalsIgnoreCase(RECEIVED); } public boolean isRejected() { return this.code.equalsIgnoreCase(REJECTED); } public boolean isForwarded() { return this.code.equalsIgnoreCase(FORWARDED); } public boolean isInProgress() { return this.code.equalsIgnoreCase(IN_PROGRESS); } public boolean isPartlyDone() { return this.code.equalsIgnoreCase(PARLTY_DONE); } public boolean isFinalized() { return this.code.equalsIgnoreCase(FINALIZED); } public boolean isDeleted() { return this.code.equalsIgnoreCase(DELETED); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/JobType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class JobType { /** * initial * no valid JobStatus, only used by the constructor */ public static final String INITIAL = "NON"; // new //$NON-NLS-1$ /** * repair */ public static final String REP = "REP"; //repair //$NON-NLS-1$ /** * Service-Check */ public static final String SAV = "SAV"; //Service-Check //$NON-NLS-1$ /** * Installation */ public static final String MON = "MON"; //Installation //$NON-NLS-1$ private String code; // private String value; public JobType() { set(INITIAL); } public JobType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isREP() { return this.code.equalsIgnoreCase(REP); } public boolean isSAV() { return this.code.equalsIgnoreCase(SAV); } public boolean isMON() { return this.code.equalsIgnoreCase(MON); } public String toString() { return code; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/ReportStatus.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class ReportStatus { /** * initial no valid JobStatus, only used by the constructor */ public static final String INITIAL = "99"; // new //$NON-NLS-1$ /** * new */ public static final String NEW = "0"; // new //$NON-NLS-1$ /** * received */ public static final String RECEIVED = "1"; // sent //$NON-NLS-1$ private String code; // private String value; public ReportStatus() { set(INITIAL); } public ReportStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isNew() { return this.code.equalsIgnoreCase(NEW); } public boolean isReceived() { return this.code.equalsIgnoreCase(RECEIVED); } public String toString() { if (isInitial()) return code + " (INITIAL)"; //$NON-NLS-1$ if (isNew()) return code + " (NEW)"; //$NON-NLS-1$ if (isReceived()) return code + " (RECEIVED)"; //$NON-NLS-1$ return super.toString(); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/SpecificFunctionType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class SpecificFunctionType { public static final String INITIAL = ""; // new //$NON-NLS-1$ public static final String TORBAUER = "T"; // new //$NON-NLS-1$ public static final String SPECIALIST = "S"; // sent //$NON-NLS-1$ private String code; // private String value; public SpecificFunctionType() { set(INITIAL); } public SpecificFunctionType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isTorbauer() { return this.code.equalsIgnoreCase(TORBAUER); } public boolean isSpezialist() { return this.code.equalsIgnoreCase(SPECIALIST); } public String toString() { if (isInitial()) return code + " (INITIAL)"; //$NON-NLS-1$ if (isTorbauer()) return code + " (TORBAUER)"; //$NON-NLS-1$ if (isSpezialist()) return code + " (SPECIALIST)"; //$NON-NLS-1$ return super.toString(); } public String getText() { if (isInitial()) return ""; //$NON-NLS-1$ if (isTorbauer()) return "Torbauer"; //$NON-NLS-1$ if (isSpezialist()) return "Spezialist"; //$NON-NLS-1$ return super.toString(); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/TimesheetStatus.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class TimesheetStatus { /** * initial * not a valid status, only used by the constructor */ public static final String INITIAL = "00"; //$NON-NLS-1$ /** * valid means the expense record fulfills the business requirements */ public static final String VALID = "01"; //$NON-NLS-1$ private String code; public TimesheetStatus() { set(INITIAL); } public TimesheetStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isValid() { return this.code.equalsIgnoreCase(VALID); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/TimesheetValidation.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class TimesheetValidation { // valid flag private boolean mValid = true; // Error indicator private boolean mInitialArbaError = false; private boolean mInitialVonError = false; private boolean mInitialBisError = false; private boolean mVonBiggerBisError = false; public boolean isValid() { return mValid; } public void setValid(boolean valid) { this.mValid = valid; } public boolean isInitialArbaError() { return mInitialArbaError; } public void setInitialArbaError(boolean initialArbaError) { this.mInitialArbaError = initialArbaError; } public boolean isInitialVonError() { return mInitialVonError; } public void setInitialVonError(boolean initialVonError) { this.mInitialVonError = initialVonError; } public boolean isInitialBisError() { return mInitialBisError; } public void setInitialBisError(boolean initialBisError) { this.mInitialBisError = initialBisError; } public boolean isVonBiggerBisError() { return mVonBiggerBisError; } public void setVonBiggerBisError(boolean vonBiggerBisError) { this.mVonBiggerBisError = vonBiggerBisError; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/types/Warehouse.java:   package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class Warehouse { /** * initial not a valid status, only used by the constructor */ public static final String VEHICLE = "FZG"; /** * new */ public static final String EXTERNAL = "ALG"; /** * sent */ public static final String MAIN = "HLG"; private String code; public Warehouse() { set(MAIN); } public Warehouse(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isMAIN() { return this.code.equalsIgnoreCase(MAIN); } public boolean isVEHICLE() { return this.code.equalsIgnoreCase(VEHICLE); } public boolean isSENT() { return this.code.equalsIgnoreCase(EXTERNAL); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/VariousExpenseFile.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.annotation.Nullable; import android.util.Base64; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.BitmapConverterUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAEXPNSPICS */ public class VariousExpenseFile { public static final Log log = LogFactory.getLog(VariousExpenseFile.class); private int personalNumber = 0; private Date date = new Date(); private String variousExpensesFileId = ""; private String description = ""; private FormType formType = new FormType(); private String signpicAt = ""; //$NON-NLS-1$ public VariousExpenseFile() { } public VariousExpenseFile(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.VariousExpenseFile.PERSONAL_NUMBER)); this.setDate(rs.getDate(DbConstants.VariousExpenses.DATE)); this.setVariousExpensesFileId(rs.getString(DbConstants.VariousExpenseFile.IDX)); this.setDescription(rs.getString(DbConstants.VariousExpenseFile.DESCRIPTION)); this.setFormType(new FormType(rs.getString(DbConstants.VariousExpenseFile.FORM_TYPE))); this.setSignPicAt(rs.getString(DbConstants.VariousExpenseFile.SIGN_PIC_AT)); } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getVariousExpensesFileId() { return variousExpensesFileId; } public void setVariousExpensesFileId(String variousExpensesFileId) { this.variousExpensesFileId = variousExpensesFileId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setSignPicBitmap(Bitmap bitmap) { setSignPicAt(BitmapConverterUtil.bitMapToString(bitmap)); } public FormType getFormType() { return formType; } public void setFormType(FormType formType) { this.formType = formType; } public String getSignpicAt() { return signpicAt; } public void setSignPicAt(String signpicAt) { this.signpicAt = signpicAt; } public Bitmap getSignPicBitmap() { return BitmapConverterUtil.stringToBitMap(signpicAt); } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.JobFile.JOB_FILE, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.JobFile.JOB_FILE, db, folder); } // public boolean isValid() { // boolean result = true; // StringBuilder error = new StringBuilder(); // error.append("\n"); // // if(equals(getGuid().trim().isEmpty())) { // error.append("Guid required \n"); // // result = false; // } // // if(getJobNumber().trim().isEmpty()) { // error.append("JobNumber required \n" ); // // result = false; // } // // if(getJobFileId().trim().isEmpty()) { // error.append("FileId required \n" ); // // result = false; // } // // if(getJobType().toString().isEmpty()) { // error.append("JobType required \n" ); // result = false; // } // // if(getType().trim().isEmpty()) { // error.append("Type required \n" ); // // result = false; // } // // if(getType().trim().equalsIgnoreCase("F") && getFormType().isINITIAL()) { // error.append("FormType required \n" ); // // result = false; // } // // if(getSignpicAt().toString().trim().isEmpty()) { // error.append("Signpic required \n" ); // // result = false; // } // // log.info("is JobFile valid -> " + result + " " + error.toString()); // // return result; // } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/VariousExpenses.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAEXPNSDIV */ public class VariousExpenses { private int personalNumber = 0; private Date date = new Date(); private String variousExpensesId = ""; private String amount = ""; private String expensesCode = ""; private VariousExpenseFile variousExpensesFile = null; VariousExpenses() { } public VariousExpenses(Date datum, int pernr, String variousExpensesId) { this.setDate(datum); this.setPersonalNumber(pernr); } public VariousExpenses(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.VariousExpenses.PERSONAL_NUMBER)); this.setDate(rs.getDate(DbConstants.VariousExpenses.DATE)); this.setVariousExpensesId(rs.getString(DbConstants.VariousExpenses.IDX)); this.setAmount(rs.getString(DbConstants.VariousExpenses.AMOUNT)); this.setExpensesCode(rs.getString(DbConstants.VariousExpenses.EXPENSES_CODE)); } public boolean isInitial() { return personalNumber == 0 &&"".equalsIgnoreCase(this.variousExpensesId) && "".equalsIgnoreCase(this.amount) && "".equalsIgnoreCase(this.expensesCode) ; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getVariousExpensesId() { return variousExpensesId; } public void setVariousExpensesId(String variousExpensesId) { this.variousExpensesId = variousExpensesId; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getExpensesCode() { return expensesCode; } public void setExpensesCode(String expensesCode) { this.expensesCode = expensesCode; } public VariousExpenseFile getVariousExpensesFile() { if (variousExpensesFile == null) { variousExpensesFile = new VariousExpenseFile(); } return variousExpensesFile; } public void setVariousExpensesFile(VariousExpenseFile variousExpensesFile) { this.variousExpensesFile = variousExpensesFile; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Expenses.EXPENSES, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Expenses.EXPENSES, db, folder); } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/VehicleInventory.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZLGSYNC */ public class VehicleInventory { private String storageLocation = ""; private String materialNumber = ""; private String materialName = ""; private String stockOfMaterial = ""; private String unit = ""; public VehicleInventory() { } public VehicleInventory(RecordSet rs) { this.setStorageLocation(rs.getString(DbConstants.VehicleInventory.STORAGE_LOCATION)); this.setMaterialNumber(rs.getString(DbConstants.VehicleInventory.MATERIAL_NUMBER)); this.setMaterialName(rs.getString(DbConstants.VehicleInventory.MATERIAL_NAME)); this.setStockOfMaterial(rs.getString(DbConstants.VehicleInventory.STOCK_OF_MATERIAL)); this.setUnit(rs.getString(DbConstants.VehicleInventory.UNIT)); } public String getStorageLocation() { return storageLocation; } public void setStorageLocation(String storageLocation) { this.storageLocation = storageLocation; } public String getMaterialNumber() { return materialNumber; } public void setMaterialNumber(String materialNumber) { this.materialNumber = materialNumber; } public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } public String getStockOfMaterial() { return stockOfMaterial; } public void setStockOfMaterial(String stockOfMaterial) { this.stockOfMaterial = stockOfMaterial; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } }     common/src/ch/mfiles/kaba/kolibri/common/businessobjects/WorkType.java:   package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZARBEITSART */ public class WorkType { private String workTypeCode = ""; //$NON-NLS-1$ private String group = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String guarantee = ""; WorkType() { } public WorkType(RecordSet rs) { this.setWorkTypeCode(rs.getString(DbConstants.WorkType.CODE)); this.setGroup(rs.getString(DbConstants.WorkType.GROUP)); this.setText(rs.getString(DbConstants.WorkType.TEXT)); this.setGuarantee(rs.getString(DbConstants.WorkType.GUARANTEE)); } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } public String getGroup() { return this.group; } public void setGroup(String group) { this.group = group; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getGuarantee() { return guarantee; } public void setGuarantee(String guarantee) { this.guarantee = guarantee; } public boolean isGuarantee() { return "X".equalsIgnoreCase(this.getGuarantee()); } public void setGuarantee(boolean isGuarantee) { if (isGuarantee) { this.setGuarantee("X"); } else { this.setGuarantee(""); } } }     common/src/ch/mfiles/kaba/kolibri/common/CommonApplication.java:   package ch.mfiles.kaba.kolibri.common; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.forms.SuperForm; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.BackupHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.bu.BackupMonitor; import ch.mfiles.kolibri.bu.RestoreMonitor; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSTable; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.NotificationMessage; /** * Main application class */ public class CommonApplication extends Application { public static final Log log = LogFactory.getLog(CommonApplication.class); private DatabaseUtil dbutil; private Notifications notifications; public MessageUtil messageUtil; @Override public ApplicationEvent onNotification(NotificationMessage message) { log.info("onNotification"); //$NON-NLS-1$ // process alert messages from backup job if (BackupHandler.getInstance().processNotification(message)) return null; // message was handled String content = message.getContent(); if (content.startsWith(CommonConstants.Prefix.SHORTMSG)) { // if (log.isDebugEnabled()) { log.info("message startsWith SHORTMSG"); //$NON-NLS-1$ // } int firstDashPos = content.indexOf('-', 0); if (firstDashPos <= 0) { return null; } int secondDashPos = content.indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return null; } final String pernr = content.substring(firstDashPos + 1, secondDashPos); final String tdName = content.substring(secondDashPos + 1, content.length()); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); if (new RemoteTransactionHandler().runGetShortMSG(Integer.parseInt(pernr), tdName)) { // Inform user about new short message new Notifications(this).shortMessageNotification(Messages.getString("newShortMessageReceived")); //$NON-NLS-1$ } } return null; } /** * Called by the framework each time the application is started. * * @param obj An (optional) object supplied by the application that started this * application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { notifications = new Notifications(this); messageUtil = MessageUtil.getInstance(); // Register broadcast receiver notifications.registerBroadcastReceiver(); setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // check start with message if (obj instanceof NotificationMessage) { NotificationMessage message = (NotificationMessage) obj; onNotification(message); return appman.exitApplication(); } return leaveToForm(SuperForm.class); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be terminated. */ @Override public boolean onApplicationExit(boolean forced) { log.info("Exit CommonApplication"); //$NON-NLS-1$ // Unregister broadcast receiver and remove the notification notifications.removeNotification(); notifications.unregisterBroadcastReceiver(); return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent the * removal in exceptional cases. */ @Override public void onApplicationRemoval() { deleteExtractedDirAndFiles(new File(Runtime.getInstallationFolder() + File.separator + CommonConstants.Application.COMMON + File.separator + FileUtils.Packages.DATA)); } /** * Called by the framework for the new application to be deployed. May be used * to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent the * upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { if (oldApplicationDescriptor != null) { Address.backup(this, new File(getApplicationFolder())); JobFile.backup(this, new File(getApplicationFolder())); Job.backup(this, new File(getApplicationFolder())); Report.backup(this, new File(getApplicationFolder())); Order.backup(this, new File(getApplicationFolder())); OrderMaterial.backup(this, new File(getApplicationFolder())); CalendarTimeSheet.backup(this, new File(getApplicationFolder())); TimeSheet.backup(this, new File(getApplicationFolder())); Expenses.backup(this, new File(getApplicationFolder())); } } /** * Called by the framework after the application has been upgraded but before * the upgrade is commited to the database. Additional upgrade postprocessing * might be implemented here. *

* This method might throw an ApplicationException to prevent the * upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { FileUtils fileUtils = new FileUtils(); fileUtils.extractFileFromJar(CommonConstants.Application.COMMON, FileUtils.Packages.DATA, FileUtils.FileNames.FIXED_MASTERDATA); CommSetupHelper.setupProductionEnvironment(); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); // reload localized texts dbutil.setupFixedMasterData(true); Job.restore(getDBSession(), new File(getApplicationFolder())); Report.restore(getDBSession(), new File(getApplicationFolder())); Order.restore(getDBSession(), new File(getApplicationFolder())); OrderMaterial.restore(getDBSession(), new File(getApplicationFolder())); CalendarTimeSheet.restore(getDBSession(), new File(getApplicationFolder())); TimeSheet.restore(getDBSession(), new File(getApplicationFolder())); Expenses.restore(getDBSession(), new File(getApplicationFolder())); createCalendarRecords(); JobMessage.restore(getDBSession(), new File(getApplicationFolder())); Address.restore(getDBSession(), new File(getApplicationFolder())); JobFile.restore(getDBSession(), new File(getApplicationFolder())); // make sure backup manager is setup as required BackupHandler.setupOnPostApplicationUpgrade(this); ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } private void createCalendarRecords() { File folder = new File(getApplicationFolder()); DBSession db = getDBSession(); try { if (folder.exists()) { File file = new File(folder, "\\" + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET); //$NON-NLS-1$ if (file.exists()) { try { BufferedReader in = new BufferedReader(new FileReader(file)); String line; String sql = "INSERT OR IGNORE INTO " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET + " (" //$NON-NLS-1$ //$NON-NLS-2$ + in.readLine() + ") VALUES "; //$NON-NLS-1$ while ((line = in.readLine()) != null) { log.info(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } in.close(); if (file.delete()) { // only if the file was deleted successfully, remaining inconsistent timesheet // entries can be deleted (as discussed with Gilgen, 06.09.11) sql = "DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET + //$NON-NLS-1$ " WHERE " + DbConstants.TimeSheet.START_TIME + " NOT IN (" //$NON-NLS-1$ //$NON-NLS-2$ + "SELECT t." + DbConstants.TimeSheet.START_TIME + " FROM " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET + " c, " //$NON-NLS-1$ + DbConstants.TimeSheet.TIME_SHEET + " t " //$NON-NLS-1$ + "WHERE t." + DbConstants.TimeSheet.START_TIME + " > c." //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.CalendarTimeSheet.DATE + " AND t." + DbConstants.TimeSheet.START_TIME + " < c." //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.CalendarTimeSheet.DATE + " + 86400000)"; //$NON-NLS-1$ int deleted = db.executeSql(sql); log.info("Number of deleted ZKDMATIME records: " + deleted + "; Statement: '" + sql + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } catch (IOException e) { log.error("Fehler beim einlesen der zwischengespeicherten CALENDAR Datensätze: " //$NON-NLS-1$ + e.getMessage()); } } else { log.info("Fehler beim einlesen zwischengespeicherter CALENDAR Datensätze: Backupdatei '" //$NON-NLS-1$ + file.getAbsolutePath() + "' nicht gefunden"); //$NON-NLS-1$ } } else { log.info( "Fehler beim einlesen zwischengespeicherter CALENDAR Datensätze: Kein ApplicationFolder vorhanden"); //$NON-NLS-1$ } } catch (NullPointerException e) { log.error( "Fehler beim einlesen zwischengespeicherter CALENDAR Datensätze: Kein ApplicationFolder vorhanden"); //$NON-NLS-1$ } } public boolean deleteExtractedDirAndFiles(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteExtractedDirAndFiles(files[i]); } else { if (files[i].delete()) { // do nothins } } } } return path.delete(); } @Override public void onCreateSnapshot(BackupMonitor monitor, Set dbTables, HashMap registry, Set folders) { // add special application folders to the folders to backup folders.add(FileUtils.getAbsoluteAppPathName(CommonConstants.Application.COMMON)); folders.add(FileUtils.getAbsoluteAppPathName(CommonConstants.Application.SERVICE)); // check mirror state DeviceMirrorringHandler.getInstance().onCreateSnapshot(monitor); } @Override public void onDbRestored(RestoreMonitor monitor, Set restoredTables) { // update mirror state DeviceMirrorringHandler.getInstance().onDbRestored(monitor, restoredTables); } }     common/src/ch/mfiles/kaba/kolibri/common/db/CALENDAR.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.CALENDARCursor.ColAccessor; /** * No description. */ public class CALENDAR extends TableRow { /** Name of table: CALENDAR */ public final static String TABLE = "CALENDAR"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("STATUS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STATUS)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DATUM_TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DATUM_TXT)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new CALENDARCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new CALENDARCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link CALENDARCursor} * instance. Use an instance of {@link CALENDARCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static CALENDAR get(RecordSet rs, boolean selectStar) { CALENDAR result = new CALENDAR(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static CALENDAR[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static CALENDAR[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); CALENDAR row = new CALENDAR(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new CALENDAR(row)); return (CALENDAR[]) list.toArray(new CALENDAR[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static CALENDAR[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static CALENDAR[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(CALENDAR row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof CALENDAR)) return false; CALENDAR test = (CALENDAR) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param DATUM null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(CALENDAR row, Date DATUM) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_DATUM); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param DATUM null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static CALENDAR[] listByPrimaryKey(DBSession db, Date DATUM, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_DATUM); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param DATUM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, Date DATUM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); return db.executeSql(sb.toString()); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param DATUM null * @param PERNR null * @return The result of the database access. */ public static CALENDAR getByPrimaryKey(DBSession db, Date DATUM, int PERNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param DATUM null * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, Date DATUM, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(CALENDAR row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_DATUM); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static CALENDAR[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_DATUM); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table CALENDAR. */ class CALENDARCursor implements TableCursor { interface ColAccessor { public void set(CALENDAR table, RecordSet rs, int index); public void setUpdate(CALENDAR table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(CALENDAR table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(CALENDAR table, DBSqlHelper sqlHelper) { sqlHelper.in(CALENDAR.COL_DATUM, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(CALENDAR table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(CALENDAR table, DBSqlHelper sqlHelper) { sqlHelper.in(CALENDAR.COL_PERNR, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(CALENDAR table, RecordSet rs, int index) { table.setSTATUS(rs.getString(index)); } public void setUpdate(CALENDAR table, DBSqlHelper sqlHelper) { sqlHelper.in(CALENDAR.COL_STATUS, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(CALENDAR table, RecordSet rs, int index) { table.setDATUM_TXT(rs.getString(index)); } public void setUpdate(CALENDAR table, DBSqlHelper sqlHelper) { sqlHelper.in(CALENDAR.COL_DATUM_TXT, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[CALENDAR.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(CALENDAR.COL_DATUM, new Integer(CALENDAR.IDX_DATUM)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(CALENDAR.COL_PERNR, new Integer(CALENDAR.IDX_PERNR)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(CALENDAR.COL_STATUS, new Integer(CALENDAR.IDX_STATUS)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(CALENDAR.COL_DATUM_TXT, new Integer(CALENDAR.IDX_DATUM_TXT)); } return s_accessor; } /** * */ private final CALENDAR m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new CALENDARCursor(row, rs, false). * * @param calendar * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ CALENDARCursor(CALENDAR row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM CALENDAR WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ CALENDARCursor(CALENDAR row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link CALENDAR} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/FORM.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.FORMCursor.ColAccessor; /** * Generic forms header data. SAP tables: ZKDMOB_FORM, ZKDMOB_FORM_T, ZKDMOB_FORM_VER */ public class FORM extends TableRow { /** Name of table: FORM */ public final static String TABLE = "FORM"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 7; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("VERSION"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VERSION)) sb.append(_col1); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STATUS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STATUS)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALIDFROM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALIDFROM)) sb.append(df.format(_col3)); sb.append(", ").append("VALIDTO"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALIDTO)) sb.append(df.format(_col4)); sb.append(", ").append("NAME"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DESCRIPTION"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DESCRIPTION)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new FORMCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new FORMCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link FORMCursor} * instance. Use an instance of {@link FORMCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static FORM get(RecordSet rs, boolean selectStar) { FORM result = new FORM(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static FORM[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static FORM[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); FORM row = new FORM(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new FORM(row)); return (FORM[]) list.toArray(new FORM[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static FORM[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static FORM[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(FORM row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof FORM)) return false; FORM test = (FORM) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORM row, String ID, boolean likeID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_VERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form id * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORM row, String ID) { return queryByPrimaryKey(row, ID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ID Form id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORM[] listByPrimaryKey(DBSession db, String ID, boolean likeID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_VERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, boolean likeID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param VERSION Form version number * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORM row, String ID, boolean likeID, int VERSION) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(VERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_VERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param ID Form id * @param VERSION Form version number * @return The result of the database access. */ public static FORM getByPrimaryKey(DBSession db, String ID, int VERSION) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VERSION).append("=").append(sqlHelper.get(VERSION)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ID Form id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param VERSION Form version number * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORM[] listByPrimaryKey(DBSession db, String ID, boolean likeID, int VERSION, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(VERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_VERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param VERSION Form version number * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, boolean likeID, int VERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(VERSION)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form id * @param VERSION Form version number * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, int VERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VERSION).append("=").append(sqlHelper.get(VERSION)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORM row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_VERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORM[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_VERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table FORM. */ class FORMCursor implements TableCursor { interface ColAccessor { public void set(FORM table, RecordSet rs, int index); public void setUpdate(FORM table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setID(rs.getString(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_ID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setVERSION(rs.getInt(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_VERSION, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setSTATUS(rs.getString(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_STATUS, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setVALIDFROM(rs.getDate(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_VALIDFROM, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setVALIDTO(rs.getDate(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_VALIDTO, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setNAME(rs.getString(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_NAME, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(FORM table, RecordSet rs, int index) { table.setDESCRIPTION(rs.getString(index)); } public void setUpdate(FORM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORM.COL_DESCRIPTION, table._col6); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[FORM.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(FORM.COL_ID, new Integer(FORM.IDX_ID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(FORM.COL_VERSION, new Integer(FORM.IDX_VERSION)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(FORM.COL_STATUS, new Integer(FORM.IDX_STATUS)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(FORM.COL_VALIDFROM, new Integer(FORM.IDX_VALIDFROM)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(FORM.COL_VALIDTO, new Integer(FORM.IDX_VALIDTO)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(FORM.COL_NAME, new Integer(FORM.IDX_NAME)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(FORM.COL_DESCRIPTION, new Integer(FORM.IDX_DESCRIPTION)); } return s_accessor; } /** * */ private final FORM m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new FORMCursor(row, rs, false). * * @param form * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMCursor(FORM row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM FORM WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMCursor(FORM row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link FORM} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/FORMDEPENDENCY.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.FORMDEPENDENCYCursor.ColAccessor; /** * Dynamic visiblity control of field item depending on entered values in other items. SAP tables: ZKDMOB_FORM_DEP */ public class FORMDEPENDENCY extends TableRow { /** Name of table: FORMDEPENDENCY */ public final static String TABLE = "FORMDEPENDENCY"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 7; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iValueId a value in a value list. If the value is set in any of the form's fields the depending form field is visible * @param VALUEID Id of a value in a the value list with id ValueListId. If the value is set in any of the form's fields the depending form field is visible */ public FORMDEPENDENCY(DBSession db, String FORMID, int FORMVERSION, String FORMITEMID, int DEPENDENCY, String CHECKBOXFORMITEMID, String VALUELISTID, String VALUEID) { super(db, null); _col0 = FORMID; _col1 = FORMVERSION; _col2 = FORMITEMID; _col3 = DEPENDENCY; _col4 = CHECKBOXFORMITEMID; _col5 = VALUELISTID; _col6 = VALUEID; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public FORMDEPENDENCY(FORMDEPENDENCY source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_FORMID)) _col0 = source._col0; if (isColumnSet(IDX_FORMVERSION)) _col1 = source._col1; if (isColumnSet(IDX_FORMITEMID)) _col2 = source._col2; if (isColumnSet(IDX_DEPENDENCY)) _col3 = source._col3; if (isColumnSet(IDX_CHECKBOXFORMITEMID)) _col4 = source._col4; if (isColumnSet(IDX_VALUELISTID)) _col5 = source._col5; if (isColumnSet(IDX_VALUEID)) _col6 = source._col6; } else { // copy all columns if (isColumnSet(IDX_FORMID)) _col0 = source._col0; if (isColumnSet(IDX_FORMVERSION)) _col1 = source._col1; if (isColumnSet(IDX_FORMITEMID)) _col2 = source._col2; if (isColumnSet(IDX_DEPENDENCY)) _col3 = source._col3; if (isColumnSet(IDX_CHECKBOXFORMITEMID)) _col4 = source._col4; if (isColumnSet(IDX_VALUELISTID)) _col5 = source._col5; if (isColumnSet(IDX_VALUEID)) _col6 = source._col6; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param FORMID Form id * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param DEPENDENCY Dependency id * @param source */ public FORMDEPENDENCY(String FORMID, int FORMVERSION, String FORMITEMID, int DEPENDENCY, FORMDEPENDENCY source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = FORMID; _col1 = FORMVERSION; _col2 = FORMITEMID; _col3 = DEPENDENCY; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_CHECKBOXFORMITEMID)) _col4 = source._col4; if (isColumnSet(IDX_VALUELISTID)) _col5 = source._col5; if (isColumnSet(IDX_VALUEID)) _col6 = source._col6; } else { // copy all columns excluding the primary key _col4 = source._col4; _col5 = source._col5; _col6 = source._col6; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public FORMDEPENDENCY(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); if ((m_usedColumns == null || !m_usedColumns.get(IDX_FORMID)) && _col0 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_FORMID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_FORMITEMID)) && _col2 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_FORMITEMID)); //$NON-NLS-1$ } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_FORMID)) m_usedColumns.clear(IDX_FORMID); if (usedColumns == null || !usedColumns.get(IDX_FORMVERSION)) m_usedColumns.clear(IDX_FORMVERSION); if (usedColumns == null || !usedColumns.get(IDX_FORMITEMID)) m_usedColumns.clear(IDX_FORMITEMID); if (usedColumns == null || !usedColumns.get(IDX_DEPENDENCY)) m_usedColumns.clear(IDX_DEPENDENCY); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_CHECKBOXFORMITEMID)) _col4 = DEF_CHECKBOXFORMITEMID; if (m_usedColumns.get(IDX_VALUELISTID)) _col5 = DEF_VALUELISTID; if (m_usedColumns.get(IDX_VALUEID)) _col6 = DEF_VALUEID; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_FORMID) || !isColumnSet(IDX_FORMVERSION) || !isColumnSet(IDX_FORMITEMID) || !isColumnSet(IDX_DEPENDENCY) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append('=').append(sqlHelper.get(_col0)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append('=').append(sqlHelper.get(_col1)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append('=').append(sqlHelper.get(_col2)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DEPENDENCY).append('=').append(sqlHelper.get(_col3)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); sqlHelper.in(_col0); sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); sqlHelper.in(_col5); sqlHelper.in(_col6); getDBSession().executeSql(sqlHelper.toString()); } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = FORMDEPENDENCYCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_CHECKBOXFORMITEMID, _col4); sqlHelper.in(COL_VALUELISTID, _col5); sqlHelper.in(COL_VALUEID, _col6); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return Form id */ public String getFORMID() { checkSparseColumn(IDX_FORMID); return _col0; } /** * @param FORMID Form id */ protected void setFORMID(String FORMID) { checkNull(FORMID); _col0 = FORMID; markUsed(IDX_FORMID); } /** * @return Form version */ public int getFORMVERSION() { checkSparseColumn(IDX_FORMVERSION); return _col1; } /** * @param FORMVERSION Form version */ protected void setFORMVERSION(int FORMVERSION) { _col1 = FORMVERSION; markUsed(IDX_FORMVERSION); } /** * @return Form item id */ public String getFORMITEMID() { checkSparseColumn(IDX_FORMITEMID); return _col2; } /** * @param FORMITEMID Form item id */ protected void setFORMITEMID(String FORMITEMID) { checkNull(FORMITEMID); _col2 = FORMITEMID; markUsed(IDX_FORMITEMID); } /** * @return Dependency id */ public int getDEPENDENCY() { checkSparseColumn(IDX_DEPENDENCY); return _col3; } /** * @param DEPENDENCY Dependency id */ protected void setDEPENDENCY(int DEPENDENCY) { _col3 = DEPENDENCY; markUsed(IDX_DEPENDENCY); } /** * @return Id of a checkbox form item of the same generic form. The depending form field is only visible if the referenced check box is checked. */ public String getCHECKBOXFORMITEMID() { checkSparseColumn(IDX_CHECKBOXFORMITEMID); return _col4; } /** * @param CHECKBOXFORMITEMID Id of a checkbox form item of the same generic form. The depending form field is only visible if the referenced check box is checked. */ public void setCHECKBOXFORMITEMID(String CHECKBOXFORMITEMID) { checkNull(CHECKBOXFORMITEMID); _col4 = CHECKBOXFORMITEMID; markUsed(IDX_CHECKBOXFORMITEMID); } /** * @return Id of a value list referencing together with attribute ValueId a value in a value list. If the value is set in any of the form's fields the depending form field is visible */ public String getVALUELISTID() { checkSparseColumn(IDX_VALUELISTID); return _col5; } /** * @param VALUELISTID Id of a value list referencing together with attribute ValueId a value in a value list. If the value is set in any of the form's fields the depending form field is visible */ public void setVALUELISTID(String VALUELISTID) { checkNull(VALUELISTID); _col5 = VALUELISTID; markUsed(IDX_VALUELISTID); } /** * @return Id of a value in a the value list with id ValueListId. If the value is set in any of the form's fields the depending form field is visible */ public String getVALUEID() { checkSparseColumn(IDX_VALUEID); return _col6; } /** * @param VALUEID Id of a value in a the value list with id ValueListId. If the value is set in any of the form's fields the depending form field is visible */ public void setVALUEID(String VALUEID) { checkNull(VALUEID); _col6 = VALUEID; markUsed(IDX_VALUEID); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("FORMID"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMID)) sb.append('\'').append(_col0).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMVERSION"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMVERSION)) sb.append(_col1); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMITEMID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMITEMID)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DEPENDENCY"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DEPENDENCY)) sb.append(_col3); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CHECKBOXFORMITEMID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CHECKBOXFORMITEMID)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUELISTID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUELISTID)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUEID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUEID)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new FORMDEPENDENCYCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new FORMDEPENDENCYCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link FORMDEPENDENCYCursor} * instance. Use an instance of {@link FORMDEPENDENCYCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static FORMDEPENDENCY get(RecordSet rs, boolean selectStar) { FORMDEPENDENCY result = new FORMDEPENDENCY(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static FORMDEPENDENCY[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static FORMDEPENDENCY[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); FORMDEPENDENCY row = new FORMDEPENDENCY(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new FORMDEPENDENCY(row)); return (FORMDEPENDENCY[]) list.toArray(new FORMDEPENDENCY[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static FORMDEPENDENCY[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static FORMDEPENDENCY[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(FORMDEPENDENCY row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof FORMDEPENDENCY)) return false; FORMDEPENDENCY test = (FORMDEPENDENCY) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && _col3 != test._col3) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID, boolean likeFORMID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID) { return queryByPrimaryKey(row, FORMID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMDEPENDENCY[] listByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID, boolean likeFORMID, int FORMVERSION) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @param FORMVERSION Form version * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID, int FORMVERSION) { return queryByPrimaryKey(row, FORMID, false, FORMVERSION); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMDEPENDENCY[] listByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int FORMVERSION, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int FORMVERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param FORMVERSION Form version * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, int FORMVERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @param FORMVERSION Form version * @param FORMITEMID Form item id * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID, int FORMVERSION, String FORMITEMID) { return queryByPrimaryKey(row, FORMID, false, FORMVERSION, FORMITEMID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMDEPENDENCY[] listByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param FORMVERSION Form version * @param FORMITEMID Form item id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, int FORMVERSION, String FORMITEMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param DEPENDENCY Dependency id * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, int DEPENDENCY) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DEPENDENCY).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DEPENDENCY)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param FORMID Form id * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param DEPENDENCY Dependency id * @return The result of the database access. */ public static FORMDEPENDENCY getByPrimaryKey(DBSession db, String FORMID, int FORMVERSION, String FORMITEMID, int DEPENDENCY) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DEPENDENCY).append("=").append(sqlHelper.get(DEPENDENCY)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param DEPENDENCY Dependency id * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMDEPENDENCY[] listByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, int DEPENDENCY, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DEPENDENCY).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DEPENDENCY)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param DEPENDENCY Dependency id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, int DEPENDENCY) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DEPENDENCY).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DEPENDENCY)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMID Form id * @param FORMVERSION Form version * @param FORMITEMID Form item id * @param DEPENDENCY Dependency id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMID, int FORMVERSION, String FORMITEMID, int DEPENDENCY) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DEPENDENCY).append("=").append(sqlHelper.get(DEPENDENCY)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMDEPENDENCY row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMDEPENDENCY[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMID); sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_DEPENDENCY); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table FORMDEPENDENCY. */ class FORMDEPENDENCYCursor implements TableCursor { interface ColAccessor { public void set(FORMDEPENDENCY table, RecordSet rs, int index); public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setFORMID(rs.getString(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_FORMID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setFORMVERSION(rs.getInt(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_FORMVERSION, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setFORMITEMID(rs.getString(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_FORMITEMID, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setDEPENDENCY(rs.getInt(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_DEPENDENCY, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setCHECKBOXFORMITEMID(rs.getString(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_CHECKBOXFORMITEMID, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setVALUELISTID(rs.getString(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_VALUELISTID, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(FORMDEPENDENCY table, RecordSet rs, int index) { table.setVALUEID(rs.getString(index)); } public void setUpdate(FORMDEPENDENCY table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMDEPENDENCY.COL_VALUEID, table._col6); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[FORMDEPENDENCY.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_FORMID, new Integer(FORMDEPENDENCY.IDX_FORMID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_FORMVERSION, new Integer(FORMDEPENDENCY.IDX_FORMVERSION)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_FORMITEMID, new Integer(FORMDEPENDENCY.IDX_FORMITEMID)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_DEPENDENCY, new Integer(FORMDEPENDENCY.IDX_DEPENDENCY)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_CHECKBOXFORMITEMID, new Integer(FORMDEPENDENCY.IDX_CHECKBOXFORMITEMID)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_VALUELISTID, new Integer(FORMDEPENDENCY.IDX_VALUELISTID)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(FORMDEPENDENCY.COL_VALUEID, new Integer(FORMDEPENDENCY.IDX_VALUEID)); } return s_accessor; } /** * */ private final FORMDEPENDENCY m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new FORMDEPENDENCYCursor(row, rs, false). * * @param formdependency * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMDEPENDENCYCursor(FORMDEPENDENCY row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM FORMDEPENDENCY WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMDEPENDENCYCursor(FORMDEPENDENCY row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link FORMDEPENDENCY} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/FORMINSTANCE.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.FORMINSTANCECursor.ColAccessor; /** * Values of a generic form associated with a report. Sap tables: ZKDMOB_FORM_INST */ public class FORMINSTANCE extends TableRow { /** Name of table: FORMINSTANCE */ public final static String TABLE = "FORMINSTANCE"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 11; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iRDBT - RadioButton
COMB - ComboBox
CHKB - CheckBox
TEXT - TextInput
NUMF - NumericInput
SIGN - Signature
TITL - Title
SEPR - Separator * @param STRINGVALUE Text value of arbitrary length. Used for textlike input fields: TextInput * @param BOOLEANVALUE Boolean value. Used for boolean like input fields: CheckBox * @param FLOATVALUE Numeric value. Used for number like input fields: NumericInput * @param ATTACHMENTVALUE Attachment (= filepath) value. Used for data like input fields: Signature */ public FORMINSTANCE(DBSession db, String GUID, String FORMID, int FORMVERSION, String FORMITEMID, String VALUELISTID, String VALUEID, String FORMITEMTYPE, String STRINGVALUE, boolean BOOLEANVALUE, double FLOATVALUE, String ATTACHMENTVALUE) { super(db, null); _col0 = GUID; _col1 = FORMID; _col2 = FORMVERSION; _col3 = FORMITEMID; _col4 = VALUELISTID; _col5 = VALUEID; _col6 = FORMITEMTYPE; _col7 = STRINGVALUE; _col8 = BOOLEANVALUE; _col9 = FLOATVALUE; _col10 = ATTACHMENTVALUE; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public FORMINSTANCE(FORMINSTANCE source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_GUID)) _col0 = source._col0; if (isColumnSet(IDX_FORMID)) _col1 = source._col1; if (isColumnSet(IDX_FORMVERSION)) _col2 = source._col2; if (isColumnSet(IDX_FORMITEMID)) _col3 = source._col3; if (isColumnSet(IDX_VALUELISTID)) _col4 = source._col4; if (isColumnSet(IDX_VALUEID)) _col5 = source._col5; if (isColumnSet(IDX_FORMITEMTYPE)) _col6 = source._col6; if (isColumnSet(IDX_STRINGVALUE)) _col7 = source._col7; if (isColumnSet(IDX_BOOLEANVALUE)) _col8 = source._col8; if (isColumnSet(IDX_FLOATVALUE)) _col9 = source._col9; if (isColumnSet(IDX_ATTACHMENTVALUE)) _col10 = source._col10; } else { // copy all columns if (isColumnSet(IDX_GUID)) _col0 = source._col0; if (isColumnSet(IDX_FORMID)) _col1 = source._col1; if (isColumnSet(IDX_FORMVERSION)) _col2 = source._col2; if (isColumnSet(IDX_FORMITEMID)) _col3 = source._col3; if (isColumnSet(IDX_VALUELISTID)) _col4 = source._col4; if (isColumnSet(IDX_VALUEID)) _col5 = source._col5; if (isColumnSet(IDX_FORMITEMTYPE)) _col6 = source._col6; if (isColumnSet(IDX_STRINGVALUE)) _col7 = source._col7; if (isColumnSet(IDX_BOOLEANVALUE)) _col8 = source._col8; if (isColumnSet(IDX_FLOATVALUE)) _col9 = source._col9; if (isColumnSet(IDX_ATTACHMENTVALUE)) _col10 = source._col10; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox * @param source */ public FORMINSTANCE(String GUID, String FORMID, int FORMVERSION, String FORMITEMID, String VALUELISTID, String VALUEID, FORMINSTANCE source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = GUID; _col1 = FORMID; _col2 = FORMVERSION; _col3 = FORMITEMID; _col4 = VALUELISTID; _col5 = VALUEID; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_FORMITEMTYPE)) _col6 = source._col6; if (isColumnSet(IDX_STRINGVALUE)) _col7 = source._col7; if (isColumnSet(IDX_BOOLEANVALUE)) _col8 = source._col8; if (isColumnSet(IDX_FLOATVALUE)) _col9 = source._col9; if (isColumnSet(IDX_ATTACHMENTVALUE)) _col10 = source._col10; } else { // copy all columns excluding the primary key _col6 = source._col6; _col7 = source._col7; _col8 = source._col8; _col9 = source._col9; _col10 = source._col10; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public FORMINSTANCE(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); if ((m_usedColumns == null || !m_usedColumns.get(IDX_GUID)) && _col0 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_GUID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_FORMID)) && _col1 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_FORMID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_FORMITEMID)) && _col3 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_FORMITEMID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_VALUELISTID)) && _col4 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_VALUELISTID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_VALUEID)) && _col5 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_VALUEID)); //$NON-NLS-1$ } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_GUID)) m_usedColumns.clear(IDX_GUID); if (usedColumns == null || !usedColumns.get(IDX_FORMID)) m_usedColumns.clear(IDX_FORMID); if (usedColumns == null || !usedColumns.get(IDX_FORMVERSION)) m_usedColumns.clear(IDX_FORMVERSION); if (usedColumns == null || !usedColumns.get(IDX_FORMITEMID)) m_usedColumns.clear(IDX_FORMITEMID); if (usedColumns == null || !usedColumns.get(IDX_VALUELISTID)) m_usedColumns.clear(IDX_VALUELISTID); if (usedColumns == null || !usedColumns.get(IDX_VALUEID)) m_usedColumns.clear(IDX_VALUEID); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_FORMITEMTYPE)) _col6 = DEF_FORMITEMTYPE; if (m_usedColumns.get(IDX_STRINGVALUE)) _col7 = DEF_STRINGVALUE; if (m_usedColumns.get(IDX_BOOLEANVALUE)) _col8 = DEF_BOOLEANVALUE; if (m_usedColumns.get(IDX_FLOATVALUE)) _col9 = DEF_FLOATVALUE; if (m_usedColumns.get(IDX_ATTACHMENTVALUE)) _col10 = DEF_ATTACHMENTVALUE; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_GUID) || !isColumnSet(IDX_FORMID) || !isColumnSet(IDX_FORMVERSION) || !isColumnSet(IDX_FORMITEMID) || !isColumnSet(IDX_VALUELISTID) || !isColumnSet(IDX_VALUEID) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append('=').append(sqlHelper.get(_col0)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append('=').append(sqlHelper.get(_col1)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append('=').append(sqlHelper.get(_col2)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append('=').append(sqlHelper.get(_col3)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append('=').append(sqlHelper.get(_col4)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append('=').append(sqlHelper.get(_col5)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); sqlHelper.in(_col0); sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); sqlHelper.in(_col5); sqlHelper.in(_col6); sqlHelper.in(_col7); sqlHelper.in(_col8); sqlHelper.in(_col9); sqlHelper.in(_col10); getDBSession().executeSql(sqlHelper.toString()); } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = FORMINSTANCECursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_FORMITEMTYPE, _col6); sqlHelper.in(COL_STRINGVALUE, _col7); sqlHelper.in(COL_BOOLEANVALUE, _col8); sqlHelper.in(COL_FLOATVALUE, _col9); sqlHelper.in(COL_ATTACHMENTVALUE, _col10); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return GUID of the associated report */ public String getGUID() { checkSparseColumn(IDX_GUID); return _col0; } /** * @param GUID GUID of the associated report */ protected void setGUID(String GUID) { checkNull(GUID); _col0 = GUID; markUsed(IDX_GUID); } /** * @return Form id of the associated generic form */ public String getFORMID() { checkSparseColumn(IDX_FORMID); return _col1; } /** * @param FORMID Form id of the associated generic form */ protected void setFORMID(String FORMID) { checkNull(FORMID); _col1 = FORMID; markUsed(IDX_FORMID); } /** * @return Form version number of the associated generic form */ public int getFORMVERSION() { checkSparseColumn(IDX_FORMVERSION); return _col2; } /** * @param FORMVERSION Form version number of the associated generic form */ protected void setFORMVERSION(int FORMVERSION) { _col2 = FORMVERSION; markUsed(IDX_FORMVERSION); } /** * @return Form item id of the associated input field */ public String getFORMITEMID() { checkSparseColumn(IDX_FORMITEMID); return _col3; } /** * @param FORMITEMID Form item id of the associated input field */ protected void setFORMITEMID(String FORMITEMID) { checkNull(FORMITEMID); _col3 = FORMITEMID; markUsed(IDX_FORMITEMID); } /** * @return Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox */ public String getVALUELISTID() { checkSparseColumn(IDX_VALUELISTID); return _col4; } /** * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox */ protected void setVALUELISTID(String VALUELISTID) { checkNull(VALUELISTID); _col4 = VALUELISTID; markUsed(IDX_VALUELISTID); } /** * @return Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox */ public String getVALUEID() { checkSparseColumn(IDX_VALUEID); return _col5; } /** * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox */ protected void setVALUEID(String VALUEID) { checkNull(VALUEID); _col5 = VALUEID; markUsed(IDX_VALUEID); } /** * @return Type of form item:
RDBT - RadioButton
COMB - ComboBox
CHKB - CheckBox
TEXT - TextInput
NUMF - NumericInput
SIGN - Signature
TITL - Title
SEPR - Separator */ public String getFORMITEMTYPE() { checkSparseColumn(IDX_FORMITEMTYPE); return _col6; } /** * @param FORMITEMTYPE Type of form item:
RDBT - RadioButton
COMB - ComboBox
CHKB - CheckBox
TEXT - TextInput
NUMF - NumericInput
SIGN - Signature
TITL - Title
SEPR - Separator */ public void setFORMITEMTYPE(String FORMITEMTYPE) { checkNull(FORMITEMTYPE); _col6 = FORMITEMTYPE; markUsed(IDX_FORMITEMTYPE); } /** * @return Text value of arbitrary length. Used for textlike input fields: TextInput */ public String getSTRINGVALUE() { checkSparseColumn(IDX_STRINGVALUE); return _col7; } /** * @param STRINGVALUE Text value of arbitrary length. Used for textlike input fields: TextInput */ public void setSTRINGVALUE(String STRINGVALUE) { checkNull(STRINGVALUE); _col7 = STRINGVALUE; markUsed(IDX_STRINGVALUE); } /** * @return Boolean value. Used for boolean like input fields: CheckBox */ public boolean isBOOLEANVALUE() { checkSparseColumn(IDX_BOOLEANVALUE); return _col8; } /** * @param BOOLEANVALUE Boolean value. Used for boolean like input fields: CheckBox */ public void setBOOLEANVALUE(boolean BOOLEANVALUE) { _col8 = BOOLEANVALUE; markUsed(IDX_BOOLEANVALUE); } /** * @return Numeric value. Used for number like input fields: NumericInput */ public double getFLOATVALUE() { checkSparseColumn(IDX_FLOATVALUE); return _col9; } /** * @param FLOATVALUE Numeric value. Used for number like input fields: NumericInput */ public void setFLOATVALUE(double FLOATVALUE) { _col9 = FLOATVALUE; markUsed(IDX_FLOATVALUE); } /** * @return Attachment (= filepath) value. Used for data like input fields: Signature */ public String getATTACHMENTVALUE() { checkSparseColumn(IDX_ATTACHMENTVALUE); return _col10; } /** * @param ATTACHMENTVALUE Attachment (= filepath) value. Used for data like input fields: Signature */ public void setATTACHMENTVALUE(String ATTACHMENTVALUE) { checkNull(ATTACHMENTVALUE); _col10 = ATTACHMENTVALUE; markUsed(IDX_ATTACHMENTVALUE); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("GUID"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GUID)) sb.append('\'').append(_col0).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMVERSION"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMVERSION)) sb.append(_col2); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMITEMID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMITEMID)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUELISTID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUELISTID)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUEID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUEID)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMITEMTYPE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMITEMTYPE)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STRINGVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STRINGVALUE)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BOOLEANVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BOOLEANVALUE)) sb.append(_col8); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FLOATVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FLOATVALUE)) sb.append(_col9); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ATTACHMENTVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ATTACHMENTVALUE)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new FORMINSTANCECursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new FORMINSTANCECursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link FORMINSTANCECursor} * instance. Use an instance of {@link FORMINSTANCECursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static FORMINSTANCE get(RecordSet rs, boolean selectStar) { FORMINSTANCE result = new FORMINSTANCE(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static FORMINSTANCE[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static FORMINSTANCE[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); FORMINSTANCE row = new FORMINSTANCE(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new FORMINSTANCE(row)); return (FORMINSTANCE[]) list.toArray(new FORMINSTANCE[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static FORMINSTANCE[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static FORMINSTANCE[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(FORMINSTANCE row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof FORMINSTANCE)) return false; FORMINSTANCE test = (FORMINSTANCE) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && _col2 != test._col2) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && _col8 != test._col8) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && _col9 != test._col9) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID) { return queryByPrimaryKey(row, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, String FORMID) { return queryByPrimaryKey(row, GUID, false, FORMID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String FORMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, String FORMID, int FORMVERSION) { return queryByPrimaryKey(row, GUID, false, FORMID, false, FORMVERSION); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String FORMID, int FORMVERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, String FORMID, int FORMVERSION, String FORMITEMID) { return queryByPrimaryKey(row, GUID, false, FORMID, false, FORMVERSION, FORMITEMID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String FORMID, int FORMVERSION, String FORMITEMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, String VALUELISTID, boolean likeVALUELISTID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, String FORMID, int FORMVERSION, String FORMITEMID, String VALUELISTID) { return queryByPrimaryKey(row, GUID, false, FORMID, false, FORMVERSION, FORMITEMID, false, VALUELISTID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, String VALUELISTID, boolean likeVALUELISTID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, String VALUELISTID, boolean likeVALUELISTID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String FORMID, int FORMVERSION, String FORMITEMID, String VALUELISTID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append("=").append(sqlHelper.get(VALUELISTID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUEID Set to true if the query for VALUEID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, String VALUELISTID, boolean likeVALUELISTID, String VALUEID, boolean likeVALUEID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append(likeVALUEID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUEID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox * @return The result of the database access. */ public static FORMINSTANCE getByPrimaryKey(DBSession db, String GUID, String FORMID, int FORMVERSION, String FORMITEMID, String VALUELISTID, String VALUEID) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append("=").append(sqlHelper.get(VALUELISTID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append("=").append(sqlHelper.get(VALUEID)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUEID Set to true if the query for VALUEID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, String VALUELISTID, boolean likeVALUELISTID, String VALUEID, boolean likeVALUEID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append(likeVALUEID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUEID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param FORMID Form id of the associated generic form * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param likeFORMITEMID Set to true if the query for FORMITEMID * should be based on LIKE instead of equality. * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox * @param likeVALUEID Set to true if the query for VALUEID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String FORMID, boolean likeFORMID, int FORMVERSION, String FORMITEMID, boolean likeFORMITEMID, String VALUELISTID, boolean likeVALUELISTID, String VALUEID, boolean likeVALUEID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append(likeFORMITEMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMITEMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append(likeVALUEID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUEID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID GUID of the associated report * @param FORMID Form id of the associated generic form * @param FORMVERSION Form version number of the associated generic form * @param FORMITEMID Form item id of the associated input field * @param VALUELISTID Id of the value list a value was chosen from (sedd ValueId). Used for list like input fields: RadioButton, ComboBox * @param VALUEID Id of the value chosen from a value list (see ValueListId). Used for list like input fields: RadioButton, ComboBox * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String FORMID, int FORMVERSION, String FORMITEMID, String VALUELISTID, String VALUEID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMITEMID).append("=").append(sqlHelper.get(FORMITEMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append("=").append(sqlHelper.get(VALUELISTID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append("=").append(sqlHelper.get(VALUEID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMINSTANCE row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMINSTANCE[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ sb.append(", ").append(COL_FORMITEMID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUELISTID); //$NON-NLS-1$ sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table FORMINSTANCE. */ class FORMINSTANCECursor implements TableCursor { interface ColAccessor { public void set(FORMINSTANCE table, RecordSet rs, int index); public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_GUID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setFORMID(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_FORMID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setFORMVERSION(rs.getInt(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_FORMVERSION, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setFORMITEMID(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_FORMITEMID, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setVALUELISTID(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_VALUELISTID, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setVALUEID(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_VALUEID, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setFORMITEMTYPE(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_FORMITEMTYPE, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setSTRINGVALUE(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_STRINGVALUE, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setBOOLEANVALUE(rs.getBoolean(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_BOOLEANVALUE, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setFLOATVALUE(rs.getDouble(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_FLOATVALUE, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(FORMINSTANCE table, RecordSet rs, int index) { table.setATTACHMENTVALUE(rs.getString(index)); } public void setUpdate(FORMINSTANCE table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMINSTANCE.COL_ATTACHMENTVALUE, table._col10); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[FORMINSTANCE.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(FORMINSTANCE.COL_GUID, new Integer(FORMINSTANCE.IDX_GUID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(FORMINSTANCE.COL_FORMID, new Integer(FORMINSTANCE.IDX_FORMID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(FORMINSTANCE.COL_FORMVERSION, new Integer(FORMINSTANCE.IDX_FORMVERSION)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(FORMINSTANCE.COL_FORMITEMID, new Integer(FORMINSTANCE.IDX_FORMITEMID)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(FORMINSTANCE.COL_VALUELISTID, new Integer(FORMINSTANCE.IDX_VALUELISTID)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(FORMINSTANCE.COL_VALUEID, new Integer(FORMINSTANCE.IDX_VALUEID)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(FORMINSTANCE.COL_FORMITEMTYPE, new Integer(FORMINSTANCE.IDX_FORMITEMTYPE)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(FORMINSTANCE.COL_STRINGVALUE, new Integer(FORMINSTANCE.IDX_STRINGVALUE)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(FORMINSTANCE.COL_BOOLEANVALUE, new Integer(FORMINSTANCE.IDX_BOOLEANVALUE)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(FORMINSTANCE.COL_FLOATVALUE, new Integer(FORMINSTANCE.IDX_FLOATVALUE)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(FORMINSTANCE.COL_ATTACHMENTVALUE, new Integer(FORMINSTANCE.IDX_ATTACHMENTVALUE)); } return s_accessor; } /** * */ private final FORMINSTANCE m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new FORMINSTANCECursor(row, rs, false). * * @param forminstance * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMINSTANCECursor(FORMINSTANCE row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM FORMINSTANCE WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMINSTANCECursor(FORMINSTANCE row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link FORMINSTANCE} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/FORMITEM.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.FORMITEMCursor.ColAccessor; /** * Generic forms field/content data. SAP tables: ZKDMOB_FORM_ITEM, ZKDMOB_FORM_I_T */ public class FORMITEM extends TableRow { /** Name of table: FORMITEM */ public final static String TABLE = "FORMITEM"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 18; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iRDBT - RadioButton
COMB - ComboBox
CHKB - CheckBox
TEXT - TextInput
NUMF - NumericInput
SIGN - Signature
TITL - Title
SEPR - Separator * @param SEQUENCE Sort index of the form item * @param LABEL Form item label * @param MANDATORY true if the field is a mandatory entry field * @param CARDNAME If given the form item is placed inside a card with other consecuting items having the same CardName. Note: nested cards are not supported * @param OBSOLETE true if the field is obsolete, i.e. not shown any more if empty/initial on initial form rendering * @param VALUELISTID Reference to relevant value list (RadioButton and ComboBox only) * @param EMPTYTEXT Text to display if no value was chosen (ComboBox only) * @param GROUPNAME Header text for grouping consecutive CheckBox items (CheckBox only) * @param MAXSTRINGSIZE Maximum string length (TextInput only) * @param VALIDATIONREGEX Regular expression for validating entered text (TextInput only) * @param MULTILINE true for multiline text input style (TextInput only) * @param FORMAT Type of numeric input (NumericInput only):
0.0 - no decimals
0.1 - 1 decimal
0.2 - 2 decimals
0.3 - 3 decimals
0.4 - 4 decimals
0.5 - 5 decimals * @param MINVALUE Minimum value allowed (inclusive; NumericInput only) * @param MAXVALUE Maximum value allowed (inclusive; NumericInput only) */ public FORMITEM(DBSession db, String FORMID, int FORMVERSION, String ID, String FORMITEMTYPE, int SEQUENCE, String LABEL, boolean MANDATORY, String CARDNAME, boolean OBSOLETE, String VALUELISTID, String EMPTYTEXT, String GROUPNAME, int MAXSTRINGSIZE, String VALIDATIONREGEX, boolean MULTILINE, String FORMAT, double MINVALUE, double MAXVALUE) { super(db, null); _col0 = FORMID; _col1 = FORMVERSION; _col2 = ID; _col3 = FORMITEMTYPE; _col4 = SEQUENCE; _col5 = LABEL; _col6 = MANDATORY; _col7 = CARDNAME; _col8 = OBSOLETE; _col9 = VALUELISTID; _col10 = EMPTYTEXT; _col11 = GROUPNAME; _col12 = MAXSTRINGSIZE; _col13 = VALIDATIONREGEX; _col14 = MULTILINE; _col15 = FORMAT; _col16 = MINVALUE; _col17 = MAXVALUE; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public FORMITEM(FORMITEM source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_FORMID)) _col0 = source._col0; if (isColumnSet(IDX_FORMVERSION)) _col1 = source._col1; if (isColumnSet(IDX_ID)) _col2 = source._col2; if (isColumnSet(IDX_FORMITEMTYPE)) _col3 = source._col3; if (isColumnSet(IDX_SEQUENCE)) _col4 = source._col4; if (isColumnSet(IDX_LABEL)) _col5 = source._col5; if (isColumnSet(IDX_MANDATORY)) _col6 = source._col6; if (isColumnSet(IDX_CARDNAME)) _col7 = source._col7; if (isColumnSet(IDX_OBSOLETE)) _col8 = source._col8; if (isColumnSet(IDX_VALUELISTID)) _col9 = source._col9; if (isColumnSet(IDX_EMPTYTEXT)) _col10 = source._col10; if (isColumnSet(IDX_GROUPNAME)) _col11 = source._col11; if (isColumnSet(IDX_MAXSTRINGSIZE)) _col12 = source._col12; if (isColumnSet(IDX_VALIDATIONREGEX)) _col13 = source._col13; if (isColumnSet(IDX_MULTILINE)) _col14 = source._col14; if (isColumnSet(IDX_FORMAT)) _col15 = source._col15; if (isColumnSet(IDX_MINVALUE)) _col16 = source._col16; if (isColumnSet(IDX_MAXVALUE)) _col17 = source._col17; } else { // copy all columns if (isColumnSet(IDX_FORMID)) _col0 = source._col0; if (isColumnSet(IDX_FORMVERSION)) _col1 = source._col1; if (isColumnSet(IDX_ID)) _col2 = source._col2; if (isColumnSet(IDX_FORMITEMTYPE)) _col3 = source._col3; if (isColumnSet(IDX_SEQUENCE)) _col4 = source._col4; if (isColumnSet(IDX_LABEL)) _col5 = source._col5; if (isColumnSet(IDX_MANDATORY)) _col6 = source._col6; if (isColumnSet(IDX_CARDNAME)) _col7 = source._col7; if (isColumnSet(IDX_OBSOLETE)) _col8 = source._col8; if (isColumnSet(IDX_VALUELISTID)) _col9 = source._col9; if (isColumnSet(IDX_EMPTYTEXT)) _col10 = source._col10; if (isColumnSet(IDX_GROUPNAME)) _col11 = source._col11; if (isColumnSet(IDX_MAXSTRINGSIZE)) _col12 = source._col12; if (isColumnSet(IDX_VALIDATIONREGEX)) _col13 = source._col13; if (isColumnSet(IDX_MULTILINE)) _col14 = source._col14; if (isColumnSet(IDX_FORMAT)) _col15 = source._col15; if (isColumnSet(IDX_MINVALUE)) _col16 = source._col16; if (isColumnSet(IDX_MAXVALUE)) _col17 = source._col17; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param FORMID Form id * @param FORMVERSION Form version number * @param ID Form item id * @param source */ public FORMITEM(String ID, String FORMID, int FORMVERSION, FORMITEM source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col2 = ID; _col0 = FORMID; _col1 = FORMVERSION; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_FORMITEMTYPE)) _col3 = source._col3; if (isColumnSet(IDX_SEQUENCE)) _col4 = source._col4; if (isColumnSet(IDX_LABEL)) _col5 = source._col5; if (isColumnSet(IDX_MANDATORY)) _col6 = source._col6; if (isColumnSet(IDX_CARDNAME)) _col7 = source._col7; if (isColumnSet(IDX_OBSOLETE)) _col8 = source._col8; if (isColumnSet(IDX_VALUELISTID)) _col9 = source._col9; if (isColumnSet(IDX_EMPTYTEXT)) _col10 = source._col10; if (isColumnSet(IDX_GROUPNAME)) _col11 = source._col11; if (isColumnSet(IDX_MAXSTRINGSIZE)) _col12 = source._col12; if (isColumnSet(IDX_VALIDATIONREGEX)) _col13 = source._col13; if (isColumnSet(IDX_MULTILINE)) _col14 = source._col14; if (isColumnSet(IDX_FORMAT)) _col15 = source._col15; if (isColumnSet(IDX_MINVALUE)) _col16 = source._col16; if (isColumnSet(IDX_MAXVALUE)) _col17 = source._col17; } else { // copy all columns excluding the primary key _col3 = source._col3; _col4 = source._col4; _col5 = source._col5; _col6 = source._col6; _col7 = source._col7; _col8 = source._col8; _col9 = source._col9; _col10 = source._col10; _col11 = source._col11; _col12 = source._col12; _col13 = source._col13; _col14 = source._col14; _col15 = source._col15; _col16 = source._col16; _col17 = source._col17; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public FORMITEM(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); if ((m_usedColumns == null || !m_usedColumns.get(IDX_ID)) && _col2 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_ID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_FORMID)) && _col0 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_FORMID)); //$NON-NLS-1$ } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_ID)) m_usedColumns.clear(IDX_ID); if (usedColumns == null || !usedColumns.get(IDX_FORMID)) m_usedColumns.clear(IDX_FORMID); if (usedColumns == null || !usedColumns.get(IDX_FORMVERSION)) m_usedColumns.clear(IDX_FORMVERSION); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_FORMITEMTYPE)) _col3 = DEF_FORMITEMTYPE; if (m_usedColumns.get(IDX_SEQUENCE)) _col4 = DEF_SEQUENCE; if (m_usedColumns.get(IDX_LABEL)) _col5 = DEF_LABEL; if (m_usedColumns.get(IDX_MANDATORY)) _col6 = DEF_MANDATORY; if (m_usedColumns.get(IDX_CARDNAME)) _col7 = DEF_CARDNAME; if (m_usedColumns.get(IDX_OBSOLETE)) _col8 = DEF_OBSOLETE; if (m_usedColumns.get(IDX_VALUELISTID)) _col9 = DEF_VALUELISTID; if (m_usedColumns.get(IDX_EMPTYTEXT)) _col10 = DEF_EMPTYTEXT; if (m_usedColumns.get(IDX_GROUPNAME)) _col11 = DEF_GROUPNAME; if (m_usedColumns.get(IDX_MAXSTRINGSIZE)) _col12 = DEF_MAXSTRINGSIZE; if (m_usedColumns.get(IDX_VALIDATIONREGEX)) _col13 = DEF_VALIDATIONREGEX; if (m_usedColumns.get(IDX_MULTILINE)) _col14 = DEF_MULTILINE; if (m_usedColumns.get(IDX_FORMAT)) _col15 = DEF_FORMAT; if (m_usedColumns.get(IDX_MINVALUE)) _col16 = DEF_MINVALUE; if (m_usedColumns.get(IDX_MAXVALUE)) _col17 = DEF_MAXVALUE; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_ID) || !isColumnSet(IDX_FORMID) || !isColumnSet(IDX_FORMVERSION) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append('=').append(sqlHelper.get(_col2)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append('=').append(sqlHelper.get(_col0)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append('=').append(sqlHelper.get(_col1)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); sqlHelper.in(_col0); sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); sqlHelper.in(_col5); sqlHelper.in(_col6); sqlHelper.in(_col7); sqlHelper.in(_col8); sqlHelper.in(_col9); sqlHelper.in(_col10); sqlHelper.in(_col11); sqlHelper.in(_col12); sqlHelper.in(_col13); sqlHelper.in(_col14); sqlHelper.in(_col15); sqlHelper.in(_col16); sqlHelper.in(_col17); getDBSession().executeSql(sqlHelper.toString()); } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = FORMITEMCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_FORMITEMTYPE, _col3); sqlHelper.in(COL_SEQUENCE, _col4); sqlHelper.in(COL_LABEL, _col5); sqlHelper.in(COL_MANDATORY, _col6); sqlHelper.in(COL_CARDNAME, _col7); sqlHelper.in(COL_OBSOLETE, _col8); sqlHelper.in(COL_VALUELISTID, _col9); sqlHelper.in(COL_EMPTYTEXT, _col10); sqlHelper.in(COL_GROUPNAME, _col11); sqlHelper.in(COL_MAXSTRINGSIZE, _col12); sqlHelper.in(COL_VALIDATIONREGEX, _col13); sqlHelper.in(COL_MULTILINE, _col14); sqlHelper.in(COL_FORMAT, _col15); sqlHelper.in(COL_MINVALUE, _col16); sqlHelper.in(COL_MAXVALUE, _col17); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return Form id */ public String getFORMID() { checkSparseColumn(IDX_FORMID); return _col0; } /** * @param FORMID Form id */ protected void setFORMID(String FORMID) { checkNull(FORMID); _col0 = FORMID; markUsed(IDX_FORMID); } /** * @return Form version number */ public int getFORMVERSION() { checkSparseColumn(IDX_FORMVERSION); return _col1; } /** * @param FORMVERSION Form version number */ protected void setFORMVERSION(int FORMVERSION) { _col1 = FORMVERSION; markUsed(IDX_FORMVERSION); } /** * @return Form item id */ public String getID() { checkSparseColumn(IDX_ID); return _col2; } /** * @param ID Form item id */ protected void setID(String ID) { checkNull(ID); _col2 = ID; markUsed(IDX_ID); } /** * @return Type of form item:
RDBT - RadioButton
COMB - ComboBox
CHKB - CheckBox
TEXT - TextInput
NUMF - NumericInput
SIGN - Signature
TITL - Title
SEPR - Separator */ public String getFORMITEMTYPE() { checkSparseColumn(IDX_FORMITEMTYPE); return _col3; } /** * @param FORMITEMTYPE Type of form item:
RDBT - RadioButton
COMB - ComboBox
CHKB - CheckBox
TEXT - TextInput
NUMF - NumericInput
SIGN - Signature
TITL - Title
SEPR - Separator */ public void setFORMITEMTYPE(String FORMITEMTYPE) { checkNull(FORMITEMTYPE); _col3 = FORMITEMTYPE; markUsed(IDX_FORMITEMTYPE); } /** * @return Sort index of the form item */ public int getSEQUENCE() { checkSparseColumn(IDX_SEQUENCE); return _col4; } /** * @param SEQUENCE Sort index of the form item */ public void setSEQUENCE(int SEQUENCE) { _col4 = SEQUENCE; markUsed(IDX_SEQUENCE); } /** * @return Form item label */ public String getLABEL() { checkSparseColumn(IDX_LABEL); return _col5; } /** * @param LABEL Form item label */ public void setLABEL(String LABEL) { checkNull(LABEL); _col5 = LABEL; markUsed(IDX_LABEL); } /** * @return true if the field is a mandatory entry field */ public boolean isMANDATORY() { checkSparseColumn(IDX_MANDATORY); return _col6; } /** * @param MANDATORY true if the field is a mandatory entry field */ public void setMANDATORY(boolean MANDATORY) { _col6 = MANDATORY; markUsed(IDX_MANDATORY); } /** * @return If given the form item is placed inside a card with other consecuting items having the same CardName. Note: nested cards are not supported */ public String getCARDNAME() { checkSparseColumn(IDX_CARDNAME); return _col7; } /** * @param CARDNAME If given the form item is placed inside a card with other consecuting items having the same CardName. Note: nested cards are not supported */ public void setCARDNAME(String CARDNAME) { checkNull(CARDNAME); _col7 = CARDNAME; markUsed(IDX_CARDNAME); } /** * @return true if the field is obsolete, i.e. not shown any more if empty/initial on initial form rendering */ public boolean isOBSOLETE() { checkSparseColumn(IDX_OBSOLETE); return _col8; } /** * @param OBSOLETE true if the field is obsolete, i.e. not shown any more if empty/initial on initial form rendering */ public void setOBSOLETE(boolean OBSOLETE) { _col8 = OBSOLETE; markUsed(IDX_OBSOLETE); } /** * @return Reference to relevant value list (RadioButton and ComboBox only) */ public String getVALUELISTID() { checkSparseColumn(IDX_VALUELISTID); return _col9; } /** * @param VALUELISTID Reference to relevant value list (RadioButton and ComboBox only) */ public void setVALUELISTID(String VALUELISTID) { checkNull(VALUELISTID); _col9 = VALUELISTID; markUsed(IDX_VALUELISTID); } /** * @return Text to display if no value was chosen (ComboBox only) */ public String getEMPTYTEXT() { checkSparseColumn(IDX_EMPTYTEXT); return _col10; } /** * @param EMPTYTEXT Text to display if no value was chosen (ComboBox only) */ public void setEMPTYTEXT(String EMPTYTEXT) { checkNull(EMPTYTEXT); _col10 = EMPTYTEXT; markUsed(IDX_EMPTYTEXT); } /** * @return Header text for grouping consecutive CheckBox items (CheckBox only) */ public String getGROUPNAME() { checkSparseColumn(IDX_GROUPNAME); return _col11; } /** * @param GROUPNAME Header text for grouping consecutive CheckBox items (CheckBox only) */ public void setGROUPNAME(String GROUPNAME) { checkNull(GROUPNAME); _col11 = GROUPNAME; markUsed(IDX_GROUPNAME); } /** * @return Maximum string length (TextInput only) */ public int getMAXSTRINGSIZE() { checkSparseColumn(IDX_MAXSTRINGSIZE); return _col12; } /** * @param MAXSTRINGSIZE Maximum string length (TextInput only) */ public void setMAXSTRINGSIZE(int MAXSTRINGSIZE) { _col12 = MAXSTRINGSIZE; markUsed(IDX_MAXSTRINGSIZE); } /** * @return Regular expression for validating entered text (TextInput only) */ public String getVALIDATIONREGEX() { checkSparseColumn(IDX_VALIDATIONREGEX); return _col13; } /** * @param VALIDATIONREGEX Regular expression for validating entered text (TextInput only) */ public void setVALIDATIONREGEX(String VALIDATIONREGEX) { checkNull(VALIDATIONREGEX); _col13 = VALIDATIONREGEX; markUsed(IDX_VALIDATIONREGEX); } /** * @return true for multiline text input style (TextInput only) */ public boolean isMULTILINE() { checkSparseColumn(IDX_MULTILINE); return _col14; } /** * @param MULTILINE true for multiline text input style (TextInput only) */ public void setMULTILINE(boolean MULTILINE) { _col14 = MULTILINE; markUsed(IDX_MULTILINE); } /** * @return Type of numeric input (NumericInput only):
0.0 - no decimals
0.1 - 1 decimal
0.2 - 2 decimals
0.3 - 3 decimals
0.4 - 4 decimals
0.5 - 5 decimals */ public String getFORMAT() { checkSparseColumn(IDX_FORMAT); return _col15; } /** * @param FORMAT Type of numeric input (NumericInput only):
0.0 - no decimals
0.1 - 1 decimal
0.2 - 2 decimals
0.3 - 3 decimals
0.4 - 4 decimals
0.5 - 5 decimals */ public void setFORMAT(String FORMAT) { checkNull(FORMAT); _col15 = FORMAT; markUsed(IDX_FORMAT); } /** * @return Minimum value allowed (inclusive; NumericInput only) */ public double getMINVALUE() { checkSparseColumn(IDX_MINVALUE); return _col16; } /** * @param MINVALUE Minimum value allowed (inclusive; NumericInput only) */ public void setMINVALUE(double MINVALUE) { _col16 = MINVALUE; markUsed(IDX_MINVALUE); } /** * @return Maximum value allowed (inclusive; NumericInput only) */ public double getMAXVALUE() { checkSparseColumn(IDX_MAXVALUE); return _col17; } /** * @param MAXVALUE Maximum value allowed (inclusive; NumericInput only) */ public void setMAXVALUE(double MAXVALUE) { _col17 = MAXVALUE; markUsed(IDX_MAXVALUE); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("FORMID"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMID)) sb.append('\'').append(_col0).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMVERSION"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMVERSION)) sb.append(_col1); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ID)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMITEMTYPE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMITEMTYPE)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SEQUENCE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SEQUENCE)) sb.append(_col4); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LABEL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LABEL)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MANDATORY"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MANDATORY)) sb.append(_col6); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CARDNAME"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CARDNAME)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("OBSOLETE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_OBSOLETE)) sb.append(_col8); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUELISTID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUELISTID)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EMPTYTEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EMPTYTEXT)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("GROUPNAME"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GROUPNAME)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAXSTRINGSIZE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAXSTRINGSIZE)) sb.append(_col12); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALIDATIONREGEX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALIDATIONREGEX)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MULTILINE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MULTILINE)) sb.append(_col14); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMAT)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MINVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MINVALUE)) sb.append(_col16); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAXVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAXVALUE)) sb.append(_col17); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new FORMITEMCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new FORMITEMCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link FORMITEMCursor} * instance. Use an instance of {@link FORMITEMCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static FORMITEM get(RecordSet rs, boolean selectStar) { FORMITEM result = new FORMITEM(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static FORMITEM[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static FORMITEM[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); FORMITEM row = new FORMITEM(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new FORMITEM(row)); return (FORMITEM[]) list.toArray(new FORMITEM[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static FORMITEM[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static FORMITEM[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(FORMITEM row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof FORMITEM)) return false; FORMITEM test = (FORMITEM) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && _col4 != test._col4) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && _col6 != test._col6) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && _col8 != test._col8) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && _col12 != test._col12) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && _col14 != test._col14) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; if ((m_usedColumns == null || !m_usedColumns.get(16)) && _col16 != test._col16) return false; if ((m_usedColumns == null || !m_usedColumns.get(17)) && _col17 != test._col17) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMITEM row, String ID, boolean likeID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form item id * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMITEM row, String ID) { return queryByPrimaryKey(row, ID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMITEM[] listByPrimaryKey(DBSession db, String ID, boolean likeID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, boolean likeID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form item id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMITEM row, String ID, boolean likeID, String FORMID, boolean likeFORMID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form item id * @param FORMID Form id * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMITEM row, String ID, String FORMID) { return queryByPrimaryKey(row, ID, false, FORMID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMITEM[] listByPrimaryKey(DBSession db, String ID, boolean likeID, String FORMID, boolean likeFORMID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, boolean likeID, String FORMID, boolean likeFORMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form item id * @param FORMID Form id * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, String FORMID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMITEM row, String ID, boolean likeID, String FORMID, boolean likeFORMID, int FORMVERSION) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param ID Form item id * @param FORMID Form id * @param FORMVERSION Form version number * @return The result of the database access. */ public static FORMITEM getByPrimaryKey(DBSession db, String ID, String FORMID, int FORMVERSION) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMITEM[] listByPrimaryKey(DBSession db, String ID, boolean likeID, String FORMID, boolean likeFORMID, int FORMVERSION, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form item id * @param likeID Set to true if the query for ID * should be based on LIKE instead of equality. * @param FORMID Form id * @param likeFORMID Set to true if the query for FORMID * should be based on LIKE instead of equality. * @param FORMVERSION Form version number * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, boolean likeID, String FORMID, boolean likeFORMID, int FORMVERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append(likeID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append(likeFORMID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=") //$NON-NLS-1$ .append(sqlHelper.get(FORMVERSION)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ID Form item id * @param FORMID Form id * @param FORMVERSION Form version number * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ID, String FORMID, int FORMVERSION) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ID).append("=").append(sqlHelper.get(ID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMID).append("=").append(sqlHelper.get(FORMID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FORMVERSION).append("=").append(sqlHelper.get(FORMVERSION)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMITEM row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMITEM[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ID); sb.append(", ").append(COL_FORMID); //$NON-NLS-1$ sb.append(", ").append(COL_FORMVERSION); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table FORMITEM. */ class FORMITEMCursor implements TableCursor { interface ColAccessor { public void set(FORMITEM table, RecordSet rs, int index); public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setFORMID(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_FORMID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setFORMVERSION(rs.getInt(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_FORMVERSION, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setID(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_ID, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setFORMITEMTYPE(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_FORMITEMTYPE, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setSEQUENCE(rs.getInt(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_SEQUENCE, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setLABEL(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_LABEL, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setMANDATORY(rs.getBoolean(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_MANDATORY, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setCARDNAME(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_CARDNAME, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setOBSOLETE(rs.getBoolean(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_OBSOLETE, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setVALUELISTID(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_VALUELISTID, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setEMPTYTEXT(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_EMPTYTEXT, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setGROUPNAME(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_GROUPNAME, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setMAXSTRINGSIZE(rs.getInt(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_MAXSTRINGSIZE, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setVALIDATIONREGEX(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_VALIDATIONREGEX, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setMULTILINE(rs.getBoolean(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_MULTILINE, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setFORMAT(rs.getString(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_FORMAT, table._col15); } } private static class Col16Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setMINVALUE(rs.getDouble(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_MINVALUE, table._col16); } } private static class Col17Accessor implements ColAccessor { public final void set(FORMITEM table, RecordSet rs, int index) { table.setMAXVALUE(rs.getDouble(index)); } public void setUpdate(FORMITEM table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMITEM.COL_MAXVALUE, table._col17); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[FORMITEM.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(FORMITEM.COL_FORMID, new Integer(FORMITEM.IDX_FORMID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(FORMITEM.COL_FORMVERSION, new Integer(FORMITEM.IDX_FORMVERSION)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(FORMITEM.COL_ID, new Integer(FORMITEM.IDX_ID)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(FORMITEM.COL_FORMITEMTYPE, new Integer(FORMITEM.IDX_FORMITEMTYPE)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(FORMITEM.COL_SEQUENCE, new Integer(FORMITEM.IDX_SEQUENCE)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(FORMITEM.COL_LABEL, new Integer(FORMITEM.IDX_LABEL)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(FORMITEM.COL_MANDATORY, new Integer(FORMITEM.IDX_MANDATORY)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(FORMITEM.COL_CARDNAME, new Integer(FORMITEM.IDX_CARDNAME)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(FORMITEM.COL_OBSOLETE, new Integer(FORMITEM.IDX_OBSOLETE)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(FORMITEM.COL_VALUELISTID, new Integer(FORMITEM.IDX_VALUELISTID)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(FORMITEM.COL_EMPTYTEXT, new Integer(FORMITEM.IDX_EMPTYTEXT)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(FORMITEM.COL_GROUPNAME, new Integer(FORMITEM.IDX_GROUPNAME)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(FORMITEM.COL_MAXSTRINGSIZE, new Integer(FORMITEM.IDX_MAXSTRINGSIZE)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(FORMITEM.COL_VALIDATIONREGEX, new Integer(FORMITEM.IDX_VALIDATIONREGEX)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(FORMITEM.COL_MULTILINE, new Integer(FORMITEM.IDX_MULTILINE)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(FORMITEM.COL_FORMAT, new Integer(FORMITEM.IDX_FORMAT)); s_accessor[16] = new Col16Accessor(); s_accessorMap.put(FORMITEM.COL_MINVALUE, new Integer(FORMITEM.IDX_MINVALUE)); s_accessor[17] = new Col17Accessor(); s_accessorMap.put(FORMITEM.COL_MAXVALUE, new Integer(FORMITEM.IDX_MAXVALUE)); } return s_accessor; } /** * */ private final FORMITEM m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new FORMITEMCursor(row, rs, false). * * @param formitem * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMITEMCursor(FORMITEM row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM FORMITEM WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMITEMCursor(FORMITEM row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link FORMITEM} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/FORMVALUELIST.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.FORMVALUELISTCursor.ColAccessor; /** * Values in value lists for use in combobox and radiobox items. SAP tables: ZKDMOB_FORM_VLS, ZKDMOB_FORM_VLST, ZKDMOB_FORM_VAL, ZKDMOB_FORM_VALT */ public class FORMVALUELIST extends TableRow { /** Name of table: FORMVALUELIST */ public final static String TABLE = "FORMVALUELIST"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; itrue if the value is the default value to be prefilled in referencing items on generic form instance creation. * @param VALUE UI representation of the value */ public FORMVALUELIST(DBSession db, String VALUELISTID, String VALUEID, int SEQUENCE, boolean DEFAULTVALUE, String VALUE) { super(db, null); _col0 = VALUELISTID; _col1 = VALUEID; _col2 = SEQUENCE; _col3 = DEFAULTVALUE; _col4 = VALUE; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public FORMVALUELIST(FORMVALUELIST source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_VALUELISTID)) _col0 = source._col0; if (isColumnSet(IDX_VALUEID)) _col1 = source._col1; if (isColumnSet(IDX_SEQUENCE)) _col2 = source._col2; if (isColumnSet(IDX_DEFAULTVALUE)) _col3 = source._col3; if (isColumnSet(IDX_VALUE)) _col4 = source._col4; } else { // copy all columns if (isColumnSet(IDX_VALUELISTID)) _col0 = source._col0; if (isColumnSet(IDX_VALUEID)) _col1 = source._col1; if (isColumnSet(IDX_SEQUENCE)) _col2 = source._col2; if (isColumnSet(IDX_DEFAULTVALUE)) _col3 = source._col3; if (isColumnSet(IDX_VALUE)) _col4 = source._col4; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param VALUELISTID Id of the value list * @param VALUEID Id of the value * @param source */ public FORMVALUELIST(String VALUELISTID, String VALUEID, FORMVALUELIST source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = VALUELISTID; _col1 = VALUEID; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_SEQUENCE)) _col2 = source._col2; if (isColumnSet(IDX_DEFAULTVALUE)) _col3 = source._col3; if (isColumnSet(IDX_VALUE)) _col4 = source._col4; } else { // copy all columns excluding the primary key _col2 = source._col2; _col3 = source._col3; _col4 = source._col4; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public FORMVALUELIST(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); if ((m_usedColumns == null || !m_usedColumns.get(IDX_VALUELISTID)) && _col0 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_VALUELISTID)); //$NON-NLS-1$ if ((m_usedColumns == null || !m_usedColumns.get(IDX_VALUEID)) && _col1 == null) throw new IllegalArgumentException(NLS.bind( "Primary key {0} must not be null!", COL_VALUEID)); //$NON-NLS-1$ } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_VALUELISTID)) m_usedColumns.clear(IDX_VALUELISTID); if (usedColumns == null || !usedColumns.get(IDX_VALUEID)) m_usedColumns.clear(IDX_VALUEID); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_SEQUENCE)) _col2 = DEF_SEQUENCE; if (m_usedColumns.get(IDX_DEFAULTVALUE)) _col3 = DEF_DEFAULTVALUE; if (m_usedColumns.get(IDX_VALUE)) _col4 = DEF_VALUE; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_VALUELISTID) || !isColumnSet(IDX_VALUEID) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append('=').append(sqlHelper.get(_col0)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append('=').append(sqlHelper.get(_col1)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); sqlHelper.in(_col0); sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); getDBSession().executeSql(sqlHelper.toString()); } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = FORMVALUELISTCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_SEQUENCE, _col2); sqlHelper.in(COL_DEFAULTVALUE, _col3); sqlHelper.in(COL_VALUE, _col4); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return Id of the value list */ public String getVALUELISTID() { checkSparseColumn(IDX_VALUELISTID); return _col0; } /** * @param VALUELISTID Id of the value list */ protected void setVALUELISTID(String VALUELISTID) { checkNull(VALUELISTID); _col0 = VALUELISTID; markUsed(IDX_VALUELISTID); } /** * @return Id of the value */ public String getVALUEID() { checkSparseColumn(IDX_VALUEID); return _col1; } /** * @param VALUEID Id of the value */ protected void setVALUEID(String VALUEID) { checkNull(VALUEID); _col1 = VALUEID; markUsed(IDX_VALUEID); } /** * @return Sort sequence of the values in a value list */ public int getSEQUENCE() { checkSparseColumn(IDX_SEQUENCE); return _col2; } /** * @param SEQUENCE Sort sequence of the values in a value list */ public void setSEQUENCE(int SEQUENCE) { _col2 = SEQUENCE; markUsed(IDX_SEQUENCE); } /** * @return true if the value is the default value to be prefilled in referencing items on generic form instance creation. */ public boolean isDEFAULTVALUE() { checkSparseColumn(IDX_DEFAULTVALUE); return _col3; } /** * @param DEFAULTVALUE true if the value is the default value to be prefilled in referencing items on generic form instance creation. */ public void setDEFAULTVALUE(boolean DEFAULTVALUE) { _col3 = DEFAULTVALUE; markUsed(IDX_DEFAULTVALUE); } /** * @return UI representation of the value */ public String getVALUE() { checkSparseColumn(IDX_VALUE); return _col4; } /** * @param VALUE UI representation of the value */ public void setVALUE(String VALUE) { checkNull(VALUE); _col4 = VALUE; markUsed(IDX_VALUE); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("VALUELISTID"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUELISTID)) sb.append('\'').append(_col0).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUEID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUEID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SEQUENCE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SEQUENCE)) sb.append(_col2); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DEFAULTVALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DEFAULTVALUE)) sb.append(_col3); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VALUE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VALUE)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new FORMVALUELISTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new FORMVALUELISTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link FORMVALUELISTCursor} * instance. Use an instance of {@link FORMVALUELISTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static FORMVALUELIST get(RecordSet rs, boolean selectStar) { FORMVALUELIST result = new FORMVALUELIST(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static FORMVALUELIST[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static FORMVALUELIST[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); FORMVALUELIST row = new FORMVALUELIST(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new FORMVALUELIST(row)); return (FORMVALUELIST[]) list.toArray(new FORMVALUELIST[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static FORMVALUELIST[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static FORMVALUELIST[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(FORMVALUELIST row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof FORMVALUELIST)) return false; FORMVALUELIST test = (FORMVALUELIST) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && _col2 != test._col2) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && _col3 != test._col3) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VALUELISTID Id of the value list * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMVALUELIST row, String VALUELISTID, boolean likeVALUELISTID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VALUELISTID); sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VALUELISTID Id of the value list * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMVALUELIST row, String VALUELISTID) { return queryByPrimaryKey(row, VALUELISTID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param VALUELISTID Id of the value list * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMVALUELIST[] listByPrimaryKey(DBSession db, String VALUELISTID, boolean likeVALUELISTID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VALUELISTID); sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VALUELISTID Id of the value list * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VALUELISTID, boolean likeVALUELISTID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VALUELISTID Id of the value list * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VALUELISTID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append("=").append(sqlHelper.get(VALUELISTID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VALUELISTID Id of the value list * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param VALUEID Id of the value * @param likeVALUEID Set to true if the query for VALUEID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMVALUELIST row, String VALUELISTID, boolean likeVALUELISTID, String VALUEID, boolean likeVALUEID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append(likeVALUEID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUEID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VALUELISTID); sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param VALUELISTID Id of the value list * @param VALUEID Id of the value * @return The result of the database access. */ public static FORMVALUELIST getByPrimaryKey(DBSession db, String VALUELISTID, String VALUEID) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append("=").append(sqlHelper.get(VALUELISTID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append("=").append(sqlHelper.get(VALUEID)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param VALUELISTID Id of the value list * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param VALUEID Id of the value * @param likeVALUEID Set to true if the query for VALUEID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMVALUELIST[] listByPrimaryKey(DBSession db, String VALUELISTID, boolean likeVALUELISTID, String VALUEID, boolean likeVALUEID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append(likeVALUEID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUEID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VALUELISTID); sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VALUELISTID Id of the value list * @param likeVALUELISTID Set to true if the query for VALUELISTID * should be based on LIKE instead of equality. * @param VALUEID Id of the value * @param likeVALUEID Set to true if the query for VALUEID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VALUELISTID, boolean likeVALUELISTID, String VALUEID, boolean likeVALUEID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append(likeVALUELISTID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUELISTID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append(likeVALUEID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VALUEID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VALUELISTID Id of the value list * @param VALUEID Id of the value * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VALUELISTID, String VALUEID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VALUELISTID).append("=").append(sqlHelper.get(VALUELISTID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VALUEID).append("=").append(sqlHelper.get(VALUEID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(FORMVALUELIST row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VALUELISTID); sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static FORMVALUELIST[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VALUELISTID); sb.append(", ").append(COL_VALUEID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table FORMVALUELIST. */ class FORMVALUELISTCursor implements TableCursor { interface ColAccessor { public void set(FORMVALUELIST table, RecordSet rs, int index); public void setUpdate(FORMVALUELIST table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(FORMVALUELIST table, RecordSet rs, int index) { table.setVALUELISTID(rs.getString(index)); } public void setUpdate(FORMVALUELIST table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMVALUELIST.COL_VALUELISTID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(FORMVALUELIST table, RecordSet rs, int index) { table.setVALUEID(rs.getString(index)); } public void setUpdate(FORMVALUELIST table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMVALUELIST.COL_VALUEID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(FORMVALUELIST table, RecordSet rs, int index) { table.setSEQUENCE(rs.getInt(index)); } public void setUpdate(FORMVALUELIST table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMVALUELIST.COL_SEQUENCE, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(FORMVALUELIST table, RecordSet rs, int index) { table.setDEFAULTVALUE(rs.getBoolean(index)); } public void setUpdate(FORMVALUELIST table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMVALUELIST.COL_DEFAULTVALUE, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(FORMVALUELIST table, RecordSet rs, int index) { table.setVALUE(rs.getString(index)); } public void setUpdate(FORMVALUELIST table, DBSqlHelper sqlHelper) { sqlHelper.in(FORMVALUELIST.COL_VALUE, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[FORMVALUELIST.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(FORMVALUELIST.COL_VALUELISTID, new Integer(FORMVALUELIST.IDX_VALUELISTID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(FORMVALUELIST.COL_VALUEID, new Integer(FORMVALUELIST.IDX_VALUEID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(FORMVALUELIST.COL_SEQUENCE, new Integer(FORMVALUELIST.IDX_SEQUENCE)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(FORMVALUELIST.COL_DEFAULTVALUE, new Integer(FORMVALUELIST.IDX_DEFAULTVALUE)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(FORMVALUELIST.COL_VALUE, new Integer(FORMVALUELIST.IDX_VALUE)); } return s_accessor; } /** * */ private final FORMVALUELIST m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new FORMVALUELISTCursor(row, rs, false). * * @param formvaluelist * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMVALUELISTCursor(FORMVALUELIST row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM FORMVALUELIST WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ FORMVALUELISTCursor(FORMVALUELIST row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link FORMVALUELIST} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/LocalizedTexts.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.LocalizedTextsCursor.ColAccessor; /** * No description. */ public class LocalizedTexts extends TableRow { /** Name of table: LOCALIZEDTEXTS */ public final static String TABLE = "LOCALIZEDTEXTS"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("LANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LANGU)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEXTTYPE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXTTYPE)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new LocalizedTextsCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new LocalizedTextsCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link LocalizedTextsCursor} * instance. Use an instance of {@link LocalizedTextsCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static LocalizedTexts get(RecordSet rs, boolean selectStar) { LocalizedTexts result = new LocalizedTexts(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static LocalizedTexts[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static LocalizedTexts[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); LocalizedTexts row = new LocalizedTexts(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new LocalizedTexts(row)); return (LocalizedTexts[]) list.toArray(new LocalizedTexts[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static LocalizedTexts[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static LocalizedTexts[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(LocalizedTexts row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof LocalizedTexts)) return false; LocalizedTexts test = (LocalizedTexts) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(LocalizedTexts row, String CODE, boolean likeCODE) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CODE null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(LocalizedTexts row, String CODE) { return queryByPrimaryKey(row, CODE, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static LocalizedTexts[] listByPrimaryKey(DBSession db, String CODE, boolean likeCODE, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CODE, boolean likeCODE) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CODE null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CODE) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append("=").append(sqlHelper.get(CODE)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(LocalizedTexts row, String CODE, boolean likeCODE, String LANGU, boolean likeLANGU) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CODE null * @param LANGU null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(LocalizedTexts row, String CODE, String LANGU) { return queryByPrimaryKey(row, CODE, false, LANGU, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static LocalizedTexts[] listByPrimaryKey(DBSession db, String CODE, boolean likeCODE, String LANGU, boolean likeLANGU, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CODE, boolean likeCODE, String LANGU, boolean likeLANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CODE null * @param LANGU null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CODE, String LANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append("=").append(sqlHelper.get(CODE)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param TEXTTYPE null * @param likeTEXTTYPE Set to true if the query for TEXTTYPE * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(LocalizedTexts row, String CODE, boolean likeCODE, String LANGU, boolean likeLANGU, String TEXTTYPE, boolean likeTEXTTYPE) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TEXTTYPE).append(likeTEXTTYPE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TEXTTYPE)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param CODE null * @param LANGU null * @param TEXTTYPE null * @return The result of the database access. */ public static LocalizedTexts getByPrimaryKey(DBSession db, String CODE, String LANGU, String TEXTTYPE) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append("=").append(sqlHelper.get(CODE)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TEXTTYPE).append("=").append(sqlHelper.get(TEXTTYPE)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param TEXTTYPE null * @param likeTEXTTYPE Set to true if the query for TEXTTYPE * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static LocalizedTexts[] listByPrimaryKey(DBSession db, String CODE, boolean likeCODE, String LANGU, boolean likeLANGU, String TEXTTYPE, boolean likeTEXTTYPE, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TEXTTYPE).append(likeTEXTTYPE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TEXTTYPE)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CODE null * @param likeCODE Set to true if the query for CODE * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param TEXTTYPE null * @param likeTEXTTYPE Set to true if the query for TEXTTYPE * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CODE, boolean likeCODE, String LANGU, boolean likeLANGU, String TEXTTYPE, boolean likeTEXTTYPE) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append(likeCODE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CODE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TEXTTYPE).append(likeTEXTTYPE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TEXTTYPE)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CODE null * @param LANGU null * @param TEXTTYPE null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CODE, String LANGU, String TEXTTYPE) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CODE).append("=").append(sqlHelper.get(CODE)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TEXTTYPE).append("=").append(sqlHelper.get(TEXTTYPE)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(LocalizedTexts row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static LocalizedTexts[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CODE); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TEXTTYPE); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table LocalizedTexts. */ class LocalizedTextsCursor implements TableCursor { interface ColAccessor { public void set(LocalizedTexts table, RecordSet rs, int index); public void setUpdate(LocalizedTexts table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(LocalizedTexts table, RecordSet rs, int index) { table.setCODE(rs.getString(index)); } public void setUpdate(LocalizedTexts table, DBSqlHelper sqlHelper) { sqlHelper.in(LocalizedTexts.COL_CODE, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(LocalizedTexts table, RecordSet rs, int index) { table.setLANGU(rs.getString(index)); } public void setUpdate(LocalizedTexts table, DBSqlHelper sqlHelper) { sqlHelper.in(LocalizedTexts.COL_LANGU, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(LocalizedTexts table, RecordSet rs, int index) { table.setTEXT(rs.getString(index)); } public void setUpdate(LocalizedTexts table, DBSqlHelper sqlHelper) { sqlHelper.in(LocalizedTexts.COL_TEXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(LocalizedTexts table, RecordSet rs, int index) { table.setTEXTTYPE(rs.getString(index)); } public void setUpdate(LocalizedTexts table, DBSqlHelper sqlHelper) { sqlHelper.in(LocalizedTexts.COL_TEXTTYPE, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[LocalizedTexts.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(LocalizedTexts.COL_CODE, new Integer(LocalizedTexts.IDX_CODE)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(LocalizedTexts.COL_LANGU, new Integer(LocalizedTexts.IDX_LANGU)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(LocalizedTexts.COL_TEXT, new Integer(LocalizedTexts.IDX_TEXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(LocalizedTexts.COL_TEXTTYPE, new Integer(LocalizedTexts.IDX_TEXTTYPE)); } return s_accessor; } /** * */ private final LocalizedTexts m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new LocalizedTextsCursor(row, rs, false). * * @param localizedtexts * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ LocalizedTextsCursor(LocalizedTexts row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM LocalizedTexts WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ LocalizedTextsCursor(LocalizedTexts row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link LocalizedTexts} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/SIGNPIC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.SIGNPICCursor.ColAccessor; /** * No description. */ public class SIGNPIC extends TableRow { /** Name of table: SIGNPIC */ public final static String TABLE = "SIGNPIC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 6; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iSet to 0 to let the database system create a * new autoincrement value when the row gets inserted. */ public SIGNPIC(DBSession db, long IDX) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); setIDX(IDX); validate(); } /** * Creates a new complete row using the given column values. * * @param db * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param GUID No description. * @param VBELN No description. * @param PARZSNR No description. * @param STANDORT No description. * @param SIGNPIC No description. */ public SIGNPIC(DBSession db, long IDX, String GUID, String VBELN, String PARZSNR, String STANDORT, String SIGNPIC) { super(db, null); _col0 = IDX; _col1 = GUID; _col2 = VBELN; _col3 = PARZSNR; _col4 = STANDORT; _col5 = SIGNPIC; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public SIGNPIC(SIGNPIC source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_GUID)) _col1 = source._col1; if (isColumnSet(IDX_VBELN)) _col2 = source._col2; if (isColumnSet(IDX_PARZSNR)) _col3 = source._col3; if (isColumnSet(IDX_STANDORT)) _col4 = source._col4; if (isColumnSet(IDX_SIGNPIC)) _col5 = source._col5; } else { // copy all columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_GUID)) _col1 = source._col1; if (isColumnSet(IDX_VBELN)) _col2 = source._col2; if (isColumnSet(IDX_PARZSNR)) _col3 = source._col3; if (isColumnSet(IDX_STANDORT)) _col4 = source._col4; if (isColumnSet(IDX_SIGNPIC)) _col5 = source._col5; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param source */ public SIGNPIC(long IDX, SIGNPIC source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = IDX; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_GUID)) _col1 = source._col1; if (isColumnSet(IDX_VBELN)) _col2 = source._col2; if (isColumnSet(IDX_PARZSNR)) _col3 = source._col3; if (isColumnSet(IDX_STANDORT)) _col4 = source._col4; if (isColumnSet(IDX_SIGNPIC)) _col5 = source._col5; } else { // copy all columns excluding the primary key _col1 = source._col1; _col2 = source._col2; _col3 = source._col3; _col4 = source._col4; _col5 = source._col5; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public SIGNPIC(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_IDX)) m_usedColumns.clear(IDX_IDX); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_GUID)) _col1 = DEF_GUID; if (m_usedColumns.get(IDX_VBELN)) _col2 = DEF_VBELN; if (m_usedColumns.get(IDX_PARZSNR)) _col3 = DEF_PARZSNR; if (m_usedColumns.get(IDX_STANDORT)) _col4 = DEF_STANDORT; if (m_usedColumns.get(IDX_SIGNPIC)) _col5 = DEF_SIGNPIC; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_IDX) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append('=').append(sqlHelper.get(_col0)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); if (_col0 == 0) { sqlHelper.inNULL(); } sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); sqlHelper.in(_col5); getDBSession().executeSql(sqlHelper.toString()); if (_col0 == 0) { DBSession db = getDBSession(); RecordSet rs = db.getRecordSet(); try { rs.setQuery("SELECT last_insert_rowid()"); //$NON-NLS-1$ rs.moveNext(); setIDX(rs.getLong(0)); } finally { rs.dispose(); } } } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = SIGNPICCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_GUID, _col1); sqlHelper.in(COL_VBELN, _col2); sqlHelper.in(COL_PARZSNR, _col3); sqlHelper.in(COL_STANDORT, _col4); sqlHelper.in(COL_SIGNPIC, _col5); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return null */ public long getIDX() { checkSparseColumn(IDX_IDX); return _col0; } /** * @param IDX null */ protected void setIDX(long IDX) { _col0 = IDX; markUsed(IDX_IDX); } /** * @return null */ public String getGUID() { checkSparseColumn(IDX_GUID); return _col1; } /** * @param GUID null */ public void setGUID(String GUID) { checkNull(GUID); _col1 = GUID; markUsed(IDX_GUID); } /** * @return null */ public String getVBELN() { checkSparseColumn(IDX_VBELN); return _col2; } /** * @param VBELN null */ public void setVBELN(String VBELN) { checkNull(VBELN); _col2 = VBELN; markUsed(IDX_VBELN); } /** * @return null */ public String getPARZSNR() { checkSparseColumn(IDX_PARZSNR); return _col3; } /** * @param PARZSNR null */ public void setPARZSNR(String PARZSNR) { checkNull(PARZSNR); _col3 = PARZSNR; markUsed(IDX_PARZSNR); } /** * @return null */ public String getSTANDORT() { checkSparseColumn(IDX_STANDORT); return _col4; } /** * @param STANDORT null */ public void setSTANDORT(String STANDORT) { checkNull(STANDORT); _col4 = STANDORT; markUsed(IDX_STANDORT); } /** * @return null */ public String getSIGNPIC() { checkSparseColumn(IDX_SIGNPIC); return _col5; } /** * @param SIGNPIC null */ public void setSIGNPIC(String SIGNPIC) { checkNull(SIGNPIC); _col5 = SIGNPIC; markUsed(IDX_SIGNPIC); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col0); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("GUID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GUID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VBELN)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARZSNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARZSNR)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STANDORT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STANDORT)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNPIC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNPIC)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new SIGNPICCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new SIGNPICCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link SIGNPICCursor} * instance. Use an instance of {@link SIGNPICCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static SIGNPIC get(RecordSet rs, boolean selectStar) { SIGNPIC result = new SIGNPIC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static SIGNPIC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static SIGNPIC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); SIGNPIC row = new SIGNPIC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new SIGNPIC(row)); return (SIGNPIC[]) list.toArray(new SIGNPIC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static SIGNPIC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static SIGNPIC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(SIGNPIC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof SIGNPIC)) return false; SIGNPIC test = (SIGNPIC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @return The result of the database access. */ public static SIGNPIC getByPrimaryKey(DBSession db, long IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, long IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(SIGNPIC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static SIGNPIC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table SIGNPIC. */ class SIGNPICCursor implements TableCursor { interface ColAccessor { public void set(SIGNPIC table, RecordSet rs, int index); public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(SIGNPIC table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper) { sqlHelper.in(SIGNPIC.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(SIGNPIC table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper) { sqlHelper.in(SIGNPIC.COL_GUID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(SIGNPIC table, RecordSet rs, int index) { table.setVBELN(rs.getString(index)); } public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper) { sqlHelper.in(SIGNPIC.COL_VBELN, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(SIGNPIC table, RecordSet rs, int index) { table.setPARZSNR(rs.getString(index)); } public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper) { sqlHelper.in(SIGNPIC.COL_PARZSNR, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(SIGNPIC table, RecordSet rs, int index) { table.setSTANDORT(rs.getString(index)); } public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper) { sqlHelper.in(SIGNPIC.COL_STANDORT, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(SIGNPIC table, RecordSet rs, int index) { table.setSIGNPIC(rs.getString(index)); } public void setUpdate(SIGNPIC table, DBSqlHelper sqlHelper) { sqlHelper.in(SIGNPIC.COL_SIGNPIC, table._col5); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[SIGNPIC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(SIGNPIC.COL_IDX, new Integer(SIGNPIC.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(SIGNPIC.COL_GUID, new Integer(SIGNPIC.IDX_GUID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(SIGNPIC.COL_VBELN, new Integer(SIGNPIC.IDX_VBELN)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(SIGNPIC.COL_PARZSNR, new Integer(SIGNPIC.IDX_PARZSNR)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(SIGNPIC.COL_STANDORT, new Integer(SIGNPIC.IDX_STANDORT)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(SIGNPIC.COL_SIGNPIC, new Integer(SIGNPIC.IDX_SIGNPIC)); } return s_accessor; } /** * */ private final SIGNPIC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new SIGNPICCursor(row, rs, false). * * @param signpic * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ SIGNPICCursor(SIGNPIC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM SIGNPIC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ SIGNPICCursor(SIGNPIC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link SIGNPIC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZARBEITSART.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZARBEITSARTCursor.ColAccessor; /** * No description. */ public class ZARBEITSART extends TableRow { /** Name of table: ZARBEITSART */ public final static String TABLE = "ZARBEITSART"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("FRM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FRM)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KNZGARENT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KNZGARENT)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZARBEITSARTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZARBEITSARTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZARBEITSARTCursor} * instance. Use an instance of {@link ZARBEITSARTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZARBEITSART get(RecordSet rs, boolean selectStar) { ZARBEITSART result = new ZARBEITSART(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZARBEITSART[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZARBEITSART[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZARBEITSART row = new ZARBEITSART(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZARBEITSART(row)); return (ZARBEITSART[]) list.toArray(new ZARBEITSART[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZARBEITSART[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZARBEITSART[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZARBEITSART row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZARBEITSART)) return false; ZARBEITSART test = (ZARBEITSART) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZARBEITSART row, String ARBA, boolean likeARBA) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_FRM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ARBA null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZARBEITSART row, String ARBA) { return queryByPrimaryKey(row, ARBA, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZARBEITSART[] listByPrimaryKey(DBSession db, String ARBA, boolean likeARBA, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_FRM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA, boolean likeARBA) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append("=").append(sqlHelper.get(ARBA)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param FRM null * @param likeFRM Set to true if the query for FRM * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZARBEITSART row, String ARBA, boolean likeARBA, String FRM, boolean likeFRM) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FRM).append(likeFRM ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FRM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_FRM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param ARBA null * @param FRM null * @return The result of the database access. */ public static ZARBEITSART getByPrimaryKey(DBSession db, String ARBA, String FRM) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append("=").append(sqlHelper.get(ARBA)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FRM).append("=").append(sqlHelper.get(FRM)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param FRM null * @param likeFRM Set to true if the query for FRM * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZARBEITSART[] listByPrimaryKey(DBSession db, String ARBA, boolean likeARBA, String FRM, boolean likeFRM, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FRM).append(likeFRM ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FRM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_FRM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param FRM null * @param likeFRM Set to true if the query for FRM * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA, boolean likeARBA, String FRM, boolean likeFRM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FRM).append(likeFRM ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FRM)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @param FRM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA, String FRM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append("=").append(sqlHelper.get(ARBA)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FRM).append("=").append(sqlHelper.get(FRM)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZARBEITSART row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_FRM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZARBEITSART[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_FRM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZARBEITSART. */ class ZARBEITSARTCursor implements TableCursor { interface ColAccessor { public void set(ZARBEITSART table, RecordSet rs, int index); public void setUpdate(ZARBEITSART table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZARBEITSART table, RecordSet rs, int index) { table.setARBA(rs.getString(index)); } public void setUpdate(ZARBEITSART table, DBSqlHelper sqlHelper) { sqlHelper.in(ZARBEITSART.COL_ARBA, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZARBEITSART table, RecordSet rs, int index) { table.setFRM(rs.getString(index)); } public void setUpdate(ZARBEITSART table, DBSqlHelper sqlHelper) { sqlHelper.in(ZARBEITSART.COL_FRM, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZARBEITSART table, RecordSet rs, int index) { table.setTEXT(rs.getString(index)); } public void setUpdate(ZARBEITSART table, DBSqlHelper sqlHelper) { sqlHelper.in(ZARBEITSART.COL_TEXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZARBEITSART table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZARBEITSART table, DBSqlHelper sqlHelper) { sqlHelper.in(ZARBEITSART.COL_REFRESHED, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZARBEITSART table, RecordSet rs, int index) { table.setKNZGARENT(rs.getString(index)); } public void setUpdate(ZARBEITSART table, DBSqlHelper sqlHelper) { sqlHelper.in(ZARBEITSART.COL_KNZGARENT, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZARBEITSART.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZARBEITSART.COL_ARBA, new Integer(ZARBEITSART.IDX_ARBA)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZARBEITSART.COL_FRM, new Integer(ZARBEITSART.IDX_FRM)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZARBEITSART.COL_TEXT, new Integer(ZARBEITSART.IDX_TEXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZARBEITSART.COL_REFRESHED, new Integer(ZARBEITSART.IDX_REFRESHED)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZARBEITSART.COL_KNZGARENT, new Integer(ZARBEITSART.IDX_KNZGARENT)); } return s_accessor; } /** * */ private final ZARBEITSART m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZARBEITSARTCursor(row, rs, false). * * @param zarbeitsart * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZARBEITSARTCursor(ZARBEITSART row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZARBEITSART WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZARBEITSARTCursor(ZARBEITSART row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZARBEITSART} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZFCODE.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZFCODECursor.ColAccessor; /** * No description. */ public class ZFCODE extends TableRow { /** Name of table: ZFCODE */ public final static String TABLE = "ZFCODE"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZFCODECursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZFCODECursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZFCODECursor} * instance. Use an instance of {@link ZFCODECursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZFCODE get(RecordSet rs, boolean selectStar) { ZFCODE result = new ZFCODE(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZFCODE[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZFCODE[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZFCODE row = new ZFCODE(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZFCODE(row)); return (ZFCODE[]) list.toArray(new ZFCODE[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZFCODE[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZFCODE[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZFCODE row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZFCODE)) return false; ZFCODE test = (ZFCODE) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FC null * @param likeFC Set to true if the query for FC * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZFCODE row, String FC, boolean likeFC) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FC).append(likeFC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FC); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param FC null * @return The result of the database access. */ public static ZFCODE getByPrimaryKey(DBSession db, String FC) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FC).append("=").append(sqlHelper.get(FC)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FC null * @param likeFC Set to true if the query for FC * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZFCODE[] listByPrimaryKey(DBSession db, String FC, boolean likeFC, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FC).append(likeFC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FC); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FC null * @param likeFC Set to true if the query for FC * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FC, boolean likeFC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FC).append(likeFC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FC)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FC null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FC).append("=").append(sqlHelper.get(FC)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZFCODE row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FC); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZFCODE[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FC); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZFCODE. */ class ZFCODECursor implements TableCursor { interface ColAccessor { public void set(ZFCODE table, RecordSet rs, int index); public void setUpdate(ZFCODE table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZFCODE table, RecordSet rs, int index) { table.setFC(rs.getString(index)); } public void setUpdate(ZFCODE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZFCODE.COL_FC, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZFCODE table, RecordSet rs, int index) { table.setTEXT(rs.getString(index)); } public void setUpdate(ZFCODE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZFCODE.COL_TEXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZFCODE table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZFCODE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZFCODE.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZFCODE.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZFCODE.COL_FC, new Integer(ZFCODE.IDX_FC)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZFCODE.COL_TEXT, new Integer(ZFCODE.IDX_TEXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZFCODE.COL_REFRESHED, new Integer(ZFCODE.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZFCODE m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZFCODECursor(row, rs, false). * * @param zfcode * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZFCODECursor(ZFCODE row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZFCODE WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZFCODECursor(ZFCODE row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZFCODE} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDCSTORC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDCSTORCCursor.ColAccessor; /** * No description. */ public class ZKDCSTORC extends TableRow { /** Name of table: ZKDCSTORC */ public final static String TABLE = "ZKDCSTORC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iSet to 0 to let the database system create a * new autoincrement value when the row gets inserted. */ public ZKDCSTORC(DBSession db, long IDX) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); setIDX(IDX); validate(); } /** * Creates a new complete row using the given column values. * * @param db * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param STORC No description. * @param ZIFF No description. * @param LANGU No description. * @param TEXT No description. */ public ZKDCSTORC(DBSession db, long IDX, String STORC, String ZIFF, String LANGU, String TEXT) { super(db, null); _col0 = IDX; _col1 = STORC; _col2 = ZIFF; _col3 = LANGU; _col4 = TEXT; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public ZKDCSTORC(ZKDCSTORC source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_STORC)) _col1 = source._col1; if (isColumnSet(IDX_ZIFF)) _col2 = source._col2; if (isColumnSet(IDX_LANGU)) _col3 = source._col3; if (isColumnSet(IDX_TEXT)) _col4 = source._col4; } else { // copy all columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_STORC)) _col1 = source._col1; if (isColumnSet(IDX_ZIFF)) _col2 = source._col2; if (isColumnSet(IDX_LANGU)) _col3 = source._col3; if (isColumnSet(IDX_TEXT)) _col4 = source._col4; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param source */ public ZKDCSTORC(long IDX, ZKDCSTORC source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = IDX; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_STORC)) _col1 = source._col1; if (isColumnSet(IDX_ZIFF)) _col2 = source._col2; if (isColumnSet(IDX_LANGU)) _col3 = source._col3; if (isColumnSet(IDX_TEXT)) _col4 = source._col4; } else { // copy all columns excluding the primary key _col1 = source._col1; _col2 = source._col2; _col3 = source._col3; _col4 = source._col4; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public ZKDCSTORC(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_IDX)) m_usedColumns.clear(IDX_IDX); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_STORC)) _col1 = DEF_STORC; if (m_usedColumns.get(IDX_ZIFF)) _col2 = DEF_ZIFF; if (m_usedColumns.get(IDX_LANGU)) _col3 = DEF_LANGU; if (m_usedColumns.get(IDX_TEXT)) _col4 = DEF_TEXT; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_IDX) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append('=').append(sqlHelper.get(_col0)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); if (_col0 == 0) { sqlHelper.inNULL(); } sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); getDBSession().executeSql(sqlHelper.toString()); if (_col0 == 0) { DBSession db = getDBSession(); RecordSet rs = db.getRecordSet(); try { rs.setQuery("SELECT last_insert_rowid()"); //$NON-NLS-1$ rs.moveNext(); setIDX(rs.getLong(0)); } finally { rs.dispose(); } } } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = ZKDCSTORCCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_STORC, _col1); sqlHelper.in(COL_ZIFF, _col2); sqlHelper.in(COL_LANGU, _col3); sqlHelper.in(COL_TEXT, _col4); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return null */ public long getIDX() { checkSparseColumn(IDX_IDX); return _col0; } /** * @param IDX null */ protected void setIDX(long IDX) { _col0 = IDX; markUsed(IDX_IDX); } /** * @return null */ public String getSTORC() { checkSparseColumn(IDX_STORC); return _col1; } /** * @param STORC null */ public void setSTORC(String STORC) { checkNull(STORC); _col1 = STORC; markUsed(IDX_STORC); } /** * @return null */ public String getZIFF() { checkSparseColumn(IDX_ZIFF); return _col2; } /** * @param ZIFF null */ public void setZIFF(String ZIFF) { checkNull(ZIFF); _col2 = ZIFF; markUsed(IDX_ZIFF); } /** * @return null */ public String getLANGU() { checkSparseColumn(IDX_LANGU); return _col3; } /** * @param LANGU null */ public void setLANGU(String LANGU) { checkNull(LANGU); _col3 = LANGU; markUsed(IDX_LANGU); } /** * @return null */ public String getTEXT() { checkSparseColumn(IDX_TEXT); return _col4; } /** * @param TEXT null */ public void setTEXT(String TEXT) { checkNull(TEXT); _col4 = TEXT; markUsed(IDX_TEXT); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col0); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STORC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STORC)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZIFF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZIFF)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LANGU)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXT)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDCSTORCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDCSTORCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDCSTORCCursor} * instance. Use an instance of {@link ZKDCSTORCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDCSTORC get(RecordSet rs, boolean selectStar) { ZKDCSTORC result = new ZKDCSTORC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDCSTORC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDCSTORC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDCSTORC row = new ZKDCSTORC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDCSTORC(row)); return (ZKDCSTORC[]) list.toArray(new ZKDCSTORC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDCSTORC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDCSTORC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDCSTORC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDCSTORC)) return false; ZKDCSTORC test = (ZKDCSTORC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @return The result of the database access. */ public static ZKDCSTORC getByPrimaryKey(DBSession db, long IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, long IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDCSTORC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDCSTORC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDCSTORC. */ class ZKDCSTORCCursor implements TableCursor { interface ColAccessor { public void set(ZKDCSTORC table, RecordSet rs, int index); public void setUpdate(ZKDCSTORC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDCSTORC table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDCSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDCSTORC.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDCSTORC table, RecordSet rs, int index) { table.setSTORC(rs.getString(index)); } public void setUpdate(ZKDCSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDCSTORC.COL_STORC, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDCSTORC table, RecordSet rs, int index) { table.setZIFF(rs.getString(index)); } public void setUpdate(ZKDCSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDCSTORC.COL_ZIFF, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDCSTORC table, RecordSet rs, int index) { table.setLANGU(rs.getString(index)); } public void setUpdate(ZKDCSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDCSTORC.COL_LANGU, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDCSTORC table, RecordSet rs, int index) { table.setTEXT(rs.getString(index)); } public void setUpdate(ZKDCSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDCSTORC.COL_TEXT, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDCSTORC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDCSTORC.COL_IDX, new Integer(ZKDCSTORC.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDCSTORC.COL_STORC, new Integer(ZKDCSTORC.IDX_STORC)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDCSTORC.COL_ZIFF, new Integer(ZKDCSTORC.IDX_ZIFF)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDCSTORC.COL_LANGU, new Integer(ZKDCSTORC.IDX_LANGU)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDCSTORC.COL_TEXT, new Integer(ZKDCSTORC.IDX_TEXT)); } return s_accessor; } /** * */ private final ZKDCSTORC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDCSTORCCursor(row, rs, false). * * @param zkdcstorc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDCSTORCCursor(ZKDCSTORC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDCSTORC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDCSTORCCursor(ZKDCSTORC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDCSTORC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDHIST.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDHISTCursor.ColAccessor; /** * No description. */ public class ZKDHIST extends TableRow { /** Name of table: ZKDHIST */ public final static String TABLE = "ZKDHIST"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col2); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXT)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDHISTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDHISTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDHISTCursor} * instance. Use an instance of {@link ZKDHISTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDHIST get(RecordSet rs, boolean selectStar) { ZKDHIST result = new ZKDHIST(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDHIST[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDHIST[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDHIST row = new ZKDHIST(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDHIST(row)); return (ZKDHIST[]) list.toArray(new ZKDHIST[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDHIST[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDHIST[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDHIST row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDHIST)) return false; ZKDHIST test = (ZKDHIST) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && _col2 != test._col2) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDHIST row, String MLDNR, boolean likeMLDNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDHIST row, String MLDNR) { return queryByPrimaryKey(row, MLDNR, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDHIST[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param IDX null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDHIST row, String MLDNR, boolean likeMLDNR, int IDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MLDNR null * @param IDX null * @return The result of the database access. */ public static ZKDHIST getByPrimaryKey(DBSession db, String MLDNR, int IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param IDX null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDHIST[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int IDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDHIST row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDHIST[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDHIST. */ class ZKDHISTCursor implements TableCursor { interface ColAccessor { public void set(ZKDHIST table, RecordSet rs, int index); public void setUpdate(ZKDHIST table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDHIST table, RecordSet rs, int index) { table.setMLDNR(rs.getString(index)); } public void setUpdate(ZKDHIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDHIST.COL_MLDNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDHIST table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDHIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDHIST.COL_AUART, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDHIST table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDHIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDHIST.COL_IDX, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDHIST table, RecordSet rs, int index) { table.setTEXT(rs.getString(index)); } public void setUpdate(ZKDHIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDHIST.COL_TEXT, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDHIST.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDHIST.COL_MLDNR, new Integer(ZKDHIST.IDX_MLDNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDHIST.COL_AUART, new Integer(ZKDHIST.IDX_AUART)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDHIST.COL_IDX, new Integer(ZKDHIST.IDX_IDX)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDHIST.COL_TEXT, new Integer(ZKDHIST.IDX_TEXT)); } return s_accessor; } /** * */ private final ZKDHIST m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDHISTCursor(row, rs, false). * * @param zkdhist * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDHISTCursor(ZKDHIST row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDHIST WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDHISTCursor(ZKDHIST row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDHIST} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMAABSENCE.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMAABSENCECursor.ColAccessor; /** * No description. */ public class ZKDMAABSENCE extends TableRow { /** Name of table: ZKDMAABSENCE */ public final static String TABLE = "ZKDMAABSENCE"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 9; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("ERFDT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERFDT)) sb.append(df.format(_col1)); sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col2); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ABWGRND"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABWGRND)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DATUMVON"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DATUMVON)) sb.append(df.format(_col4)); sb.append(", ").append("DATUMBIS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DATUMBIS)) sb.append(df.format(_col5)); sb.append(", ").append("ZEITVON"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZEITVON)) sb.append(df.format(_col6)); sb.append(", ").append("ZEITBIS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZEITBIS)) sb.append(df.format(_col7)); sb.append(", ").append("TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEXT)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMAABSENCECursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMAABSENCECursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMAABSENCECursor} * instance. Use an instance of {@link ZKDMAABSENCECursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMAABSENCE get(RecordSet rs, boolean selectStar) { ZKDMAABSENCE result = new ZKDMAABSENCE(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMAABSENCE[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMAABSENCE[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMAABSENCE row = new ZKDMAABSENCE(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMAABSENCE(row)); return (ZKDMAABSENCE[]) list.toArray(new ZKDMAABSENCE[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMAABSENCE[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMAABSENCE[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMAABSENCE row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMAABSENCE)) return false; ZKDMAABSENCE test = (ZKDMAABSENCE) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && _col2 != test._col2) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAABSENCE row, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAABSENCE row, String GUID) { return queryByPrimaryKey(row, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAABSENCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param ERFDT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAABSENCE row, String GUID, boolean likeGUID, Date ERFDT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=") //$NON-NLS-1$ .append(sqlHelper.get(ERFDT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param ERFDT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAABSENCE row, String GUID, Date ERFDT) { return queryByPrimaryKey(row, GUID, false, ERFDT); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param ERFDT null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAABSENCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, Date ERFDT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=") //$NON-NLS-1$ .append(sqlHelper.get(ERFDT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param ERFDT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, Date ERFDT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=") //$NON-NLS-1$ .append(sqlHelper.get(ERFDT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param ERFDT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, Date ERFDT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=").append(sqlHelper.get(ERFDT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param ERFDT null * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAABSENCE row, String GUID, boolean likeGUID, Date ERFDT, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=") //$NON-NLS-1$ .append(sqlHelper.get(ERFDT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param GUID null * @param ERFDT null * @param PERNR null * @return The result of the database access. */ public static ZKDMAABSENCE getByPrimaryKey(DBSession db, String GUID, Date ERFDT, int PERNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=").append(sqlHelper.get(ERFDT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param ERFDT null * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAABSENCE[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, Date ERFDT, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=") //$NON-NLS-1$ .append(sqlHelper.get(ERFDT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param ERFDT null * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, Date ERFDT, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=") //$NON-NLS-1$ .append(sqlHelper.get(ERFDT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param ERFDT null * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, Date ERFDT, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_ERFDT).append("=").append(sqlHelper.get(ERFDT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAABSENCE row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAABSENCE[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_ERFDT); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMAABSENCE. */ class ZKDMAABSENCECursor implements TableCursor { interface ColAccessor { public void set(ZKDMAABSENCE table, RecordSet rs, int index); public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_GUID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setERFDT(rs.getDate(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_ERFDT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_PERNR, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setABWGRND(rs.getString(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_ABWGRND, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setDATUMVON(rs.getDate(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_DATUMVON, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setDATUMBIS(rs.getDate(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_DATUMBIS, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setZEITVON(rs.getDate(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_ZEITVON, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setZEITBIS(rs.getDate(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_ZEITBIS, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMAABSENCE table, RecordSet rs, int index) { table.setTEXT(rs.getString(index)); } public void setUpdate(ZKDMAABSENCE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAABSENCE.COL_TEXT, table._col8); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMAABSENCE.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_GUID, new Integer(ZKDMAABSENCE.IDX_GUID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_ERFDT, new Integer(ZKDMAABSENCE.IDX_ERFDT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_PERNR, new Integer(ZKDMAABSENCE.IDX_PERNR)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_ABWGRND, new Integer(ZKDMAABSENCE.IDX_ABWGRND)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_DATUMVON, new Integer(ZKDMAABSENCE.IDX_DATUMVON)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_DATUMBIS, new Integer(ZKDMAABSENCE.IDX_DATUMBIS)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_ZEITVON, new Integer(ZKDMAABSENCE.IDX_ZEITVON)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_ZEITBIS, new Integer(ZKDMAABSENCE.IDX_ZEITBIS)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMAABSENCE.COL_TEXT, new Integer(ZKDMAABSENCE.IDX_TEXT)); } return s_accessor; } /** * */ private final ZKDMAABSENCE m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMAABSENCECursor(row, rs, false). * * @param zkdmaabsence * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAABSENCECursor(ZKDMAABSENCE row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMAABSENCE WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAABSENCECursor(ZKDMAABSENCE row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMAABSENCE} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMAESPNSPICS.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMAESPNSPICSCursor.ColAccessor; /** * No description. */ public class ZKDMAESPNSPICS extends TableRow { /** Name of table: ZKDMAESPNSPICS */ public final static String TABLE = "ZKDMAESPNSPICS"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 6; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("DESC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DESC)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMTYP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMTYP)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNPIC_AT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNPIC_AT)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMAESPNSPICSCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMAESPNSPICSCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMAESPNSPICSCursor} * instance. Use an instance of {@link ZKDMAESPNSPICSCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMAESPNSPICS get(RecordSet rs, boolean selectStar) { ZKDMAESPNSPICS result = new ZKDMAESPNSPICS(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMAESPNSPICS[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMAESPNSPICS[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMAESPNSPICS row = new ZKDMAESPNSPICS(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMAESPNSPICS(row)); return (ZKDMAESPNSPICS[]) list.toArray(new ZKDMAESPNSPICS[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMAESPNSPICS[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMAESPNSPICS[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMAESPNSPICS row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMAESPNSPICS)) return false; ZKDMAESPNSPICS test = (ZKDMAESPNSPICS) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAESPNSPICS row, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAESPNSPICS[] listByPrimaryKey(DBSession db, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param DATUM null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAESPNSPICS row, int PERNR, Date DATUM) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param DATUM null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAESPNSPICS[] listByPrimaryKey(DBSession db, int PERNR, Date DATUM, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param DATUM null * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAESPNSPICS row, int PERNR, Date DATUM, String IDX, boolean likeIDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @param DATUM null * @param IDX null * @return The result of the database access. */ public static ZKDMAESPNSPICS getByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=").append(sqlHelper.get(DATUM)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param DATUM null * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAESPNSPICS[] listByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX, boolean likeIDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX, boolean likeIDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=").append(sqlHelper.get(DATUM)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAESPNSPICS row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAESPNSPICS[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMAESPNSPICS. */ class ZKDMAESPNSPICSCursor implements TableCursor { interface ColAccessor { public void set(ZKDMAESPNSPICS table, RecordSet rs, int index); public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMAESPNSPICS table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAESPNSPICS.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMAESPNSPICS table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAESPNSPICS.COL_DATUM, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMAESPNSPICS table, RecordSet rs, int index) { table.setIDX(rs.getString(index)); } public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAESPNSPICS.COL_IDX, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMAESPNSPICS table, RecordSet rs, int index) { table.setDESC(rs.getString(index)); } public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAESPNSPICS.COL_DESC, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMAESPNSPICS table, RecordSet rs, int index) { table.setFORMTYP(rs.getString(index)); } public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAESPNSPICS.COL_FORMTYP, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMAESPNSPICS table, RecordSet rs, int index) { table.setSIGNPIC_AT(rs.getString(index)); } public void setUpdate(ZKDMAESPNSPICS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAESPNSPICS.COL_SIGNPIC_AT, table._col5); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMAESPNSPICS.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMAESPNSPICS.COL_PERNR, new Integer(ZKDMAESPNSPICS.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMAESPNSPICS.COL_DATUM, new Integer(ZKDMAESPNSPICS.IDX_DATUM)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMAESPNSPICS.COL_IDX, new Integer(ZKDMAESPNSPICS.IDX_IDX)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMAESPNSPICS.COL_DESC, new Integer(ZKDMAESPNSPICS.IDX_DESC)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMAESPNSPICS.COL_FORMTYP, new Integer(ZKDMAESPNSPICS.IDX_FORMTYP)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMAESPNSPICS.COL_SIGNPIC_AT, new Integer(ZKDMAESPNSPICS.IDX_SIGNPIC_AT)); } return s_accessor; } /** * */ private final ZKDMAESPNSPICS m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMAESPNSPICSCursor(row, rs, false). * * @param zkdmaespnspics * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAESPNSPICSCursor(ZKDMAESPNSPICS row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMAESPNSPICS WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAESPNSPICSCursor(ZKDMAESPNSPICS row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMAESPNSPICS} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMAEXPNS.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMAEXPNSCursor.ColAccessor; /** * No description. */ public class ZKDMAEXPNS extends TableRow { /** Name of table: ZKDMAEXPNS */ public final static String TABLE = "ZKDMAEXPNS"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 15; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("DATUM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DATUM)) sb.append(df.format(_col1)); sb.append(", ").append("SPSNDAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPSNDAT)) sb.append(df.format(_col2)); sb.append(", ").append("KEINESPSSEN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KEINESPSSEN)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TGSPSN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TGSPSN)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DIVSPNS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DIVSPNS)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ABZG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABZG)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SPNSKEY"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPNSKEY)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PIKETT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PIKETT)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SPNSTXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPNSTXT)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BVON"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BVON)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BBIS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BBIS)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BTOT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BTOT)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ABZGTXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABZGTXT)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VERG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VERG)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMAEXPNSCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMAEXPNSCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMAEXPNSCursor} * instance. Use an instance of {@link ZKDMAEXPNSCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMAEXPNS get(RecordSet rs, boolean selectStar) { ZKDMAEXPNS result = new ZKDMAEXPNS(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMAEXPNS[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMAEXPNS[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMAEXPNS row = new ZKDMAEXPNS(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMAEXPNS(row)); return (ZKDMAEXPNS[]) list.toArray(new ZKDMAEXPNS[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMAEXPNS[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMAEXPNS[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMAEXPNS row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMAEXPNS)) return false; ZKDMAEXPNS test = (ZKDMAEXPNS) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAEXPNS row, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAEXPNS[] listByPrimaryKey(DBSession db, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @param DATUM null * @return The result of the database access. */ public static ZKDMAEXPNS getByPrimaryKey(DBSession db, int PERNR, Date DATUM) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAEXPNS row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAEXPNS[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMAEXPNS. */ class ZKDMAEXPNSCursor implements TableCursor { interface ColAccessor { public void set(ZKDMAEXPNS table, RecordSet rs, int index); public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_DATUM, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setSPSNDAT(rs.getDate(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_SPSNDAT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setKEINESPSSEN(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_KEINESPSSEN, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setTGSPSN(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_TGSPSN, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setDIVSPNS(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_DIVSPNS, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setABZG(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_ABZG, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setSPNSKEY(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_SPNSKEY, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setPIKETT(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_PIKETT, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setSPNSTXT(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_SPNSTXT, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setBVON(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_BVON, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setBBIS(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_BBIS, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setBTOT(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_BTOT, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setABZGTXT(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_ABZGTXT, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMAEXPNS table, RecordSet rs, int index) { table.setVERG(rs.getString(index)); } public void setUpdate(ZKDMAEXPNS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNS.COL_VERG, table._col14); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMAEXPNS.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_PERNR, new Integer(ZKDMAEXPNS.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_DATUM, new Integer(ZKDMAEXPNS.IDX_DATUM)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_SPSNDAT, new Integer(ZKDMAEXPNS.IDX_SPSNDAT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_KEINESPSSEN, new Integer(ZKDMAEXPNS.IDX_KEINESPSSEN)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_TGSPSN, new Integer(ZKDMAEXPNS.IDX_TGSPSN)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_DIVSPNS, new Integer(ZKDMAEXPNS.IDX_DIVSPNS)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_ABZG, new Integer(ZKDMAEXPNS.IDX_ABZG)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_SPNSKEY, new Integer(ZKDMAEXPNS.IDX_SPNSKEY)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_PIKETT, new Integer(ZKDMAEXPNS.IDX_PIKETT)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_SPNSTXT, new Integer(ZKDMAEXPNS.IDX_SPNSTXT)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_BVON, new Integer(ZKDMAEXPNS.IDX_BVON)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_BBIS, new Integer(ZKDMAEXPNS.IDX_BBIS)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_BTOT, new Integer(ZKDMAEXPNS.IDX_BTOT)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_ABZGTXT, new Integer(ZKDMAEXPNS.IDX_ABZGTXT)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMAEXPNS.COL_VERG, new Integer(ZKDMAEXPNS.IDX_VERG)); } return s_accessor; } /** * */ private final ZKDMAEXPNS m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMAEXPNSCursor(row, rs, false). * * @param zkdmaexpns * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAEXPNSCursor(ZKDMAEXPNS row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMAEXPNS WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAEXPNSCursor(ZKDMAEXPNS row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMAEXPNS} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMAEXPNSDIV.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMAEXPNSDIVCursor.ColAccessor; /** * No description. */ public class ZKDMAEXPNSDIV extends TableRow { /** Name of table: ZKDMAEXPNSDIV */ public final static String TABLE = "ZKDMAEXPNSDIV"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("DIVSPNS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DIVSPNS)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SPNSTXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPNSTXT)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMAEXPNSDIVCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMAEXPNSDIVCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMAEXPNSDIVCursor} * instance. Use an instance of {@link ZKDMAEXPNSDIVCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMAEXPNSDIV get(RecordSet rs, boolean selectStar) { ZKDMAEXPNSDIV result = new ZKDMAEXPNSDIV(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMAEXPNSDIV[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMAEXPNSDIV[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMAEXPNSDIV row = new ZKDMAEXPNSDIV(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMAEXPNSDIV(row)); return (ZKDMAEXPNSDIV[]) list.toArray(new ZKDMAEXPNSDIV[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMAEXPNSDIV[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMAEXPNSDIV[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMAEXPNSDIV row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMAEXPNSDIV)) return false; ZKDMAEXPNSDIV test = (ZKDMAEXPNSDIV) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAEXPNSDIV row, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAEXPNSDIV[] listByPrimaryKey(DBSession db, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param DATUM null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAEXPNSDIV row, int PERNR, Date DATUM) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param DATUM null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAEXPNSDIV[] listByPrimaryKey(DBSession db, int PERNR, Date DATUM, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param DATUM null * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAEXPNSDIV row, int PERNR, Date DATUM, String IDX, boolean likeIDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @param DATUM null * @param IDX null * @return The result of the database access. */ public static ZKDMAEXPNSDIV getByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=").append(sqlHelper.get(DATUM)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param DATUM null * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAEXPNSDIV[] listByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX, boolean likeIDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX, boolean likeIDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM, String IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=").append(sqlHelper.get(DATUM)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAEXPNSDIV row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAEXPNSDIV[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMAEXPNSDIV. */ class ZKDMAEXPNSDIVCursor implements TableCursor { interface ColAccessor { public void set(ZKDMAEXPNSDIV table, RecordSet rs, int index); public void setUpdate(ZKDMAEXPNSDIV table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMAEXPNSDIV table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMAEXPNSDIV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNSDIV.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMAEXPNSDIV table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(ZKDMAEXPNSDIV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNSDIV.COL_DATUM, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMAEXPNSDIV table, RecordSet rs, int index) { table.setIDX(rs.getString(index)); } public void setUpdate(ZKDMAEXPNSDIV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNSDIV.COL_IDX, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMAEXPNSDIV table, RecordSet rs, int index) { table.setDIVSPNS(rs.getString(index)); } public void setUpdate(ZKDMAEXPNSDIV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNSDIV.COL_DIVSPNS, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMAEXPNSDIV table, RecordSet rs, int index) { table.setSPNSTXT(rs.getString(index)); } public void setUpdate(ZKDMAEXPNSDIV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAEXPNSDIV.COL_SPNSTXT, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMAEXPNSDIV.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMAEXPNSDIV.COL_PERNR, new Integer(ZKDMAEXPNSDIV.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMAEXPNSDIV.COL_DATUM, new Integer(ZKDMAEXPNSDIV.IDX_DATUM)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMAEXPNSDIV.COL_IDX, new Integer(ZKDMAEXPNSDIV.IDX_IDX)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMAEXPNSDIV.COL_DIVSPNS, new Integer(ZKDMAEXPNSDIV.IDX_DIVSPNS)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMAEXPNSDIV.COL_SPNSTXT, new Integer(ZKDMAEXPNSDIV.IDX_SPNSTXT)); } return s_accessor; } /** * */ private final ZKDMAEXPNSDIV m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMAEXPNSDIVCursor(row, rs, false). * * @param zkdmaexpnsdiv * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAEXPNSDIVCursor(ZKDMAEXPNSDIV row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMAEXPNSDIV WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAEXPNSDIVCursor(ZKDMAEXPNSDIV row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMAEXPNSDIV} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMAMAT.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMAMATCursor.ColAccessor; /** * No description. */ public class ZKDMAMAT extends TableRow { /** Name of table: ZKDMAMAT */ public final static String TABLE = "ZKDMAMAT"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 8; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("DATUM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DATUM)) sb.append(df.format(_col1)); sb.append(", ").append("STCK"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STCK)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MATNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MATNR)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EXPR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EXPR)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAKTX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAKTX)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAUNIT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAUNIT)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BESTDAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BESTDAT)) sb.append(df.format(_col7)); sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMAMATCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMAMATCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMAMATCursor} * instance. Use an instance of {@link ZKDMAMATCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMAMAT get(RecordSet rs, boolean selectStar) { ZKDMAMAT result = new ZKDMAMAT(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMAMAT[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMAMAT[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMAMAT row = new ZKDMAMAT(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMAMAT(row)); return (ZKDMAMAT[]) list.toArray(new ZKDMAMAT[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMAMAT[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMAMAT[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMAMAT row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMAMAT)) return false; ZKDMAMAT test = (ZKDMAMAT) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAMAT row, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAMAT[] listByPrimaryKey(DBSession db, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @param DATUM null * @return The result of the database access. */ public static ZKDMAMAT getByPrimaryKey(DBSession db, int PERNR, Date DATUM) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param DATUM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, Date DATUM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMAMAT row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMAMAT[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMAMAT. */ class ZKDMAMATCursor implements TableCursor { interface ColAccessor { public void set(ZKDMAMAT table, RecordSet rs, int index); public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_DATUM, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setSTCK(rs.getString(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_STCK, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_MATNR, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setEXPR(rs.getString(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_EXPR, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setMAKTX(rs.getString(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_MAKTX, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setMAUNIT(rs.getString(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_MAUNIT, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMAMAT table, RecordSet rs, int index) { table.setBESTDAT(rs.getDate(index)); } public void setUpdate(ZKDMAMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMAMAT.COL_BESTDAT, table._col7); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMAMAT.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMAMAT.COL_PERNR, new Integer(ZKDMAMAT.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMAMAT.COL_DATUM, new Integer(ZKDMAMAT.IDX_DATUM)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMAMAT.COL_STCK, new Integer(ZKDMAMAT.IDX_STCK)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMAMAT.COL_MATNR, new Integer(ZKDMAMAT.IDX_MATNR)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMAMAT.COL_EXPR, new Integer(ZKDMAMAT.IDX_EXPR)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMAMAT.COL_MAKTX, new Integer(ZKDMAMAT.IDX_MAKTX)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMAMAT.COL_MAUNIT, new Integer(ZKDMAMAT.IDX_MAUNIT)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMAMAT.COL_BESTDAT, new Integer(ZKDMAMAT.IDX_BESTDAT)); } return s_accessor; } /** * */ private final ZKDMAMAT m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMAMATCursor(row, rs, false). * * @param zkdmamat * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAMATCursor(ZKDMAMAT row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMAMAT WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMAMATCursor(ZKDMAMAT row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMAMAT} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMATIME.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMATIMECursor.ColAccessor; /** * No description. */ public class ZKDMATIME extends TableRow { /** Name of table: ZKDMATIME */ public final static String TABLE = "ZKDMATIME"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 8; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("ARBA"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ARBA)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PIKETT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PIKETT)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMATIMECursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMATIMECursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMATIMECursor} * instance. Use an instance of {@link ZKDMATIMECursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMATIME get(RecordSet rs, boolean selectStar) { ZKDMATIME result = new ZKDMATIME(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMATIME[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMATIME[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMATIME row = new ZKDMATIME(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMATIME(row)); return (ZKDMATIME[]) list.toArray(new ZKDMATIME[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMATIME[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMATIME[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMATIME row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMATIME)) return false; ZKDMATIME test = (ZKDMATIME) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATIME row, int IDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMATIME[] listByPrimaryKey(DBSession db, int IDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATIME row, int IDX, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMATIME[] listByPrimaryKey(DBSession db, int IDX, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @param PERNR null * @param DATUM null * @return The result of the database access. */ public static ZKDMATIME getByPrimaryKey(DBSession db, int IDX, int PERNR, Date DATUM) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param PERNR null * @param DATUM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, int PERNR, Date DATUM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_DATUM).append("=") //$NON-NLS-1$ .append(sqlHelper.get(DATUM)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATIME row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMATIME[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ sb.append(", ").append(COL_DATUM); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMATIME. */ class ZKDMATIMECursor implements TableCursor { interface ColAccessor { public void set(ZKDMATIME table, RecordSet rs, int index); public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_PERNR, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_DATUM, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setVON(rs.getDate(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_VON, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setBIS(rs.getDate(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_BIS, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setKOSTL(rs.getString(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_KOSTL, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setARBA(rs.getString(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_ARBA, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMATIME table, RecordSet rs, int index) { table.setPIKETT(rs.getString(index)); } public void setUpdate(ZKDMATIME table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATIME.COL_PIKETT, table._col7); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMATIME.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMATIME.COL_IDX, new Integer(ZKDMATIME.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMATIME.COL_PERNR, new Integer(ZKDMATIME.IDX_PERNR)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMATIME.COL_DATUM, new Integer(ZKDMATIME.IDX_DATUM)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMATIME.COL_VON, new Integer(ZKDMATIME.IDX_VON)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMATIME.COL_BIS, new Integer(ZKDMATIME.IDX_BIS)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMATIME.COL_KOSTL, new Integer(ZKDMATIME.IDX_KOSTL)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMATIME.COL_ARBA, new Integer(ZKDMATIME.IDX_ARBA)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMATIME.COL_PIKETT, new Integer(ZKDMATIME.IDX_PIKETT)); } return s_accessor; } /** * */ private final ZKDMATIME m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMATIMECursor(row, rs, false). * * @param zkdmatime * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMATIMECursor(ZKDMATIME row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMATIME WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMATIMECursor(ZKDMATIME row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMATIME} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMATORD.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMATORDCursor.ColAccessor; /** * No description. */ public class ZKDMATORD extends TableRow { /** Name of table: ZKDMATORD */ public final static String TABLE = "ZKDMATORD"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 16; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col1); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MATNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MATNR)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col3); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VBELN)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STCK"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STCK)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MLIF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MLIF)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EXPR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EXPR)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VERRC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VERRC)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAUNIT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAUNIT)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAKTX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAKTX)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PRICE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PRICE)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BARC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BARC)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("K14"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_K14)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BARCTXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BARCTXT)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BARCFLG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BARCFLG)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMATORDCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMATORDCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMATORDCursor} * instance. Use an instance of {@link ZKDMATORDCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMATORD get(RecordSet rs, boolean selectStar) { ZKDMATORD result = new ZKDMATORD(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMATORD[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMATORD[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMATORD row = new ZKDMATORD(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMATORD(row)); return (ZKDMATORD[]) list.toArray(new ZKDMATORD[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMATORD[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMATORD[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMATORD row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMATORD)) return false; ZKDMATORD test = (ZKDMATORD) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && _col3 != test._col3) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATORD row, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATORD row, String GUID) { return queryByPrimaryKey(row, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMATORD[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param IDX null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATORD row, String GUID, boolean likeGUID, int IDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param GUID null * @param IDX null * @return The result of the database access. */ public static ZKDMATORD getByPrimaryKey(DBSession db, String GUID, int IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param IDX null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMATORD[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int IDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMATORD row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMATORD[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_IDX); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMATORD. */ class ZKDMATORDCursor implements TableCursor { interface ColAccessor { public void set(ZKDMATORD table, RecordSet rs, int index); public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_GUID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_IDX, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_MATNR, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_PERNR, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setVBELN(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_VBELN, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setSTCK(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_STCK, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setMLIF(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_MLIF, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setEXPR(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_EXPR, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setVERRC(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_VERRC, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setMAUNIT(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_MAUNIT, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setMAKTX(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_MAKTX, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setPRICE(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_PRICE, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setBARC(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_BARC, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setK14(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_K14, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setBARCTXT(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_BARCTXT, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(ZKDMATORD table, RecordSet rs, int index) { table.setBARCFLG(rs.getString(index)); } public void setUpdate(ZKDMATORD table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMATORD.COL_BARCFLG, table._col15); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMATORD.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMATORD.COL_GUID, new Integer(ZKDMATORD.IDX_GUID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMATORD.COL_IDX, new Integer(ZKDMATORD.IDX_IDX)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMATORD.COL_MATNR, new Integer(ZKDMATORD.IDX_MATNR)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMATORD.COL_PERNR, new Integer(ZKDMATORD.IDX_PERNR)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMATORD.COL_VBELN, new Integer(ZKDMATORD.IDX_VBELN)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMATORD.COL_STCK, new Integer(ZKDMATORD.IDX_STCK)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMATORD.COL_MLIF, new Integer(ZKDMATORD.IDX_MLIF)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMATORD.COL_EXPR, new Integer(ZKDMATORD.IDX_EXPR)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMATORD.COL_VERRC, new Integer(ZKDMATORD.IDX_VERRC)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMATORD.COL_MAUNIT, new Integer(ZKDMATORD.IDX_MAUNIT)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMATORD.COL_MAKTX, new Integer(ZKDMATORD.IDX_MAKTX)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMATORD.COL_PRICE, new Integer(ZKDMATORD.IDX_PRICE)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMATORD.COL_BARC, new Integer(ZKDMATORD.IDX_BARC)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMATORD.COL_K14, new Integer(ZKDMATORD.IDX_K14)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMATORD.COL_BARCTXT, new Integer(ZKDMATORD.IDX_BARCTXT)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(ZKDMATORD.COL_BARCFLG, new Integer(ZKDMATORD.IDX_BARCFLG)); } return s_accessor; } /** * */ private final ZKDMATORD m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMATORDCursor(row, rs, false). * * @param zkdmatord * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMATORDCursor(ZKDMATORD row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMATORD WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMATORDCursor(ZKDMATORD row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMATORD} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOB.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBCursor.ColAccessor; /** * No description. */ public class ZKDMOB extends TableRow { /** Name of table: ZKDMOB */ public final static String TABLE = "ZKDMOB"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 55; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col2); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STATUS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STATUS)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PRIO"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PRIO)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERSNO2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERSNO2)) sb.append(_col5); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VBELN)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ERNAM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERNAM)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ERNAMTEL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERNAMTEL)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EDATE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EDATE)) sb.append(df.format(_col9)); sb.append(", ").append("KW"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KW)) sb.append(_col10); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FIX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FIX)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TVRB"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TVRB)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BSTKD"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BSTKD)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARAPNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARAPNR)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARZRNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARZRNR)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARZSNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARZSNR)) sb.append('\'').append(_col16).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARANMNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARANMNR)) sb.append('\'').append(_col17).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("OBJNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_OBJNR)) sb.append('\'').append(_col18).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARZANR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARZANR)) sb.append('\'').append(_col19).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ERDAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERDAT)) sb.append(df.format(_col20)); sb.append(", ").append("ACTIVE_DATE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ACTIVE_DATE)) sb.append(df.format(_col21)); sb.append(", ").append("EDATE_DT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EDATE_DT)) sb.append(df.format(_col22)); sb.append(", ").append("EDATE_TI"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EDATE_TI)) sb.append(df.format(_col23)); sb.append(", ").append("FC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FC)) sb.append('\'').append(_col24).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PIKETT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PIKETT)) sb.append('\'').append(_col25).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVC)) sb.append('\'').append(_col26).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD1)) sb.append('\'').append(_col27).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD2)) sb.append('\'').append(_col28).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD3)) sb.append('\'').append(_col29).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD4"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD4)) sb.append('\'').append(_col30).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD5"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD5)) sb.append('\'').append(_col31).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD6"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD6)) sb.append('\'').append(_col32).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVOFF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVOFF)) sb.append('\'').append(_col33).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("USER_SAV"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_USER_SAV)) sb.append('\'').append(_col34).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("USER_SAVTEL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_USER_SAVTEL)) sb.append('\'').append(_col35).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZMNAM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZMNAM)) sb.append('\'').append(_col36).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZMTEL1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZMTEL1)) sb.append('\'').append(_col37).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZVNAM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZVNAM)) sb.append('\'').append(_col38).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZVTEL1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZVTEL1)) sb.append('\'').append(_col39).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ANTRTXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ANTRTXT)) sb.append('\'').append(_col40).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ANTRTXT_UPD"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ANTRTXT_UPD)) sb.append('\'').append(_col41).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZKDINDZEIT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZKDINDZEIT)) sb.append('\'').append(_col42).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LTXT1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LTXT1)) sb.append('\'').append(_col43).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LTXT2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LTXT2)) sb.append('\'').append(_col44).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CURRENTRAPPORTGUID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CURRENTRAPPORTGUID)) sb.append('\'').append(_col45).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STEDTDATE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STEDTDATE)) sb.append(df.format(_col46)); sb.append(", ").append("ZYKFLG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZYKFLG)) sb.append('\'').append(_col47).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMDESC1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMDESC1)) sb.append('\'').append(_col48).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMDESC2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMDESC2)) sb.append('\'').append(_col49).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMDESC3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMDESC3)) sb.append('\'').append(_col50).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KNZSAVPFL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KNZSAVPFL)) sb.append('\'').append(_col51).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LINK"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LINK)) sb.append('\'').append(_col52).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KNZGARANT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KNZGARANT)) sb.append('\'').append(_col53).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KNZERWKOM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KNZERWKOM)) sb.append('\'').append(_col54).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBCursor} * instance. Use an instance of {@link ZKDMOBCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOB get(RecordSet rs, boolean selectStar) { ZKDMOB result = new ZKDMOB(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOB[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOB[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOB row = new ZKDMOB(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOB(row)); return (ZKDMOB[]) list.toArray(new ZKDMOB[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOB[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOB[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOB row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOB)) return false; ZKDMOB test = (ZKDMOB) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && _col2 != test._col2) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && _col5 != test._col5) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && _col10 != test._col10) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; if ((m_usedColumns == null || !m_usedColumns.get(16)) && !_col16.equals(test._col16)) return false; if ((m_usedColumns == null || !m_usedColumns.get(17)) && !_col17.equals(test._col17)) return false; if ((m_usedColumns == null || !m_usedColumns.get(18)) && !_col18.equals(test._col18)) return false; if ((m_usedColumns == null || !m_usedColumns.get(19)) && !_col19.equals(test._col19)) return false; if ((m_usedColumns == null || !m_usedColumns.get(20)) && !_col20.equals(test._col20)) return false; if ((m_usedColumns == null || !m_usedColumns.get(21)) && !_col21.equals(test._col21)) return false; if ((m_usedColumns == null || !m_usedColumns.get(22)) && !_col22.equals(test._col22)) return false; if ((m_usedColumns == null || !m_usedColumns.get(23)) && !_col23.equals(test._col23)) return false; if ((m_usedColumns == null || !m_usedColumns.get(24)) && !_col24.equals(test._col24)) return false; if ((m_usedColumns == null || !m_usedColumns.get(25)) && !_col25.equals(test._col25)) return false; if ((m_usedColumns == null || !m_usedColumns.get(26)) && !_col26.equals(test._col26)) return false; if ((m_usedColumns == null || !m_usedColumns.get(27)) && !_col27.equals(test._col27)) return false; if ((m_usedColumns == null || !m_usedColumns.get(28)) && !_col28.equals(test._col28)) return false; if ((m_usedColumns == null || !m_usedColumns.get(29)) && !_col29.equals(test._col29)) return false; if ((m_usedColumns == null || !m_usedColumns.get(30)) && !_col30.equals(test._col30)) return false; if ((m_usedColumns == null || !m_usedColumns.get(31)) && !_col31.equals(test._col31)) return false; if ((m_usedColumns == null || !m_usedColumns.get(32)) && !_col32.equals(test._col32)) return false; if ((m_usedColumns == null || !m_usedColumns.get(33)) && !_col33.equals(test._col33)) return false; if ((m_usedColumns == null || !m_usedColumns.get(34)) && !_col34.equals(test._col34)) return false; if ((m_usedColumns == null || !m_usedColumns.get(35)) && !_col35.equals(test._col35)) return false; if ((m_usedColumns == null || !m_usedColumns.get(36)) && !_col36.equals(test._col36)) return false; if ((m_usedColumns == null || !m_usedColumns.get(37)) && !_col37.equals(test._col37)) return false; if ((m_usedColumns == null || !m_usedColumns.get(38)) && !_col38.equals(test._col38)) return false; if ((m_usedColumns == null || !m_usedColumns.get(39)) && !_col39.equals(test._col39)) return false; if ((m_usedColumns == null || !m_usedColumns.get(40)) && !_col40.equals(test._col40)) return false; if ((m_usedColumns == null || !m_usedColumns.get(41)) && !_col41.equals(test._col41)) return false; if ((m_usedColumns == null || !m_usedColumns.get(42)) && !_col42.equals(test._col42)) return false; if ((m_usedColumns == null || !m_usedColumns.get(43)) && !_col43.equals(test._col43)) return false; if ((m_usedColumns == null || !m_usedColumns.get(44)) && !_col44.equals(test._col44)) return false; if ((m_usedColumns == null || !m_usedColumns.get(45)) && !_col45.equals(test._col45)) return false; if ((m_usedColumns == null || !m_usedColumns.get(46)) && !_col46.equals(test._col46)) return false; if ((m_usedColumns == null || !m_usedColumns.get(47)) && !_col47.equals(test._col47)) return false; if ((m_usedColumns == null || !m_usedColumns.get(48)) && !_col48.equals(test._col48)) return false; if ((m_usedColumns == null || !m_usedColumns.get(49)) && !_col49.equals(test._col49)) return false; if ((m_usedColumns == null || !m_usedColumns.get(50)) && !_col50.equals(test._col50)) return false; if ((m_usedColumns == null || !m_usedColumns.get(51)) && !_col51.equals(test._col51)) return false; if ((m_usedColumns == null || !m_usedColumns.get(52)) && !_col52.equals(test._col52)) return false; if ((m_usedColumns == null || !m_usedColumns.get(53)) && !_col53.equals(test._col53)) return false; if ((m_usedColumns == null || !m_usedColumns.get(54)) && !_col54.equals(test._col54)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOB row, String MLDNR, boolean likeMLDNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOB row, String MLDNR) { return queryByPrimaryKey(row, MLDNR, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOB[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOB row, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MLDNR null * @param AUART null * @return The result of the database access. */ public static ZKDMOB getByPrimaryKey(DBSession db, String MLDNR, String AUART) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOB[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param AUART null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, String AUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOB row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOB[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOB. */ class ZKDMOBCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOB table, RecordSet rs, int index); public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setMLDNR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_MLDNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_AUART, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PERNR, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSTATUS(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_STATUS, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPRIO(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PRIO, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPERSNO2(rs.getInt(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PERSNO2, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setVBELN(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_VBELN, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setERNAM(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ERNAM, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setERNAMTEL(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ERNAMTEL, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setEDATE(rs.getDate(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_EDATE, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setKW(rs.getInt(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_KW, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setFIX(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_FIX, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setTVRB(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_TVRB, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setBSTKD(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_BSTKD, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPARAPNR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PARAPNR, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPARZRNR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PARZRNR, table._col15); } } private static class Col16Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPARZSNR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PARZSNR, table._col16); } } private static class Col17Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPARANMNR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PARANMNR, table._col17); } } private static class Col18Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setOBJNR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_OBJNR, table._col18); } } private static class Col19Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPARZANR(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PARZANR, table._col19); } } private static class Col20Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setERDAT(rs.getDate(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ERDAT, table._col20); } } private static class Col21Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setACTIVE_DATE(rs.getDate(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ACTIVE_DATE, table._col21); } } private static class Col22Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setEDATE_DT(rs.getDate(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_EDATE_DT, table._col22); } } private static class Col23Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setEDATE_TI(rs.getDate(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_EDATE_TI, table._col23); } } private static class Col24Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setFC(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_FC, table._col24); } } private static class Col25Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setPIKETT(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_PIKETT, table._col25); } } private static class Col26Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVC(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVC, table._col26); } } private static class Col27Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVLFD1(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVLFD1, table._col27); } } private static class Col28Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVLFD2(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVLFD2, table._col28); } } private static class Col29Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVLFD3(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVLFD3, table._col29); } } private static class Col30Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVLFD4(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVLFD4, table._col30); } } private static class Col31Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVLFD5(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVLFD5, table._col31); } } private static class Col32Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVLFD6(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVLFD6, table._col32); } } private static class Col33Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSAVOFF(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_SAVOFF, table._col33); } } private static class Col34Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setUSER_SAV(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_USER_SAV, table._col34); } } private static class Col35Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setUSER_SAVTEL(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_USER_SAVTEL, table._col35); } } private static class Col36Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setZMNAM(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ZMNAM, table._col36); } } private static class Col37Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setZMTEL1(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ZMTEL1, table._col37); } } private static class Col38Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setZVNAM(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ZVNAM, table._col38); } } private static class Col39Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setZVTEL1(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ZVTEL1, table._col39); } } private static class Col40Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setANTRTXT(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ANTRTXT, table._col40); } } private static class Col41Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setANTRTXT_UPD(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ANTRTXT_UPD, table._col41); } } private static class Col42Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setZKDINDZEIT(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ZKDINDZEIT, table._col42); } } private static class Col43Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setLTXT1(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_LTXT1, table._col43); } } private static class Col44Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setLTXT2(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_LTXT2, table._col44); } } private static class Col45Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setCURRENTRAPPORTGUID(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_CURRENTRAPPORTGUID, table._col45); } } private static class Col46Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setSTEDTDATE(rs.getDate(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_STEDTDATE, table._col46); } } private static class Col47Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setZYKFLG(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_ZYKFLG, table._col47); } } private static class Col48Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setFORMDESC1(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_FORMDESC1, table._col48); } } private static class Col49Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setFORMDESC2(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_FORMDESC2, table._col49); } } private static class Col50Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setFORMDESC3(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_FORMDESC3, table._col50); } } private static class Col51Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setKNZSAVPFL(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_KNZSAVPFL, table._col51); } } private static class Col52Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setLINK(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_LINK, table._col52); } } private static class Col53Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setKNZGARANT(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_KNZGARANT, table._col53); } } private static class Col54Accessor implements ColAccessor { public final void set(ZKDMOB table, RecordSet rs, int index) { table.setKNZERWKOM(rs.getString(index)); } public void setUpdate(ZKDMOB table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOB.COL_KNZERWKOM, table._col54); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOB.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOB.COL_MLDNR, new Integer(ZKDMOB.IDX_MLDNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOB.COL_AUART, new Integer(ZKDMOB.IDX_AUART)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOB.COL_PERNR, new Integer(ZKDMOB.IDX_PERNR)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOB.COL_STATUS, new Integer(ZKDMOB.IDX_STATUS)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOB.COL_PRIO, new Integer(ZKDMOB.IDX_PRIO)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOB.COL_PERSNO2, new Integer(ZKDMOB.IDX_PERSNO2)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOB.COL_VBELN, new Integer(ZKDMOB.IDX_VBELN)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOB.COL_ERNAM, new Integer(ZKDMOB.IDX_ERNAM)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOB.COL_ERNAMTEL, new Integer(ZKDMOB.IDX_ERNAMTEL)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOB.COL_EDATE, new Integer(ZKDMOB.IDX_EDATE)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOB.COL_KW, new Integer(ZKDMOB.IDX_KW)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOB.COL_FIX, new Integer(ZKDMOB.IDX_FIX)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOB.COL_TVRB, new Integer(ZKDMOB.IDX_TVRB)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMOB.COL_BSTKD, new Integer(ZKDMOB.IDX_BSTKD)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMOB.COL_PARAPNR, new Integer(ZKDMOB.IDX_PARAPNR)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(ZKDMOB.COL_PARZRNR, new Integer(ZKDMOB.IDX_PARZRNR)); s_accessor[16] = new Col16Accessor(); s_accessorMap.put(ZKDMOB.COL_PARZSNR, new Integer(ZKDMOB.IDX_PARZSNR)); s_accessor[17] = new Col17Accessor(); s_accessorMap.put(ZKDMOB.COL_PARANMNR, new Integer(ZKDMOB.IDX_PARANMNR)); s_accessor[18] = new Col18Accessor(); s_accessorMap.put(ZKDMOB.COL_OBJNR, new Integer(ZKDMOB.IDX_OBJNR)); s_accessor[19] = new Col19Accessor(); s_accessorMap.put(ZKDMOB.COL_PARZANR, new Integer(ZKDMOB.IDX_PARZANR)); s_accessor[20] = new Col20Accessor(); s_accessorMap.put(ZKDMOB.COL_ERDAT, new Integer(ZKDMOB.IDX_ERDAT)); s_accessor[21] = new Col21Accessor(); s_accessorMap.put(ZKDMOB.COL_ACTIVE_DATE, new Integer(ZKDMOB.IDX_ACTIVE_DATE)); s_accessor[22] = new Col22Accessor(); s_accessorMap.put(ZKDMOB.COL_EDATE_DT, new Integer(ZKDMOB.IDX_EDATE_DT)); s_accessor[23] = new Col23Accessor(); s_accessorMap.put(ZKDMOB.COL_EDATE_TI, new Integer(ZKDMOB.IDX_EDATE_TI)); s_accessor[24] = new Col24Accessor(); s_accessorMap.put(ZKDMOB.COL_FC, new Integer(ZKDMOB.IDX_FC)); s_accessor[25] = new Col25Accessor(); s_accessorMap.put(ZKDMOB.COL_PIKETT, new Integer(ZKDMOB.IDX_PIKETT)); s_accessor[26] = new Col26Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVC, new Integer(ZKDMOB.IDX_SAVC)); s_accessor[27] = new Col27Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVLFD1, new Integer(ZKDMOB.IDX_SAVLFD1)); s_accessor[28] = new Col28Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVLFD2, new Integer(ZKDMOB.IDX_SAVLFD2)); s_accessor[29] = new Col29Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVLFD3, new Integer(ZKDMOB.IDX_SAVLFD3)); s_accessor[30] = new Col30Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVLFD4, new Integer(ZKDMOB.IDX_SAVLFD4)); s_accessor[31] = new Col31Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVLFD5, new Integer(ZKDMOB.IDX_SAVLFD5)); s_accessor[32] = new Col32Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVLFD6, new Integer(ZKDMOB.IDX_SAVLFD6)); s_accessor[33] = new Col33Accessor(); s_accessorMap.put(ZKDMOB.COL_SAVOFF, new Integer(ZKDMOB.IDX_SAVOFF)); s_accessor[34] = new Col34Accessor(); s_accessorMap.put(ZKDMOB.COL_USER_SAV, new Integer(ZKDMOB.IDX_USER_SAV)); s_accessor[35] = new Col35Accessor(); s_accessorMap.put(ZKDMOB.COL_USER_SAVTEL, new Integer(ZKDMOB.IDX_USER_SAVTEL)); s_accessor[36] = new Col36Accessor(); s_accessorMap.put(ZKDMOB.COL_ZMNAM, new Integer(ZKDMOB.IDX_ZMNAM)); s_accessor[37] = new Col37Accessor(); s_accessorMap.put(ZKDMOB.COL_ZMTEL1, new Integer(ZKDMOB.IDX_ZMTEL1)); s_accessor[38] = new Col38Accessor(); s_accessorMap.put(ZKDMOB.COL_ZVNAM, new Integer(ZKDMOB.IDX_ZVNAM)); s_accessor[39] = new Col39Accessor(); s_accessorMap.put(ZKDMOB.COL_ZVTEL1, new Integer(ZKDMOB.IDX_ZVTEL1)); s_accessor[40] = new Col40Accessor(); s_accessorMap.put(ZKDMOB.COL_ANTRTXT, new Integer(ZKDMOB.IDX_ANTRTXT)); s_accessor[41] = new Col41Accessor(); s_accessorMap.put(ZKDMOB.COL_ANTRTXT_UPD, new Integer(ZKDMOB.IDX_ANTRTXT_UPD)); s_accessor[42] = new Col42Accessor(); s_accessorMap.put(ZKDMOB.COL_ZKDINDZEIT, new Integer(ZKDMOB.IDX_ZKDINDZEIT)); s_accessor[43] = new Col43Accessor(); s_accessorMap.put(ZKDMOB.COL_LTXT1, new Integer(ZKDMOB.IDX_LTXT1)); s_accessor[44] = new Col44Accessor(); s_accessorMap.put(ZKDMOB.COL_LTXT2, new Integer(ZKDMOB.IDX_LTXT2)); s_accessor[45] = new Col45Accessor(); s_accessorMap.put(ZKDMOB.COL_CURRENTRAPPORTGUID, new Integer(ZKDMOB.IDX_CURRENTRAPPORTGUID)); s_accessor[46] = new Col46Accessor(); s_accessorMap.put(ZKDMOB.COL_STEDTDATE, new Integer(ZKDMOB.IDX_STEDTDATE)); s_accessor[47] = new Col47Accessor(); s_accessorMap.put(ZKDMOB.COL_ZYKFLG, new Integer(ZKDMOB.IDX_ZYKFLG)); s_accessor[48] = new Col48Accessor(); s_accessorMap.put(ZKDMOB.COL_FORMDESC1, new Integer(ZKDMOB.IDX_FORMDESC1)); s_accessor[49] = new Col49Accessor(); s_accessorMap.put(ZKDMOB.COL_FORMDESC2, new Integer(ZKDMOB.IDX_FORMDESC2)); s_accessor[50] = new Col50Accessor(); s_accessorMap.put(ZKDMOB.COL_FORMDESC3, new Integer(ZKDMOB.IDX_FORMDESC3)); s_accessor[51] = new Col51Accessor(); s_accessorMap.put(ZKDMOB.COL_KNZSAVPFL, new Integer(ZKDMOB.IDX_KNZSAVPFL)); s_accessor[52] = new Col52Accessor(); s_accessorMap.put(ZKDMOB.COL_LINK, new Integer(ZKDMOB.IDX_LINK)); s_accessor[53] = new Col53Accessor(); s_accessorMap.put(ZKDMOB.COL_KNZGARANT, new Integer(ZKDMOB.IDX_KNZGARANT)); s_accessor[54] = new Col54Accessor(); s_accessorMap.put(ZKDMOB.COL_KNZERWKOM, new Integer(ZKDMOB.IDX_KNZERWKOM)); } return s_accessor; } /** * */ private final ZKDMOB m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBCursor(row, rs, false). * * @param zkdmob * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBCursor(ZKDMOB row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOB WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBCursor(ZKDMOB row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOB} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBABSC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBABSCCursor.ColAccessor; /** * No description. */ public class ZKDMOBABSC extends TableRow { /** Name of table: ZKDMOBABSC */ public final static String TABLE = "ZKDMOBABSC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("LANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LANGU)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBABSCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBABSCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBABSCCursor} * instance. Use an instance of {@link ZKDMOBABSCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBABSC get(RecordSet rs, boolean selectStar) { ZKDMOBABSC result = new ZKDMOBABSC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBABSC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBABSC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBABSC row = new ZKDMOBABSC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBABSC(row)); return (ZKDMOBABSC[]) list.toArray(new ZKDMOBABSC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBABSC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBABSC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBABSC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBABSC)) return false; ZKDMOBABSC test = (ZKDMOBABSC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBABSC row, String ABWGRND, boolean likeABWGRND) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ABWGRND null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBABSC row, String ABWGRND) { return queryByPrimaryKey(row, ABWGRND, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBABSC[] listByPrimaryKey(DBSession db, String ABWGRND, boolean likeABWGRND, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ABWGRND, boolean likeABWGRND) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ABWGRND null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ABWGRND) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append("=").append(sqlHelper.get(ABWGRND)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBABSC row, String ABWGRND, boolean likeABWGRND, String LANGU, boolean likeLANGU) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ABWGRND null * @param LANGU null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBABSC row, String ABWGRND, String LANGU) { return queryByPrimaryKey(row, ABWGRND, false, LANGU, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBABSC[] listByPrimaryKey(DBSession db, String ABWGRND, boolean likeABWGRND, String LANGU, boolean likeLANGU, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ABWGRND, boolean likeABWGRND, String LANGU, boolean likeLANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ABWGRND null * @param LANGU null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ABWGRND, String LANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append("=").append(sqlHelper.get(ABWGRND)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBABSC row, String ABWGRND, boolean likeABWGRND, String LANGU, boolean likeLANGU, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param ABWGRND null * @param LANGU null * @param TXT null * @return The result of the database access. */ public static ZKDMOBABSC getByPrimaryKey(DBSession db, String ABWGRND, String LANGU, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append("=").append(sqlHelper.get(ABWGRND)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBABSC[] listByPrimaryKey(DBSession db, String ABWGRND, boolean likeABWGRND, String LANGU, boolean likeLANGU, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ABWGRND null * @param likeABWGRND Set to true if the query for ABWGRND * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ABWGRND, boolean likeABWGRND, String LANGU, boolean likeLANGU, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append(likeABWGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ABWGRND)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ABWGRND null * @param LANGU null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ABWGRND, String LANGU, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ABWGRND).append("=").append(sqlHelper.get(ABWGRND)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBABSC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBABSC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ABWGRND); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBABSC. */ class ZKDMOBABSCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBABSC table, RecordSet rs, int index); public void setUpdate(ZKDMOBABSC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBABSC table, RecordSet rs, int index) { table.setABWGRND(rs.getString(index)); } public void setUpdate(ZKDMOBABSC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBABSC.COL_ABWGRND, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBABSC table, RecordSet rs, int index) { table.setLANGU(rs.getString(index)); } public void setUpdate(ZKDMOBABSC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBABSC.COL_LANGU, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBABSC table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBABSC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBABSC.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBABSC table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBABSC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBABSC.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBABSC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBABSC.COL_ABWGRND, new Integer(ZKDMOBABSC.IDX_ABWGRND)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBABSC.COL_LANGU, new Integer(ZKDMOBABSC.IDX_LANGU)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBABSC.COL_TXT, new Integer(ZKDMOBABSC.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBABSC.COL_REFRESHED, new Integer(ZKDMOBABSC.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBABSC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBABSCCursor(row, rs, false). * * @param zkdmobabsc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBABSCCursor(ZKDMOBABSC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBABSC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBABSCCursor(ZKDMOBABSC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBABSC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBADR.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBADRCursor.ColAccessor; /** * No description. */ public class ZKDMOBADR extends TableRow { /** Name of table: ZKDMOBADR */ public final static String TABLE = "ZKDMOBADR"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 20; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARNR)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VBELN)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KUNNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KUNNR)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TITLE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TITLE)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NAME1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME1)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NAME2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME2)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NAME3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME3)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NAME4"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME4)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STREET"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STREET)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CITY1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CITY1)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("POST_CODE1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_POST_CODE1)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEL_NUMBER1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEL_NUMBER1)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEL_NUMBER2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEL_NUMBER2)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FAX_NUMBER1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FAX_NUMBER1)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TYPE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TYPE)) sb.append('\'').append(_col16).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EMAIL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EMAIL)) sb.append('\'').append(_col17).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("UPD"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_UPD)) sb.append('\'').append(_col18).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DIRTYFLG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DIRTYFLG)) sb.append('\'').append(_col19).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBADRCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBADRCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBADRCursor} * instance. Use an instance of {@link ZKDMOBADRCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBADR get(RecordSet rs, boolean selectStar) { ZKDMOBADR result = new ZKDMOBADR(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBADR[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBADR[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBADR row = new ZKDMOBADR(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBADR(row)); return (ZKDMOBADR[]) list.toArray(new ZKDMOBADR[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBADR[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBADR[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBADR row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBADR)) return false; ZKDMOBADR test = (ZKDMOBADR) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; if ((m_usedColumns == null || !m_usedColumns.get(16)) && !_col16.equals(test._col16)) return false; if ((m_usedColumns == null || !m_usedColumns.get(17)) && !_col17.equals(test._col17)) return false; if ((m_usedColumns == null || !m_usedColumns.get(18)) && !_col18.equals(test._col18)) return false; if ((m_usedColumns == null || !m_usedColumns.get(19)) && !_col19.equals(test._col19)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBADR row, String MLDNR, boolean likeMLDNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBADR row, String MLDNR) { return queryByPrimaryKey(row, MLDNR, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBADR[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBADR row, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param AUART null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBADR row, String MLDNR, String AUART) { return queryByPrimaryKey(row, MLDNR, false, AUART, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBADR[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param AUART null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, String AUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBADR row, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MLDNR null * @param AUART null * @param PARNR null * @return The result of the database access. */ public static ZKDMOBADR getByPrimaryKey(DBSession db, String MLDNR, String AUART, String PARNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append("=").append(sqlHelper.get(PARNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBADR[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param AUART null * @param PARNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, String AUART, String PARNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append("=").append(sqlHelper.get(PARNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBADR row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBADR[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBADR. */ class ZKDMOBADRCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBADR table, RecordSet rs, int index); public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setMLDNR(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_MLDNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_AUART, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setPARNR(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_PARNR, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setVBELN(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_VBELN, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setKUNNR(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_KUNNR, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setTITLE(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_TITLE, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setNAME1(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_NAME1, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setNAME2(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_NAME2, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setNAME3(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_NAME3, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setNAME4(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_NAME4, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setSTREET(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_STREET, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setCITY1(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_CITY1, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setPOST_CODE1(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_POST_CODE1, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setTEL_NUMBER1(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_TEL_NUMBER1, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setTEL_NUMBER2(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_TEL_NUMBER2, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setFAX_NUMBER1(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_FAX_NUMBER1, table._col15); } } private static class Col16Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setTYPE(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_TYPE, table._col16); } } private static class Col17Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setEMAIL(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_EMAIL, table._col17); } } private static class Col18Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setUPD(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_UPD, table._col18); } } private static class Col19Accessor implements ColAccessor { public final void set(ZKDMOBADR table, RecordSet rs, int index) { table.setDIRTYFLG(rs.getString(index)); } public void setUpdate(ZKDMOBADR table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBADR.COL_DIRTYFLG, table._col19); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBADR.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBADR.COL_MLDNR, new Integer(ZKDMOBADR.IDX_MLDNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBADR.COL_AUART, new Integer(ZKDMOBADR.IDX_AUART)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBADR.COL_PARNR, new Integer(ZKDMOBADR.IDX_PARNR)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBADR.COL_VBELN, new Integer(ZKDMOBADR.IDX_VBELN)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBADR.COL_KUNNR, new Integer(ZKDMOBADR.IDX_KUNNR)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBADR.COL_TITLE, new Integer(ZKDMOBADR.IDX_TITLE)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBADR.COL_NAME1, new Integer(ZKDMOBADR.IDX_NAME1)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBADR.COL_NAME2, new Integer(ZKDMOBADR.IDX_NAME2)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBADR.COL_NAME3, new Integer(ZKDMOBADR.IDX_NAME3)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBADR.COL_NAME4, new Integer(ZKDMOBADR.IDX_NAME4)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBADR.COL_STREET, new Integer(ZKDMOBADR.IDX_STREET)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOBADR.COL_CITY1, new Integer(ZKDMOBADR.IDX_CITY1)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOBADR.COL_POST_CODE1, new Integer(ZKDMOBADR.IDX_POST_CODE1)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMOBADR.COL_TEL_NUMBER1, new Integer(ZKDMOBADR.IDX_TEL_NUMBER1)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMOBADR.COL_TEL_NUMBER2, new Integer(ZKDMOBADR.IDX_TEL_NUMBER2)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(ZKDMOBADR.COL_FAX_NUMBER1, new Integer(ZKDMOBADR.IDX_FAX_NUMBER1)); s_accessor[16] = new Col16Accessor(); s_accessorMap.put(ZKDMOBADR.COL_TYPE, new Integer(ZKDMOBADR.IDX_TYPE)); s_accessor[17] = new Col17Accessor(); s_accessorMap.put(ZKDMOBADR.COL_EMAIL, new Integer(ZKDMOBADR.IDX_EMAIL)); s_accessor[18] = new Col18Accessor(); s_accessorMap.put(ZKDMOBADR.COL_UPD, new Integer(ZKDMOBADR.IDX_UPD)); s_accessor[19] = new Col19Accessor(); s_accessorMap.put(ZKDMOBADR.COL_DIRTYFLG, new Integer(ZKDMOBADR.IDX_DIRTYFLG)); } return s_accessor; } /** * */ private final ZKDMOBADR m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBADRCursor(row, rs, false). * * @param zkdmobadr * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBADRCursor(ZKDMOBADR row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBADR WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBADRCursor(ZKDMOBADR row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBADR} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBANTRTYP.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBANTRTYPCursor.ColAccessor; /** * No description. */ public class ZKDMOBANTRTYP extends TableRow { /** Name of table: ZKDMOBANTRTYP */ public final static String TABLE = "ZKDMOBANTRTYP"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iSet to 0 to let the database system create a * new autoincrement value when the row gets inserted. */ public ZKDMOBANTRTYP(DBSession db, long IDX) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); setIDX(IDX); validate(); } /** * Creates a new complete row using the given column values. * * @param db * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param ANTRC No description. * @param TXT No description. * @param LTEXT No description. * @param REFRESHED No description. */ public ZKDMOBANTRTYP(DBSession db, long IDX, String ANTRC, String TXT, String LTEXT, String REFRESHED) { super(db, null); _col0 = IDX; _col1 = ANTRC; _col2 = TXT; _col3 = LTEXT; _col4 = REFRESHED; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public ZKDMOBANTRTYP(ZKDMOBANTRTYP source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_ANTRC)) _col1 = source._col1; if (isColumnSet(IDX_TXT)) _col2 = source._col2; if (isColumnSet(IDX_LTEXT)) _col3 = source._col3; if (isColumnSet(IDX_REFRESHED)) _col4 = source._col4; } else { // copy all columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_ANTRC)) _col1 = source._col1; if (isColumnSet(IDX_TXT)) _col2 = source._col2; if (isColumnSet(IDX_LTEXT)) _col3 = source._col3; if (isColumnSet(IDX_REFRESHED)) _col4 = source._col4; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param source */ public ZKDMOBANTRTYP(long IDX, ZKDMOBANTRTYP source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = IDX; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_ANTRC)) _col1 = source._col1; if (isColumnSet(IDX_TXT)) _col2 = source._col2; if (isColumnSet(IDX_LTEXT)) _col3 = source._col3; if (isColumnSet(IDX_REFRESHED)) _col4 = source._col4; } else { // copy all columns excluding the primary key _col1 = source._col1; _col2 = source._col2; _col3 = source._col3; _col4 = source._col4; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public ZKDMOBANTRTYP(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_IDX)) m_usedColumns.clear(IDX_IDX); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_ANTRC)) _col1 = DEF_ANTRC; if (m_usedColumns.get(IDX_TXT)) _col2 = DEF_TXT; if (m_usedColumns.get(IDX_LTEXT)) _col3 = DEF_LTEXT; if (m_usedColumns.get(IDX_REFRESHED)) _col4 = DEF_REFRESHED; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_IDX) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append('=').append(sqlHelper.get(_col0)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); if (_col0 == 0) { sqlHelper.inNULL(); } sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); getDBSession().executeSql(sqlHelper.toString()); if (_col0 == 0) { DBSession db = getDBSession(); RecordSet rs = db.getRecordSet(); try { rs.setQuery("SELECT last_insert_rowid()"); //$NON-NLS-1$ rs.moveNext(); setIDX(rs.getLong(0)); } finally { rs.dispose(); } } } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = ZKDMOBANTRTYPCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_ANTRC, _col1); sqlHelper.in(COL_TXT, _col2); sqlHelper.in(COL_LTEXT, _col3); sqlHelper.in(COL_REFRESHED, _col4); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return null */ public long getIDX() { checkSparseColumn(IDX_IDX); return _col0; } /** * @param IDX null */ protected void setIDX(long IDX) { _col0 = IDX; markUsed(IDX_IDX); } /** * @return null */ public String getANTRC() { checkSparseColumn(IDX_ANTRC); return _col1; } /** * @param ANTRC null */ public void setANTRC(String ANTRC) { checkNull(ANTRC); _col1 = ANTRC; markUsed(IDX_ANTRC); } /** * @return null */ public String getTXT() { checkSparseColumn(IDX_TXT); return _col2; } /** * @param TXT null */ public void setTXT(String TXT) { checkNull(TXT); _col2 = TXT; markUsed(IDX_TXT); } /** * @return null */ public String getLTEXT() { checkSparseColumn(IDX_LTEXT); return _col3; } /** * @param LTEXT null */ public void setLTEXT(String LTEXT) { checkNull(LTEXT); _col3 = LTEXT; markUsed(IDX_LTEXT); } /** * @return null */ public String getREFRESHED() { checkSparseColumn(IDX_REFRESHED); return _col4; } /** * @param REFRESHED null */ public void setREFRESHED(String REFRESHED) { checkNull(REFRESHED); _col4 = REFRESHED; markUsed(IDX_REFRESHED); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col0); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ANTRC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ANTRC)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LTEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LTEXT)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBANTRTYPCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBANTRTYPCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBANTRTYPCursor} * instance. Use an instance of {@link ZKDMOBANTRTYPCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBANTRTYP get(RecordSet rs, boolean selectStar) { ZKDMOBANTRTYP result = new ZKDMOBANTRTYP(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBANTRTYP[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBANTRTYP[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBANTRTYP row = new ZKDMOBANTRTYP(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBANTRTYP(row)); return (ZKDMOBANTRTYP[]) list.toArray(new ZKDMOBANTRTYP[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBANTRTYP[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBANTRTYP[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBANTRTYP row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBANTRTYP)) return false; ZKDMOBANTRTYP test = (ZKDMOBANTRTYP) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @return The result of the database access. */ public static ZKDMOBANTRTYP getByPrimaryKey(DBSession db, long IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, long IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBANTRTYP row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBANTRTYP[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBANTRTYP. */ class ZKDMOBANTRTYPCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBANTRTYP table, RecordSet rs, int index); public void setUpdate(ZKDMOBANTRTYP table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBANTRTYP table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDMOBANTRTYP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBANTRTYP.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBANTRTYP table, RecordSet rs, int index) { table.setANTRC(rs.getString(index)); } public void setUpdate(ZKDMOBANTRTYP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBANTRTYP.COL_ANTRC, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBANTRTYP table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBANTRTYP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBANTRTYP.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBANTRTYP table, RecordSet rs, int index) { table.setLTEXT(rs.getString(index)); } public void setUpdate(ZKDMOBANTRTYP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBANTRTYP.COL_LTEXT, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBANTRTYP table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBANTRTYP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBANTRTYP.COL_REFRESHED, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBANTRTYP.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBANTRTYP.COL_IDX, new Integer(ZKDMOBANTRTYP.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBANTRTYP.COL_ANTRC, new Integer(ZKDMOBANTRTYP.IDX_ANTRC)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBANTRTYP.COL_TXT, new Integer(ZKDMOBANTRTYP.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBANTRTYP.COL_LTEXT, new Integer(ZKDMOBANTRTYP.IDX_LTEXT)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBANTRTYP.COL_REFRESHED, new Integer(ZKDMOBANTRTYP.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBANTRTYP m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBANTRTYPCursor(row, rs, false). * * @param zkdmobantrtyp * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBANTRTYPCursor(ZKDMOBANTRTYP row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBANTRTYP WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBANTRTYPCursor(ZKDMOBANTRTYP row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBANTRTYP} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBARBA.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBARBACursor.ColAccessor; /** * No description. */ public class ZKDMOBARBA extends TableRow { /** Name of table: ZKDMOBARBA */ public final static String TABLE = "ZKDMOBARBA"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBARBACursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBARBACursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBARBACursor} * instance. Use an instance of {@link ZKDMOBARBACursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBARBA get(RecordSet rs, boolean selectStar) { ZKDMOBARBA result = new ZKDMOBARBA(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBARBA[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBARBA[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBARBA row = new ZKDMOBARBA(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBARBA(row)); return (ZKDMOBARBA[]) list.toArray(new ZKDMOBARBA[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBARBA[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBARBA[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBARBA row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBARBA)) return false; ZKDMOBARBA test = (ZKDMOBARBA) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBARBA row, String ARBA, boolean likeARBA) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ARBA null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBARBA row, String ARBA) { return queryByPrimaryKey(row, ARBA, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBARBA[] listByPrimaryKey(DBSession db, String ARBA, boolean likeARBA, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA, boolean likeARBA) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append("=").append(sqlHelper.get(ARBA)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBARBA row, String ARBA, boolean likeARBA, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param ARBA null * @param TXT null * @return The result of the database access. */ public static ZKDMOBARBA getByPrimaryKey(DBSession db, String ARBA, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append("=").append(sqlHelper.get(ARBA)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBARBA[] listByPrimaryKey(DBSession db, String ARBA, boolean likeARBA, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @param likeARBA Set to true if the query for ARBA * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA, boolean likeARBA, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append(likeARBA ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(ARBA)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param ARBA null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String ARBA, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_ARBA).append("=").append(sqlHelper.get(ARBA)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBARBA row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBARBA[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_ARBA); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBARBA. */ class ZKDMOBARBACursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBARBA table, RecordSet rs, int index); public void setUpdate(ZKDMOBARBA table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBARBA table, RecordSet rs, int index) { table.setARBA(rs.getString(index)); } public void setUpdate(ZKDMOBARBA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBARBA.COL_ARBA, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBARBA table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBARBA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBARBA.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBARBA table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBARBA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBARBA.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBARBA.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBARBA.COL_ARBA, new Integer(ZKDMOBARBA.IDX_ARBA)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBARBA.COL_TXT, new Integer(ZKDMOBARBA.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBARBA.COL_REFRESHED, new Integer(ZKDMOBARBA.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBARBA m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBARBACursor(row, rs, false). * * @param zkdmobarba * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBARBACursor(ZKDMOBARBA row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBARBA WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBARBACursor(ZKDMOBARBA row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBARBA} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBBEGRSAV.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBBEGRSAVCursor.ColAccessor; /** * No description. */ public class ZKDMOBBEGRSAV extends TableRow { /** Name of table: ZKDMOBBEGRSAV */ public final static String TABLE = "ZKDMOBBEGRSAV"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("SPRAS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPRAS)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBBEGRSAVCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBBEGRSAVCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBBEGRSAVCursor} * instance. Use an instance of {@link ZKDMOBBEGRSAVCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBBEGRSAV get(RecordSet rs, boolean selectStar) { ZKDMOBBEGRSAV result = new ZKDMOBBEGRSAV(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBBEGRSAV[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBBEGRSAV[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBBEGRSAV row = new ZKDMOBBEGRSAV(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBBEGRSAV(row)); return (ZKDMOBBEGRSAV[]) list.toArray(new ZKDMOBBEGRSAV[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBBEGRSAV[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBBEGRSAV[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBBEGRSAV row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBBEGRSAV)) return false; ZKDMOBBEGRSAV test = (ZKDMOBBEGRSAV) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBEGRSAV row, String SAVRET, boolean likeSAVRET) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param SAVRET null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBEGRSAV row, String SAVRET) { return queryByPrimaryKey(row, SAVRET, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBBEGRSAV[] listByPrimaryKey(DBSession db, String SAVRET, boolean likeSAVRET, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String SAVRET, boolean likeSAVRET) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param SAVRET null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String SAVRET) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append("=").append(sqlHelper.get(SAVRET)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param SPRAS null * @param likeSPRAS Set to true if the query for SPRAS * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBEGRSAV row, String SAVRET, boolean likeSAVRET, String SPRAS, boolean likeSPRAS) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append(likeSPRAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SPRAS)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param SAVRET null * @param SPRAS null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBEGRSAV row, String SAVRET, String SPRAS) { return queryByPrimaryKey(row, SAVRET, false, SPRAS, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param SPRAS null * @param likeSPRAS Set to true if the query for SPRAS * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBBEGRSAV[] listByPrimaryKey(DBSession db, String SAVRET, boolean likeSAVRET, String SPRAS, boolean likeSPRAS, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append(likeSPRAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SPRAS)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param SPRAS null * @param likeSPRAS Set to true if the query for SPRAS * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String SAVRET, boolean likeSAVRET, String SPRAS, boolean likeSPRAS) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append(likeSPRAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SPRAS)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param SAVRET null * @param SPRAS null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String SAVRET, String SPRAS) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append("=").append(sqlHelper.get(SAVRET)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append("=").append(sqlHelper.get(SPRAS)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param SPRAS null * @param likeSPRAS Set to true if the query for SPRAS * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBEGRSAV row, String SAVRET, boolean likeSAVRET, String SPRAS, boolean likeSPRAS, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append(likeSPRAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SPRAS)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param SAVRET null * @param SPRAS null * @param TXT null * @return The result of the database access. */ public static ZKDMOBBEGRSAV getByPrimaryKey(DBSession db, String SAVRET, String SPRAS, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append("=").append(sqlHelper.get(SAVRET)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append("=").append(sqlHelper.get(SPRAS)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param SPRAS null * @param likeSPRAS Set to true if the query for SPRAS * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBBEGRSAV[] listByPrimaryKey(DBSession db, String SAVRET, boolean likeSAVRET, String SPRAS, boolean likeSPRAS, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append(likeSPRAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SPRAS)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param SAVRET null * @param likeSAVRET Set to true if the query for SAVRET * should be based on LIKE instead of equality. * @param SPRAS null * @param likeSPRAS Set to true if the query for SPRAS * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String SAVRET, boolean likeSAVRET, String SPRAS, boolean likeSPRAS, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append(likeSAVRET ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SAVRET)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append(likeSPRAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(SPRAS)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param SAVRET null * @param SPRAS null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String SAVRET, String SPRAS, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_SAVRET).append("=").append(sqlHelper.get(SAVRET)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_SPRAS).append("=").append(sqlHelper.get(SPRAS)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBEGRSAV row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBBEGRSAV[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_SAVRET); sb.append(", ").append(COL_SPRAS); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBBEGRSAV. */ class ZKDMOBBEGRSAVCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBBEGRSAV table, RecordSet rs, int index); public void setUpdate(ZKDMOBBEGRSAV table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBBEGRSAV table, RecordSet rs, int index) { table.setSAVRET(rs.getString(index)); } public void setUpdate(ZKDMOBBEGRSAV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBEGRSAV.COL_SAVRET, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBBEGRSAV table, RecordSet rs, int index) { table.setSPRAS(rs.getString(index)); } public void setUpdate(ZKDMOBBEGRSAV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBEGRSAV.COL_SPRAS, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBBEGRSAV table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBBEGRSAV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBEGRSAV.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBBEGRSAV table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBBEGRSAV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBEGRSAV.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBBEGRSAV.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBBEGRSAV.COL_SAVRET, new Integer(ZKDMOBBEGRSAV.IDX_SAVRET)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBBEGRSAV.COL_SPRAS, new Integer(ZKDMOBBEGRSAV.IDX_SPRAS)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBBEGRSAV.COL_TXT, new Integer(ZKDMOBBEGRSAV.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBBEGRSAV.COL_REFRESHED, new Integer(ZKDMOBBEGRSAV.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBBEGRSAV m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBBEGRSAVCursor(row, rs, false). * * @param zkdmobbegrsav * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBBEGRSAVCursor(ZKDMOBBEGRSAV row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBBEGRSAV WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBBEGRSAVCursor(ZKDMOBBEGRSAV row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBBEGRSAV} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBBTRBZUST.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBBTRBZUSTCursor.ColAccessor; /** * No description. */ public class ZKDMOBBTRBZUST extends TableRow { /** Name of table: ZKDMOBBTRBZUST */ public final static String TABLE = "ZKDMOBBTRBZUST"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBBTRBZUSTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBBTRBZUSTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBBTRBZUSTCursor} * instance. Use an instance of {@link ZKDMOBBTRBZUSTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBBTRBZUST get(RecordSet rs, boolean selectStar) { ZKDMOBBTRBZUST result = new ZKDMOBBTRBZUST(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBBTRBZUST[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBBTRBZUST[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBBTRBZUST row = new ZKDMOBBTRBZUST(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBBTRBZUST(row)); return (ZKDMOBBTRBZUST[]) list.toArray(new ZKDMOBBTRBZUST[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBBTRBZUST[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBBTRBZUST[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBBTRBZUST row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBBTRBZUST)) return false; ZKDMOBBTRBZUST test = (ZKDMOBBTRBZUST) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param BTRBZUST null * @param likeBTRBZUST Set to true if the query for BTRBZUST * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBTRBZUST row, String BTRBZUST, boolean likeBTRBZUST) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_BTRBZUST).append(likeBTRBZUST ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(BTRBZUST)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_BTRBZUST); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param BTRBZUST null * @return The result of the database access. */ public static ZKDMOBBTRBZUST getByPrimaryKey(DBSession db, String BTRBZUST) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_BTRBZUST).append("=").append(sqlHelper.get(BTRBZUST)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param BTRBZUST null * @param likeBTRBZUST Set to true if the query for BTRBZUST * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBBTRBZUST[] listByPrimaryKey(DBSession db, String BTRBZUST, boolean likeBTRBZUST, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_BTRBZUST).append(likeBTRBZUST ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(BTRBZUST)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_BTRBZUST); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param BTRBZUST null * @param likeBTRBZUST Set to true if the query for BTRBZUST * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String BTRBZUST, boolean likeBTRBZUST) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_BTRBZUST).append(likeBTRBZUST ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(BTRBZUST)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param BTRBZUST null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String BTRBZUST) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_BTRBZUST).append("=").append(sqlHelper.get(BTRBZUST)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBBTRBZUST row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_BTRBZUST); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBBTRBZUST[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_BTRBZUST); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBBTRBZUST. */ class ZKDMOBBTRBZUSTCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBBTRBZUST table, RecordSet rs, int index); public void setUpdate(ZKDMOBBTRBZUST table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBBTRBZUST table, RecordSet rs, int index) { table.setBTRBZUST(rs.getString(index)); } public void setUpdate(ZKDMOBBTRBZUST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBTRBZUST.COL_BTRBZUST, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBBTRBZUST table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBBTRBZUST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBTRBZUST.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBBTRBZUST table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBBTRBZUST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBBTRBZUST.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBBTRBZUST.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBBTRBZUST.COL_BTRBZUST, new Integer(ZKDMOBBTRBZUST.IDX_BTRBZUST)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBBTRBZUST.COL_TXT, new Integer(ZKDMOBBTRBZUST.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBBTRBZUST.COL_REFRESHED, new Integer(ZKDMOBBTRBZUST.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBBTRBZUST m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBBTRBZUSTCursor(row, rs, false). * * @param zkdmobbtrbzust * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBBTRBZUSTCursor(ZKDMOBBTRBZUST row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBBTRBZUST WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBBTRBZUSTCursor(ZKDMOBBTRBZUST row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBBTRBZUST} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBCHKLIST.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBCHKLISTCursor.ColAccessor; /** * No description. */ public class ZKDMOBCHKLIST extends TableRow { /** Name of table: ZKDMOBCHKLIST */ public final static String TABLE = "ZKDMOBCHKLIST"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBCHKLISTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBCHKLISTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBCHKLISTCursor} * instance. Use an instance of {@link ZKDMOBCHKLISTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBCHKLIST get(RecordSet rs, boolean selectStar) { ZKDMOBCHKLIST result = new ZKDMOBCHKLIST(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBCHKLIST[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBCHKLIST[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBCHKLIST row = new ZKDMOBCHKLIST(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBCHKLIST(row)); return (ZKDMOBCHKLIST[]) list.toArray(new ZKDMOBCHKLIST[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBCHKLIST[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBCHKLIST[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBCHKLIST row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBCHKLIST)) return false; ZKDMOBCHKLIST test = (ZKDMOBCHKLIST) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CHCKLISTE null * @param likeCHCKLISTE Set to true if the query for CHCKLISTE * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBCHKLIST row, String CHCKLISTE, boolean likeCHCKLISTE) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append(likeCHCKLISTE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CHCKLISTE)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CHCKLISTE null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBCHKLIST row, String CHCKLISTE) { return queryByPrimaryKey(row, CHCKLISTE, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param CHCKLISTE null * @param likeCHCKLISTE Set to true if the query for CHCKLISTE * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBCHKLIST[] listByPrimaryKey(DBSession db, String CHCKLISTE, boolean likeCHCKLISTE, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append(likeCHCKLISTE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CHCKLISTE)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CHCKLISTE null * @param likeCHCKLISTE Set to true if the query for CHCKLISTE * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CHCKLISTE, boolean likeCHCKLISTE) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append(likeCHCKLISTE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CHCKLISTE)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CHCKLISTE null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CHCKLISTE) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append("=").append(sqlHelper.get(CHCKLISTE)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param CHCKLISTE null * @param likeCHCKLISTE Set to true if the query for CHCKLISTE * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBCHKLIST row, String CHCKLISTE, boolean likeCHCKLISTE, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append(likeCHCKLISTE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CHCKLISTE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param CHCKLISTE null * @param TXT null * @return The result of the database access. */ public static ZKDMOBCHKLIST getByPrimaryKey(DBSession db, String CHCKLISTE, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append("=").append(sqlHelper.get(CHCKLISTE)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param CHCKLISTE null * @param likeCHCKLISTE Set to true if the query for CHCKLISTE * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBCHKLIST[] listByPrimaryKey(DBSession db, String CHCKLISTE, boolean likeCHCKLISTE, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append(likeCHCKLISTE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CHCKLISTE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CHCKLISTE null * @param likeCHCKLISTE Set to true if the query for CHCKLISTE * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CHCKLISTE, boolean likeCHCKLISTE, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append(likeCHCKLISTE ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(CHCKLISTE)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param CHCKLISTE null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String CHCKLISTE, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE).append("=").append(sqlHelper.get(CHCKLISTE)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBCHKLIST row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBCHKLIST[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_CHCKLISTE); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBCHKLIST. */ class ZKDMOBCHKLISTCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBCHKLIST table, RecordSet rs, int index); public void setUpdate(ZKDMOBCHKLIST table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBCHKLIST table, RecordSet rs, int index) { table.setCHCKLISTE(rs.getString(index)); } public void setUpdate(ZKDMOBCHKLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBCHKLIST.COL_CHCKLISTE, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBCHKLIST table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBCHKLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBCHKLIST.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBCHKLIST table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBCHKLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBCHKLIST.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBCHKLIST.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBCHKLIST.COL_CHCKLISTE, new Integer(ZKDMOBCHKLIST.IDX_CHCKLISTE)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBCHKLIST.COL_TXT, new Integer(ZKDMOBCHKLIST.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBCHKLIST.COL_REFRESHED, new Integer(ZKDMOBCHKLIST.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBCHKLIST m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBCHKLISTCursor(row, rs, false). * * @param zkdmobchklist * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBCHKLISTCursor(ZKDMOBCHKLIST row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBCHKLIST WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBCHKLISTCursor(ZKDMOBCHKLIST row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBCHKLIST} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBDELVRYLIST.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBDELVRYLISTCursor.ColAccessor; /** * No description. */ public class ZKDMOBDELVRYLIST extends TableRow { /** Name of table: ZKDMOBDELVRYLIST */ public final static String TABLE = "ZKDMOBDELVRYLIST"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 13; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("EBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EBELN)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EBELP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EBELP)) sb.append(_col3); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MATNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MATNR)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAKTX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAKTX)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGORT_FROM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGORT_FROM)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGORT_TO"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGORT_TO)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGKNZ"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGKNZ)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ENTRY_QNT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ENTRY_QNT)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ENTRY_UOM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ENTRY_UOM)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("WADAK"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_WADAK)) sb.append(df.format(_col11)); sb.append(", ").append("KNZDLVRY"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KNZDLVRY)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBDELVRYLISTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBDELVRYLISTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBDELVRYLISTCursor} * instance. Use an instance of {@link ZKDMOBDELVRYLISTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBDELVRYLIST get(RecordSet rs, boolean selectStar) { ZKDMOBDELVRYLIST result = new ZKDMOBDELVRYLIST(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBDELVRYLIST[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBDELVRYLIST[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBDELVRYLIST row = new ZKDMOBDELVRYLIST(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBDELVRYLIST(row)); return (ZKDMOBDELVRYLIST[]) list.toArray(new ZKDMOBDELVRYLIST[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBDELVRYLIST[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBDELVRYLIST[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBDELVRYLIST row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBDELVRYLIST)) return false; ZKDMOBDELVRYLIST test = (ZKDMOBDELVRYLIST) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && _col3 != test._col3) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBDELVRYLIST[] listByPrimaryKey(DBSession db, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID) { return queryByPrimaryKey(row, PERNR, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBDELVRYLIST[] listByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @param EBELN null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID, String EBELN) { return queryByPrimaryKey(row, PERNR, GUID, false, EBELN, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBDELVRYLIST[] listByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param EBELN null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, String EBELN) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param EBELP null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int EBELP) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=") //$NON-NLS-1$ .append(sqlHelper.get(EBELP)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @param EBELN null * @param EBELP null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID, String EBELN, int EBELP) { return queryByPrimaryKey(row, PERNR, GUID, false, EBELN, false, EBELP); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param EBELP null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBDELVRYLIST[] listByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int EBELP, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=") //$NON-NLS-1$ .append(sqlHelper.get(EBELP)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param EBELP null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int EBELP) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=") //$NON-NLS-1$ .append(sqlHelper.get(EBELP)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param EBELN null * @param EBELP null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, String EBELN, int EBELP) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=").append(sqlHelper.get(EBELP)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param EBELP null * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int EBELP, String MATNR, boolean likeMATNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=") //$NON-NLS-1$ .append(sqlHelper.get(EBELP)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @param GUID null * @param EBELN null * @param EBELP null * @param MATNR null * @return The result of the database access. */ public static ZKDMOBDELVRYLIST getByPrimaryKey(DBSession db, int PERNR, String GUID, String EBELN, int EBELP, String MATNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=").append(sqlHelper.get(EBELP)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param EBELP null * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBDELVRYLIST[] listByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int EBELP, String MATNR, boolean likeMATNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=") //$NON-NLS-1$ .append(sqlHelper.get(EBELP)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param EBELP null * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int EBELP, String MATNR, boolean likeMATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=") //$NON-NLS-1$ .append(sqlHelper.get(EBELP)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param GUID null * @param EBELN null * @param EBELP null * @param MATNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String GUID, String EBELN, int EBELP, String MATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELP).append("=").append(sqlHelper.get(EBELP)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBDELVRYLIST row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBDELVRYLIST[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_EBELP); //$NON-NLS-1$ sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBDELVRYLIST. */ class ZKDMOBDELVRYLISTCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index); public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_GUID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setEBELN(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_EBELN, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setEBELP(rs.getInt(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_EBELP, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_MATNR, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setMAKTX(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_MAKTX, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setLGORT_FROM(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_LGORT_FROM, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setLGORT_TO(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_LGORT_TO, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setLGKNZ(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_LGKNZ, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setENTRY_QNT(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_ENTRY_QNT, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setENTRY_UOM(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_ENTRY_UOM, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setWADAK(rs.getDate(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_WADAK, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOBDELVRYLIST table, RecordSet rs, int index) { table.setKNZDLVRY(rs.getString(index)); } public void setUpdate(ZKDMOBDELVRYLIST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBDELVRYLIST.COL_KNZDLVRY, table._col12); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBDELVRYLIST.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_PERNR, new Integer(ZKDMOBDELVRYLIST.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_GUID, new Integer(ZKDMOBDELVRYLIST.IDX_GUID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_EBELN, new Integer(ZKDMOBDELVRYLIST.IDX_EBELN)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_EBELP, new Integer(ZKDMOBDELVRYLIST.IDX_EBELP)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_MATNR, new Integer(ZKDMOBDELVRYLIST.IDX_MATNR)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_MAKTX, new Integer(ZKDMOBDELVRYLIST.IDX_MAKTX)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_LGORT_FROM, new Integer(ZKDMOBDELVRYLIST.IDX_LGORT_FROM)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_LGORT_TO, new Integer(ZKDMOBDELVRYLIST.IDX_LGORT_TO)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_LGKNZ, new Integer(ZKDMOBDELVRYLIST.IDX_LGKNZ)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_ENTRY_QNT, new Integer(ZKDMOBDELVRYLIST.IDX_ENTRY_QNT)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_ENTRY_UOM, new Integer(ZKDMOBDELVRYLIST.IDX_ENTRY_UOM)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_WADAK, new Integer(ZKDMOBDELVRYLIST.IDX_WADAK)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOBDELVRYLIST.COL_KNZDLVRY, new Integer(ZKDMOBDELVRYLIST.IDX_KNZDLVRY)); } return s_accessor; } /** * */ private final ZKDMOBDELVRYLIST m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBDELVRYLISTCursor(row, rs, false). * * @param zkdmobdelvrylist * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBDELVRYLISTCursor(ZKDMOBDELVRYLIST row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBDELVRYLIST WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBDELVRYLISTCursor(ZKDMOBDELVRYLIST row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBDELVRYLIST} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBFLGVRG.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBFLGVRGCursor.ColAccessor; /** * No description. */ public class ZKDMOBFLGVRG extends TableRow { /** Name of table: ZKDMOBFLGVRG */ public final static String TABLE = "ZKDMOBFLGVRG"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBFLGVRGCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBFLGVRGCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBFLGVRGCursor} * instance. Use an instance of {@link ZKDMOBFLGVRGCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBFLGVRG get(RecordSet rs, boolean selectStar) { ZKDMOBFLGVRG result = new ZKDMOBFLGVRG(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBFLGVRG[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBFLGVRG[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBFLGVRG row = new ZKDMOBFLGVRG(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBFLGVRG(row)); return (ZKDMOBFLGVRG[]) list.toArray(new ZKDMOBFLGVRG[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBFLGVRG[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBFLGVRG[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBFLGVRG row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBFLGVRG)) return false; ZKDMOBFLGVRG test = (ZKDMOBFLGVRG) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FLGVRG null * @param likeFLGVRG Set to true if the query for FLGVRG * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFLGVRG row, String FLGVRG, boolean likeFLGVRG) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FLGVRG).append(likeFLGVRG ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FLGVRG)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FLGVRG); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param FLGVRG null * @return The result of the database access. */ public static ZKDMOBFLGVRG getByPrimaryKey(DBSession db, String FLGVRG) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FLGVRG).append("=").append(sqlHelper.get(FLGVRG)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FLGVRG null * @param likeFLGVRG Set to true if the query for FLGVRG * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFLGVRG[] listByPrimaryKey(DBSession db, String FLGVRG, boolean likeFLGVRG, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FLGVRG).append(likeFLGVRG ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FLGVRG)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FLGVRG); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FLGVRG null * @param likeFLGVRG Set to true if the query for FLGVRG * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FLGVRG, boolean likeFLGVRG) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FLGVRG).append(likeFLGVRG ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FLGVRG)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FLGVRG null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FLGVRG) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FLGVRG).append("=").append(sqlHelper.get(FLGVRG)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFLGVRG row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FLGVRG); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFLGVRG[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FLGVRG); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBFLGVRG. */ class ZKDMOBFLGVRGCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBFLGVRG table, RecordSet rs, int index); public void setUpdate(ZKDMOBFLGVRG table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBFLGVRG table, RecordSet rs, int index) { table.setFLGVRG(rs.getString(index)); } public void setUpdate(ZKDMOBFLGVRG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFLGVRG.COL_FLGVRG, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBFLGVRG table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBFLGVRG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFLGVRG.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBFLGVRG table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBFLGVRG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFLGVRG.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBFLGVRG.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBFLGVRG.COL_FLGVRG, new Integer(ZKDMOBFLGVRG.IDX_FLGVRG)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBFLGVRG.COL_TXT, new Integer(ZKDMOBFLGVRG.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBFLGVRG.COL_REFRESHED, new Integer(ZKDMOBFLGVRG.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBFLGVRG m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBFLGVRGCursor(row, rs, false). * * @param zkdmobflgvrg * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFLGVRGCursor(ZKDMOBFLGVRG row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBFLGVRG WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFLGVRGCursor(ZKDMOBFLGVRG row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBFLGVRG} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBFORMDESC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBFORMDESCCursor.ColAccessor; /** * No description. */ public class ZKDMOBFORMDESC extends TableRow { /** Name of table: ZKDMOBFORMDESC */ public final static String TABLE = "ZKDMOBFORMDESC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBFORMDESCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBFORMDESCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBFORMDESCCursor} * instance. Use an instance of {@link ZKDMOBFORMDESCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBFORMDESC get(RecordSet rs, boolean selectStar) { ZKDMOBFORMDESC result = new ZKDMOBFORMDESC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBFORMDESC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBFORMDESC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBFORMDESC row = new ZKDMOBFORMDESC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBFORMDESC(row)); return (ZKDMOBFORMDESC[]) list.toArray(new ZKDMOBFORMDESC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBFORMDESC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBFORMDESC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBFORMDESC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBFORMDESC)) return false; ZKDMOBFORMDESC test = (ZKDMOBFORMDESC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param FORMDESC null * @param likeFORMDESC Set to true if the query for FORMDESC * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFORMDESC row, String FORMDESC, boolean likeFORMDESC) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMDESC).append(likeFORMDESC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMDESC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMDESC); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param FORMDESC null * @return The result of the database access. */ public static ZKDMOBFORMDESC getByPrimaryKey(DBSession db, String FORMDESC) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMDESC).append("=").append(sqlHelper.get(FORMDESC)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param FORMDESC null * @param likeFORMDESC Set to true if the query for FORMDESC * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFORMDESC[] listByPrimaryKey(DBSession db, String FORMDESC, boolean likeFORMDESC, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMDESC).append(likeFORMDESC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMDESC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMDESC); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMDESC null * @param likeFORMDESC Set to true if the query for FORMDESC * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMDESC, boolean likeFORMDESC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMDESC).append(likeFORMDESC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FORMDESC)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param FORMDESC null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String FORMDESC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_FORMDESC).append("=").append(sqlHelper.get(FORMDESC)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFORMDESC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMDESC); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFORMDESC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_FORMDESC); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBFORMDESC. */ class ZKDMOBFORMDESCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBFORMDESC table, RecordSet rs, int index); public void setUpdate(ZKDMOBFORMDESC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBFORMDESC table, RecordSet rs, int index) { table.setFORMDESC(rs.getString(index)); } public void setUpdate(ZKDMOBFORMDESC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFORMDESC.COL_FORMDESC, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBFORMDESC table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBFORMDESC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFORMDESC.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBFORMDESC table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBFORMDESC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFORMDESC.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBFORMDESC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBFORMDESC.COL_FORMDESC, new Integer(ZKDMOBFORMDESC.IDX_FORMDESC)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBFORMDESC.COL_TXT, new Integer(ZKDMOBFORMDESC.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBFORMDESC.COL_REFRESHED, new Integer(ZKDMOBFORMDESC.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBFORMDESC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBFORMDESCCursor(row, rs, false). * * @param zkdmobformdesc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFORMDESCCursor(ZKDMOBFORMDESC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBFORMDESC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFORMDESCCursor(ZKDMOBFORMDESC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBFORMDESC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBFZGMBEW.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBFZGMBEWCursor.ColAccessor; /** * No description. */ public class ZKDMOBFZGMBEW extends TableRow { /** Name of table: ZKDMOBFZGMBEW */ public final static String TABLE = "ZKDMOBFZGMBEW"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 13; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("EBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EBELN)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EBELP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EBELP)) sb.append(_col2); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col3); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MATNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MATNR)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGORT_FROM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGORT_FROM)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGORT_TO"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGORT_TO)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ENTRY_QNT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ENTRY_QNT)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ENTRY_UOM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ENTRY_UOM)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("WEGRND"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_WEGRND)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BARC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BARC)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BARCTXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BARCTXT)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CONF_PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CONF_PERNR)) sb.append(_col12); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBFZGMBEWCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBFZGMBEWCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBFZGMBEWCursor} * instance. Use an instance of {@link ZKDMOBFZGMBEWCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBFZGMBEW get(RecordSet rs, boolean selectStar) { ZKDMOBFZGMBEW result = new ZKDMOBFZGMBEW(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBFZGMBEW[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBFZGMBEW[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBFZGMBEW row = new ZKDMOBFZGMBEW(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBFZGMBEW(row)); return (ZKDMOBFZGMBEW[]) list.toArray(new ZKDMOBFZGMBEW[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBFZGMBEW[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBFZGMBEW[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBFZGMBEW row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBFZGMBEW)) return false; ZKDMOBFZGMBEW test = (ZKDMOBFZGMBEW) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && _col2 != test._col2) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && _col3 != test._col3) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && _col12 != test._col12) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZGMBEW row, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZGMBEW row, String GUID) { return queryByPrimaryKey(row, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZGMBEW[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZGMBEW row, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param EBELN null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZGMBEW row, String GUID, String EBELN) { return queryByPrimaryKey(row, GUID, false, EBELN, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZGMBEW[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param EBELN null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String EBELN) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZGMBEW row, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param GUID null * @param EBELN null * @param PERNR null * @return The result of the database access. */ public static ZKDMOBFZGMBEW getByPrimaryKey(DBSession db, String GUID, String EBELN, int PERNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZGMBEW[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param EBELN null * @param likeEBELN Set to true if the query for EBELN * should be based on LIKE instead of equality. * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String EBELN, boolean likeEBELN, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append(likeEBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param EBELN null * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String EBELN, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EBELN).append("=").append(sqlHelper.get(EBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZGMBEW row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZGMBEW[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_EBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBFZGMBEW. */ class ZKDMOBFZGMBEWCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBFZGMBEW table, RecordSet rs, int index); public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_GUID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setEBELN(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_EBELN, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setEBELP(rs.getInt(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_EBELP, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_PERNR, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_MATNR, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setLGORT_FROM(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_LGORT_FROM, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setLGORT_TO(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_LGORT_TO, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setENTRY_QNT(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_ENTRY_QNT, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setENTRY_UOM(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_ENTRY_UOM, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setWEGRND(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_WEGRND, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setBARC(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_BARC, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setBARCTXT(rs.getString(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_BARCTXT, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOBFZGMBEW table, RecordSet rs, int index) { table.setCONF_PERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBFZGMBEW table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZGMBEW.COL_CONF_PERNR, table._col12); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBFZGMBEW.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_GUID, new Integer(ZKDMOBFZGMBEW.IDX_GUID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_EBELN, new Integer(ZKDMOBFZGMBEW.IDX_EBELN)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_EBELP, new Integer(ZKDMOBFZGMBEW.IDX_EBELP)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_PERNR, new Integer(ZKDMOBFZGMBEW.IDX_PERNR)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_MATNR, new Integer(ZKDMOBFZGMBEW.IDX_MATNR)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_LGORT_FROM, new Integer(ZKDMOBFZGMBEW.IDX_LGORT_FROM)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_LGORT_TO, new Integer(ZKDMOBFZGMBEW.IDX_LGORT_TO)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_ENTRY_QNT, new Integer(ZKDMOBFZGMBEW.IDX_ENTRY_QNT)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_ENTRY_UOM, new Integer(ZKDMOBFZGMBEW.IDX_ENTRY_UOM)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_WEGRND, new Integer(ZKDMOBFZGMBEW.IDX_WEGRND)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_BARC, new Integer(ZKDMOBFZGMBEW.IDX_BARC)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_BARCTXT, new Integer(ZKDMOBFZGMBEW.IDX_BARCTXT)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOBFZGMBEW.COL_CONF_PERNR, new Integer(ZKDMOBFZGMBEW.IDX_CONF_PERNR)); } return s_accessor; } /** * */ private final ZKDMOBFZGMBEW m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBFZGMBEWCursor(row, rs, false). * * @param zkdmobfzgmbew * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFZGMBEWCursor(ZKDMOBFZGMBEW row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBFZGMBEW WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFZGMBEWCursor(ZKDMOBFZGMBEW row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBFZGMBEW} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBFZLG.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBFZLGCursor.ColAccessor; /** * No description. */ public class ZKDMOBFZLG extends TableRow { /** Name of table: ZKDMOBFZLG */ public final static String TABLE = "ZKDMOBFZLG"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col1); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NAME_TEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME_TEXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGKNZ"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGKNZ)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBFZLGCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBFZLGCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBFZLGCursor} * instance. Use an instance of {@link ZKDMOBFZLGCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBFZLG get(RecordSet rs, boolean selectStar) { ZKDMOBFZLG result = new ZKDMOBFZLG(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBFZLG[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBFZLG[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBFZLG row = new ZKDMOBFZLG(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBFZLG(row)); return (ZKDMOBFZLG[]) list.toArray(new ZKDMOBFZLG[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBFZLG[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBFZLG[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBFZLG row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBFZLG)) return false; ZKDMOBFZLG test = (ZKDMOBFZLG) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLG row, String LGORT, boolean likeLGORT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param LGORT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLG row, String LGORT) { return queryByPrimaryKey(row, LGORT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZLG[] listByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append("=").append(sqlHelper.get(LGORT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLG row, String LGORT, boolean likeLGORT, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param LGORT null * @param PERNR null * @return The result of the database access. */ public static ZKDMOBFZLG getByPrimaryKey(DBSession db, String LGORT, int PERNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append("=").append(sqlHelper.get(LGORT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZLG[] listByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append("=").append(sqlHelper.get(LGORT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLG row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZLG[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_PERNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBFZLG. */ class ZKDMOBFZLGCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBFZLG table, RecordSet rs, int index); public void setUpdate(ZKDMOBFZLG table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBFZLG table, RecordSet rs, int index) { table.setLGORT(rs.getString(index)); } public void setUpdate(ZKDMOBFZLG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLG.COL_LGORT, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBFZLG table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBFZLG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLG.COL_PERNR, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBFZLG table, RecordSet rs, int index) { table.setNAME_TEXT(rs.getString(index)); } public void setUpdate(ZKDMOBFZLG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLG.COL_NAME_TEXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBFZLG table, RecordSet rs, int index) { table.setLGKNZ(rs.getString(index)); } public void setUpdate(ZKDMOBFZLG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLG.COL_LGKNZ, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBFZLG table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBFZLG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLG.COL_REFRESHED, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBFZLG.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBFZLG.COL_LGORT, new Integer(ZKDMOBFZLG.IDX_LGORT)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBFZLG.COL_PERNR, new Integer(ZKDMOBFZLG.IDX_PERNR)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBFZLG.COL_NAME_TEXT, new Integer(ZKDMOBFZLG.IDX_NAME_TEXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBFZLG.COL_LGKNZ, new Integer(ZKDMOBFZLG.IDX_LGKNZ)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBFZLG.COL_REFRESHED, new Integer(ZKDMOBFZLG.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBFZLG m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBFZLGCursor(row, rs, false). * * @param zkdmobfzlg * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFZLGCursor(ZKDMOBFZLG row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBFZLG WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFZLGCursor(ZKDMOBFZLG row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBFZLG} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBFZLGSYNC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBFZLGSYNCCursor.ColAccessor; /** * No description. */ public class ZKDMOBFZLGSYNC extends TableRow { /** Name of table: ZKDMOBFZLGSYNC */ public final static String TABLE = "ZKDMOBFZLGSYNC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 5; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("MATNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MATNR)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAKTX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAKTX)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LABST"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LABST)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MEINS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MEINS)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBFZLGSYNCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBFZLGSYNCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBFZLGSYNCCursor} * instance. Use an instance of {@link ZKDMOBFZLGSYNCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBFZLGSYNC get(RecordSet rs, boolean selectStar) { ZKDMOBFZLGSYNC result = new ZKDMOBFZLGSYNC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBFZLGSYNC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBFZLGSYNC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBFZLGSYNC row = new ZKDMOBFZLGSYNC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBFZLGSYNC(row)); return (ZKDMOBFZLGSYNC[]) list.toArray(new ZKDMOBFZLGSYNC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBFZLGSYNC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBFZLGSYNC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBFZLGSYNC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBFZLGSYNC)) return false; ZKDMOBFZLGSYNC test = (ZKDMOBFZLGSYNC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLGSYNC row, String LGORT, boolean likeLGORT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param LGORT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLGSYNC row, String LGORT) { return queryByPrimaryKey(row, LGORT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZLGSYNC[] listByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append("=").append(sqlHelper.get(LGORT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLGSYNC row, String LGORT, boolean likeLGORT, String MATNR, boolean likeMATNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param LGORT null * @param MATNR null * @return The result of the database access. */ public static ZKDMOBFZLGSYNC getByPrimaryKey(DBSession db, String LGORT, String MATNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append("=").append(sqlHelper.get(LGORT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZLGSYNC[] listByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT, String MATNR, boolean likeMATNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @param likeLGORT Set to true if the query for LGORT * should be based on LIKE instead of equality. * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT, boolean likeLGORT, String MATNR, boolean likeMATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append(likeLGORT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LGORT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param LGORT null * @param MATNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String LGORT, String MATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_LGORT).append("=").append(sqlHelper.get(LGORT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBFZLGSYNC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBFZLGSYNC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_LGORT); sb.append(", ").append(COL_MATNR); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBFZLGSYNC. */ class ZKDMOBFZLGSYNCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBFZLGSYNC table, RecordSet rs, int index); public void setUpdate(ZKDMOBFZLGSYNC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBFZLGSYNC table, RecordSet rs, int index) { table.setLGORT(rs.getString(index)); } public void setUpdate(ZKDMOBFZLGSYNC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLGSYNC.COL_LGORT, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBFZLGSYNC table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMOBFZLGSYNC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLGSYNC.COL_MATNR, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBFZLGSYNC table, RecordSet rs, int index) { table.setMAKTX(rs.getString(index)); } public void setUpdate(ZKDMOBFZLGSYNC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLGSYNC.COL_MAKTX, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBFZLGSYNC table, RecordSet rs, int index) { table.setLABST(rs.getString(index)); } public void setUpdate(ZKDMOBFZLGSYNC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLGSYNC.COL_LABST, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBFZLGSYNC table, RecordSet rs, int index) { table.setMEINS(rs.getString(index)); } public void setUpdate(ZKDMOBFZLGSYNC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBFZLGSYNC.COL_MEINS, table._col4); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBFZLGSYNC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBFZLGSYNC.COL_LGORT, new Integer(ZKDMOBFZLGSYNC.IDX_LGORT)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBFZLGSYNC.COL_MATNR, new Integer(ZKDMOBFZLGSYNC.IDX_MATNR)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBFZLGSYNC.COL_MAKTX, new Integer(ZKDMOBFZLGSYNC.IDX_MAKTX)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBFZLGSYNC.COL_LABST, new Integer(ZKDMOBFZLGSYNC.IDX_LABST)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBFZLGSYNC.COL_MEINS, new Integer(ZKDMOBFZLGSYNC.IDX_MEINS)); } return s_accessor; } /** * */ private final ZKDMOBFZLGSYNC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBFZLGSYNCCursor(row, rs, false). * * @param zkdmobfzlgsync * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFZLGSYNCCursor(ZKDMOBFZLGSYNC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBFZLGSYNC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBFZLGSYNCCursor(ZKDMOBFZLGSYNC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBFZLGSYNC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMA.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMACursor.ColAccessor; /** * No description. */ public class ZKDMOBMA extends TableRow { /** Name of table: ZKDMOBMA */ public final static String TABLE = "ZKDMOBMA"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 18; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("VORNA"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VORNA)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("INITS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_INITS)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STVPERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STVPERNR)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TELNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TELNR)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NUM01"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NUM01)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VKBUR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VKBUR)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ABWVON"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABWVON)) sb.append(df.format(_col8)); sb.append(", ").append("ABWBIS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABWBIS)) sb.append(df.format(_col9)); sb.append(", ").append("COMLANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_COMLANGU)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("GID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GID)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PWD"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PWD)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGORT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGORT)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ANLFORMAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ANLFORMAT)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SPESENERF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPESENERF)) sb.append(_col16); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSTEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSTEXT)) sb.append('\'').append(_col17).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMACursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMACursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMACursor} * instance. Use an instance of {@link ZKDMOBMACursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMA get(RecordSet rs, boolean selectStar) { ZKDMOBMA result = new ZKDMOBMA(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMA[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMA[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMA row = new ZKDMOBMA(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMA(row)); return (ZKDMOBMA[]) list.toArray(new ZKDMOBMA[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMA[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMA[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMA row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMA)) return false; ZKDMOBMA test = (ZKDMOBMA) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; if ((m_usedColumns == null || !m_usedColumns.get(16)) && _col16 != test._col16) return false; if ((m_usedColumns == null || !m_usedColumns.get(17)) && !_col17.equals(test._col17)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @return The result of the database access. */ public static ZKDMOBMA getByPrimaryKey(DBSession db, int PERNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMA row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMA[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMA. */ class ZKDMOBMACursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMA table, RecordSet rs, int index); public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setNACHN(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_NACHN, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setVORNA(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_VORNA, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setINITS(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_INITS, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setSTVPERNR(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_STVPERNR, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setTELNR(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_TELNR, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setNUM01(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_NUM01, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setVKBUR(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_VKBUR, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setABWVON(rs.getDate(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_ABWVON, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setABWBIS(rs.getDate(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_ABWBIS, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setCOMLANGU(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_COMLANGU, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setGID(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_GID, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setPWD(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_PWD, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_REFRESHED, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setLGORT(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_LGORT, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setANLFORMAT(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_ANLFORMAT, table._col15); } } private static class Col16Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setSPESENERF(rs.getBoolean(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_SPESENERF, table._col16); } } private static class Col17Accessor implements ColAccessor { public final void set(ZKDMOBMA table, RecordSet rs, int index) { table.setIBSTEXT(rs.getString(index)); } public void setUpdate(ZKDMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMA.COL_IBSTEXT, table._col17); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMA.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMA.COL_PERNR, new Integer(ZKDMOBMA.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMA.COL_NACHN, new Integer(ZKDMOBMA.IDX_NACHN)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMA.COL_VORNA, new Integer(ZKDMOBMA.IDX_VORNA)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMA.COL_INITS, new Integer(ZKDMOBMA.IDX_INITS)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMA.COL_STVPERNR, new Integer(ZKDMOBMA.IDX_STVPERNR)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMA.COL_TELNR, new Integer(ZKDMOBMA.IDX_TELNR)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBMA.COL_NUM01, new Integer(ZKDMOBMA.IDX_NUM01)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBMA.COL_VKBUR, new Integer(ZKDMOBMA.IDX_VKBUR)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBMA.COL_ABWVON, new Integer(ZKDMOBMA.IDX_ABWVON)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBMA.COL_ABWBIS, new Integer(ZKDMOBMA.IDX_ABWBIS)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBMA.COL_COMLANGU, new Integer(ZKDMOBMA.IDX_COMLANGU)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOBMA.COL_GID, new Integer(ZKDMOBMA.IDX_GID)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOBMA.COL_PWD, new Integer(ZKDMOBMA.IDX_PWD)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMOBMA.COL_REFRESHED, new Integer(ZKDMOBMA.IDX_REFRESHED)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMOBMA.COL_LGORT, new Integer(ZKDMOBMA.IDX_LGORT)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(ZKDMOBMA.COL_ANLFORMAT, new Integer(ZKDMOBMA.IDX_ANLFORMAT)); s_accessor[16] = new Col16Accessor(); s_accessorMap.put(ZKDMOBMA.COL_SPESENERF, new Integer(ZKDMOBMA.IDX_SPESENERF)); s_accessor[17] = new Col17Accessor(); s_accessorMap.put(ZKDMOBMA.COL_IBSTEXT, new Integer(ZKDMOBMA.IDX_IBSTEXT)); } return s_accessor; } /** * */ private final ZKDMOBMA m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMACursor(row, rs, false). * * @param zkdmobma * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMACursor(ZKDMOBMA row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMA WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMACursor(ZKDMOBMA row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMA} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMAT.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMATCursor.ColAccessor; /** * No description. */ public class ZKDMOBMAT extends TableRow { /** Name of table: ZKDMOBMAT */ public final static String TABLE = "ZKDMOBMAT"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 15; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("MAKTX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAKTX)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KDMAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KDMAT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MONMAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MONMAT)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MAUNIT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAUNIT)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VPME"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VPME)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KBETR_NP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KBETR_NP)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KBETR_AP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KBETR_AP)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KPEIN_NP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KPEIN_NP)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KPEIN_AP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KPEIN_AP)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KMEIN_NP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KMEIN_NP)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KMEIN_AP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KMEIN_AP)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("WAERK_NP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_WAERK_NP)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("WAERK_AP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_WAERK_AP)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMATCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMATCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMATCursor} * instance. Use an instance of {@link ZKDMOBMATCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMAT get(RecordSet rs, boolean selectStar) { ZKDMOBMAT result = new ZKDMOBMAT(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMAT[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMAT[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMAT row = new ZKDMOBMAT(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMAT(row)); return (ZKDMOBMAT[]) list.toArray(new ZKDMOBMAT[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMAT[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMAT[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMAT row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMAT)) return false; ZKDMOBMAT test = (ZKDMOBMAT) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMAT row, String MATNR, boolean likeMATNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MATNR null * @return The result of the database access. */ public static ZKDMOBMAT getByPrimaryKey(DBSession db, String MATNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMAT[] listByPrimaryKey(DBSession db, String MATNR, boolean likeMATNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MATNR, boolean likeMATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MATNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMAT row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMAT[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMAT. */ class ZKDMOBMATCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMAT table, RecordSet rs, int index); public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_MATNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setMAKTX(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_MAKTX, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKDMAT(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KDMAT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setMONMAT(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_MONMAT, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setMAUNIT(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_MAUNIT, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setVPME(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_VPME, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKBETR_NP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KBETR_NP, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKBETR_AP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KBETR_AP, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKPEIN_NP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KPEIN_NP, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKPEIN_AP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KPEIN_AP, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKMEIN_NP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KMEIN_NP, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setKMEIN_AP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_KMEIN_AP, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setWAERK_NP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_WAERK_NP, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setWAERK_AP(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_WAERK_AP, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMOBMAT table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBMAT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMAT.COL_REFRESHED, table._col14); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMAT.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_MATNR, new Integer(ZKDMOBMAT.IDX_MATNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_MAKTX, new Integer(ZKDMOBMAT.IDX_MAKTX)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KDMAT, new Integer(ZKDMOBMAT.IDX_KDMAT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_MONMAT, new Integer(ZKDMOBMAT.IDX_MONMAT)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_MAUNIT, new Integer(ZKDMOBMAT.IDX_MAUNIT)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_VPME, new Integer(ZKDMOBMAT.IDX_VPME)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KBETR_NP, new Integer(ZKDMOBMAT.IDX_KBETR_NP)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KBETR_AP, new Integer(ZKDMOBMAT.IDX_KBETR_AP)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KPEIN_NP, new Integer(ZKDMOBMAT.IDX_KPEIN_NP)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KPEIN_AP, new Integer(ZKDMOBMAT.IDX_KPEIN_AP)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KMEIN_NP, new Integer(ZKDMOBMAT.IDX_KMEIN_NP)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_KMEIN_AP, new Integer(ZKDMOBMAT.IDX_KMEIN_AP)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_WAERK_NP, new Integer(ZKDMOBMAT.IDX_WAERK_NP)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_WAERK_AP, new Integer(ZKDMOBMAT.IDX_WAERK_AP)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMOBMAT.COL_REFRESHED, new Integer(ZKDMOBMAT.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBMAT m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMATCursor(row, rs, false). * * @param zkdmobmat * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMATCursor(ZKDMOBMAT row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMAT WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMATCursor(ZKDMOBMAT row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMAT} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMATPERS.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMATPERSCursor.ColAccessor; /** * No description. */ public class ZKDMOBMATPERS extends TableRow { /** Name of table: ZKDMOBMATPERS */ public final static String TABLE = "ZKDMOBMATPERS"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("MAKTX"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MAKTX)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KDMAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KDMAT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MONMAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MONMAT)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMATPERSCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMATPERSCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMATPERSCursor} * instance. Use an instance of {@link ZKDMOBMATPERSCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMATPERS get(RecordSet rs, boolean selectStar) { ZKDMOBMATPERS result = new ZKDMOBMATPERS(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMATPERS[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMATPERS[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMATPERS row = new ZKDMOBMATPERS(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMATPERS(row)); return (ZKDMOBMATPERS[]) list.toArray(new ZKDMOBMATPERS[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMATPERS[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMATPERS[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMATPERS row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMATPERS)) return false; ZKDMOBMATPERS test = (ZKDMOBMATPERS) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMATPERS row, String MATNR, boolean likeMATNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MATNR null * @return The result of the database access. */ public static ZKDMOBMATPERS getByPrimaryKey(DBSession db, String MATNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMATPERS[] listByPrimaryKey(DBSession db, String MATNR, boolean likeMATNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MATNR null * @param likeMATNR Set to true if the query for MATNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MATNR, boolean likeMATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append(likeMATNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MATNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MATNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MATNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MATNR).append("=").append(sqlHelper.get(MATNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMATPERS row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMATPERS[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MATNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMATPERS. */ class ZKDMOBMATPERSCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMATPERS table, RecordSet rs, int index); public void setUpdate(ZKDMOBMATPERS table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMATPERS table, RecordSet rs, int index) { table.setMATNR(rs.getString(index)); } public void setUpdate(ZKDMOBMATPERS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMATPERS.COL_MATNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMATPERS table, RecordSet rs, int index) { table.setMAKTX(rs.getString(index)); } public void setUpdate(ZKDMOBMATPERS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMATPERS.COL_MAKTX, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMATPERS table, RecordSet rs, int index) { table.setKDMAT(rs.getString(index)); } public void setUpdate(ZKDMOBMATPERS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMATPERS.COL_KDMAT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMATPERS table, RecordSet rs, int index) { table.setMONMAT(rs.getString(index)); } public void setUpdate(ZKDMOBMATPERS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMATPERS.COL_MONMAT, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMATPERS.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMATPERS.COL_MATNR, new Integer(ZKDMOBMATPERS.IDX_MATNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMATPERS.COL_MAKTX, new Integer(ZKDMOBMATPERS.IDX_MAKTX)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMATPERS.COL_KDMAT, new Integer(ZKDMOBMATPERS.IDX_KDMAT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMATPERS.COL_MONMAT, new Integer(ZKDMOBMATPERS.IDX_MONMAT)); } return s_accessor; } /** * */ private final ZKDMOBMATPERS m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMATPERSCursor(row, rs, false). * * @param zkdmobmatpers * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMATPERSCursor(ZKDMOBMATPERS row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMATPERS WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMATPERSCursor(ZKDMOBMATPERS row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMATPERS} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMCCursor.ColAccessor; /** * No description. */ public class ZKDMOBMC extends TableRow { /** Name of table: ZKDMOBMC */ public final static String TABLE = "ZKDMOBMC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 10; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VBELN)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STREET"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STREET)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CITY1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CITY1)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("POST_CODE1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_POST_CODE1)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NAME4"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NAME4)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVC)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVOFF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVOFF)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LKDPERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LKDPERNR)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMCCursor} * instance. Use an instance of {@link ZKDMOBMCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMC get(RecordSet rs, boolean selectStar) { ZKDMOBMC result = new ZKDMOBMC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMC row = new ZKDMOBMC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMC(row)); return (ZKDMOBMC[]) list.toArray(new ZKDMOBMC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMC)) return false; ZKDMOBMC test = (ZKDMOBMC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMC row, String MLDNR, boolean likeMLDNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MLDNR null * @return The result of the database access. */ public static ZKDMOBMC getByPrimaryKey(DBSession db, String MLDNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMC[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMC. */ class ZKDMOBMCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMC table, RecordSet rs, int index); public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setMLDNR(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_MLDNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_AUART, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setVBELN(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_VBELN, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setSTREET(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_STREET, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setCITY1(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_CITY1, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setPOST_CODE1(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_POST_CODE1, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setNAME4(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_NAME4, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setSAVC(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_SAVC, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setSAVOFF(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_SAVOFF, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBMC table, RecordSet rs, int index) { table.setLKDPERNR(rs.getString(index)); } public void setUpdate(ZKDMOBMC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMC.COL_LKDPERNR, table._col9); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMC.COL_MLDNR, new Integer(ZKDMOBMC.IDX_MLDNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMC.COL_AUART, new Integer(ZKDMOBMC.IDX_AUART)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMC.COL_VBELN, new Integer(ZKDMOBMC.IDX_VBELN)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMC.COL_STREET, new Integer(ZKDMOBMC.IDX_STREET)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMC.COL_CITY1, new Integer(ZKDMOBMC.IDX_CITY1)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMC.COL_POST_CODE1, new Integer(ZKDMOBMC.IDX_POST_CODE1)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBMC.COL_NAME4, new Integer(ZKDMOBMC.IDX_NAME4)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBMC.COL_SAVC, new Integer(ZKDMOBMC.IDX_SAVC)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBMC.COL_SAVOFF, new Integer(ZKDMOBMC.IDX_SAVOFF)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBMC.COL_LKDPERNR, new Integer(ZKDMOBMC.IDX_LKDPERNR)); } return s_accessor; } /** * */ private final ZKDMOBMC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMCCursor(row, rs, false). * * @param zkdmobmc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMCCursor(ZKDMOBMC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMCCursor(ZKDMOBMC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMEAS.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMEASCursor.ColAccessor; /** * No description. */ public class ZKDMOBMEAS extends TableRow { /** Name of table: ZKDMOBMEAS */ public final static String TABLE = "ZKDMOBMEAS"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 11; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("VBELN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VBELN)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PNT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PNT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col3); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MEAS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MEAS)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FDYN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FDYN)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TDYN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TDYN)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FEND"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FEND)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DEVTYPE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DEVTYPE)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SNUMBER"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SNUMBER)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CALDAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CALDAT)) sb.append(df.format(_col10)); sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMEASCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMEASCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMEASCursor} * instance. Use an instance of {@link ZKDMOBMEASCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMEAS get(RecordSet rs, boolean selectStar) { ZKDMOBMEAS result = new ZKDMOBMEAS(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMEAS[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMEAS[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMEAS row = new ZKDMOBMEAS(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMEAS(row)); return (ZKDMOBMEAS[]) list.toArray(new ZKDMOBMEAS[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMEAS[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMEAS[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMEAS row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMEAS)) return false; ZKDMOBMEAS test = (ZKDMOBMEAS) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && _col3 != test._col3) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID) { return queryByPrimaryKey(row, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMEAS[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param VBELN null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID, String VBELN) { return queryByPrimaryKey(row, GUID, false, VBELN, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMEAS[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param VBELN null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String VBELN) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append("=").append(sqlHelper.get(VBELN)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param PNT null * @param likePNT Set to true if the query for PNT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, String PNT, boolean likePNT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append(likePNT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PNT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param VBELN null * @param PNT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID, String VBELN, String PNT) { return queryByPrimaryKey(row, GUID, false, VBELN, false, PNT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param PNT null * @param likePNT Set to true if the query for PNT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMEAS[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, String PNT, boolean likePNT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append(likePNT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PNT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param PNT null * @param likePNT Set to true if the query for PNT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, String PNT, boolean likePNT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append(likePNT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PNT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param VBELN null * @param PNT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String VBELN, String PNT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append("=").append(sqlHelper.get(VBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append("=").append(sqlHelper.get(PNT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param PNT null * @param likePNT Set to true if the query for PNT * should be based on LIKE instead of equality. * @param MEAS null * @param likeMEAS Set to true if the query for MEAS * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, String PNT, boolean likePNT, String MEAS, boolean likeMEAS) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append(likePNT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PNT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MEAS).append(likeMEAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MEAS)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param GUID null * @param VBELN null * @param PNT null * @param MEAS null * @return The result of the database access. */ public static ZKDMOBMEAS getByPrimaryKey(DBSession db, String GUID, String VBELN, String PNT, String MEAS) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append("=").append(sqlHelper.get(VBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append("=").append(sqlHelper.get(PNT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MEAS).append("=").append(sqlHelper.get(MEAS)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param PNT null * @param likePNT Set to true if the query for PNT * should be based on LIKE instead of equality. * @param MEAS null * @param likeMEAS Set to true if the query for MEAS * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMEAS[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, String PNT, boolean likePNT, String MEAS, boolean likeMEAS, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append(likePNT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PNT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MEAS).append(likeMEAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MEAS)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param VBELN null * @param likeVBELN Set to true if the query for VBELN * should be based on LIKE instead of equality. * @param PNT null * @param likePNT Set to true if the query for PNT * should be based on LIKE instead of equality. * @param MEAS null * @param likeMEAS Set to true if the query for MEAS * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String VBELN, boolean likeVBELN, String PNT, boolean likePNT, String MEAS, boolean likeMEAS) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append(likeVBELN ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VBELN)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append(likePNT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PNT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MEAS).append(likeMEAS ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MEAS)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param VBELN null * @param PNT null * @param MEAS null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String VBELN, String PNT, String MEAS) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_VBELN).append("=").append(sqlHelper.get(VBELN)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PNT).append("=").append(sqlHelper.get(PNT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MEAS).append("=").append(sqlHelper.get(MEAS)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMEAS row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMEAS[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_VBELN); //$NON-NLS-1$ sb.append(", ").append(COL_PNT); //$NON-NLS-1$ sb.append(", ").append(COL_MEAS); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMEAS. */ class ZKDMOBMEASCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMEAS table, RecordSet rs, int index); public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_GUID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setVBELN(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_VBELN, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setPNT(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_PNT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_PERNR, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setMEAS(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_MEAS, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setFDYN(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_FDYN, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setTDYN(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_TDYN, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setFEND(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_FEND, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setDEVTYPE(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_DEVTYPE, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setSNUMBER(rs.getString(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_SNUMBER, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBMEAS table, RecordSet rs, int index) { table.setCALDAT(rs.getDate(index)); } public void setUpdate(ZKDMOBMEAS table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMEAS.COL_CALDAT, table._col10); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMEAS.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_GUID, new Integer(ZKDMOBMEAS.IDX_GUID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_VBELN, new Integer(ZKDMOBMEAS.IDX_VBELN)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_PNT, new Integer(ZKDMOBMEAS.IDX_PNT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_PERNR, new Integer(ZKDMOBMEAS.IDX_PERNR)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_MEAS, new Integer(ZKDMOBMEAS.IDX_MEAS)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_FDYN, new Integer(ZKDMOBMEAS.IDX_FDYN)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_TDYN, new Integer(ZKDMOBMEAS.IDX_TDYN)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_FEND, new Integer(ZKDMOBMEAS.IDX_FEND)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_DEVTYPE, new Integer(ZKDMOBMEAS.IDX_DEVTYPE)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_SNUMBER, new Integer(ZKDMOBMEAS.IDX_SNUMBER)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBMEAS.COL_CALDAT, new Integer(ZKDMOBMEAS.IDX_CALDAT)); } return s_accessor; } /** * */ private final ZKDMOBMEAS m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMEASCursor(row, rs, false). * * @param zkdmobmeas * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMEASCursor(ZKDMOBMEAS row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMEAS WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMEASCursor(ZKDMOBMEAS row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMEAS} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMONSTK.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMONSTKCursor.ColAccessor; /** * No description. */ public class ZKDMOBMONSTK extends TableRow { /** Name of table: ZKDMOBMONSTK */ public final static String TABLE = "ZKDMOBMONSTK"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("SPRAS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPRAS)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMONSTKCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMONSTKCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMONSTKCursor} * instance. Use an instance of {@link ZKDMOBMONSTKCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMONSTK get(RecordSet rs, boolean selectStar) { ZKDMOBMONSTK result = new ZKDMOBMONSTK(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMONSTK[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMONSTK[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMONSTK row = new ZKDMOBMONSTK(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMONSTK(row)); return (ZKDMOBMONSTK[]) list.toArray(new ZKDMOBMONSTK[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMONSTK[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMONSTK[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMONSTK row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMONSTK)) return false; ZKDMOBMONSTK test = (ZKDMOBMONSTK) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MONSTK null * @param likeMONSTK Set to true if the query for MONSTK * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONSTK row, String MONSTK, boolean likeMONSTK) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append(likeMONSTK ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONSTK)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONSTK); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MONSTK null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONSTK row, String MONSTK) { return queryByPrimaryKey(row, MONSTK, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MONSTK null * @param likeMONSTK Set to true if the query for MONSTK * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMONSTK[] listByPrimaryKey(DBSession db, String MONSTK, boolean likeMONSTK, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append(likeMONSTK ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONSTK)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONSTK); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONSTK null * @param likeMONSTK Set to true if the query for MONSTK * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONSTK, boolean likeMONSTK) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append(likeMONSTK ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONSTK)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONSTK null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONSTK) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append("=").append(sqlHelper.get(MONSTK)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MONSTK null * @param likeMONSTK Set to true if the query for MONSTK * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONSTK row, String MONSTK, boolean likeMONSTK, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append(likeMONSTK ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONSTK)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONSTK); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MONSTK null * @param TXT null * @return The result of the database access. */ public static ZKDMOBMONSTK getByPrimaryKey(DBSession db, String MONSTK, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append("=").append(sqlHelper.get(MONSTK)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MONSTK null * @param likeMONSTK Set to true if the query for MONSTK * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMONSTK[] listByPrimaryKey(DBSession db, String MONSTK, boolean likeMONSTK, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append(likeMONSTK ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONSTK)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONSTK); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONSTK null * @param likeMONSTK Set to true if the query for MONSTK * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONSTK, boolean likeMONSTK, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append(likeMONSTK ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONSTK)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONSTK null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONSTK, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONSTK).append("=").append(sqlHelper.get(MONSTK)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONSTK row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONSTK); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMONSTK[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONSTK); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMONSTK. */ class ZKDMOBMONSTKCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMONSTK table, RecordSet rs, int index); public void setUpdate(ZKDMOBMONSTK table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMONSTK table, RecordSet rs, int index) { table.setMONSTK(rs.getString(index)); } public void setUpdate(ZKDMOBMONSTK table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONSTK.COL_MONSTK, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMONSTK table, RecordSet rs, int index) { table.setSPRAS(rs.getString(index)); } public void setUpdate(ZKDMOBMONSTK table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONSTK.COL_SPRAS, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMONSTK table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBMONSTK table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONSTK.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMONSTK table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBMONSTK table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONSTK.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMONSTK.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMONSTK.COL_MONSTK, new Integer(ZKDMOBMONSTK.IDX_MONSTK)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMONSTK.COL_SPRAS, new Integer(ZKDMOBMONSTK.IDX_SPRAS)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMONSTK.COL_TXT, new Integer(ZKDMOBMONSTK.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMONSTK.COL_REFRESHED, new Integer(ZKDMOBMONSTK.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBMONSTK m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMONSTKCursor(row, rs, false). * * @param zkdmobmonstk * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMONSTKCursor(ZKDMOBMONSTK row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMONSTK WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMONSTKCursor(ZKDMOBMONSTK row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMONSTK} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMONTXT.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMONTXTCursor.ColAccessor; /** * No description. */ public class ZKDMOBMONTXT extends TableRow { /** Name of table: ZKDMOBMONTXT */ public final static String TABLE = "ZKDMOBMONTXT"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("LANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LANGU)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMONTXTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMONTXTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMONTXTCursor} * instance. Use an instance of {@link ZKDMOBMONTXTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMONTXT get(RecordSet rs, boolean selectStar) { ZKDMOBMONTXT result = new ZKDMOBMONTXT(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMONTXT[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMONTXT[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMONTXT row = new ZKDMOBMONTXT(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMONTXT(row)); return (ZKDMOBMONTXT[]) list.toArray(new ZKDMOBMONTXT[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMONTXT[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMONTXT[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMONTXT row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMONTXT)) return false; ZKDMOBMONTXT test = (ZKDMOBMONTXT) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MONTXT null * @param likeMONTXT Set to true if the query for MONTXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONTXT row, String MONTXT, boolean likeMONTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append(likeMONTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONTXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MONTXT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONTXT row, String MONTXT) { return queryByPrimaryKey(row, MONTXT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MONTXT null * @param likeMONTXT Set to true if the query for MONTXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMONTXT[] listByPrimaryKey(DBSession db, String MONTXT, boolean likeMONTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append(likeMONTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONTXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONTXT null * @param likeMONTXT Set to true if the query for MONTXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONTXT, boolean likeMONTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append(likeMONTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONTXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONTXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append("=").append(sqlHelper.get(MONTXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MONTXT null * @param likeMONTXT Set to true if the query for MONTXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONTXT row, String MONTXT, boolean likeMONTXT, String LANGU, boolean likeLANGU) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append(likeMONTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONTXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MONTXT null * @param LANGU null * @return The result of the database access. */ public static ZKDMOBMONTXT getByPrimaryKey(DBSession db, String MONTXT, String LANGU) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append("=").append(sqlHelper.get(MONTXT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MONTXT null * @param likeMONTXT Set to true if the query for MONTXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMONTXT[] listByPrimaryKey(DBSession db, String MONTXT, boolean likeMONTXT, String LANGU, boolean likeLANGU, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append(likeMONTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONTXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONTXT null * @param likeMONTXT Set to true if the query for MONTXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONTXT, boolean likeMONTXT, String LANGU, boolean likeLANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append(likeMONTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MONTXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MONTXT null * @param LANGU null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MONTXT, String LANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MONTXT).append("=").append(sqlHelper.get(MONTXT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMONTXT row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMONTXT[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MONTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMONTXT. */ class ZKDMOBMONTXTCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMONTXT table, RecordSet rs, int index); public void setUpdate(ZKDMOBMONTXT table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMONTXT table, RecordSet rs, int index) { table.setMONTXT(rs.getString(index)); } public void setUpdate(ZKDMOBMONTXT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONTXT.COL_MONTXT, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMONTXT table, RecordSet rs, int index) { table.setLANGU(rs.getString(index)); } public void setUpdate(ZKDMOBMONTXT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONTXT.COL_LANGU, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMONTXT table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBMONTXT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONTXT.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMONTXT table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBMONTXT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMONTXT.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMONTXT.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMONTXT.COL_MONTXT, new Integer(ZKDMOBMONTXT.IDX_MONTXT)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMONTXT.COL_LANGU, new Integer(ZKDMOBMONTXT.IDX_LANGU)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMONTXT.COL_TXT, new Integer(ZKDMOBMONTXT.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMONTXT.COL_REFRESHED, new Integer(ZKDMOBMONTXT.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBMONTXT m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMONTXTCursor(row, rs, false). * * @param zkdmobmontxt * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMONTXTCursor(ZKDMOBMONTXT row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMONTXT WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMONTXTCursor(ZKDMOBMONTXT row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMONTXT} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMSG.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMSGCursor.ColAccessor; /** * No description. */ public class ZKDMOBMSG extends TableRow { /** Name of table: ZKDMOBMSG */ public final static String TABLE = "ZKDMOBMSG"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 6; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("MSGID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MSGID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MSGC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MSGC)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT1)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT2)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT3)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMSGCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMSGCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMSGCursor} * instance. Use an instance of {@link ZKDMOBMSGCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMSG get(RecordSet rs, boolean selectStar) { ZKDMOBMSG result = new ZKDMOBMSG(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMSG[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMSG[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMSG row = new ZKDMOBMSG(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMSG(row)); return (ZKDMOBMSG[]) list.toArray(new ZKDMOBMSG[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMSG[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMSG[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMSG row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMSG)) return false; ZKDMOBMSG test = (ZKDMOBMSG) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMSG row, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_MSGID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMSG row, String GUID) { return queryByPrimaryKey(row, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMSG[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_MSGID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MSGID null * @param likeMSGID Set to true if the query for MSGID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMSG row, String GUID, boolean likeGUID, String MSGID, boolean likeMSGID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MSGID).append(likeMSGID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MSGID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_MSGID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param GUID null * @param MSGID null * @return The result of the database access. */ public static ZKDMOBMSG getByPrimaryKey(DBSession db, String GUID, String MSGID) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MSGID).append("=").append(sqlHelper.get(MSGID)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MSGID null * @param likeMSGID Set to true if the query for MSGID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMSG[] listByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String MSGID, boolean likeMSGID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MSGID).append(likeMSGID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MSGID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_MSGID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MSGID null * @param likeMSGID Set to true if the query for MSGID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, boolean likeGUID, String MSGID, boolean likeMSGID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MSGID).append(likeMSGID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MSGID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param GUID null * @param MSGID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String GUID, String MSGID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MSGID).append("=").append(sqlHelper.get(MSGID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMSG row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_MSGID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMSG[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_GUID); sb.append(", ").append(COL_MSGID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMSG. */ class ZKDMOBMSGCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMSG table, RecordSet rs, int index); public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMSG table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSG.COL_GUID, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMSG table, RecordSet rs, int index) { table.setMSGID(rs.getString(index)); } public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSG.COL_MSGID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMSG table, RecordSet rs, int index) { table.setMSGC(rs.getString(index)); } public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSG.COL_MSGC, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMSG table, RecordSet rs, int index) { table.setTXT1(rs.getString(index)); } public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSG.COL_TXT1, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMSG table, RecordSet rs, int index) { table.setTXT2(rs.getString(index)); } public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSG.COL_TXT2, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMSG table, RecordSet rs, int index) { table.setTXT3(rs.getString(index)); } public void setUpdate(ZKDMOBMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSG.COL_TXT3, table._col5); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMSG.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMSG.COL_GUID, new Integer(ZKDMOBMSG.IDX_GUID)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMSG.COL_MSGID, new Integer(ZKDMOBMSG.IDX_MSGID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMSG.COL_MSGC, new Integer(ZKDMOBMSG.IDX_MSGC)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMSG.COL_TXT1, new Integer(ZKDMOBMSG.IDX_TXT1)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMSG.COL_TXT2, new Integer(ZKDMOBMSG.IDX_TXT2)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMSG.COL_TXT3, new Integer(ZKDMOBMSG.IDX_TXT3)); } return s_accessor; } /** * */ private final ZKDMOBMSG m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMSGCursor(row, rs, false). * * @param zkdmobmsg * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMSGCursor(ZKDMOBMSG row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMSG WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMSGCursor(ZKDMOBMSG row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMSG} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMSGC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMSGCCursor.ColAccessor; /** * No description. */ public class ZKDMOBMSGC extends TableRow { /** Name of table: ZKDMOBMSGC */ public final static String TABLE = "ZKDMOBMSGC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 7; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iSet to 0 to let the database system create a * new autoincrement value when the row gets inserted. */ public ZKDMOBMSGC(DBSession db, long IDX) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); setIDX(IDX); validate(); } /** * Creates a new complete row using the given column values. * * @param db * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param MSGC No description. * @param TXT No description. * @param ABTL No description. * @param KND No description. * @param KDZ No description. * @param REFRESHED No description. */ public ZKDMOBMSGC(DBSession db, long IDX, String MSGC, String TXT, String ABTL, String KND, String KDZ, String REFRESHED) { super(db, null); _col0 = IDX; _col1 = MSGC; _col2 = TXT; _col3 = ABTL; _col4 = KND; _col5 = KDZ; _col6 = REFRESHED; validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public ZKDMOBMSGC(ZKDMOBMSGC source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_MSGC)) _col1 = source._col1; if (isColumnSet(IDX_TXT)) _col2 = source._col2; if (isColumnSet(IDX_ABTL)) _col3 = source._col3; if (isColumnSet(IDX_KND)) _col4 = source._col4; if (isColumnSet(IDX_KDZ)) _col5 = source._col5; if (isColumnSet(IDX_REFRESHED)) _col6 = source._col6; } else { // copy all columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_MSGC)) _col1 = source._col1; if (isColumnSet(IDX_TXT)) _col2 = source._col2; if (isColumnSet(IDX_ABTL)) _col3 = source._col3; if (isColumnSet(IDX_KND)) _col4 = source._col4; if (isColumnSet(IDX_KDZ)) _col5 = source._col5; if (isColumnSet(IDX_REFRESHED)) _col6 = source._col6; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param source */ public ZKDMOBMSGC(long IDX, ZKDMOBMSGC source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = IDX; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_MSGC)) _col1 = source._col1; if (isColumnSet(IDX_TXT)) _col2 = source._col2; if (isColumnSet(IDX_ABTL)) _col3 = source._col3; if (isColumnSet(IDX_KND)) _col4 = source._col4; if (isColumnSet(IDX_KDZ)) _col5 = source._col5; if (isColumnSet(IDX_REFRESHED)) _col6 = source._col6; } else { // copy all columns excluding the primary key _col1 = source._col1; _col2 = source._col2; _col3 = source._col3; _col4 = source._col4; _col5 = source._col5; _col6 = source._col6; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public ZKDMOBMSGC(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_IDX)) m_usedColumns.clear(IDX_IDX); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_MSGC)) _col1 = DEF_MSGC; if (m_usedColumns.get(IDX_TXT)) _col2 = DEF_TXT; if (m_usedColumns.get(IDX_ABTL)) _col3 = DEF_ABTL; if (m_usedColumns.get(IDX_KND)) _col4 = DEF_KND; if (m_usedColumns.get(IDX_KDZ)) _col5 = DEF_KDZ; if (m_usedColumns.get(IDX_REFRESHED)) _col6 = DEF_REFRESHED; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_IDX) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append('=').append(sqlHelper.get(_col0)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); if (_col0 == 0) { sqlHelper.inNULL(); } sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); sqlHelper.in(_col5); sqlHelper.in(_col6); getDBSession().executeSql(sqlHelper.toString()); if (_col0 == 0) { DBSession db = getDBSession(); RecordSet rs = db.getRecordSet(); try { rs.setQuery("SELECT last_insert_rowid()"); //$NON-NLS-1$ rs.moveNext(); setIDX(rs.getLong(0)); } finally { rs.dispose(); } } } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = ZKDMOBMSGCCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_MSGC, _col1); sqlHelper.in(COL_TXT, _col2); sqlHelper.in(COL_ABTL, _col3); sqlHelper.in(COL_KND, _col4); sqlHelper.in(COL_KDZ, _col5); sqlHelper.in(COL_REFRESHED, _col6); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return null */ public long getIDX() { checkSparseColumn(IDX_IDX); return _col0; } /** * @param IDX null */ protected void setIDX(long IDX) { _col0 = IDX; markUsed(IDX_IDX); } /** * @return null */ public String getMSGC() { checkSparseColumn(IDX_MSGC); return _col1; } /** * @param MSGC null */ public void setMSGC(String MSGC) { checkNull(MSGC); _col1 = MSGC; markUsed(IDX_MSGC); } /** * @return null */ public String getTXT() { checkSparseColumn(IDX_TXT); return _col2; } /** * @param TXT null */ public void setTXT(String TXT) { checkNull(TXT); _col2 = TXT; markUsed(IDX_TXT); } /** * @return null */ public String getABTL() { checkSparseColumn(IDX_ABTL); return _col3; } /** * @param ABTL null */ public void setABTL(String ABTL) { checkNull(ABTL); _col3 = ABTL; markUsed(IDX_ABTL); } /** * @return null */ public String getKND() { checkSparseColumn(IDX_KND); return _col4; } /** * @param KND null */ public void setKND(String KND) { checkNull(KND); _col4 = KND; markUsed(IDX_KND); } /** * @return null */ public String getKDZ() { checkSparseColumn(IDX_KDZ); return _col5; } /** * @param KDZ null */ public void setKDZ(String KDZ) { checkNull(KDZ); _col5 = KDZ; markUsed(IDX_KDZ); } /** * @return null */ public String getREFRESHED() { checkSparseColumn(IDX_REFRESHED); return _col6; } /** * @param REFRESHED null */ public void setREFRESHED(String REFRESHED) { checkNull(REFRESHED); _col6 = REFRESHED; markUsed(IDX_REFRESHED); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col0); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MSGC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MSGC)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ABTL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABTL)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KND"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KND)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KDZ"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KDZ)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMSGCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMSGCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMSGCCursor} * instance. Use an instance of {@link ZKDMOBMSGCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMSGC get(RecordSet rs, boolean selectStar) { ZKDMOBMSGC result = new ZKDMOBMSGC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMSGC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMSGC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMSGC row = new ZKDMOBMSGC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMSGC(row)); return (ZKDMOBMSGC[]) list.toArray(new ZKDMOBMSGC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMSGC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMSGC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMSGC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMSGC)) return false; ZKDMOBMSGC test = (ZKDMOBMSGC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @return The result of the database access. */ public static ZKDMOBMSGC getByPrimaryKey(DBSession db, long IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, long IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMSGC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMSGC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMSGC. */ class ZKDMOBMSGCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMSGC table, RecordSet rs, int index); public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setMSGC(rs.getString(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_MSGC, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setABTL(rs.getString(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_ABTL, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setKND(rs.getString(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_KND, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setKDZ(rs.getString(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_KDZ, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBMSGC table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBMSGC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMSGC.COL_REFRESHED, table._col6); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMSGC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_IDX, new Integer(ZKDMOBMSGC.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_MSGC, new Integer(ZKDMOBMSGC.IDX_MSGC)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_TXT, new Integer(ZKDMOBMSGC.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_ABTL, new Integer(ZKDMOBMSGC.IDX_ABTL)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_KND, new Integer(ZKDMOBMSGC.IDX_KND)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_KDZ, new Integer(ZKDMOBMSGC.IDX_KDZ)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBMSGC.COL_REFRESHED, new Integer(ZKDMOBMSGC.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBMSGC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMSGCCursor(row, rs, false). * * @param zkdmobmsgc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMSGCCursor(ZKDMOBMSGC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMSGC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMSGCCursor(ZKDMOBMSGC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMSGC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMV.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMVCursor.ColAccessor; /** * No description. */ public class ZKDMOBMV extends TableRow { /** Name of table: ZKDMOBMV */ public final static String TABLE = "ZKDMOBMV"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 10; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("GUID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GUID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MDLNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MDLNR)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ATTCLAS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ATTCLAS)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DESC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DESC)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNPIC_AT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNPIC_AT)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMTYPE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMTYPE)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FORMDESC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FORMDESC)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SENTDATE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SENTDATE)) sb.append(df.format(_col9)); sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMVCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMVCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMVCursor} * instance. Use an instance of {@link ZKDMOBMVCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMV get(RecordSet rs, boolean selectStar) { ZKDMOBMV result = new ZKDMOBMV(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMV[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMV[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMV row = new ZKDMOBMV(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMV(row)); return (ZKDMOBMV[]) list.toArray(new ZKDMOBMV[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMV[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMV[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMV row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMV)) return false; ZKDMOBMV test = (ZKDMOBMV) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMV row, String IDX, boolean likeIDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @return The result of the database access. */ public static ZKDMOBMV getByPrimaryKey(DBSession db, String IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMV[] listByPrimaryKey(DBSession db, String IDX, boolean likeIDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param likeIDX Set to true if the query for IDX * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String IDX, boolean likeIDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append(likeIDX ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMV row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMV[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMV. */ class ZKDMOBMVCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMV table, RecordSet rs, int index); public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setIDX(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_GUID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setMDLNR(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_MDLNR, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_AUART, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setATTCLAS(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_ATTCLAS, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setDESC(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_DESC, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setSIGNPIC_AT(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_SIGNPIC_AT, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setFORMTYPE(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_FORMTYPE, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setFORMDESC(rs.getString(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_FORMDESC, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBMV table, RecordSet rs, int index) { table.setSENTDATE(rs.getDate(index)); } public void setUpdate(ZKDMOBMV table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMV.COL_SENTDATE, table._col9); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMV.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMV.COL_IDX, new Integer(ZKDMOBMV.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMV.COL_GUID, new Integer(ZKDMOBMV.IDX_GUID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMV.COL_MDLNR, new Integer(ZKDMOBMV.IDX_MDLNR)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMV.COL_AUART, new Integer(ZKDMOBMV.IDX_AUART)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBMV.COL_ATTCLAS, new Integer(ZKDMOBMV.IDX_ATTCLAS)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBMV.COL_DESC, new Integer(ZKDMOBMV.IDX_DESC)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBMV.COL_SIGNPIC_AT, new Integer(ZKDMOBMV.IDX_SIGNPIC_AT)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBMV.COL_FORMTYPE, new Integer(ZKDMOBMV.IDX_FORMTYPE)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBMV.COL_FORMDESC, new Integer(ZKDMOBMV.IDX_FORMDESC)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBMV.COL_SENTDATE, new Integer(ZKDMOBMV.IDX_SENTDATE)); } return s_accessor; } /** * */ private final ZKDMOBMV m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMVCursor(row, rs, false). * * @param zkdmobmv * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMVCursor(ZKDMOBMV row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMV WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMVCursor(ZKDMOBMV row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMV} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBMVCASE.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMVCASECursor.ColAccessor; /** * No description. */ public class ZKDMOBMVCASE extends TableRow { /** Name of table: ZKDMOBMVCASE */ public final static String TABLE = "ZKDMOBMVCASE"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("LANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LANGU)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBMVCASECursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBMVCASECursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBMVCASECursor} * instance. Use an instance of {@link ZKDMOBMVCASECursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBMVCASE get(RecordSet rs, boolean selectStar) { ZKDMOBMVCASE result = new ZKDMOBMVCASE(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBMVCASE[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBMVCASE[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBMVCASE row = new ZKDMOBMVCASE(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBMVCASE(row)); return (ZKDMOBMVCASE[]) list.toArray(new ZKDMOBMVCASE[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBMVCASE[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBMVCASE[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBMVCASE row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBMVCASE)) return false; ZKDMOBMVCASE test = (ZKDMOBMVCASE) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MVCASETXT null * @param likeMVCASETXT Set to true if the query for MVCASETXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMVCASE row, String MVCASETXT, boolean likeMVCASETXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append(likeMVCASETXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MVCASETXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MVCASETXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MVCASETXT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMVCASE row, String MVCASETXT) { return queryByPrimaryKey(row, MVCASETXT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MVCASETXT null * @param likeMVCASETXT Set to true if the query for MVCASETXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMVCASE[] listByPrimaryKey(DBSession db, String MVCASETXT, boolean likeMVCASETXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append(likeMVCASETXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MVCASETXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MVCASETXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MVCASETXT null * @param likeMVCASETXT Set to true if the query for MVCASETXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MVCASETXT, boolean likeMVCASETXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append(likeMVCASETXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MVCASETXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MVCASETXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MVCASETXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append("=").append(sqlHelper.get(MVCASETXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MVCASETXT null * @param likeMVCASETXT Set to true if the query for MVCASETXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMVCASE row, String MVCASETXT, boolean likeMVCASETXT, String LANGU, boolean likeLANGU) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append(likeMVCASETXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MVCASETXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MVCASETXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MVCASETXT null * @param LANGU null * @return The result of the database access. */ public static ZKDMOBMVCASE getByPrimaryKey(DBSession db, String MVCASETXT, String LANGU) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append("=").append(sqlHelper.get(MVCASETXT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MVCASETXT null * @param likeMVCASETXT Set to true if the query for MVCASETXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMVCASE[] listByPrimaryKey(DBSession db, String MVCASETXT, boolean likeMVCASETXT, String LANGU, boolean likeLANGU, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append(likeMVCASETXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MVCASETXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MVCASETXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MVCASETXT null * @param likeMVCASETXT Set to true if the query for MVCASETXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MVCASETXT, boolean likeMVCASETXT, String LANGU, boolean likeLANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append(likeMVCASETXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MVCASETXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MVCASETXT null * @param LANGU null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MVCASETXT, String LANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MVCASETXT).append("=").append(sqlHelper.get(MVCASETXT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBMVCASE row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MVCASETXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBMVCASE[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MVCASETXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBMVCASE. */ class ZKDMOBMVCASECursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBMVCASE table, RecordSet rs, int index); public void setUpdate(ZKDMOBMVCASE table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBMVCASE table, RecordSet rs, int index) { table.setMVCASETXT(rs.getString(index)); } public void setUpdate(ZKDMOBMVCASE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMVCASE.COL_MVCASETXT, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBMVCASE table, RecordSet rs, int index) { table.setLANGU(rs.getString(index)); } public void setUpdate(ZKDMOBMVCASE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMVCASE.COL_LANGU, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBMVCASE table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBMVCASE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMVCASE.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBMVCASE table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBMVCASE table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBMVCASE.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBMVCASE.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBMVCASE.COL_MVCASETXT, new Integer(ZKDMOBMVCASE.IDX_MVCASETXT)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBMVCASE.COL_LANGU, new Integer(ZKDMOBMVCASE.IDX_LANGU)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBMVCASE.COL_TXT, new Integer(ZKDMOBMVCASE.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBMVCASE.COL_REFRESHED, new Integer(ZKDMOBMVCASE.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBMVCASE m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBMVCASECursor(row, rs, false). * * @param zkdmobmvcase * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMVCASECursor(ZKDMOBMVCASE row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBMVCASE WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBMVCASECursor(ZKDMOBMVCASE row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBMVCASE} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBNOFORM.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBNOFORMCursor.ColAccessor; /** * No description. */ public class ZKDMOBNOFORM extends TableRow { /** Name of table: ZKDMOBNOFORM */ public final static String TABLE = "ZKDMOBNOFORM"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBNOFORMCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBNOFORMCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBNOFORMCursor} * instance. Use an instance of {@link ZKDMOBNOFORMCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBNOFORM get(RecordSet rs, boolean selectStar) { ZKDMOBNOFORM result = new ZKDMOBNOFORM(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBNOFORM[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBNOFORM[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBNOFORM row = new ZKDMOBNOFORM(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBNOFORM(row)); return (ZKDMOBNOFORM[]) list.toArray(new ZKDMOBNOFORM[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBNOFORM[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBNOFORM[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBNOFORM row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBNOFORM)) return false; ZKDMOBNOFORM test = (ZKDMOBNOFORM) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param NO_FORM null * @param likeNO_FORM Set to true if the query for NO_FORM * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBNOFORM row, String NO_FORM, boolean likeNO_FORM) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_NO_FORM).append(likeNO_FORM ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(NO_FORM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_NO_FORM); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param NO_FORM null * @return The result of the database access. */ public static ZKDMOBNOFORM getByPrimaryKey(DBSession db, String NO_FORM) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_NO_FORM).append("=").append(sqlHelper.get(NO_FORM)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param NO_FORM null * @param likeNO_FORM Set to true if the query for NO_FORM * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBNOFORM[] listByPrimaryKey(DBSession db, String NO_FORM, boolean likeNO_FORM, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_NO_FORM).append(likeNO_FORM ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(NO_FORM)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_NO_FORM); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param NO_FORM null * @param likeNO_FORM Set to true if the query for NO_FORM * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String NO_FORM, boolean likeNO_FORM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_NO_FORM).append(likeNO_FORM ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(NO_FORM)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param NO_FORM null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String NO_FORM) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_NO_FORM).append("=").append(sqlHelper.get(NO_FORM)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBNOFORM row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_NO_FORM); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBNOFORM[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_NO_FORM); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBNOFORM. */ class ZKDMOBNOFORMCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBNOFORM table, RecordSet rs, int index); public void setUpdate(ZKDMOBNOFORM table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBNOFORM table, RecordSet rs, int index) { table.setNO_FORM(rs.getString(index)); } public void setUpdate(ZKDMOBNOFORM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBNOFORM.COL_NO_FORM, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBNOFORM table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBNOFORM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBNOFORM.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBNOFORM table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBNOFORM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBNOFORM.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBNOFORM.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBNOFORM.COL_NO_FORM, new Integer(ZKDMOBNOFORM.IDX_NO_FORM)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBNOFORM.COL_TXT, new Integer(ZKDMOBNOFORM.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBNOFORM.COL_REFRESHED, new Integer(ZKDMOBNOFORM.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBNOFORM m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBNOFORMCursor(row, rs, false). * * @param zkdmobnoform * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBNOFORMCursor(ZKDMOBNOFORM row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBNOFORM WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBNOFORMCursor(ZKDMOBNOFORM row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBNOFORM} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBREP.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBREPCursor.ColAccessor; /** * No description. */ public class ZKDMOBREP extends TableRow { /** Name of table: ZKDMOBREP */ public final static String TABLE = "ZKDMOBREP"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 62; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("GUID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GUID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ERDAT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERDAT)) sb.append(df.format(_col2)); sb.append(", ").append("MLDNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MLDNR)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ANLNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ANLNR)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col6); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TEILREP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TEILREP)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ENDREP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ENDREP)) sb.append('\'').append(_col8).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FOLGEREP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FOLGEREP)) sb.append('\'').append(_col9).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STORC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STORC)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VERRC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VERRC)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SECRAP"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SECRAP)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("RAPSEND"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_RAPSEND)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("RAPSENDCOM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_RAPSENDCOM)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("CHCKLISTE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_CHCKLISTE)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMC1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMC1)) sb.append('\'').append(_col16).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMH1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMH1)) sb.append('\'').append(_col17).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FM1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FM1)) sb.append('\'').append(_col18).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMC2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMC2)) sb.append('\'').append(_col19).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMH2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMH2)) sb.append('\'').append(_col20).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FM2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FM2)) sb.append('\'').append(_col21).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMC3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMC3)) sb.append('\'').append(_col22).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMH3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMH3)) sb.append('\'').append(_col23).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FM3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FM3)) sb.append('\'').append(_col24).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FMB"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FMB)) sb.append('\'').append(_col25).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("KM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_KM)) sb.append('\'').append(_col26).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SPESEN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SPESEN)) sb.append('\'').append(_col27).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD1)) sb.append('\'').append(_col28).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD2)) sb.append('\'').append(_col29).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD3)) sb.append('\'').append(_col30).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD4"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD4)) sb.append('\'').append(_col31).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD5"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD5)) sb.append('\'').append(_col32).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVLFD6"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVLFD6)) sb.append('\'').append(_col33).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SAVERL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SAVERL)) sb.append('\'').append(_col34).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BSTKD"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BSTKD)) sb.append('\'').append(_col35).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REPORTSTATUS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REPORTSTATUS)) sb.append('\'').append(_col36).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNGUID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNGUID)) sb.append('\'').append(_col37).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNFLG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNFLG)) sb.append('\'').append(_col38).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNINFO"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNINFO)) sb.append('\'').append(_col39).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNPIC"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNPIC)) sb.append('\'').append(_col40).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ARBA"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ARBA)) sb.append('\'').append(_col41).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNBUNDLE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNBUNDLE)) sb.append('\'').append(_col42).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NOMATUSED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NOMATUSED)) sb.append('\'').append(_col43).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ZYKINT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ZYKINT)) sb.append('\'').append(_col44).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NO_FORM1"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NO_FORM1)) sb.append('\'').append(_col45).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NO_FORM2"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NO_FORM2)) sb.append('\'').append(_col46).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NO_FORM3"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NO_FORM3)) sb.append('\'').append(_col47).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BGRSAV"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BGRSAV)) sb.append('\'').append(_col48).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PEND"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PEND)) sb.append('\'').append(_col49).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REGIE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REGIE)) sb.append('\'').append(_col50).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSSTATE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSSTATE)) sb.append('\'').append(_col51).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSSIA"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSSIA)) sb.append('\'').append(_col52).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSREADY"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSREADY)) sb.append('\'').append(_col53).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSINSTR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSINSTR)) sb.append('\'').append(_col54).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSVKF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSVKF)) sb.append('\'').append(_col55).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("IBSTEST"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IBSTEST)) sb.append('\'').append(_col56).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("SIGNNAME"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_SIGNNAME)) sb.append('\'').append(_col57).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("MONSTK"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_MONSTK)) sb.append('\'').append(_col58).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EDATE"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EDATE)) sb.append(df.format(_col59)); sb.append(", ").append("BTRBZUST"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BTRBZUST)) sb.append('\'').append(_col60).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FLGVRG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FLGVRG)) sb.append('\'').append(_col61).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBREPCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBREPCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBREPCursor} * instance. Use an instance of {@link ZKDMOBREPCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBREP get(RecordSet rs, boolean selectStar) { ZKDMOBREP result = new ZKDMOBREP(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBREP[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBREP[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBREP row = new ZKDMOBREP(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBREP(row)); return (ZKDMOBREP[]) list.toArray(new ZKDMOBREP[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBREP[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBREP[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBREP row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBREP)) return false; ZKDMOBREP test = (ZKDMOBREP) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && _col6 != test._col6) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; if ((m_usedColumns == null || !m_usedColumns.get(16)) && !_col16.equals(test._col16)) return false; if ((m_usedColumns == null || !m_usedColumns.get(17)) && !_col17.equals(test._col17)) return false; if ((m_usedColumns == null || !m_usedColumns.get(18)) && !_col18.equals(test._col18)) return false; if ((m_usedColumns == null || !m_usedColumns.get(19)) && !_col19.equals(test._col19)) return false; if ((m_usedColumns == null || !m_usedColumns.get(20)) && !_col20.equals(test._col20)) return false; if ((m_usedColumns == null || !m_usedColumns.get(21)) && !_col21.equals(test._col21)) return false; if ((m_usedColumns == null || !m_usedColumns.get(22)) && !_col22.equals(test._col22)) return false; if ((m_usedColumns == null || !m_usedColumns.get(23)) && !_col23.equals(test._col23)) return false; if ((m_usedColumns == null || !m_usedColumns.get(24)) && !_col24.equals(test._col24)) return false; if ((m_usedColumns == null || !m_usedColumns.get(25)) && !_col25.equals(test._col25)) return false; if ((m_usedColumns == null || !m_usedColumns.get(26)) && !_col26.equals(test._col26)) return false; if ((m_usedColumns == null || !m_usedColumns.get(27)) && !_col27.equals(test._col27)) return false; if ((m_usedColumns == null || !m_usedColumns.get(28)) && !_col28.equals(test._col28)) return false; if ((m_usedColumns == null || !m_usedColumns.get(29)) && !_col29.equals(test._col29)) return false; if ((m_usedColumns == null || !m_usedColumns.get(30)) && !_col30.equals(test._col30)) return false; if ((m_usedColumns == null || !m_usedColumns.get(31)) && !_col31.equals(test._col31)) return false; if ((m_usedColumns == null || !m_usedColumns.get(32)) && !_col32.equals(test._col32)) return false; if ((m_usedColumns == null || !m_usedColumns.get(33)) && !_col33.equals(test._col33)) return false; if ((m_usedColumns == null || !m_usedColumns.get(34)) && !_col34.equals(test._col34)) return false; if ((m_usedColumns == null || !m_usedColumns.get(35)) && !_col35.equals(test._col35)) return false; if ((m_usedColumns == null || !m_usedColumns.get(36)) && !_col36.equals(test._col36)) return false; if ((m_usedColumns == null || !m_usedColumns.get(37)) && !_col37.equals(test._col37)) return false; if ((m_usedColumns == null || !m_usedColumns.get(38)) && !_col38.equals(test._col38)) return false; if ((m_usedColumns == null || !m_usedColumns.get(39)) && !_col39.equals(test._col39)) return false; if ((m_usedColumns == null || !m_usedColumns.get(40)) && !_col40.equals(test._col40)) return false; if ((m_usedColumns == null || !m_usedColumns.get(41)) && !_col41.equals(test._col41)) return false; if ((m_usedColumns == null || !m_usedColumns.get(42)) && !_col42.equals(test._col42)) return false; if ((m_usedColumns == null || !m_usedColumns.get(43)) && !_col43.equals(test._col43)) return false; if ((m_usedColumns == null || !m_usedColumns.get(44)) && !_col44.equals(test._col44)) return false; if ((m_usedColumns == null || !m_usedColumns.get(45)) && !_col45.equals(test._col45)) return false; if ((m_usedColumns == null || !m_usedColumns.get(46)) && !_col46.equals(test._col46)) return false; if ((m_usedColumns == null || !m_usedColumns.get(47)) && !_col47.equals(test._col47)) return false; if ((m_usedColumns == null || !m_usedColumns.get(48)) && !_col48.equals(test._col48)) return false; if ((m_usedColumns == null || !m_usedColumns.get(49)) && !_col49.equals(test._col49)) return false; if ((m_usedColumns == null || !m_usedColumns.get(50)) && !_col50.equals(test._col50)) return false; if ((m_usedColumns == null || !m_usedColumns.get(51)) && !_col51.equals(test._col51)) return false; if ((m_usedColumns == null || !m_usedColumns.get(52)) && !_col52.equals(test._col52)) return false; if ((m_usedColumns == null || !m_usedColumns.get(53)) && !_col53.equals(test._col53)) return false; if ((m_usedColumns == null || !m_usedColumns.get(54)) && !_col54.equals(test._col54)) return false; if ((m_usedColumns == null || !m_usedColumns.get(55)) && !_col55.equals(test._col55)) return false; if ((m_usedColumns == null || !m_usedColumns.get(56)) && !_col56.equals(test._col56)) return false; if ((m_usedColumns == null || !m_usedColumns.get(57)) && !_col57.equals(test._col57)) return false; if ((m_usedColumns == null || !m_usedColumns.get(58)) && !_col58.equals(test._col58)) return false; if ((m_usedColumns == null || !m_usedColumns.get(59)) && !_col59.equals(test._col59)) return false; if ((m_usedColumns == null || !m_usedColumns.get(60)) && !_col60.equals(test._col60)) return false; if ((m_usedColumns == null || !m_usedColumns.get(61)) && !_col61.equals(test._col61)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row, int IDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBREP[] listByPrimaryKey(DBSession db, int IDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row, int IDX, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param GUID null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row, int IDX, String GUID) { return queryByPrimaryKey(row, IDX, GUID, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBREP[] listByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row, int IDX, String GUID, boolean likeGUID, String MLDNR, boolean likeMLDNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param GUID null * @param MLDNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row, int IDX, String GUID, String MLDNR) { return queryByPrimaryKey(row, IDX, GUID, false, MLDNR, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBREP[] listByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID, String MLDNR, boolean likeMLDNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID, String MLDNR, boolean likeMLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @param MLDNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID, String MLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row, int IDX, String GUID, boolean likeGUID, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @param GUID null * @param MLDNR null * @param AUART null * @return The result of the database access. */ public static ZKDMOBREP getByPrimaryKey(DBSession db, int IDX, String GUID, String MLDNR, String AUART) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBREP[] listByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @param MLDNR null * @param AUART null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID, String MLDNR, String AUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBREP row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBREP[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ sb.append(", ").append(COL_MLDNR); //$NON-NLS-1$ sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBREP. */ class ZKDMOBREPCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBREP table, RecordSet rs, int index); public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_GUID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setERDAT(rs.getDate(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_ERDAT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setMLDNR(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_MLDNR, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_AUART, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setANLNR(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_ANLNR, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_PERNR, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setTEILREP(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_TEILREP, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setENDREP(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_ENDREP, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFOLGEREP(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FOLGEREP, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSTORC(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_STORC, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setVERRC(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_VERRC, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSECRAP(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SECRAP, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setRAPSEND(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_RAPSEND, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setRAPSENDCOM(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_RAPSENDCOM, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setCHCKLISTE(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_CHCKLISTE, table._col15); } } private static class Col16Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMC1(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMC1, table._col16); } } private static class Col17Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMH1(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMH1, table._col17); } } private static class Col18Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFM1(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FM1, table._col18); } } private static class Col19Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMC2(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMC2, table._col19); } } private static class Col20Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMH2(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMH2, table._col20); } } private static class Col21Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFM2(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FM2, table._col21); } } private static class Col22Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMC3(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMC3, table._col22); } } private static class Col23Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMH3(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMH3, table._col23); } } private static class Col24Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFM3(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FM3, table._col24); } } private static class Col25Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFMB(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FMB, table._col25); } } private static class Col26Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setKM(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_KM, table._col26); } } private static class Col27Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSPESEN(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SPESEN, table._col27); } } private static class Col28Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVLFD1(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVLFD1, table._col28); } } private static class Col29Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVLFD2(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVLFD2, table._col29); } } private static class Col30Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVLFD3(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVLFD3, table._col30); } } private static class Col31Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVLFD4(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVLFD4, table._col31); } } private static class Col32Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVLFD5(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVLFD5, table._col32); } } private static class Col33Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVLFD6(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVLFD6, table._col33); } } private static class Col34Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSAVERL(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SAVERL, table._col34); } } private static class Col35Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setBSTKD(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_BSTKD, table._col35); } } private static class Col36Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setREPORTSTATUS(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_REPORTSTATUS, table._col36); } } private static class Col37Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSIGNGUID(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SIGNGUID, table._col37); } } private static class Col38Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSIGNFLG(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SIGNFLG, table._col38); } } private static class Col39Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSIGNINFO(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SIGNINFO, table._col39); } } private static class Col40Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSIGNPIC(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SIGNPIC, table._col40); } } private static class Col41Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setARBA(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_ARBA, table._col41); } } private static class Col42Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSIGNBUNDLE(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SIGNBUNDLE, table._col42); } } private static class Col43Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setNOMATUSED(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_NOMATUSED, table._col43); } } private static class Col44Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setZYKINT(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_ZYKINT, table._col44); } } private static class Col45Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setNO_FORM1(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_NO_FORM1, table._col45); } } private static class Col46Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setNO_FORM2(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_NO_FORM2, table._col46); } } private static class Col47Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setNO_FORM3(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_NO_FORM3, table._col47); } } private static class Col48Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setBGRSAV(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_BGRSAV, table._col48); } } private static class Col49Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setPEND(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_PEND, table._col49); } } private static class Col50Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setREGIE(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_REGIE, table._col50); } } private static class Col51Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIBSSTATE(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IBSSTATE, table._col51); } } private static class Col52Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIBSSIA(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IBSSIA, table._col52); } } private static class Col53Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIBSREADY(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IBSREADY, table._col53); } } private static class Col54Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIBSINSTR(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IBSINSTR, table._col54); } } private static class Col55Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIBSVKF(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IBSVKF, table._col55); } } private static class Col56Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setIBSTEST(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_IBSTEST, table._col56); } } private static class Col57Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setSIGNNAME(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_SIGNNAME, table._col57); } } private static class Col58Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setMONSTK(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_MONSTK, table._col58); } } private static class Col59Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setEDATE(rs.getDate(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_EDATE, table._col59); } } private static class Col60Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setBTRBZUST(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_BTRBZUST, table._col60); } } private static class Col61Accessor implements ColAccessor { public final void set(ZKDMOBREP table, RecordSet rs, int index) { table.setFLGVRG(rs.getString(index)); } public void setUpdate(ZKDMOBREP table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBREP.COL_FLGVRG, table._col61); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBREP.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IDX, new Integer(ZKDMOBREP.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBREP.COL_GUID, new Integer(ZKDMOBREP.IDX_GUID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBREP.COL_ERDAT, new Integer(ZKDMOBREP.IDX_ERDAT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBREP.COL_MLDNR, new Integer(ZKDMOBREP.IDX_MLDNR)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBREP.COL_AUART, new Integer(ZKDMOBREP.IDX_AUART)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBREP.COL_ANLNR, new Integer(ZKDMOBREP.IDX_ANLNR)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDMOBREP.COL_PERNR, new Integer(ZKDMOBREP.IDX_PERNR)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDMOBREP.COL_TEILREP, new Integer(ZKDMOBREP.IDX_TEILREP)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDMOBREP.COL_ENDREP, new Integer(ZKDMOBREP.IDX_ENDREP)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FOLGEREP, new Integer(ZKDMOBREP.IDX_FOLGEREP)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDMOBREP.COL_STORC, new Integer(ZKDMOBREP.IDX_STORC)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDMOBREP.COL_VERRC, new Integer(ZKDMOBREP.IDX_VERRC)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SECRAP, new Integer(ZKDMOBREP.IDX_SECRAP)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDMOBREP.COL_RAPSEND, new Integer(ZKDMOBREP.IDX_RAPSEND)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDMOBREP.COL_RAPSENDCOM, new Integer(ZKDMOBREP.IDX_RAPSENDCOM)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(ZKDMOBREP.COL_CHCKLISTE, new Integer(ZKDMOBREP.IDX_CHCKLISTE)); s_accessor[16] = new Col16Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMC1, new Integer(ZKDMOBREP.IDX_FMC1)); s_accessor[17] = new Col17Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMH1, new Integer(ZKDMOBREP.IDX_FMH1)); s_accessor[18] = new Col18Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FM1, new Integer(ZKDMOBREP.IDX_FM1)); s_accessor[19] = new Col19Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMC2, new Integer(ZKDMOBREP.IDX_FMC2)); s_accessor[20] = new Col20Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMH2, new Integer(ZKDMOBREP.IDX_FMH2)); s_accessor[21] = new Col21Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FM2, new Integer(ZKDMOBREP.IDX_FM2)); s_accessor[22] = new Col22Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMC3, new Integer(ZKDMOBREP.IDX_FMC3)); s_accessor[23] = new Col23Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMH3, new Integer(ZKDMOBREP.IDX_FMH3)); s_accessor[24] = new Col24Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FM3, new Integer(ZKDMOBREP.IDX_FM3)); s_accessor[25] = new Col25Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FMB, new Integer(ZKDMOBREP.IDX_FMB)); s_accessor[26] = new Col26Accessor(); s_accessorMap.put(ZKDMOBREP.COL_KM, new Integer(ZKDMOBREP.IDX_KM)); s_accessor[27] = new Col27Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SPESEN, new Integer(ZKDMOBREP.IDX_SPESEN)); s_accessor[28] = new Col28Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVLFD1, new Integer(ZKDMOBREP.IDX_SAVLFD1)); s_accessor[29] = new Col29Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVLFD2, new Integer(ZKDMOBREP.IDX_SAVLFD2)); s_accessor[30] = new Col30Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVLFD3, new Integer(ZKDMOBREP.IDX_SAVLFD3)); s_accessor[31] = new Col31Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVLFD4, new Integer(ZKDMOBREP.IDX_SAVLFD4)); s_accessor[32] = new Col32Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVLFD5, new Integer(ZKDMOBREP.IDX_SAVLFD5)); s_accessor[33] = new Col33Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVLFD6, new Integer(ZKDMOBREP.IDX_SAVLFD6)); s_accessor[34] = new Col34Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SAVERL, new Integer(ZKDMOBREP.IDX_SAVERL)); s_accessor[35] = new Col35Accessor(); s_accessorMap.put(ZKDMOBREP.COL_BSTKD, new Integer(ZKDMOBREP.IDX_BSTKD)); s_accessor[36] = new Col36Accessor(); s_accessorMap.put(ZKDMOBREP.COL_REPORTSTATUS, new Integer(ZKDMOBREP.IDX_REPORTSTATUS)); s_accessor[37] = new Col37Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SIGNGUID, new Integer(ZKDMOBREP.IDX_SIGNGUID)); s_accessor[38] = new Col38Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SIGNFLG, new Integer(ZKDMOBREP.IDX_SIGNFLG)); s_accessor[39] = new Col39Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SIGNINFO, new Integer(ZKDMOBREP.IDX_SIGNINFO)); s_accessor[40] = new Col40Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SIGNPIC, new Integer(ZKDMOBREP.IDX_SIGNPIC)); s_accessor[41] = new Col41Accessor(); s_accessorMap.put(ZKDMOBREP.COL_ARBA, new Integer(ZKDMOBREP.IDX_ARBA)); s_accessor[42] = new Col42Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SIGNBUNDLE, new Integer(ZKDMOBREP.IDX_SIGNBUNDLE)); s_accessor[43] = new Col43Accessor(); s_accessorMap.put(ZKDMOBREP.COL_NOMATUSED, new Integer(ZKDMOBREP.IDX_NOMATUSED)); s_accessor[44] = new Col44Accessor(); s_accessorMap.put(ZKDMOBREP.COL_ZYKINT, new Integer(ZKDMOBREP.IDX_ZYKINT)); s_accessor[45] = new Col45Accessor(); s_accessorMap.put(ZKDMOBREP.COL_NO_FORM1, new Integer(ZKDMOBREP.IDX_NO_FORM1)); s_accessor[46] = new Col46Accessor(); s_accessorMap.put(ZKDMOBREP.COL_NO_FORM2, new Integer(ZKDMOBREP.IDX_NO_FORM2)); s_accessor[47] = new Col47Accessor(); s_accessorMap.put(ZKDMOBREP.COL_NO_FORM3, new Integer(ZKDMOBREP.IDX_NO_FORM3)); s_accessor[48] = new Col48Accessor(); s_accessorMap.put(ZKDMOBREP.COL_BGRSAV, new Integer(ZKDMOBREP.IDX_BGRSAV)); s_accessor[49] = new Col49Accessor(); s_accessorMap.put(ZKDMOBREP.COL_PEND, new Integer(ZKDMOBREP.IDX_PEND)); s_accessor[50] = new Col50Accessor(); s_accessorMap.put(ZKDMOBREP.COL_REGIE, new Integer(ZKDMOBREP.IDX_REGIE)); s_accessor[51] = new Col51Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IBSSTATE, new Integer(ZKDMOBREP.IDX_IBSSTATE)); s_accessor[52] = new Col52Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IBSSIA, new Integer(ZKDMOBREP.IDX_IBSSIA)); s_accessor[53] = new Col53Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IBSREADY, new Integer(ZKDMOBREP.IDX_IBSREADY)); s_accessor[54] = new Col54Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IBSINSTR, new Integer(ZKDMOBREP.IDX_IBSINSTR)); s_accessor[55] = new Col55Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IBSVKF, new Integer(ZKDMOBREP.IDX_IBSVKF)); s_accessor[56] = new Col56Accessor(); s_accessorMap.put(ZKDMOBREP.COL_IBSTEST, new Integer(ZKDMOBREP.IDX_IBSTEST)); s_accessor[57] = new Col57Accessor(); s_accessorMap.put(ZKDMOBREP.COL_SIGNNAME, new Integer(ZKDMOBREP.IDX_SIGNNAME)); s_accessor[58] = new Col58Accessor(); s_accessorMap.put(ZKDMOBREP.COL_MONSTK, new Integer(ZKDMOBREP.IDX_MONSTK)); s_accessor[59] = new Col59Accessor(); s_accessorMap.put(ZKDMOBREP.COL_EDATE, new Integer(ZKDMOBREP.IDX_EDATE)); s_accessor[60] = new Col60Accessor(); s_accessorMap.put(ZKDMOBREP.COL_BTRBZUST, new Integer(ZKDMOBREP.IDX_BTRBZUST)); s_accessor[61] = new Col61Accessor(); s_accessorMap.put(ZKDMOBREP.COL_FLGVRG, new Integer(ZKDMOBREP.IDX_FLGVRG)); } return s_accessor; } /** * */ private final ZKDMOBREP m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBREPCursor(row, rs, false). * * @param zkdmobrep * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBREPCursor(ZKDMOBREP row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBREP WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBREPCursor(ZKDMOBREP row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBREP} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBRETURN.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBRETURNCursor.ColAccessor; /** * No description. */ public class ZKDMOBRETURN extends TableRow { /** Name of table: ZKDMOBRETURN */ public final static String TABLE = "ZKDMOBRETURN"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("LANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LANGU)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBRETURNCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBRETURNCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBRETURNCursor} * instance. Use an instance of {@link ZKDMOBRETURNCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBRETURN get(RecordSet rs, boolean selectStar) { ZKDMOBRETURN result = new ZKDMOBRETURN(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBRETURN[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBRETURN[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBRETURN row = new ZKDMOBRETURN(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBRETURN(row)); return (ZKDMOBRETURN[]) list.toArray(new ZKDMOBRETURN[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBRETURN[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBRETURN[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBRETURN row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBRETURN)) return false; ZKDMOBRETURN test = (ZKDMOBRETURN) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param RETTXT null * @param likeRETTXT Set to true if the query for RETTXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRETURN row, String RETTXT, boolean likeRETTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append(likeRETTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(RETTXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_RETTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param RETTXT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRETURN row, String RETTXT) { return queryByPrimaryKey(row, RETTXT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param RETTXT null * @param likeRETTXT Set to true if the query for RETTXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBRETURN[] listByPrimaryKey(DBSession db, String RETTXT, boolean likeRETTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append(likeRETTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(RETTXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_RETTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param RETTXT null * @param likeRETTXT Set to true if the query for RETTXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String RETTXT, boolean likeRETTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append(likeRETTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(RETTXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param RETTXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String RETTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append("=").append(sqlHelper.get(RETTXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param RETTXT null * @param likeRETTXT Set to true if the query for RETTXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRETURN row, String RETTXT, boolean likeRETTXT, String LANGU, boolean likeLANGU) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append(likeRETTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(RETTXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_RETTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param RETTXT null * @param LANGU null * @return The result of the database access. */ public static ZKDMOBRETURN getByPrimaryKey(DBSession db, String RETTXT, String LANGU) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append("=").append(sqlHelper.get(RETTXT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param RETTXT null * @param likeRETTXT Set to true if the query for RETTXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBRETURN[] listByPrimaryKey(DBSession db, String RETTXT, boolean likeRETTXT, String LANGU, boolean likeLANGU, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append(likeRETTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(RETTXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_RETTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param RETTXT null * @param likeRETTXT Set to true if the query for RETTXT * should be based on LIKE instead of equality. * @param LANGU null * @param likeLANGU Set to true if the query for LANGU * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String RETTXT, boolean likeRETTXT, String LANGU, boolean likeLANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append(likeRETTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(RETTXT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append(likeLANGU ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(LANGU)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param RETTXT null * @param LANGU null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String RETTXT, String LANGU) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_RETTXT).append("=").append(sqlHelper.get(RETTXT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_LANGU).append("=").append(sqlHelper.get(LANGU)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRETURN row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_RETTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBRETURN[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_RETTXT); sb.append(", ").append(COL_LANGU); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBRETURN. */ class ZKDMOBRETURNCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBRETURN table, RecordSet rs, int index); public void setUpdate(ZKDMOBRETURN table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBRETURN table, RecordSet rs, int index) { table.setRETTXT(rs.getString(index)); } public void setUpdate(ZKDMOBRETURN table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRETURN.COL_RETTXT, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBRETURN table, RecordSet rs, int index) { table.setLANGU(rs.getString(index)); } public void setUpdate(ZKDMOBRETURN table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRETURN.COL_LANGU, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBRETURN table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBRETURN table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRETURN.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBRETURN table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBRETURN table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRETURN.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBRETURN.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBRETURN.COL_RETTXT, new Integer(ZKDMOBRETURN.IDX_RETTXT)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBRETURN.COL_LANGU, new Integer(ZKDMOBRETURN.IDX_LANGU)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBRETURN.COL_TXT, new Integer(ZKDMOBRETURN.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBRETURN.COL_REFRESHED, new Integer(ZKDMOBRETURN.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBRETURN m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBRETURNCursor(row, rs, false). * * @param zkdmobreturn * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBRETURNCursor(ZKDMOBRETURN row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBRETURN WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBRETURNCursor(ZKDMOBRETURN row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBRETURN} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBRTIM.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBRTIMCursor.ColAccessor; /** * No description. */ public class ZKDMOBRTIM extends TableRow { /** Name of table: ZKDMOBRTIM */ public final static String TABLE = "ZKDMOBRTIM"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 6; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("GUID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GUID)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("DATUM"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_DATUM)) sb.append(df.format(_col2)); sb.append(", ").append("VON"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VON)) sb.append(df.format(_col3)); sb.append(", ").append("BIS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BIS)) sb.append(df.format(_col4)); sb.append(", ").append("ARBA"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ARBA)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBRTIMCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBRTIMCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBRTIMCursor} * instance. Use an instance of {@link ZKDMOBRTIMCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBRTIM get(RecordSet rs, boolean selectStar) { ZKDMOBRTIM result = new ZKDMOBRTIM(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBRTIM[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBRTIM[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBRTIM row = new ZKDMOBRTIM(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBRTIM(row)); return (ZKDMOBRTIM[]) list.toArray(new ZKDMOBRTIM[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBRTIM[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBRTIM[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBRTIM row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBRTIM)) return false; ZKDMOBRTIM test = (ZKDMOBRTIM) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRTIM row, int IDX) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBRTIM[] listByPrimaryKey(DBSession db, int IDX, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRTIM row, int IDX, String GUID, boolean likeGUID) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @param GUID null * @return The result of the database access. */ public static ZKDMOBRTIM getByPrimaryKey(DBSession db, int IDX, String GUID) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBRTIM[] listByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @param likeGUID Set to true if the query for GUID * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID, boolean likeGUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append(likeGUID ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(GUID)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @param GUID null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int IDX, String GUID) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=").append(sqlHelper.get(IDX)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_GUID).append("=").append(sqlHelper.get(GUID)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBRTIM row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBRTIM[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); sb.append(", ").append(COL_GUID); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBRTIM. */ class ZKDMOBRTIMCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBRTIM table, RecordSet rs, int index); public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBRTIM table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRTIM.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBRTIM table, RecordSet rs, int index) { table.setGUID(rs.getString(index)); } public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRTIM.COL_GUID, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBRTIM table, RecordSet rs, int index) { table.setDATUM(rs.getDate(index)); } public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRTIM.COL_DATUM, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBRTIM table, RecordSet rs, int index) { table.setVON(rs.getDate(index)); } public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRTIM.COL_VON, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDMOBRTIM table, RecordSet rs, int index) { table.setBIS(rs.getDate(index)); } public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRTIM.COL_BIS, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDMOBRTIM table, RecordSet rs, int index) { table.setARBA(rs.getString(index)); } public void setUpdate(ZKDMOBRTIM table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBRTIM.COL_ARBA, table._col5); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBRTIM.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBRTIM.COL_IDX, new Integer(ZKDMOBRTIM.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBRTIM.COL_GUID, new Integer(ZKDMOBRTIM.IDX_GUID)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBRTIM.COL_DATUM, new Integer(ZKDMOBRTIM.IDX_DATUM)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBRTIM.COL_VON, new Integer(ZKDMOBRTIM.IDX_VON)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDMOBRTIM.COL_BIS, new Integer(ZKDMOBRTIM.IDX_BIS)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDMOBRTIM.COL_ARBA, new Integer(ZKDMOBRTIM.IDX_ARBA)); } return s_accessor; } /** * */ private final ZKDMOBRTIM m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBRTIMCursor(row, rs, false). * * @param zkdmobrtim * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBRTIMCursor(ZKDMOBRTIM row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBRTIM WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBRTIMCursor(ZKDMOBRTIM row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBRTIM} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBSTORC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBSTORCCursor.ColAccessor; /** * No description. */ public class ZKDMOBSTORC extends TableRow { /** Name of table: ZKDMOBSTORC */ public final static String TABLE = "ZKDMOBSTORC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("FCT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FCT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBSTORCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBSTORCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBSTORCCursor} * instance. Use an instance of {@link ZKDMOBSTORCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBSTORC get(RecordSet rs, boolean selectStar) { ZKDMOBSTORC result = new ZKDMOBSTORC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBSTORC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBSTORC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBSTORC row = new ZKDMOBSTORC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBSTORC(row)); return (ZKDMOBSTORC[]) list.toArray(new ZKDMOBSTORC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBSTORC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBSTORC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBSTORC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBSTORC)) return false; ZKDMOBSTORC test = (ZKDMOBSTORC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBSTORC row, String STORC, boolean likeSTORC) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param STORC null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBSTORC row, String STORC) { return queryByPrimaryKey(row, STORC, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBSTORC[] listByPrimaryKey(DBSession db, String STORC, boolean likeSTORC, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String STORC, boolean likeSTORC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param STORC null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String STORC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append("=").append(sqlHelper.get(STORC)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param FCT null * @param likeFCT Set to true if the query for FCT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBSTORC row, String STORC, boolean likeSTORC, String FCT, boolean likeFCT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append(likeFCT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FCT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param STORC null * @param FCT null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBSTORC row, String STORC, String FCT) { return queryByPrimaryKey(row, STORC, false, FCT, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param FCT null * @param likeFCT Set to true if the query for FCT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBSTORC[] listByPrimaryKey(DBSession db, String STORC, boolean likeSTORC, String FCT, boolean likeFCT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append(likeFCT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FCT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param FCT null * @param likeFCT Set to true if the query for FCT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String STORC, boolean likeSTORC, String FCT, boolean likeFCT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append(likeFCT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FCT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param STORC null * @param FCT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String STORC, String FCT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append("=").append(sqlHelper.get(STORC)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append("=").append(sqlHelper.get(FCT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param FCT null * @param likeFCT Set to true if the query for FCT * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBSTORC row, String STORC, boolean likeSTORC, String FCT, boolean likeFCT, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append(likeFCT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FCT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param STORC null * @param FCT null * @param TXT null * @return The result of the database access. */ public static ZKDMOBSTORC getByPrimaryKey(DBSession db, String STORC, String FCT, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append("=").append(sqlHelper.get(STORC)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append("=").append(sqlHelper.get(FCT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param FCT null * @param likeFCT Set to true if the query for FCT * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBSTORC[] listByPrimaryKey(DBSession db, String STORC, boolean likeSTORC, String FCT, boolean likeFCT, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append(likeFCT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FCT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param STORC null * @param likeSTORC Set to true if the query for STORC * should be based on LIKE instead of equality. * @param FCT null * @param likeFCT Set to true if the query for FCT * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String STORC, boolean likeSTORC, String FCT, boolean likeFCT, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append(likeSTORC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(STORC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append(likeFCT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(FCT)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param STORC null * @param FCT null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String STORC, String FCT, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_STORC).append("=").append(sqlHelper.get(STORC)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_FCT).append("=").append(sqlHelper.get(FCT)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBSTORC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBSTORC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_STORC); sb.append(", ").append(COL_FCT); //$NON-NLS-1$ sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBSTORC. */ class ZKDMOBSTORCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBSTORC table, RecordSet rs, int index); public void setUpdate(ZKDMOBSTORC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBSTORC table, RecordSet rs, int index) { table.setSTORC(rs.getString(index)); } public void setUpdate(ZKDMOBSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBSTORC.COL_STORC, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBSTORC table, RecordSet rs, int index) { table.setFCT(rs.getString(index)); } public void setUpdate(ZKDMOBSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBSTORC.COL_FCT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBSTORC table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBSTORC.COL_TXT, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBSTORC table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBSTORC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBSTORC.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBSTORC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBSTORC.COL_STORC, new Integer(ZKDMOBSTORC.IDX_STORC)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBSTORC.COL_FCT, new Integer(ZKDMOBSTORC.IDX_FCT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBSTORC.COL_TXT, new Integer(ZKDMOBSTORC.IDX_TXT)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBSTORC.COL_REFRESHED, new Integer(ZKDMOBSTORC.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBSTORC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBSTORCCursor(row, rs, false). * * @param zkdmobstorc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBSTORCCursor(ZKDMOBSTORC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBSTORC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBSTORCCursor(ZKDMOBSTORC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBSTORC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBVERRC.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBVERRCCursor.ColAccessor; /** * No description. */ public class ZKDMOBVERRC extends TableRow { /** Name of table: ZKDMOBVERRC */ public final static String TABLE = "ZKDMOBVERRC"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBVERRCCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBVERRCCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBVERRCCursor} * instance. Use an instance of {@link ZKDMOBVERRCCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBVERRC get(RecordSet rs, boolean selectStar) { ZKDMOBVERRC result = new ZKDMOBVERRC(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBVERRC[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBVERRC[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBVERRC row = new ZKDMOBVERRC(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBVERRC(row)); return (ZKDMOBVERRC[]) list.toArray(new ZKDMOBVERRC[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBVERRC[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBVERRC[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBVERRC row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBVERRC)) return false; ZKDMOBVERRC test = (ZKDMOBVERRC) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VERRC null * @param likeVERRC Set to true if the query for VERRC * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVERRC row, String VERRC, boolean likeVERRC) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append(likeVERRC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VERRC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VERRC); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VERRC null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVERRC row, String VERRC) { return queryByPrimaryKey(row, VERRC, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param VERRC null * @param likeVERRC Set to true if the query for VERRC * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBVERRC[] listByPrimaryKey(DBSession db, String VERRC, boolean likeVERRC, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append(likeVERRC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VERRC)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VERRC); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VERRC null * @param likeVERRC Set to true if the query for VERRC * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VERRC, boolean likeVERRC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append(likeVERRC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VERRC)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VERRC null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VERRC) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append("=").append(sqlHelper.get(VERRC)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VERRC null * @param likeVERRC Set to true if the query for VERRC * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVERRC row, String VERRC, boolean likeVERRC, String TXT, boolean likeTXT) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append(likeVERRC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VERRC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VERRC); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param VERRC null * @param TXT null * @return The result of the database access. */ public static ZKDMOBVERRC getByPrimaryKey(DBSession db, String VERRC, String TXT) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append("=").append(sqlHelper.get(VERRC)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param VERRC null * @param likeVERRC Set to true if the query for VERRC * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBVERRC[] listByPrimaryKey(DBSession db, String VERRC, boolean likeVERRC, String TXT, boolean likeTXT, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append(likeVERRC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VERRC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VERRC); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VERRC null * @param likeVERRC Set to true if the query for VERRC * should be based on LIKE instead of equality. * @param TXT null * @param likeTXT Set to true if the query for TXT * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VERRC, boolean likeVERRC, String TXT, boolean likeTXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append(likeVERRC ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VERRC)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append(likeTXT ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TXT)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VERRC null * @param TXT null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VERRC, String TXT) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VERRC).append("=").append(sqlHelper.get(VERRC)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TXT).append("=").append(sqlHelper.get(TXT)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVERRC row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VERRC); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBVERRC[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VERRC); sb.append(", ").append(COL_TXT); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBVERRC. */ class ZKDMOBVERRCCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBVERRC table, RecordSet rs, int index); public void setUpdate(ZKDMOBVERRC table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBVERRC table, RecordSet rs, int index) { table.setVERRC(rs.getString(index)); } public void setUpdate(ZKDMOBVERRC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVERRC.COL_VERRC, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBVERRC table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBVERRC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVERRC.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBVERRC table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBVERRC table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVERRC.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBVERRC.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBVERRC.COL_VERRC, new Integer(ZKDMOBVERRC.IDX_VERRC)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBVERRC.COL_TXT, new Integer(ZKDMOBVERRC.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBVERRC.COL_REFRESHED, new Integer(ZKDMOBVERRC.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBVERRC m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBVERRCCursor(row, rs, false). * * @param zkdmobverrc * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBVERRCCursor(ZKDMOBVERRC row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBVERRC WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBVERRCCursor(ZKDMOBVERRC row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBVERRC} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBVRCINT.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBVRCINTCursor.ColAccessor; /** * No description. */ public class ZKDMOBVRCINT extends TableRow { /** Name of table: ZKDMOBVRCINT */ public final static String TABLE = "ZKDMOBVRCINT"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBVRCINTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBVRCINTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBVRCINTCursor} * instance. Use an instance of {@link ZKDMOBVRCINTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBVRCINT get(RecordSet rs, boolean selectStar) { ZKDMOBVRCINT result = new ZKDMOBVRCINT(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBVRCINT[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBVRCINT[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBVRCINT row = new ZKDMOBVRCINT(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBVRCINT(row)); return (ZKDMOBVRCINT[]) list.toArray(new ZKDMOBVRCINT[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBVRCINT[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBVRCINT[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBVRCINT row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBVRCINT)) return false; ZKDMOBVRCINT test = (ZKDMOBVRCINT) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VRCD null * @param likeVRCD Set to true if the query for VRCD * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVRCINT row, String VRCD, boolean likeVRCD) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append(likeVRCD ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VRCD)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VRCD); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VRCD null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVRCINT row, String VRCD) { return queryByPrimaryKey(row, VRCD, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param VRCD null * @param likeVRCD Set to true if the query for VRCD * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBVRCINT[] listByPrimaryKey(DBSession db, String VRCD, boolean likeVRCD, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append(likeVRCD ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VRCD)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VRCD); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VRCD null * @param likeVRCD Set to true if the query for VRCD * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VRCD, boolean likeVRCD) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append(likeVRCD ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VRCD)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VRCD null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VRCD) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append("=").append(sqlHelper.get(VRCD)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param VRCD null * @param likeVRCD Set to true if the query for VRCD * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVRCINT row, String VRCD, boolean likeVRCD, String AUART, boolean likeAUART) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append(likeVRCD ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VRCD)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VRCD); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param VRCD null * @param AUART null * @return The result of the database access. */ public static ZKDMOBVRCINT getByPrimaryKey(DBSession db, String VRCD, String AUART) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append("=").append(sqlHelper.get(VRCD)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param VRCD null * @param likeVRCD Set to true if the query for VRCD * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBVRCINT[] listByPrimaryKey(DBSession db, String VRCD, boolean likeVRCD, String AUART, boolean likeAUART, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append(likeVRCD ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VRCD)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VRCD); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VRCD null * @param likeVRCD Set to true if the query for VRCD * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VRCD, boolean likeVRCD, String AUART, boolean likeAUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append(likeVRCD ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(VRCD)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param VRCD null * @param AUART null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String VRCD, String AUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_VRCD).append("=").append(sqlHelper.get(VRCD)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBVRCINT row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VRCD); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBVRCINT[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_VRCD); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBVRCINT. */ class ZKDMOBVRCINTCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBVRCINT table, RecordSet rs, int index); public void setUpdate(ZKDMOBVRCINT table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBVRCINT table, RecordSet rs, int index) { table.setVRCD(rs.getString(index)); } public void setUpdate(ZKDMOBVRCINT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVRCINT.COL_VRCD, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBVRCINT table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBVRCINT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVRCINT.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBVRCINT table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDMOBVRCINT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVRCINT.COL_AUART, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDMOBVRCINT table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBVRCINT table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBVRCINT.COL_REFRESHED, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBVRCINT.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBVRCINT.COL_VRCD, new Integer(ZKDMOBVRCINT.IDX_VRCD)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBVRCINT.COL_TXT, new Integer(ZKDMOBVRCINT.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBVRCINT.COL_AUART, new Integer(ZKDMOBVRCINT.IDX_AUART)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDMOBVRCINT.COL_REFRESHED, new Integer(ZKDMOBVRCINT.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBVRCINT m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBVRCINTCursor(row, rs, false). * * @param zkdmobvrcint * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBVRCINTCursor(ZKDMOBVRCINT row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBVRCINT WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBVRCINTCursor(ZKDMOBVRCINT row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBVRCINT} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDMOBWERET.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBWERETCursor.ColAccessor; /** * No description. */ public class ZKDMOBWERET extends TableRow { /** Name of table: ZKDMOBWERET */ public final static String TABLE = "ZKDMOBWERET"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 3; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TXT)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDMOBWERETCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDMOBWERETCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDMOBWERETCursor} * instance. Use an instance of {@link ZKDMOBWERETCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDMOBWERET get(RecordSet rs, boolean selectStar) { ZKDMOBWERET result = new ZKDMOBWERET(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDMOBWERET[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDMOBWERET[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDMOBWERET row = new ZKDMOBWERET(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDMOBWERET(row)); return (ZKDMOBWERET[]) list.toArray(new ZKDMOBWERET[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDMOBWERET[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDMOBWERET[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDMOBWERET row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDMOBWERET)) return false; ZKDMOBWERET test = (ZKDMOBWERET) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param WEGRND null * @param likeWEGRND Set to true if the query for WEGRND * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBWERET row, String WEGRND, boolean likeWEGRND) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_WEGRND).append(likeWEGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(WEGRND)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_WEGRND); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param WEGRND null * @return The result of the database access. */ public static ZKDMOBWERET getByPrimaryKey(DBSession db, String WEGRND) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_WEGRND).append("=").append(sqlHelper.get(WEGRND)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param WEGRND null * @param likeWEGRND Set to true if the query for WEGRND * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBWERET[] listByPrimaryKey(DBSession db, String WEGRND, boolean likeWEGRND, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_WEGRND).append(likeWEGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(WEGRND)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_WEGRND); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param WEGRND null * @param likeWEGRND Set to true if the query for WEGRND * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String WEGRND, boolean likeWEGRND) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_WEGRND).append(likeWEGRND ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(WEGRND)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param WEGRND null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String WEGRND) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_WEGRND).append("=").append(sqlHelper.get(WEGRND)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDMOBWERET row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_WEGRND); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDMOBWERET[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_WEGRND); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDMOBWERET. */ class ZKDMOBWERETCursor implements TableCursor { interface ColAccessor { public void set(ZKDMOBWERET table, RecordSet rs, int index); public void setUpdate(ZKDMOBWERET table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDMOBWERET table, RecordSet rs, int index) { table.setWEGRND(rs.getString(index)); } public void setUpdate(ZKDMOBWERET table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBWERET.COL_WEGRND, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDMOBWERET table, RecordSet rs, int index) { table.setTXT(rs.getString(index)); } public void setUpdate(ZKDMOBWERET table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBWERET.COL_TXT, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDMOBWERET table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDMOBWERET table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDMOBWERET.COL_REFRESHED, table._col2); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDMOBWERET.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDMOBWERET.COL_WEGRND, new Integer(ZKDMOBWERET.IDX_WEGRND)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDMOBWERET.COL_TXT, new Integer(ZKDMOBWERET.IDX_TXT)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDMOBWERET.COL_REFRESHED, new Integer(ZKDMOBWERET.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDMOBWERET m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDMOBWERETCursor(row, rs, false). * * @param zkdmobweret * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBWERETCursor(ZKDMOBWERET row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDMOBWERET WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDMOBWERETCursor(ZKDMOBWERET row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDMOBWERET} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDSMOBEMAIL.java:   package ch.mfiles.kaba.kolibri.common.db; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDSMOBEMAILCursor.ColAccessor; /** * No description. */ public class ZKDSMOBEMAIL extends TableRow { /** Name of table: ZKDSMOBEMAIL */ public final static String TABLE = "ZKDSMOBEMAIL"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 4; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("AUART"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_AUART)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PARNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PARNR)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EMAIL"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EMAIL)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDSMOBEMAILCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDSMOBEMAILCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDSMOBEMAILCursor} * instance. Use an instance of {@link ZKDSMOBEMAILCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDSMOBEMAIL get(RecordSet rs, boolean selectStar) { ZKDSMOBEMAIL result = new ZKDSMOBEMAIL(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDSMOBEMAIL[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDSMOBEMAIL[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDSMOBEMAIL row = new ZKDSMOBEMAIL(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDSMOBEMAIL(row)); return (ZKDSMOBEMAIL[]) list.toArray(new ZKDSMOBEMAIL[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDSMOBEMAIL[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDSMOBEMAIL[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDSMOBEMAIL row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDSMOBEMAIL)) return false; ZKDSMOBEMAIL test = (ZKDSMOBEMAIL) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && !_col0.equals(test._col0)) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR, boolean likeMLDNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR) { return queryByPrimaryKey(row, MLDNR, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDSMOBEMAIL[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param AUART null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR, String AUART) { return queryByPrimaryKey(row, MLDNR, false, AUART, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDSMOBEMAIL[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param AUART null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, String AUART) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param AUART null * @param PARNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR, String AUART, String PARNR) { return queryByPrimaryKey(row, MLDNR, false, AUART, false, PARNR, false); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDSMOBEMAIL[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param AUART null * @param PARNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, String AUART, String PARNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append("=").append(sqlHelper.get(PARNR)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @param EMAIL null * @param likeEMAIL Set to true if the query for EMAIL * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR, String EMAIL, boolean likeEMAIL) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EMAIL).append(likeEMAIL ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EMAIL)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param MLDNR null * @param AUART null * @param PARNR null * @param EMAIL null * @return The result of the database access. */ public static ZKDSMOBEMAIL getByPrimaryKey(DBSession db, String MLDNR, String AUART, String PARNR, String EMAIL) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append("=").append(sqlHelper.get(PARNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EMAIL).append("=").append(sqlHelper.get(EMAIL)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @param EMAIL null * @param likeEMAIL Set to true if the query for EMAIL * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDSMOBEMAIL[] listByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR, String EMAIL, boolean likeEMAIL, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EMAIL).append(likeEMAIL ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EMAIL)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param likeMLDNR Set to true if the query for MLDNR * should be based on LIKE instead of equality. * @param AUART null * @param likeAUART Set to true if the query for AUART * should be based on LIKE instead of equality. * @param PARNR null * @param likePARNR Set to true if the query for PARNR * should be based on LIKE instead of equality. * @param EMAIL null * @param likeEMAIL Set to true if the query for EMAIL * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, boolean likeMLDNR, String AUART, boolean likeAUART, String PARNR, boolean likePARNR, String EMAIL, boolean likeEMAIL) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append(likeMLDNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(MLDNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append(likeAUART ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(AUART)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append(likePARNR ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(PARNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EMAIL).append(likeEMAIL ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(EMAIL)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param MLDNR null * @param AUART null * @param PARNR null * @param EMAIL null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, String MLDNR, String AUART, String PARNR, String EMAIL) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_MLDNR).append("=").append(sqlHelper.get(MLDNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_AUART).append("=").append(sqlHelper.get(AUART)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_PARNR).append("=").append(sqlHelper.get(PARNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_EMAIL).append("=").append(sqlHelper.get(EMAIL)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBEMAIL row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDSMOBEMAIL[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_MLDNR); sb.append(", ").append(COL_AUART); //$NON-NLS-1$ sb.append(", ").append(COL_PARNR); //$NON-NLS-1$ sb.append(", ").append(COL_EMAIL); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDSMOBEMAIL. */ class ZKDSMOBEMAILCursor implements TableCursor { interface ColAccessor { public void set(ZKDSMOBEMAIL table, RecordSet rs, int index); public void setUpdate(ZKDSMOBEMAIL table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDSMOBEMAIL table, RecordSet rs, int index) { table.setMLDNR(rs.getString(index)); } public void setUpdate(ZKDSMOBEMAIL table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBEMAIL.COL_MLDNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDSMOBEMAIL table, RecordSet rs, int index) { table.setAUART(rs.getString(index)); } public void setUpdate(ZKDSMOBEMAIL table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBEMAIL.COL_AUART, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDSMOBEMAIL table, RecordSet rs, int index) { table.setPARNR(rs.getString(index)); } public void setUpdate(ZKDSMOBEMAIL table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBEMAIL.COL_PARNR, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDSMOBEMAIL table, RecordSet rs, int index) { table.setEMAIL(rs.getString(index)); } public void setUpdate(ZKDSMOBEMAIL table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBEMAIL.COL_EMAIL, table._col3); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDSMOBEMAIL.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDSMOBEMAIL.COL_MLDNR, new Integer(ZKDSMOBEMAIL.IDX_MLDNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDSMOBEMAIL.COL_AUART, new Integer(ZKDSMOBEMAIL.IDX_AUART)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDSMOBEMAIL.COL_PARNR, new Integer(ZKDSMOBEMAIL.IDX_PARNR)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDSMOBEMAIL.COL_EMAIL, new Integer(ZKDSMOBEMAIL.IDX_EMAIL)); } return s_accessor; } /** * */ private final ZKDSMOBEMAIL m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDSMOBEMAILCursor(row, rs, false). * * @param zkdsmobemail * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDSMOBEMAILCursor(ZKDSMOBEMAIL row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDSMOBEMAIL WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDSMOBEMAILCursor(ZKDSMOBEMAIL row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDSMOBEMAIL} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKDSMOBMA.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKDSMOBMACursor.ColAccessor; /** * No description. */ public class ZKDSMOBMA extends TableRow { /** Name of table: ZKDSMOBMA */ public final static String TABLE = "ZKDSMOBMA"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 16; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("VORNA"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VORNA)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("INITS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_INITS)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STVPERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STVPERNR)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("TELNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TELNR)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("NUM01"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_NUM01)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("VKBUR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_VKBUR)) sb.append('\'').append(_col7).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ABWVON"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABWVON)) sb.append(df.format(_col8)); sb.append(", ").append("ABWBIS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ABWBIS)) sb.append(df.format(_col9)); sb.append(", ").append("COMLANGU"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_COMLANGU)) sb.append('\'').append(_col10).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("GID"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GID)) sb.append('\'').append(_col11).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PWD"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PWD)) sb.append('\'').append(_col12).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("FKT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_FKT)) sb.append('\'').append(_col13).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LGORT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LGORT)) sb.append('\'').append(_col14).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("REFRESHED"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_REFRESHED)) sb.append('\'').append(_col15).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKDSMOBMACursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKDSMOBMACursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKDSMOBMACursor} * instance. Use an instance of {@link ZKDSMOBMACursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKDSMOBMA get(RecordSet rs, boolean selectStar) { ZKDSMOBMA result = new ZKDSMOBMA(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKDSMOBMA[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKDSMOBMA[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKDSMOBMA row = new ZKDSMOBMA(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKDSMOBMA(row)); return (ZKDSMOBMA[]) list.toArray(new ZKDSMOBMA[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKDSMOBMA[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKDSMOBMA[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKDSMOBMA row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKDSMOBMA)) return false; ZKDSMOBMA test = (ZKDSMOBMA) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; if ((m_usedColumns == null || !m_usedColumns.get(8)) && !_col8.equals(test._col8)) return false; if ((m_usedColumns == null || !m_usedColumns.get(9)) && !_col9.equals(test._col9)) return false; if ((m_usedColumns == null || !m_usedColumns.get(10)) && !_col10.equals(test._col10)) return false; if ((m_usedColumns == null || !m_usedColumns.get(11)) && !_col11.equals(test._col11)) return false; if ((m_usedColumns == null || !m_usedColumns.get(12)) && !_col12.equals(test._col12)) return false; if ((m_usedColumns == null || !m_usedColumns.get(13)) && !_col13.equals(test._col13)) return false; if ((m_usedColumns == null || !m_usedColumns.get(14)) && !_col14.equals(test._col14)) return false; if ((m_usedColumns == null || !m_usedColumns.get(15)) && !_col15.equals(test._col15)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @return The result of the database access. */ public static ZKDSMOBMA getByPrimaryKey(DBSession db, int PERNR) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKDSMOBMA row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKDSMOBMA[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKDSMOBMA. */ class ZKDSMOBMACursor implements TableCursor { interface ColAccessor { public void set(ZKDSMOBMA table, RecordSet rs, int index); public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setNACHN(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_NACHN, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setVORNA(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_VORNA, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setINITS(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_INITS, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setSTVPERNR(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_STVPERNR, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setTELNR(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_TELNR, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setNUM01(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_NUM01, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setVKBUR(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_VKBUR, table._col7); } } private static class Col8Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setABWVON(rs.getDate(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_ABWVON, table._col8); } } private static class Col9Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setABWBIS(rs.getDate(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_ABWBIS, table._col9); } } private static class Col10Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setCOMLANGU(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_COMLANGU, table._col10); } } private static class Col11Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setGID(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_GID, table._col11); } } private static class Col12Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setPWD(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_PWD, table._col12); } } private static class Col13Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setFKT(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_FKT, table._col13); } } private static class Col14Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setLGORT(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_LGORT, table._col14); } } private static class Col15Accessor implements ColAccessor { public final void set(ZKDSMOBMA table, RecordSet rs, int index) { table.setREFRESHED(rs.getString(index)); } public void setUpdate(ZKDSMOBMA table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKDSMOBMA.COL_REFRESHED, table._col15); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKDSMOBMA.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_PERNR, new Integer(ZKDSMOBMA.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_NACHN, new Integer(ZKDSMOBMA.IDX_NACHN)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_VORNA, new Integer(ZKDSMOBMA.IDX_VORNA)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_INITS, new Integer(ZKDSMOBMA.IDX_INITS)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_STVPERNR, new Integer(ZKDSMOBMA.IDX_STVPERNR)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_TELNR, new Integer(ZKDSMOBMA.IDX_TELNR)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_NUM01, new Integer(ZKDSMOBMA.IDX_NUM01)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_VKBUR, new Integer(ZKDSMOBMA.IDX_VKBUR)); s_accessor[8] = new Col8Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_ABWVON, new Integer(ZKDSMOBMA.IDX_ABWVON)); s_accessor[9] = new Col9Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_ABWBIS, new Integer(ZKDSMOBMA.IDX_ABWBIS)); s_accessor[10] = new Col10Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_COMLANGU, new Integer(ZKDSMOBMA.IDX_COMLANGU)); s_accessor[11] = new Col11Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_GID, new Integer(ZKDSMOBMA.IDX_GID)); s_accessor[12] = new Col12Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_PWD, new Integer(ZKDSMOBMA.IDX_PWD)); s_accessor[13] = new Col13Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_FKT, new Integer(ZKDSMOBMA.IDX_FKT)); s_accessor[14] = new Col14Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_LGORT, new Integer(ZKDSMOBMA.IDX_LGORT)); s_accessor[15] = new Col15Accessor(); s_accessorMap.put(ZKDSMOBMA.COL_REFRESHED, new Integer(ZKDSMOBMA.IDX_REFRESHED)); } return s_accessor; } /** * */ private final ZKDSMOBMA m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKDSMOBMACursor(row, rs, false). * * @param zkdsmobma * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDSMOBMACursor(ZKDSMOBMA row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKDSMOBMA WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKDSMOBMACursor(ZKDSMOBMA row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKDSMOBMA} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZKSMABEST.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZKSMABESTCursor.ColAccessor; /** * No description. */ public class ZKSMABEST extends TableRow { /** Name of table: ZKSMABEST */ public final static String TABLE = "ZKSMABEST"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 6; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; iSet to 0 to let the database system create a * new autoincrement value when the row gets inserted. */ public ZKSMABEST(DBSession db, long IDX) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); setIDX(IDX); validate(); } /** * Creates a new complete row using the given column values. * * @param db * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param PERNR No description. * @param STATUS No description. * @param ANZ No description. * @param ERFASST No description. * @param GESENDET No description. */ public ZKSMABEST(DBSession db, long IDX, int PERNR, String STATUS, String ANZ, Date ERFASST, Date GESENDET) { super(db, null); _col0 = IDX; _col1 = PERNR; _col2 = STATUS; _col3 = ANZ; _col4 = ERFASST instanceof ImmutableDate ? ERFASST : new ImmutableDate(ERFASST); _col5 = GESENDET instanceof ImmutableDate ? GESENDET : new ImmutableDate(GESENDET); validate(); } /** * Creates a new row with values taken from the given source row. The newly * created row is either complete or sparse depending on the source row. * * @param source */ public ZKSMABEST(ZKSMABEST source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); if (isSparse()) { // copy only used columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_PERNR)) _col1 = source._col1; if (isColumnSet(IDX_STATUS)) _col2 = source._col2; if (isColumnSet(IDX_ANZ)) _col3 = source._col3; if (isColumnSet(IDX_ERFASST)) _col4 = source._col4; if (isColumnSet(IDX_GESENDET)) _col5 = source._col5; } else { // copy all columns if (isColumnSet(IDX_IDX)) _col0 = source._col0; if (isColumnSet(IDX_PERNR)) _col1 = source._col1; if (isColumnSet(IDX_STATUS)) _col2 = source._col2; if (isColumnSet(IDX_ANZ)) _col3 = source._col3; if (isColumnSet(IDX_ERFASST)) _col4 = source._col4; if (isColumnSet(IDX_GESENDET)) _col5 = source._col5; } validate(); } /** * Creates a new row with values taken from the given source row but * replacing the primary key with the given values. The newly created row is * either complete or sparse depending on the source row. * * @param IDX No description. *

Set to 0 to let the database system create a * new autoincrement value when the row gets inserted. * @param source */ public ZKSMABEST(long IDX, ZKSMABEST source) { super(source.getDBSession(), (source.m_usedColumns != null) ? (BitSet) source.m_usedColumns .clone() : null); // set the primary key _col0 = IDX; if (isSparse()) { // copy only used columns excluding the primary key if (isColumnSet(IDX_PERNR)) _col1 = source._col1; if (isColumnSet(IDX_STATUS)) _col2 = source._col2; if (isColumnSet(IDX_ANZ)) _col3 = source._col3; if (isColumnSet(IDX_ERFASST)) _col4 = source._col4; if (isColumnSet(IDX_GESENDET)) _col5 = source._col5; } else { // copy all columns excluding the primary key _col1 = source._col1; _col2 = source._col2; _col3 = source._col3; _col4 = source._col4; _col5 = source._col5; } validate(); } /** * Creates a new sparse row with all columns unspecified. This constructor * should only be used to create a row for a {@link TableCursor}. * * @param db */ public ZKSMABEST(DBSession db) { super(db, (BitSet)BITSET_NO_COLUMN_SET.clone()); } protected void validate() { super.validate(); } public void reset() { BitSet usedColumns = m_usedColumns; m_usedColumns = (BitSet)BITSET_NO_COLUMN_SET.clone(); if (usedColumns == null || !usedColumns.get(IDX_IDX)) m_usedColumns.clear(IDX_IDX); } public void complete() { if (m_usedColumns == null) return; if (m_usedColumns.get(IDX_PERNR)) _col1 = DEF_PERNR; if (m_usedColumns.get(IDX_STATUS)) _col2 = DEF_STATUS; if (m_usedColumns.get(IDX_ANZ)) _col3 = DEF_ANZ; if (m_usedColumns.get(IDX_ERFASST)) _col4 = DEF_ERFASST; if (m_usedColumns.get(IDX_GESENDET)) _col5 = DEF_GESENDET; m_usedColumns = null; } private void appendWhereClause(StringBuffer sb, DBSqlHelper sqlHelper) { if (isSparse()) if ( !isColumnSet(IDX_IDX) ) throw new UnsupportedOperationException( "DML operation only if the table row's primary key was fully specified!"); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append('=').append(sqlHelper.get(_col0)); } public void insert() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); if (isSparse()) complete(); sqlHelper.INSERT_COMPLETE(TABLE); if (_col0 == 0) { sqlHelper.inNULL(); } sqlHelper.in(_col1); sqlHelper.in(_col2); sqlHelper.in(_col3); sqlHelper.in(_col4); sqlHelper.in(_col5); getDBSession().executeSql(sqlHelper.toString()); if (_col0 == 0) { DBSession db = getDBSession(); RecordSet rs = db.getRecordSet(); try { rs.setQuery("SELECT last_insert_rowid()"); //$NON-NLS-1$ rs.moveNext(); setIDX(rs.getLong(0)); } finally { rs.dispose(); } } } public boolean delete() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); StringBuffer sb = new StringBuffer("DELETE FROM "); //$NON-NLS-1$ sb.append(TABLE); appendWhereClause(sb, sqlHelper); int deletedRows = getDBSession().executeSql(sb.toString()); return deletedRows == 1; } public boolean update() { DBSqlHelper sqlHelper = new DBSqlHelper(getDBSession()); sqlHelper.UPDATE(TABLE); if (isSparse()) { // update only used columns ColAccessor[] accessors = ZKSMABESTCursor.getAccessors(); boolean update = false; for (int i = NUM_PK_COLUMNS; i < NUM_COLUMNS; i++) if (isColumnSet(i)) { accessors[i].setUpdate(this, sqlHelper); update = true; } if (!update) return false; // no column to update found } else { // update all non pk columns sqlHelper.in(COL_PERNR, _col1); sqlHelper.in(COL_STATUS, _col2); sqlHelper.in(COL_ANZ, _col3); sqlHelper.in(COL_ERFASST, _col4); sqlHelper.in(COL_GESENDET, _col5); } StringBuffer sb = new StringBuffer(sqlHelper.toString()); appendWhereClause(sb, sqlHelper); int updatedRows = getDBSession().executeSql(sb.toString()); return updatedRows == 1; } /** * @return null */ public long getIDX() { checkSparseColumn(IDX_IDX); return _col0; } /** * @param IDX null */ protected void setIDX(long IDX) { _col0 = IDX; markUsed(IDX_IDX); } /** * @return null */ public int getPERNR() { checkSparseColumn(IDX_PERNR); return _col1; } /** * @param PERNR null */ public void setPERNR(int PERNR) { _col1 = PERNR; markUsed(IDX_PERNR); } /** * @return null */ public String getSTATUS() { checkSparseColumn(IDX_STATUS); return _col2; } /** * @param STATUS null */ public void setSTATUS(String STATUS) { checkNull(STATUS); _col2 = STATUS; markUsed(IDX_STATUS); } /** * @return null */ public String getANZ() { checkSparseColumn(IDX_ANZ); return _col3; } /** * @param ANZ null */ public void setANZ(String ANZ) { checkNull(ANZ); _col3 = ANZ; markUsed(IDX_ANZ); } /** * @return null */ public Date getERFASST() { checkSparseColumn(IDX_ERFASST); return _col4; } /** * @param ERFASST null */ public void setERFASST(Date ERFASST) { checkNull(ERFASST); _col4 = ERFASST instanceof ImmutableDate ? ERFASST : new ImmutableDate(ERFASST); markUsed(IDX_ERFASST); } /** * @return null */ public Date getGESENDET() { checkSparseColumn(IDX_GESENDET); return _col5; } /** * @param GESENDET null */ public void setGESENDET(Date GESENDET) { checkNull(GESENDET); _col5 = GESENDET instanceof ImmutableDate ? GESENDET : new ImmutableDate(GESENDET); markUsed(IDX_GESENDET); } public String toString() { DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG); StringBuffer sb = new StringBuffer(); sb.append("[").append(TABLE).append(": ").append("IDX"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_IDX)) sb.append(_col0); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("PERNR"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_PERNR)) sb.append(_col1); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STATUS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STATUS)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ANZ"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ANZ)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ERFASST"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERFASST)) sb.append(df.format(_col4)); sb.append(", ").append("GESENDET"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_GESENDET)) sb.append(df.format(_col5)); sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZKSMABESTCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZKSMABESTCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZKSMABESTCursor} * instance. Use an instance of {@link ZKSMABESTCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZKSMABEST get(RecordSet rs, boolean selectStar) { ZKSMABEST result = new ZKSMABEST(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZKSMABEST[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZKSMABEST[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZKSMABEST row = new ZKSMABEST(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZKSMABEST(row)); return (ZKSMABEST[]) list.toArray(new ZKSMABEST[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZKSMABEST[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZKSMABEST[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZKSMABEST row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZKSMABEST)) return false; ZKSMABEST test = (ZKSMABEST) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && _col1 != test._col1) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param IDX null * @return The result of the database access. */ public static ZKSMABEST getByPrimaryKey(DBSession db, long IDX) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param IDX null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, long IDX) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_IDX).append("=") //$NON-NLS-1$ .append(sqlHelper.get(IDX)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZKSMABEST row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZKSMABEST[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_IDX); rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZKSMABEST. */ class ZKSMABESTCursor implements TableCursor { interface ColAccessor { public void set(ZKSMABEST table, RecordSet rs, int index); public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZKSMABEST table, RecordSet rs, int index) { table.setIDX(rs.getInt(index)); } public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKSMABEST.COL_IDX, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZKSMABEST table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKSMABEST.COL_PERNR, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZKSMABEST table, RecordSet rs, int index) { table.setSTATUS(rs.getString(index)); } public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKSMABEST.COL_STATUS, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZKSMABEST table, RecordSet rs, int index) { table.setANZ(rs.getString(index)); } public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKSMABEST.COL_ANZ, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZKSMABEST table, RecordSet rs, int index) { table.setERFASST(rs.getDate(index)); } public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKSMABEST.COL_ERFASST, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZKSMABEST table, RecordSet rs, int index) { table.setGESENDET(rs.getDate(index)); } public void setUpdate(ZKSMABEST table, DBSqlHelper sqlHelper) { sqlHelper.in(ZKSMABEST.COL_GESENDET, table._col5); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZKSMABEST.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZKSMABEST.COL_IDX, new Integer(ZKSMABEST.IDX_IDX)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZKSMABEST.COL_PERNR, new Integer(ZKSMABEST.IDX_PERNR)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZKSMABEST.COL_STATUS, new Integer(ZKSMABEST.IDX_STATUS)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZKSMABEST.COL_ANZ, new Integer(ZKSMABEST.IDX_ANZ)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZKSMABEST.COL_ERFASST, new Integer(ZKSMABEST.IDX_ERFASST)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZKSMABEST.COL_GESENDET, new Integer(ZKSMABEST.IDX_GESENDET)); } return s_accessor; } /** * */ private final ZKSMABEST m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZKSMABESTCursor(row, rs, false). * * @param zksmabest * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKSMABESTCursor(ZKSMABEST row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZKSMABEST WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZKSMABESTCursor(ZKSMABEST row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZKSMABEST} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/db/ZSHORTMSG.java:   package ch.mfiles.kaba.kolibri.common.db; import java.text.DateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.HashMap; import org.eclipse.osgi.util.NLS; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.db.gen.ImmutableDate; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.db.gen.TableRow; import ch.mfiles.kaba.kolibri.common.db.ZSHORTMSGCursor.ColAccessor; /** * No description. */ public class ZSHORTMSG extends TableRow { /** Name of table: ZSHORTMSG */ public final static String TABLE = "ZSHORTMSG"; //$NON-NLS-1$ /** Number of table columns */ public final static int NUM_COLUMNS = 8; /** Bitset representing all columns not set */ private final static BitSet BITSET_NO_COLUMN_SET = new BitSet(NUM_COLUMNS); static { for (int i=0; i"); //$NON-NLS-1$ sb.append(", ").append("TDNAME"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_TDNAME)) sb.append('\'').append(_col1).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BETREFF"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BETREFF)) sb.append('\'').append(_col2).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("BESTAETIGT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_BESTAETIGT)) sb.append('\'').append(_col3).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("LTEXT"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_LTEXT)) sb.append('\'').append(_col4).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("STATUS"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_STATUS)) sb.append('\'').append(_col5).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("ERHALTEN"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_ERHALTEN)) sb.append('\'').append(_col6).append('\''); else sb.append(""); //$NON-NLS-1$ sb.append(", ").append("EINGANG"); //$NON-NLS-1$ //$NON-NLS-2$ sb.append("="); //$NON-NLS-1$ if (isComplete() || isColumnSet(IDX_EINGANG)) sb.append(df.format(_col7)); sb.append("]"); //$NON-NLS-1$ return sb.toString(); } public TableCursor createCursor(RecordSet rs) { return new ZSHORTMSGCursor(this, rs); } public TableCursor createCursor(RecordSet rs, boolean selectStar) { return new ZSHORTMSGCursor(this, rs, selectStar); } /** * Returns a new row object from the given record set's current row. The * record set must have been moved to a valid row before using this * constructor. *

* Note: do not use this constructor if traversing a (possibly large) * record set since every time this method is called, the record set's actual * columns have to be mapped to the table object by a new {@link ZSHORTMSGCursor} * instance. Use an instance of {@link ZSHORTMSGCursor} instead to reuse the * record set mapping on consecutive rows. * * @param rs * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return The row. */ public static ZSHORTMSG get(RecordSet rs, boolean selectStar) { ZSHORTMSG result = new ZSHORTMSG(rs.getDBSession()); TableCursor cursor = result.createCursor(rs, selectStar); cursor.current(); return result; } /** * @param rs * @return Returns an array of row objects of all (remaining) entries from * the given record set beginning with the next row. */ public static ZSHORTMSG[] drain(RecordSet rs) { return drain(rs, Integer.MAX_VALUE); } /** * @param rs * @param maxRows The maximum number of rows to drain from the record set * return. * @return Returns a possibly empty array of row objects of all (remaining) * entries from the given record set beginning with the next row. */ public static ZSHORTMSG[] drain(RecordSet rs, int maxRows) { ArrayList list = new ArrayList(); ZSHORTMSG row = new ZSHORTMSG(rs.getDBSession()); TableCursor cursor = row.createCursor(rs); for (int i = 0; i< maxRows && cursor.next(); i++) list.add(new ZSHORTMSG(row)); return (ZSHORTMSG[]) list.toArray(new ZSHORTMSG[list.size()]); } /** * @param db * @param sql * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. */ public static ZSHORTMSG[] list(DBSession db, String sql) { return list(db, sql, Integer.MAX_VALUE); } /** * @param db * @param sql * @param maxRows The maximum number of rows to retrieve. * @return Returns a possibly empty array of row objects retrieved * from the database using the given SQL command. The number of rows * returned is limited to the given number maxRows. */ public static ZSHORTMSG[] list(DBSession db, String sql, int maxRows) { RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * @param row * @param sql * @param selectStar Set to true if the record set contains * all columns of the table. This will speed up column * mapping. * @return Returns a table cursor using the given row object as accessor class */ public static TableCursor query(ZSHORTMSG row, String sql, boolean selectStar) { RecordSet rs = row.getDBSession().getRecordSet(); rs.setQuery(sql); return row.createCursor(rs, selectStar); } /** * Compares whether the given row's columns equal the receiver's columns. * @param row The row to compare. * @return Returns true if all columns of the possibly sparse * rows are equal. **/ public boolean compareTo(TableRow row) { if (row == null || !(row instanceof ZSHORTMSG)) return false; ZSHORTMSG test = (ZSHORTMSG) row; if (!m_usedColumns.equals(test.m_usedColumns)) return false; if ((m_usedColumns == null || !m_usedColumns.get(0)) && _col0 != test._col0) return false; if ((m_usedColumns == null || !m_usedColumns.get(1)) && !_col1.equals(test._col1)) return false; if ((m_usedColumns == null || !m_usedColumns.get(2)) && !_col2.equals(test._col2)) return false; if ((m_usedColumns == null || !m_usedColumns.get(3)) && !_col3.equals(test._col3)) return false; if ((m_usedColumns == null || !m_usedColumns.get(4)) && !_col4.equals(test._col4)) return false; if ((m_usedColumns == null || !m_usedColumns.get(5)) && !_col5.equals(test._col5)) return false; if ((m_usedColumns == null || !m_usedColumns.get(6)) && !_col6.equals(test._col6)) return false; if ((m_usedColumns == null || !m_usedColumns.get(7)) && !_col7.equals(test._col7)) return false; return true; } /** * Returns the names of the columns in the order they appear in the table. */ protected String[] getColumnNames() { return COLUMN_NAMES; } /** * Deletes all rows of the table. * * @return The number of rows deleted. */ public static int delete(DBSession db) { return db.executeSql("DELETE FROM " + TABLE); //$NON-NLS-1$ } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZSHORTMSG row, int PERNR) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_TDNAME); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZSHORTMSG[] listByPrimaryKey(DBSession db, int PERNR, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_TDNAME); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); return db.executeSql(sb.toString()); } /** * Returns a cursor to access complete rows of the queried table using the table * index PrimaryKey. The rows accessed by the cursor are complete rows and * are ordered by the index used. * * @param row The row object used to access the current cursor. * @param PERNR null * @param TDNAME null * @param likeTDNAME Set to true if the query for TDNAME * should be based on LIKE instead of equality. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZSHORTMSG row, int PERNR, String TDNAME, boolean likeTDNAME) { RecordSet rs = row.getDBSession().getRecordSet(); DBSqlHelper sqlHelper = new DBSqlHelper(row.getDBSession()); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TDNAME).append(likeTDNAME ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TDNAME)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_TDNAME); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns the unique result or null using the table index PrimaryKey * to search the database table. The resulting row object contains a complete row. * @param db * @param PERNR null * @param TDNAME null * @return The result of the database access. */ public static ZSHORTMSG getByPrimaryKey(DBSession db, int PERNR, String TDNAME) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TDNAME).append("=").append(sqlHelper.get(TDNAME)); //$NON-NLS-1$ rs.setQuery(sb.toString()); int count = rs.getCount(); if (count == 0) return null; if (count > 1) throw new ApplicationException( "Unique query returned more than one result!"); //$NON-NLS-1$ if (!rs.moveNext()) return null; return get(rs, true); } finally { rs.dispose(); } } /** * Returns an array of rows of the queried table using the table * index PrimaryKey. The rows are complete rows and * are ordered by the index used. * * @param db * @param PERNR null * @param TDNAME null * @param likeTDNAME Set to true if the query for TDNAME * should be based on LIKE instead of equality. * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZSHORTMSG[] listByPrimaryKey(DBSession db, int PERNR, String TDNAME, boolean likeTDNAME, int maxRows) { RecordSet rs = db.getRecordSet(); try { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TDNAME).append(likeTDNAME ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TDNAME)); sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_TDNAME); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param TDNAME null * @param likeTDNAME Set to true if the query for TDNAME * should be based on LIKE instead of equality. * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String TDNAME, boolean likeTDNAME) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=") //$NON-NLS-1$ .append(sqlHelper.get(PERNR)); sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TDNAME).append(likeTDNAME ? " like " : "=") //$NON-NLS-1$ //$NON-NLS-2$ .append(sqlHelper.get(TDNAME)); return db.executeSql(sb.toString()); } /** * Deletes all rows of the table that match the given selection using * index PrimaryKey. * * @param PERNR null * @param TDNAME null * @return The number of rows deleted. */ public static int deleteByPrimaryKey(DBSession db, int PERNR, String TDNAME) { DBSqlHelper sqlHelper = new DBSqlHelper(db); StringBuffer sb = new StringBuffer("DELETE FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" WHERE "); //$NON-NLS-1$ sb.append(COL_PERNR).append("=").append(sqlHelper.get(PERNR)); //$NON-NLS-1$ sb.append(" AND "); //$NON-NLS-1$ sb.append(COL_TDNAME).append("=").append(sqlHelper.get(TDNAME)); //$NON-NLS-1$ return db.executeSql(sb.toString()); } /** * Returns a cursor to access all rows of the queried table. The rows * accessed by the cursor are complete rows and are ordered by the * table index PrimaryKey. * * @param row The row object used to access the current cursor. * @return The result of the database access. */ public static TableCursor queryByPrimaryKey(ZSHORTMSG row) { RecordSet rs = row.getDBSession().getRecordSet(); StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_TDNAME); //$NON-NLS-1$ rs.setQuery(sb.toString()); return row.createCursor(rs, true); } /** * Returns an array of all rows of the queried table. The rows returned * are complete rows and are ordered by the table index PrimaryKey. * * @param db * @param maxRows The maximum number of rows to retrieve. * @return The result of the database access. */ public static ZSHORTMSG[] listByPrimaryKey(DBSession db, int maxRows) { RecordSet rs = db.getRecordSet(); try { StringBuffer sb = new StringBuffer("SELECT * FROM ").append(TABLE); //$NON-NLS-1$ sb.append(" ORDER BY "); //$NON-NLS-1$ sb.append(COL_PERNR); sb.append(", ").append(COL_TDNAME); //$NON-NLS-1$ rs.setQuery(sb.toString()); return drain(rs, maxRows); } finally { rs.dispose(); } } } /** * A cursor used to access table ZSHORTMSG. */ class ZSHORTMSGCursor implements TableCursor { interface ColAccessor { public void set(ZSHORTMSG table, RecordSet rs, int index); public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper); }; private static class Col0Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setPERNR(rs.getInt(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_PERNR, table._col0); } } private static class Col1Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setTDNAME(rs.getString(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_TDNAME, table._col1); } } private static class Col2Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setBETREFF(rs.getString(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_BETREFF, table._col2); } } private static class Col3Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setBESTAETIGT(rs.getString(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_BESTAETIGT, table._col3); } } private static class Col4Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setLTEXT(rs.getString(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_LTEXT, table._col4); } } private static class Col5Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setSTATUS(rs.getString(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_STATUS, table._col5); } } private static class Col6Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setERHALTEN(rs.getString(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_ERHALTEN, table._col6); } } private static class Col7Accessor implements ColAccessor { public final void set(ZSHORTMSG table, RecordSet rs, int index) { table.setEINGANG(rs.getDate(index)); } public void setUpdate(ZSHORTMSG table, DBSqlHelper sqlHelper) { sqlHelper.in(ZSHORTMSG.COL_EINGANG, table._col7); } } private static ColAccessor[] s_accessor = null; private static HashMap s_accessorMap = null; static ColAccessor[] getAccessors() { if (s_accessor == null) { s_accessor = new ColAccessor[ZSHORTMSG.NUM_COLUMNS]; s_accessorMap = new HashMap(); s_accessor[0] = new Col0Accessor(); s_accessorMap.put(ZSHORTMSG.COL_PERNR, new Integer(ZSHORTMSG.IDX_PERNR)); s_accessor[1] = new Col1Accessor(); s_accessorMap.put(ZSHORTMSG.COL_TDNAME, new Integer(ZSHORTMSG.IDX_TDNAME)); s_accessor[2] = new Col2Accessor(); s_accessorMap.put(ZSHORTMSG.COL_BETREFF, new Integer(ZSHORTMSG.IDX_BETREFF)); s_accessor[3] = new Col3Accessor(); s_accessorMap.put(ZSHORTMSG.COL_BESTAETIGT, new Integer(ZSHORTMSG.IDX_BESTAETIGT)); s_accessor[4] = new Col4Accessor(); s_accessorMap.put(ZSHORTMSG.COL_LTEXT, new Integer(ZSHORTMSG.IDX_LTEXT)); s_accessor[5] = new Col5Accessor(); s_accessorMap.put(ZSHORTMSG.COL_STATUS, new Integer(ZSHORTMSG.IDX_STATUS)); s_accessor[6] = new Col6Accessor(); s_accessorMap.put(ZSHORTMSG.COL_ERHALTEN, new Integer(ZSHORTMSG.IDX_ERHALTEN)); s_accessor[7] = new Col7Accessor(); s_accessorMap.put(ZSHORTMSG.COL_EINGANG, new Integer(ZSHORTMSG.IDX_EINGANG)); } return s_accessor; } /** * */ private final ZSHORTMSG m_table; // state of cursor private ColAccessor[] m_colMap = null; private RecordSet m_rs; private boolean m_firstRow = true; /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. The * record set is scanned for relevant columns: columns with names (or * aliases) matching an attribute of the receiver are mapped. Other columns * are ignored. *

* This constructor is equivalent to new ZSHORTMSGCursor(row, rs, false). * * @param zshortmsg * @param rs * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZSHORTMSGCursor(ZSHORTMSG row, RecordSet rs) { this(row, rs, false); } /** * Creates a table cursor for the given record set which must have a query * set already. Call {@link #next()} to retrieve the 1st record. * * @param rs * @param selectStar * If true, the record set is assumed to be based on * a complete select on the table TEST, i.e. * "SELECT * FROM ZSHORTMSG WHERE..." in which case the record set's * attributes don't have to be analyzed. If false * the record set is scanned for relevant columns: columns with * names (or aliases) matching an attribute of the receiver are * mapped. Other columns are ignored. * @param row * @throws ApplicationException * Thrown if the primary key is not fully contained in the * record set. */ ZSHORTMSGCursor(ZSHORTMSG row, RecordSet rs, boolean selectStar) { m_table = row; m_rs = rs; int cols = rs.getColumnCount(); m_colMap = new ColAccessor[cols]; if (selectStar) // id-mapping m_colMap = getAccessors(); else { // create record set - table mapping ColAccessor[] accessors = getAccessors(); for (int i = 0; i < cols; i++) { String colName = rs.getColumnName(i).toUpperCase(); Integer columnIndex = (Integer) s_accessorMap.get(colName); if (columnIndex == null) continue; int j = columnIndex.intValue(); m_colMap[i] = accessors[j]; } } } /** * Moves the cursor to the next record and reads all relevant columns from * the new row. The associated {@link ZSHORTMSG} object is refreshed with the * columns from the new record set. * * @return Returns true if there is actually another row. */ public boolean next() { boolean result = m_rs.moveNext(); if (result) { current(); } return result; } /** * Initializes all available values of the associated row object from the * associated record set's current row. The record set is not moved to the * next row. */ public void current() { if (m_firstRow) { m_table.reset(); m_firstRow = false; } for (int i = 0; i < m_colMap.length; i++) { if (m_colMap[i] != null) { m_colMap[i].set(m_table, m_rs, i); } } } /** * Disposes the record set of the cursor. */ public void dispose() { if (m_rs != null) m_rs.dispose(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/adapters/CustomArrayAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; import java.util.List; import android.content.Context; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; public class CustomArrayAdapter extends ArrayAdapter { public CustomArrayAdapter(Context context, int textViewResourceId, List spinnerList) { super(context, textViewResourceId, spinnerList); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return view; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getDropDownView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return view; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/adapters/CustomAutoCompleteItemAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; public class CustomAutoCompleteItemAdapter extends ArrayAdapter { /** * - items for original list passed from activity code. - tempItems for closing original one and do compare with editable character from user - suggestions for actual filter dropdown values */ private List items, tempItems, suggestions; public CustomAutoCompleteItemAdapter(Context context, int textViewResourceId, List items) { super(context, textViewResourceId, items); this.items = items; tempItems = new ArrayList<>(items); suggestions = new ArrayList<>(); } // Affects default (closed) state of the spinner @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); CustomSpinnerItem customSpinner = getItem(position); view.setText(customSpinner.getName()); return view; } @Nullable @Override public CustomSpinnerItem getItem(int position) { return items.get(position); } @Override public int getCount() { return items.size(); } @Override public long getItemId(int position) { return position; } @NonNull @Override public Filter getFilter() { return CustomSpinnerItemFilter; } private Filter CustomSpinnerItemFilter = new Filter() { @Override public CharSequence convertResultToString(Object resultValue) { CustomSpinnerItem CustomSpinnerItem = (CustomSpinnerItem) resultValue; return CustomSpinnerItem.getName(); } @Override protected FilterResults performFiltering(CharSequence charSequence) { if (charSequence != null) { suggestions.clear(); for (CustomSpinnerItem CustomSpinnerItem : tempItems) { if (CustomSpinnerItem.getName().toLowerCase().startsWith(charSequence.toString().toLowerCase())) { suggestions.add(CustomSpinnerItem); } } FilterResults filterResults = new FilterResults(); filterResults.values = suggestions; filterResults.count = suggestions.size(); return filterResults; } else { return new FilterResults(); } } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { ArrayList tempValues = (ArrayList) filterResults.values; if (filterResults != null && filterResults.count > 0) { clear(); for (CustomSpinnerItem CustomSpinnerItemObj : tempValues) { add(CustomSpinnerItemObj); } notifyDataSetChanged(); } else { clear(); notifyDataSetChanged(); } } }; /** * Gets Item Name By Id. * * @param id * @return */ public String getNameById(String id) { for (int i = 0; i < items.size(); i++) { CustomSpinnerItem customSpinner = items.get(i); if (id.equals(customSpinner.getId())) { return customSpinner.getName(); } } return ""; } /** * Gets Item Position By Id. * * @param id * @return */ public int getPositionById(String id) { for (int i = 0; i < items.size(); i++) { CustomSpinnerItem customSpinner = items.get(i); if (id.equals(customSpinner.getId())) { return i; } } return 0; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/adapters/CustomSpinnerAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; import java.util.List; import android.content.Context; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; public class CustomSpinnerAdapter extends ArrayAdapter { private final List spinnerList; private SpinnerTextStyle closedViewTextStyle = SpinnerTextStyle.none(); public CustomSpinnerAdapter(Context context, int textViewResourceId, List spinnerList) { this(context, textViewResourceId, spinnerList, SpinnerTextStyle.none()); } public CustomSpinnerAdapter(Context context, int textViewResourceId, List spinnerList, SpinnerTextStyle closedViewTextStyle) { super(context, textViewResourceId, spinnerList); this.spinnerList = spinnerList; setClosedViewTextStyle(closedViewTextStyle); } // Affects default (closed) state of the spinner @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); closedViewTextStyle.applyTo(view); CustomSpinnerItem customSpinner = spinnerList.get(position); view.setText(customSpinner.getName()); return view; } // Affects opened state of the spinner @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getDropDownView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return view; } public void setClosedViewTextStyle(SpinnerTextStyle closedViewTextStyle) { if (closedViewTextStyle == null) { this.closedViewTextStyle = SpinnerTextStyle.none(); return; } this.closedViewTextStyle = closedViewTextStyle; } /** * Gets Item Position. * * @param input * @return */ public int getPosition(String input) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if (input.equals(customSpinner.getId()) || input.equals(customSpinner.getName())) { return i; } } return 0; } /** * Gets Item Position By Id. * * @param id * @return */ public int getPositionById(String id) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if (id.equals(customSpinner.getId())) { return i; } } return 0; } /** * Gets Item Position By Name. * * @param id * @return */ public int getPositionByName(String name) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if (name.equals(customSpinner.getName())) { return i; } } return 0; } /** * Gets Item Position By Description. * * @param id * @return */ public int getPositionByDescription(String description) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if ((customSpinner.getDescription() != null && description.equals(customSpinner.getDescription()))) { return i; } } return 0; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/adapters/CustomSpinnerItem.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; public class CustomSpinnerItem { private String id; private String name; private String description; public CustomSpinnerItem(String id, String name) { this.id = id; this.name = name; } public CustomSpinnerItem(String id, String name, String description) { this.id = id; this.name = name; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } // to display object as a string in spinner @Override public String toString() { return name; } @Override public boolean equals(Object obj) { if (obj instanceof CustomSpinnerItem) { CustomSpinnerItem c = (CustomSpinnerItem) obj; if (c.getName().equals(name) && c.getId() == id && c.getDescription() == description) { return true; } } return false; } @Override public int hashCode(){ return this.hashCode(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/adapters/SpinnerTextStyle.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; import android.graphics.Typeface; import android.widget.TextView; public class SpinnerTextStyle { private static final SpinnerTextStyle NONE = new SpinnerTextStyle(false, 0, null, 0, 0); private final boolean custom; private final int textColor; private final Typeface typeface; private final int textSizeUnit; private final int textSize; private SpinnerTextStyle(boolean custom, int textColor, Typeface typeface, int textSizeUnit, int textSize) { this.custom = custom; this.textColor = textColor; this.typeface = typeface; this.textSizeUnit = textSizeUnit; this.textSize = textSize; } public static SpinnerTextStyle none() { return NONE; } public static SpinnerTextStyle custom(int textColor, Typeface typeface, int textSizeUnit, int textSize) { return new SpinnerTextStyle(true, textColor, typeface, textSizeUnit, textSize); } public boolean isCustom() { return custom; } public int getTextColor() { return textColor; } public Typeface getTypeface() { return typeface; } public int getTextSizeUnit() { return textSizeUnit; } public int getTextSize() { return textSize; } public void applyTo(TextView view) { if (view == null || !custom) { return; } view.setTextColor(textColor); if (typeface != null) { view.setTypeface(typeface); } view.setTextSize(textSizeUnit, textSize); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/adapters/StepAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.adapters; import com.stepstone.stepper.adapter.AbstractStepAdapter; import com.stepstone.stepper.viewmodel.StepViewModel; import android.content.Context; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.util.StepUtil; public class StepAdapter extends AbstractStepAdapter { private StepUtil[] mStepUtils; public StepAdapter(Context context, StepUtil...stepUtils) { super(context); this.mStepUtils = stepUtils; } public StepUtil createStep(int position) { return mStepUtils[position]; } public StepUtil findStep(int position) { return mStepUtils[position]; } @Override public int getCount() { return mStepUtils.length; } @Override public StepViewModel getViewModel(int position) { return new StepViewModel.Builder(context).setTitle( "Title pos " + position).create(); } @Override public Object instantiateItem(ViewGroup container, int position) { // create view for given position container.addView(mStepUtils[position].getView()); // create step for the position if it does not already exist if (findStep(position) == null) createStep(position); return mStepUtils[position].getView(); }; @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); }; @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/CommonUtilForm.java:   package ch.mfiles.kaba.kolibri.common.forms; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.util.TypedValue; import android.widget.EditText; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; public class CommonUtilForm extends Form { public static Application mCurrentAplicationApp = null; public static void showValidationErrorMessageBox(Application application) { mCurrentAplicationApp.showMessageBox( Messages.getString("validationError"), //$NON-NLS-1$ Messages.getString("error"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_ERROR); //$NON-NLS-1$ } /** * Gets text view. */ public static TextView getTextView(Context context, String text) { TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textView.setText(text); textView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); return textView; } /** * Gets check box. */ public static AppCompatCheckBox getCheckBox(Context context, String text) { AppCompatCheckBox checkBox = new AppCompatCheckBox(context); checkBox.setText(text); checkBox.setContentDescription(text); checkBox.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); checkBox.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return checkBox; } /** * Gets edit text. */ public static EditText getEditText(Context context, String hint, int inputType) { EditText editText = new EditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); if (inputType != 0) { editText.setInputType(inputType); } if (hint != null) { editText.setHint(hint); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); return editText; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/dlg/DialogForm.java:   package ch.mfiles.kaba.kolibri.common.forms.dlg; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.design.widget.Snackbar; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * New Form. */ public abstract class DialogForm extends Form { public static Application app; // don't make this CommonApplication /** * Base class for all Dialog interfaces. The dialog must be called with a * derived class. Derived classes hold a model of the dialog's content. * * @author joerg * */ public static class DialogInterface { private boolean cancelled; /** * @return Returns {@code true} if the dialog was cancelled or the back * button was pressed. */ public boolean isCancelled() { return cancelled; } } private DialogInterface m_dialogInterface = null; /** * The dialog's save action. */ protected ActionCtrl saveButton = null; /** * Sets the Toolbar's navigation icon with a left arrow. If clicked the * Form's {@link #onBackPressed()} method is invoked on the AM thread and * {@link DialogInterface#isCancelled()} will return true. The Form's menu * consists of a sole save action rendered by a disk symbol. *

* Derived classes call this implementation and returen their own View. * * @return Returns null. */ @Override public View onFormLoad(Context context, LayoutInflater inflater) { final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // FIXME: derive from common color scheme // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); // create save action saveButton = addActionCtrl(false, true, 9, "onSavePressed"); //$NON-NLS-1$ setEnableSaveButton(true); return null; } /** * Sets the dialog to cancelled and returns {@link Application#closeForm()}. */ @Override public ApplicationEvent onBackPressed() { if (m_dialogInterface != null) m_dialogInterface.cancelled = true; return app.closeForm(); } /** * Called when the dialog's save action was clicked. *

* Validates the dialog's content using {@link #validate()}. If a validation * error occurred, the causing view is rendered with a reddish background * color (if possible) and the validation message is shown in a SnackBar. * Only if no validation error occurred, the Dialog's { {@link #onSave()} * method is called and the form closed if successful. *

* Derived dialogs use {@link #onSave()} to implement special actions after * validation if the user requested to save the dialog data. * * @return */ protected ApplicationEvent onSavePressed() { KeyboardUtil.closeKeyboard(appman, getView()); // get validation result ValidationResult result = validate(); if (result == null && onSave()) { if (m_dialogInterface != null) m_dialogInterface.cancelled = false; return app.closeForm(); } if (result != null) { Snackbar.make(getView(), result.message, Snackbar.LENGTH_LONG).setCallback(new Snackbar.Callback() { @Override public void onDismissed(Snackbar snackbar, int event) { validationRemoveHighlight(); } }).show(); validationHighlightBadView(result.badView); return null; } validationRemoveHighlight(); return null; } private View m_highlightedView = null; private Drawable m_highlightedViewBackground = null; private TextWatcher m_highlightedViewWatcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if (m_highlightedView == null) return; validationRemoveHighlight(); } }; /** * Highlight the given view (if supported). * * @param view */ protected void validationHighlightBadView(View view) { // make specific views show highlighted if (view instanceof EditText) { EditText editText = (EditText) view; m_highlightedView = editText; m_highlightedViewBackground = editText.getBackground(); // FIXME: derive from common color scheme editText.setBackgroundColor(Color.rgb(255, 190, 190)); editText.removeTextChangedListener(m_highlightedViewWatcher); editText.addTextChangedListener(m_highlightedViewWatcher); } } /** * Removes the hightlight from the currently highligted view (if any). */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) protected void validationRemoveHighlight() { if (m_highlightedView == null) return; // reset background if (m_highlightedViewBackground != null) m_highlightedView.setBackground(m_highlightedViewBackground); m_highlightedView = null; m_highlightedViewBackground = null; } /** * Called when the user performed the save action and no validation error * did occur. *

* This implementation returns always true. * * @return Returns true if the save was successful, * false otherwise. */ protected boolean onSave() { return true; } /** * Result of a dialog validation. * * @author joerg * */ public static class ValidationResult { /** * The first view as seen from top to bottom, left to right, that * doesn't pass validation test. */ public View badView; /** * The message why the validation failed. */ public String message; public ValidationResult(View badView, String message) { this.badView = badView; this.message = message; } } /** * This method gets called, when the user requests to save the dialog's * data. *

* This implementation always returns null indicating a * successful validation. *

* Derived dialogs replace this method to add dialog specific validations. * * @return The result of the validation. */ protected ValidationResult validate() { return null; } /** * Accepts a {@link DialogInterface} to report the user request to the * calling form: save or cancel. *

* Derived classes override this method to get a reference to the derived * dialog specific interface and initialice the dialog accordingly. * * @param The * parameter given on form call must be derived from * {@link DialogInterface}. */ @Override public void onFormCall(Object parameter) { m_dialogInterface = (DialogInterface) parameter; m_dialogInterface.cancelled = false; validationRemoveHighlight(); } public void setEnableSaveButton(boolean enabled) { ImagesUtil imagesUtil = ImagesUtil.getInstance(app); Image saveImage; if (enabled) { saveImage = imagesUtil.getImage(ImagesUtil.Images.SAVE_WHITE, CommonConstants.Images.IMAGE_DPI); } else { saveImage = imagesUtil.getImage(ImagesUtil.Images.SAVE_WHITE_DISABLED, CommonConstants.Images.IMAGE_DPI); } saveButton.setImage(saveImage); saveButton.setEnabled(enabled); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/MaterialSearchForm.java:   package ch.mfiles.kaba.kolibri.common.forms; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.CommonApplication; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.onQueryTextListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.MaterialNumberMaskWatcher; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class MaterialSearchForm extends DialogForm { private static Log log = LogFactory.getLog(MaterialSearchForm.class); public static Application app; // don't make this CommonApplication public MaterialSearchView searchView; public MDEditText nameEditText; public MDEditText numberEditText; public String barcode; protected LinearLayout view; protected LinearLayout middleContentLinearLayout; protected MaterialNumberMaskWatcher materialNumberMaskWatcher; private LinearLayout.LayoutParams numberLayoutParams; private LinearLayout.LayoutParams cameraValueParams; protected void addContentLinearLayout(LinearLayout contentLinearLayout) { this.middleContentLinearLayout.addView(contentLinearLayout); } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setFocusable(true); view.setFocusableInTouchMode(true); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); // create SearchView searchView = new MaterialSearchView(context); searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionClick(int position) { String matnr = searchView.getSuggessionItemList().get(position).getNumber(); String matname = searchView.getSuggessionItemList().get(position).getName(); log.info("select matNo " + matnr); nameEditText.setText(matname); numberEditText.setText(matnr); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); loadMaterialsList(matnr); return true; } @Override public boolean onSuggestionSelect(int position) { return true; } }); searchView.setQueryTextListener(new onQueryTextListener() { @Override public void onQueryTextChange(String query) { loadMaterialsList(query); } }); toolbar.addView(searchView); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); nameEditText = MDEditText.createDefaultEditText(contentLinearLayout, Messages.getString("materialName"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true); //$NON-NLS-1$ nameEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout numberLinearLayout = new LinearLayout(context); numberLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams numberLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); numberLinearLayoutParams.gravity = Gravity.CENTER; numberLinearLayoutParams.width = LayoutParams.MATCH_PARENT; numberLinearLayoutParams.height = LayoutParams.MATCH_PARENT; numberLinearLayoutParams.weight = 1; numberLinearLayout.setLayoutParams(numberLinearLayoutParams); numberEditText = MDEditText.createDefaultEditText(numberLinearLayout, Messages.getString("materialNumber"), InputType.TYPE_CLASS_PHONE, true); //$NON-NLS-1$ numberEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FOURTEEN) }); materialNumberMaskWatcher = new MaterialNumberMaskWatcher(numberEditText); numberEditText.addTextChangedListener(materialNumberMaskWatcher); numberLayoutParams = new LinearLayout.LayoutParams(0, 0); numberLayoutParams.gravity = Gravity.CENTER; numberLayoutParams.width = 0; numberLayoutParams.height = LayoutParams.MATCH_PARENT; numberLayoutParams.weight = 1.0f; numberEditText.getParentTextInputLayout().setLayoutParams(numberLayoutParams); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.0f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); if (result == null) { // app.messageUtil.showMessage(Messages.getString("aborted")); } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { processBarcode(); } }; } }); cameraLinearLayout.addView(gridImageView); numberLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(numberLinearLayout); middleContentLinearLayout = new LinearLayout(context); contentLinearLayout.addView(middleContentLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); loadData(); processBarcode(); return null; } private void processBarcode() { System.out.println("barcode " + barcode); if (barcode != null && !barcode.isEmpty()) { numberEditText.setEnabled(false); String matNoQuery = StringUtil.getMaterialNoFromScan(barcode.trim()); System.out.println("matNoQuery " + matNoQuery); searchView.setQuery(matNoQuery, true); if (searchView.getSuggessionItemList().isEmpty()) { numberEditText.setText(matNoQuery); } barcode = null; } } protected void setEnabledControls(boolean enabled) { searchView.setEnabled(enabled); nameEditText.setEnabled(enabled); numberEditText.setEnabled(enabled); } protected void loadData() { resetView(); } protected void resetView() { if (!numberEditText.isEnabled()) { numberEditText.setEnabled(true); } nameEditText.clearError(); numberEditText.clearError(); nameEditText.clearFocus(); numberEditText.clearFocus(); nameEditText.setText(""); nameEditText.getText().clear(); numberEditText.getText().clear(); numberEditText.setText(""); searchView.setQuery("", false); searchView.clearFocus(); } public boolean isMatrialNumberWrongFormat(){ Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if(numberEditText.getText().length() >= 14 && !numberEditText.getText().toString().isEmpty() && !matcher.matches()) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { return null; } @Override public void runOnUIThread() { numberEditText.setError(Messages.getString("WrongFormatXX-XXXX-XXX/XX")); } }; return true; } return false; } public void setShowScanNumber(boolean isShow) { if (isShow) { numberLayoutParams.weight = 0.9f; cameraValueParams.weight = 0.1f; } } protected void loadMaterialsList(String queryText) { } }     common/src/ch/mfiles/kaba/kolibri/common/forms/Navigation.java:   /** * */ package ch.mfiles.kaba.kolibri.common.forms; import java.util.List; import android.content.Context; import android.support.v4.widget.DrawerLayout; import android.widget.LinearLayout; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm.NavigationMenuListAdapter; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm.NavigationMenuListItem; /** * The Navigation Interface. * * @author nop * */ public interface Navigation { /** * Gets the Context. * * @return */ public Context getContext(); /** * Sets the Context. * * @param context */ public void setContext(Context context); /** * Gets the view. * * @return */ public DrawerLayout getView(); /** * Sets the view. * * @param view */ public void setView(DrawerLayout view); /** * Gets the content view. * * @return */ public LinearLayout getContentView(); /** * Sets the content view. * * @param contentView */ public void setContentView(LinearLayout contentView); /** * Gets the menu list adapter. * * @return */ public NavigationMenuListAdapter getMenuListAdapter(); /** * Sets the menu list adapter. * * @param menuListAdapter */ public void setMenuListAdapter(NavigationMenuListAdapter menuListAdapter); /** * Gets the menu list view. * * @return */ public List getMenuListView(); /** * Sets the menu list view. * * @param menuListView */ public void setMenuListView(List menuListView); /** * On menu item load. * * @param menuListView */ public void onMenuItemLoad(List menuListView); /** * On menu item load. * * @param menuListView */ public void onMenuItemClickListener(ListView menuView); /** * On menu item notify data set changed. * * @param menuListView */ public void onMenuItemNotifyDataSetChanged(); }     common/src/ch/mfiles/kaba/kolibri/common/forms/NavigationForm.java:   package ch.mfiles.kaba.kolibri.common.forms; import java.util.ArrayList; import java.util.List; import android.R.color; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ui.LayoutInflater; public abstract class NavigationForm extends SuperForm implements Navigation { // initialized by the kolibri framework... public static Application app; private Context context; private DrawerLayout view; private LinearLayout contentView; private NavigationMenuListAdapter menuListAdapter; private List menuListView = new ArrayList(); @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // prepare toolbar getToolbar().setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // create content including navigation view view = new DrawerLayout(context); view.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always // show below toolbar view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // create the dialog's view hierarchy, one may use inflation instead contentView = new LinearLayout(context); contentView.setOrientation(LinearLayout.VERTICAL); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); frameLayout.addView(contentView); ListView menuView = new ListView(context); menuView.setDivider(new ColorDrawable(LayoutUtils.DEFAULT_LABEL_COLOR)); menuView.setDividerHeight(1); menuView.setBackgroundColor(Color.WHITE); menuView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); menuView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); onMenuItemClickListener(menuView); menuListAdapter = new NavigationMenuListAdapter(context, menuListView); menuView.setAdapter(menuListAdapter); // link toolbar to drawer layout (creating animated left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null,view,getToolbar(),0,0){ @Override public void onDrawerClosed(View v){ super.onDrawerClosed(v); KeyboardUtil.closeKeyboard(appman, getView()); } @Override public void onDrawerOpened(View v) { super.onDrawerOpened(v); KeyboardUtil.closeKeyboard(appman, getView()); } }; view.addDrawerListener(drawerToggle); drawerToggle.syncState(); onMenuItemLoad(getMenuListView()); // add views to drawer view.addView(frameLayout); view.addView(menuView); return view; } @Override public void onMenuItemClickListener(ListView menuView) { // Auto-generated method stub } @Override public void onMenuItemLoad(List menuListView) { // Auto-generated method stub } @Override public void onMenuItemNotifyDataSetChanged() { menuListAdapter.notifyDataSetChanged(); } @Override public Context getContext() { return context; } @Override public void setContext(Context context) { this.context = context; } @Override public DrawerLayout getView() { return view; } @Override public void setView(DrawerLayout view) { this.view = view; } @Override public LinearLayout getContentView() { return contentView; } @Override public void setContentView(LinearLayout contentView) { this.contentView = contentView; } @Override public NavigationMenuListAdapter getMenuListAdapter() { return menuListAdapter; } @Override public void setMenuListAdapter(NavigationMenuListAdapter menuListAdapter) { this.menuListAdapter = menuListAdapter; } @Override public List getMenuListView() { return menuListView; } @Override public void setMenuListView(List menuListView) { this.menuListView = menuListView; } /** * A item that has an icon on the left, a text and a tag. * * @author nop * */ public static class NavigationMenuListItem { private Drawable icon = null; private String text; private String tag; private boolean enable = true; private OnClickListener onClickListener = null; public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public boolean isEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } public OnClickListener getOnClickListener() { return onClickListener; } public void setOnClickListener(OnClickListener onClickListener) { this.onClickListener = onClickListener; } } public class NavigationMenuListAdapter extends BaseAdapter { private static final int ICON = 7777; private static final int TEXT = 8888; private static final int TAG = 9999; private List mData; private Context context; public NavigationMenuListAdapter(Context context, List coll) { mData = coll; this.context = context; } /** * @see android.widget.Adapter#getCount() */ public int getCount() { return mData.size(); } /** * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return mData.get(position); } /** * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { return position; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { return createView(position, convertView, parent); } private View createView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { LinearLayout rootLayout = new LinearLayout(context); rootLayout.setId(TAG); rootLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams rootLayoutParams = new LinearLayout.LayoutParams(0, 0); rootLayoutParams.width = LayoutParams.MATCH_PARENT; rootLayoutParams.height = LayoutUtils.convertDpToPixel(context, 65); rootLayout.setLayoutParams(rootLayoutParams); rootLayout.setBackgroundColor(color.white); rootLayout.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); LinearLayout leftIconLinearLayout = new LinearLayout(context); leftIconLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; leftIconLinearLayoutParams.width = 0; leftIconLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; leftIconLinearLayoutParams.weight = 0.5f; leftIconLinearLayoutParams.leftMargin = LayoutUtils.convertDpToPixel(context, 10); leftIconLinearLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 10); leftIconLinearLayout.setLayoutParams(leftIconLinearLayoutParams); FrameLayout beginFrameLayout = new FrameLayout(context); LinearLayout.LayoutParams beginFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); beginFrameParams.gravity = Gravity.LEFT; beginFrameLayout.setLayoutParams(beginFrameParams); beginFrameLayout.setBackgroundColor(color.holo_green_light); ImageView icon = new ImageView(context); icon.setId(ICON); icon.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); beginFrameLayout.addView(icon); leftIconLinearLayout.addView(beginFrameLayout); rootLayout.addView(leftIconLinearLayout); LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 2f; midLinearLayout.setLayoutParams(midLinearLayoutParams); TextView titleTextView = new TextView(context); titleTextView.setId(TEXT); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(titleTextView); rootLayout.addView(midLinearLayout); v = rootLayout; } else { v = convertView; } bindView(position, v); return v; } /** * Sets the {@link android.content.res.Resources.Theme} against which * drop-down views are inflated. *

* By default, drop-down views are inflated against the theme of the * {@link Context} passed to the adapter's constructor. * * @param theme * the theme against which to inflate drop-down views or * {@code null} to use the theme from the adapter's context * @see #getDropDownView(int, View, ViewGroup) */ @SuppressLint("NewApi") public void setDropDownViewTheme(Resources.Theme theme) { //Do nothings } public Resources.Theme getDropDownViewTheme() { return null; } private void bindView(int position, View view) { final NavigationMenuListItem dataSet = mData.get(position); if (dataSet == null) { return; } if (null == view) { return; } ImageView icon = (ImageView) view.findViewById(ICON); TextView text = (TextView) view.findViewById(TEXT); LinearLayout root = (LinearLayout) view; if (null != dataSet.getIcon() && icon != null) { icon.setImageDrawable(dataSet.getIcon()); } if (null != dataSet.getText() && text != null) { setViewText(text, dataSet.getText()); if (dataSet.isEnable()) { text.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); } else { text.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); } } if (null != dataSet.getTag()) { root.setTag(dataSet.getTag()); } } /** * Called by bindView() to set the text for a TextView but only if there * is no existing ViewBinder or if the existing ViewBinder cannot handle * binding to a TextView. * * @param v TextView to receive text * @param text the text to be set for the TextView */ public void setViewText(TextView v, String text) { v.setText(text); } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/SuperForm.java:   package ch.mfiles.kaba.kolibri.common.forms; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.graphics.Color; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The super class of all forms within this application. Contains common * members, methods and controls. * */ public class SuperForm extends Form { /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(Context context, LayoutInflater inflater) { ListView listView = new ListView(context); listView.setBackgroundColor(Color.CYAN); listView.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); return listView; } public static void showValidationErrorMessageBox(Application application) { showErrorMessageBox(application, Messages.getString("validationError")); //$NON-NLS-1$ } public static void showErrorMessageBox(Application application, String errorMessage){ application.showMessageBox(errorMessage, Messages.getString("error"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_ERROR); } public static void showWarningMessageBox(Application application, String warningMessage){ application.showMessageBox(warningMessage, Messages.getString("warning"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/AmountEditText.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class AmountEditText extends MDEditText { private static Log log = LogFactory.getLog(AmountEditText.class); private static boolean removeDot; private static AmountEditText editText = null;; public AmountEditText(Context context) { super(context); } public static AmountEditText createDefaultEditText(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); AmountEditText editText = createEditText(context, label, required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private static AmountEditText createEditText(Context context, String label, final boolean required) { editText = new AmountEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SIX) }); // editText.setDirectionRight(false); editText.setGravity(Gravity.RIGHT); if (required) { editText.setRequired(required); } if (label != null) { editText.setHint(label); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, Mode.SRC_ATOP); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { format(); } } }); editText.addTextChangedListener(new TextWatcher() { public int beforeCharSequence; public int afterCharSequence; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } @Override public void afterTextChanged(Editable s) { String value = s.toString().trim(); if (StringUtil.isEmpty(value)) { return; } editText.removeTextChangedListener(this); if(value.contains(" ")) { value = value.replace(" ", ""); } if (beforeCharSequence < afterCharSequence) { if(value.length() >= CommonConstants.MaxLength.THREE) { if(!value.contains(".")) { value = value.substring(0,CommonConstants.MaxLength.THREE) + "." + value.substring(CommonConstants.MaxLength.THREE); } } } editText.setText(value); if (editText.hasFocus()) { editText.clearError(); } editText.addTextChangedListener(this); } }); return editText; } private static void format() { String userInput = editText.getText().toString(); if (!TextUtils.isEmpty(userInput)) { try { Locale locale = Locale.ENGLISH; if (userInput.contains(",")) { userInput = userInput.replace(",", "."); } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(userInput))); if (floatValue > 999.99) { floatValue = (float) 999.99; } if (floatValue < 1) { floatValue = (float) 1; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("###", symbols); format.setMaximumFractionDigits(2); userInput = format.format(floatValue); } catch (NumberFormatException e) { userInput = ""; } catch (ParseException e) { userInput = ""; } } editText.setText(userInput); } public void setText(String text) { setTextAndSelection(text); } public void setLabel(String label) { super.setHint(label); } @Override public String toString() { format(); return super.toString(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/CommissionNumberLayout.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.text.Editable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class CommissionNumberLayout extends LinearLayout { public CommissionNumberLayout(Context context) { super(context); } private Form currentform; private CommissionNumberText commissionNumberText; private LinearLayout cameraLinearLayout; private ImageView cameraImageView; private BitmapDrawable cameraBlack; private BitmapDrawable cameraDisabled; public static CommissionNumberLayout createCommissionNumberText(Application app, Form form, ViewGroup parent, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); CommissionNumberLayout content = new CommissionNumberLayout(context); content.currentform = form; content.cameraBlack = form.getBitmanDrawable(ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI)); content.cameraDisabled = form.getBitmanDrawable(ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.CAMERA_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI)); content.createCommissionNumberText(required); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.addView(content); parent.addView(contentLinearLayout); return content; } private void createCommissionNumberText(final boolean required) { Context context = getContext(); setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams barcodeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLinearLayoutParams.gravity = Gravity.CENTER; barcodeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.weight = 1; setLayoutParams(barcodeLinearLayoutParams); commissionNumberText = CommissionNumberText.createDefaultEditText(this, required); //$NON-NLS-1$ LinearLayout.LayoutParams commissionNumberLayoutParams = new LinearLayout.LayoutParams(0, 0); commissionNumberLayoutParams.gravity = Gravity.CENTER; commissionNumberLayoutParams.width = 0; commissionNumberLayoutParams.height = LayoutParams.MATCH_PARENT; commissionNumberLayoutParams.weight = 0.9f; commissionNumberText.getParentTextInputLayout().setLayoutParams(commissionNumberLayoutParams); cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.1f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); cameraImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); cameraImageView.setLayoutParams(gridImageViewParams); cameraImageView.setImageDrawable(cameraBlack); cameraImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(currentform) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String commissionNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(currentform); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { MessageUtil.getInstance().showMessage(Messages.getString("aborted")); //$NON-NLS-1$ } else { commissionNumber = result.getContents(); commissionNumberText.setText(commissionNumber); } return null; } }; } }); cameraLinearLayout.addView(cameraImageView); addView(cameraLinearLayout); } public CommissionNumberText getCommissionNumberText() { return commissionNumberText; } public Editable commissionNumberText() { return commissionNumberText.getText(); } public void setEnabled(boolean enabled) { super.setEnabled(enabled); commissionNumberText.getParentTextInputLayout().setEnabled(enabled); cameraLinearLayout.setEnabled(enabled); cameraImageView.setEnabled(enabled); cameraImageView.setClickable(enabled); if (!enabled) { commissionNumberText.clearFocus(); } if (enabled) { cameraImageView.setImageDrawable(cameraBlack); } else { cameraImageView.setImageDrawable(cameraDisabled); } } public void setJobTypeAndFormat(JobType jobType, String communicationNumberFormat) { commissionNumberText.setJobTypeAndFormat(jobType, communicationNumberFormat); } public void setRequired(boolean isRequired) { commissionNumberText.setRequired(isRequired); } public void setHint(String hint) { commissionNumberText.getParentTextInputLayout().setHint(hint); } public void setError(String errorMessage) { commissionNumberText.setError(errorMessage); } public void clearError() { commissionNumberText.clearError(); } public void clear() { commissionNumberText().clear(); } public String getCommissionNumber() { return commissionNumberText.getCommissionNumber(); } public void setText(String commissionNumber) { commissionNumberText.setText(commissionNumber); } public boolean isRequired() { return commissionNumberText.isRequired(); } public String getErrorMessage() { return commissionNumberText.getErrorMessage(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/CommissionNumberText.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.Application; public class CommissionNumberText extends MDEditText { private static Log log = LogFactory.getLog(CommissionNumberText.class); private JobType jobType; private String commissionNumberFormat; public CommissionNumberText(Context context) { super(context); } public static CommissionNumberText createDefaultEditText(ViewGroup parent, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); CommissionNumberText editText = new CommissionNumberText(context); editText.initialize(required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private void initialize(final boolean required) { final CommissionNumberText editText = this; editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setRawInputType(InputType.TYPE_TEXT_VARIATION_NORMAL); editText.setHint(Messages.getString("commNo")); if (required) { editText.setRequired(required); } editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { if(hasFocus) { if(jobType.isMON()) { editText.setRawInputType(InputType.TYPE_CLASS_NUMBER); } else { editText.setRawInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } } // new AsyncTask(app.getCurrentForm()) { // // @Override // protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, // TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { // // return null; // } // // @Override // protected void runOnUIThread() { // if (!hasFocus && !editText.isValid()) { // editText.setError(editText.getErrorMessage()); //$NON-NLS-1$ // } else { // editText.clearError(); // } // } // }; } }); editText.addTextChangedListener(new TextWatcher() { private int beforeCharSequence; private int afterCharSequence; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } @Override public void afterTextChanged(Editable s) { String value = s.toString().trim(); if (StringUtil.isEmpty(value) || jobType == null) { return; } if(value.contains(",")) { value = value.replace(",", ""); } if(value.contains(".")) { value = value.replace(".", ""); } if(value.contains(" ")) { value = value.replace(" ", ""); } editText.removeTextChangedListener(this); if(jobType.isMON()) { if (isFormatCH()) { //'CH' 'MON' xxxxxx } else { //'DE' 'MON' xxxxxxxxxx } } else { if (isFormatCH()) { //'CH' 'REP' 'SAV' 0xxxxxx-yy if (!value.startsWith("0")) { //$NON-NLS-1$ value = "0" + value; //$NON-NLS-1$ editText.setText(value); } } //'DE' 'REP' 'SAV' xxxxxxx-yy if (value.length() == CommonConstants.CommissionNumber.DASH_POSITION && beforeCharSequence < afterCharSequence) { value = value + "-"; //$NON-NLS-1$ editText.setText(value); } // check dash position if (value.length() >= CommonConstants.CommissionNumber.DASH_POSITION +1 && value.charAt(CommonConstants.CommissionNumber.DASH_POSITION) != '-' && beforeCharSequence < afterCharSequence) { String temp = value.substring(0, CommonConstants.CommissionNumber.DASH_POSITION); String number = value.substring(CommonConstants.CommissionNumber.DASH_POSITION, value.length()); value = temp + "-" + number; //$NON-NLS-1$ editText.setText(value); } // remove "-" position 0..6 if(value.indexOf('-') != CommonConstants.CommissionNumber.DASH_POSITION || value.endsWith("-")) { value = value.replace("-", ""); } // remove "-" position 8..10 if (value.length() > CommonConstants.CommissionNumber.DASH_POSITION+1) { if(value.charAt(value.length()-1) == '-') { value = value.substring(0, value.length()-1); } } } Pattern pattern = Pattern.compile(getRegx()); Matcher matcher = pattern.matcher(value.trim()); if (matcher.matches() || matcher.hitEnd()) { editText.setText(value.trim()); } if (editText.hasFocus()) { editText.clearError(); } editText.addTextChangedListener(this); } }); editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, Mode.SRC_ATOP); } public void setJobTypeAndFormat(JobType jobType, String commissionNumberFormat) { log.info("jobType " + jobType.toString() + " commissionNumberFormat " + commissionNumberFormat); this.jobType = jobType; this.commissionNumberFormat = commissionNumberFormat; setFilters(new InputFilter[0]); setFilters(new InputFilter[] {new InputFilter.LengthFilter(getCommissionNumberMaxLenght())}); } public boolean isValid() { return isMatch(getText().toString()); } private boolean isMatch(String value) { Pattern pattern = Pattern.compile(getRegx()); Matcher matcher = pattern.matcher(value); return matcher.matches(); } public String getErrorMessage() { String errorMessage = ""; Object[] arguments = new Object[] { getFormat() }; errorMessage = MessageFormat .format(Messages.getString("WrongFormat"), arguments); //$NON-NLS-1$ return errorMessage; } public void setLabel(String label) { setHint(label); } /** * REP, SAV 0xxxxxx-yy x: [0-9] y: [0-9][A-Z] numpad (numeric only) default. *

* MON (CH) xxxxxx x: [0-9] numpad (numeric only) hide the leading 0's leading 0's have to be transmitted to backend → xxxxxxxxxx (x: [0-9]). */ public void setText(String text) { log.info("jobType " + jobType.toString() + " commissionNumberFormat " + commissionNumberFormat + " text " + text); if(jobType.isMON() && isFormatCH() && text.length() > CommonConstants.MaxLength.SIX) { setTextAndSelection(text.substring(text.length()-CommonConstants.MaxLength.SIX)); } else { setTextAndSelection(text); } } /** * MON leading 0's have to be transmitted to backend → xxxxxxxxxx (x: [0-9]). */ public String getCommissionNumber() { if(jobType != null && jobType.isMON() && isFormatCH() && !super.getText().toString().isEmpty()) { String text = super.getText().toString(); log.info("Job type MON commission number -> " + text); StringBuilder builder = new StringBuilder(); if(text.length() < CommonConstants.MaxLength.TEN) { for (int i = 0; i < CommonConstants.MaxLength.TEN - text.length(); i++) { builder.append("0"); } text = builder.toString() + text; log.info("MON leading 0's have to be transmitted to backend → xxxxxxxxxx (x: [0-9]). -> " + text); return text; } } return super.getText().toString(); } private boolean isFormatCH() { return commissionNumberFormat.equalsIgnoreCase(CommonConstants.CommissionNumber.CH); } private String getRegx() { if (isFormatCH()) { if(jobType.isMON()) { return CommonConstants.CommissionNumber.REGX_MON_CH; } else { return CommonConstants.CommissionNumber.REGX_REP_SAV_CH; } } else { if(jobType.isMON()) { return CommonConstants.CommissionNumber.REGX_MON_DE; } else { return CommonConstants.CommissionNumber.REGX_REP_SAV_DE; } } } private int getCommissionNumberMaxLenght() { if(jobType.isMON() && isFormatCH()) { return CommonConstants.MaxLength.SIX; } else { return CommonConstants.MaxLength.TEN; } } private String getFormat() { if (isFormatCH()) { if(jobType.isMON()) { return "XXXXXX"; } else { return "0XXXXXX-YY"; } } else { if(jobType.isMON()) { return "XXXXXXXXXX"; } else { return "0XXXXXX-YY"; } } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/DividerView.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class DividerView extends View { public DividerView(Context context) { super(context); LinearLayout.LayoutParams linearLayoutParam = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); setLayoutParams(linearLayoutParam); TypedArray array = context.getTheme() .obtainStyledAttributes(new int[] {android.R.attr.listDivider}); Drawable draw = array.getDrawable(0); array.recycle(); setBackground(draw); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/ExpenseMaskEditText.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.InputFilter; import android.text.InputType; import android.util.TypedValue; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.ExpenseMaskWatcher; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class ExpenseMaskEditText extends MDEditText { private static Log log = LogFactory.getLog(ExpenseMaskEditText.class); private static boolean removeDot; private static ExpenseMaskEditText editText = null; public ExpenseMaskEditText(Context context) { super(context); } public static ExpenseMaskEditText createDefaultEditText(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); ExpenseMaskEditText editText = createEditText(context, label, required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private static ExpenseMaskEditText createEditText(Context context, String label, final boolean required) { editText = new ExpenseMaskEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); if (required) { editText.setRequired(required); } if (label != null) { editText.setHint(label); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); editText.addTextChangedListener(new ExpenseMaskWatcher(editText)); return editText; } public void setText(String text) { setTextAndSelection(text); } public void setLabel(String label) { super.setHint(label); } public String getValue() { return getText().toString(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/inputmasks/ExpenseMaskWatcher.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.regex.Pattern; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.View.OnFocusChangeListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class ExpenseMaskWatcher extends Watcher { public ExpenseMaskWatcher(final MDEditText editText) { super(editText, Pattern.compile(CommonConstants.TimeSheet.REGEX)); editText.setDirectionRight(true); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String userInput = editText.getText().toString(); if (userInput.length() < 5) { editText.setText(""); return; } else { format(); } } else { String userInput = editText.getText().toString(); String temps[] = userInput.split(" "); if (temps.length > 1 && !TextUtils.isEmpty(temps[1])) { userInput = temps[1]; } editText.setTextAndSelection(userInput); } } }); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if (!editText.isFocused()) { editText.removeTextChangedListener(this); format(); editText.addTextChangedListener(this); } } }); } private void format() { String userInput = editText.getText().toString(); String temps[] = userInput.split(" "); if (temps.length > 1 && !TextUtils.isEmpty(temps[1])) { temps[1] = StringUtil.removeLettersAndCountDot(temps[1], '.'); if (temps[1].isEmpty()) { editText.setText(userInput); } try { Locale locale = Locale.ENGLISH; if (temps[1].contains(",")) { locale = Locale.GERMAN; } float floatValue = Float .valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(temps[1]))); if (floatValue > 999.99) { floatValue = (float) 999.99; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("##0.00", symbols); format.setMaximumFractionDigits(2); if (floatValue > 0) { temps[1] = format.format(floatValue); userInput = temps[0] + " " + temps[1]; } else { userInput = ""; } editText.setText(userInput); } catch (NumberFormatException e) { editText.setText(userInput); } catch (ParseException e) { editText.setText(userInput); } } } @Override public String toString() { format(); return super.toString(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/inputmasks/MaterialNumberMaskWatcher.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.util.regex.Matcher; import java.util.regex.Pattern; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class MaterialNumberMaskWatcher extends Watcher { public MaterialNumberMaskWatcher(final MDEditText materialNumber) { super(materialNumber, Pattern.compile(CommonConstants.Material.REGEX)); } protected void afterTextChanged(String value) { // 45-1234-123/12 if (beforeCharSequence < afterCharSequence) { value = StringUtil.getMaterialNoFromText(value); Matcher matcher = pattern.matcher(value.trim()); if (matcher.matches() || matcher.hitEnd()) { if (!editText.toString().equalsIgnoreCase(value)) { editText.setTextAndSelection(value); } } } if (editText.hasFocus()) { editText.clearError(); } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/inputmasks/VehicleMaskWatcher.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.TextUtils; import android.view.View; import android.view.View.OnFocusChangeListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class VehicleMaskWatcher extends Watcher { public VehicleMaskWatcher(final MDEditText editText) { super(editText, Pattern.compile(CommonConstants.TimeSheet.VEHICLE_REGEX)); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String userInput = editText.getText().toString(); if (!TextUtils.isEmpty(userInput)) { try { Locale locale = Locale.ENGLISH; if (userInput.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(userInput))); if(floatValue > 1999999.9) { floatValue = (float) 1999999.9; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("#######.00", symbols); userInput = format.format(floatValue); } catch (NumberFormatException e) { userInput = ""; } catch (ParseException e) { userInput = ""; } } editText.setTextAndSelection(userInput); } } }); } protected void afterTextChanged(String value) { // 9999999.9 if (beforeCharSequence < afterCharSequence) { if (value.length() == 7 && !StringUtil.findChar(value, '.')) { value = value + "."; //$NON-NLS-1$ editText.setTextAndSelection(value); } } Matcher matcher = pattern.matcher(value); if (!matcher.matches() && !matcher.hitEnd()) { editText.setTextAndSelection(value); } if (editText.hasFocus()) { editText.clearError(); } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/inputmasks/Watcher.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.util.regex.Pattern; import android.text.Editable; import android.text.TextWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; public class Watcher implements TextWatcher{ public int beforeCharSequence; public int afterCharSequence; public MDEditText editText; public Pattern pattern; boolean active = false; public Watcher(final MDEditText editText, Pattern pattern) { this.editText = editText; this.pattern = pattern; } @Override public void afterTextChanged(Editable s) { // materialNumber.removeTextChangedListener(this); if (active) // prevent recursions return; active = true; try { // ... do 'the thing'... including a rather expensive RegEx operation // or even replace the RegEx code by a handmade algorithm afterTextChanged(s.toString()); } finally { active = false; } // materialNumber.addTextChangedListener(this); } protected void afterTextChanged(String text) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/CheckBoxListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class CheckBoxListWidget extends DetailListWidget { public CheckBoxListWidget(Context context) { this(context, null); } public CheckBoxListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public CheckBoxListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public CheckBoxListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new CheckBoxListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/CheckBoxListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class CheckBoxListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_LEFT_CHECK_BOX = 1070; private static final int ID_LEFT_CHECK = 1090; private Context context; public CheckBoxListWidgetAdapter(Context context, List coll) { super(context, coll); mData = coll; this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { FrameLayout frameLayout = new FrameLayout(context); LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); endFrameParams.gravity = Gravity.CENTER | Gravity.CENTER_VERTICAL; frameLayout.setLayoutParams(endFrameParams); FrameLayout.LayoutParams checkBoxParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); checkBoxParams.gravity = Gravity.CENTER ; checkBoxParams.height = 80; checkBoxParams.width = 80; final CheckBox checkBox = new CheckBox(context); checkBox.setId(ID_LEFT_CHECK_BOX); checkBox.setChecked(false); checkBox.setLayoutParams(checkBoxParams); frameLayout.addView(checkBox); FrameLayout.LayoutParams iconParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); iconParams.gravity = Gravity.CENTER ; iconParams.height = 80; iconParams.width = 80; ImageView icon = new ImageView(context); icon.setId(ID_LEFT_CHECK); icon.setLayoutParams(iconParams); frameLayout.addView(icon); return frameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final CheckBoxListWidgetItem dataSet = (CheckBoxListWidgetItem) mData.get(position); if (dataSet == null) { return; } TextView titleTextView = (TextView) view.findViewById(ID_TITLE); TextView lineOneTextView = (TextView) view.findViewById(ID_TEXE_LINE_ONE); TextView lineTwoTextView = (TextView) view.findViewById(ID_TEXE_LINE_TWO); titleTextView.setTextColor(dataSet.getTextColor()); lineOneTextView.setTextColor(dataSet.getTextColor()); lineTwoTextView.setTextColor(dataSet.getTextColor()); CheckBox leftCheckBox = (CheckBox) view.findViewById(ID_LEFT_CHECK_BOX); ImageView imageView = (ImageView) view.findViewById(ID_LEFT_CHECK); if (dataSet.isShowLeftCheckBox()) { leftCheckBox.setVisibility(View.VISIBLE); imageView.setVisibility(View.INVISIBLE); if (null != dataSet.getLeftCheckBoxTag()) { leftCheckBox.setTag(dataSet.getLeftCheckBoxTag()); } leftCheckBox.setOnClickListener(dataSet.getOnClickListener()); leftCheckBox.setFocusable(false); leftCheckBox.setChecked(dataSet.isCheck()); } else { leftCheckBox.setVisibility(View.INVISIBLE); imageView.setVisibility(View.VISIBLE); if (dataSet.getDrawable() != null) { imageView.setImageDrawable(dataSet.getDrawable()); } } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/CheckBoxListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.drawable.Drawable; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class CheckBoxListWidgetItem extends DetailListWidgetItem { private boolean isShowLeftCheckBox; private String leftCheckBoxTag; private boolean isCheck; private Drawable drawable; private int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; public void isShowLeftCheckBox(boolean isShowLeftCheckBox) { this.isShowLeftCheckBox = isShowLeftCheckBox; } public boolean isShowLeftCheckBox() { return isShowLeftCheckBox; } public String getLeftCheckBoxTag() { return leftCheckBoxTag; } public void setLeftCheckBoxTag(String leftCheckBoxTag) { this.leftCheckBoxTag = leftCheckBoxTag; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } public Drawable getDrawable() { return drawable; } public void setDrawable(Drawable drawable) { this.drawable = drawable; } public int getTextColor() { return textColor; } public void setTextColor(int layoutUtils) { this.textColor = layoutUtils; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/DefaultListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class DefaultListWidget extends StatusListWidget { public DefaultListWidget(Context context) { this(context, null); } public DefaultListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public DefaultListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public DefaultListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new DefaultListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/DefaultListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class DefaultListWidgetAdapter extends StatusListWidgetAdapter { private static final int ID_CHECK = 1080; protected Context context; public DefaultListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setRightView(createRightLayout()); return super.getView(position, convertView, parent); } private View createRightLayout() { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; endFrameLayout.setLayoutParams(endFrameParams); endFrameLayout.setBackgroundColor(color.holo_green_light); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setId(ID_BUTTON); imageButton.setContentDescription("Menu"); endFrameLayout.addView(imageButton); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); overlayParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; final CheckBox checkBox = new CheckBox(context); checkBox.setId(ID_CHECK); checkBox.setChecked(false); checkBox.setLayoutParams(overlayParams); endFrameLayout.addView(checkBox); return endFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final DefaultListWidgetItem dataSet = (DefaultListWidgetItem)mData.get(position); if (dataSet == null) { return; } ImageButton imageButton = (ImageButton) view .findViewById(ID_BUTTON); CheckBox checkBox = (CheckBox) view .findViewById(ID_CHECK); if (0 != dataSet.getStatusColor()) { GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(dataSet.getStatusColor()); gradientDrawable.setCornerRadius(LayoutUtils.convertDpToPixel(view.getContext(), 50)); gradientDrawable.setStroke(2, dataSet.getStatusColor()); } if (null == imageButton) { return; } if (dataSet.isShowCheckBox()) { checkBox.setVisibility(View.VISIBLE); imageButton.setVisibility(View.INVISIBLE); checkBox.setOnClickListener(dataSet.getOnClickListener()); checkBox.setFocusable(false); checkBox.setChecked(dataSet.isCheck()); checkBox.setEnabled(dataSet.isEnabledCheckBox()); } else { checkBox.setVisibility(View.INVISIBLE); imageButton.setVisibility(View.VISIBLE); if (null != dataSet.getOnClickListener()) { imageButton.setOnClickListener(dataSet.getOnClickListener()); } imageButton.setFocusable(false); } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/DefaultListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; public class DefaultListWidgetItem extends StatusListWidgetItem { private boolean isShowCheckBox; private boolean isShowMenuIcon; private boolean isEnabledCheckBox = true; private boolean isCheck; public void isShowCheckBox(boolean isShowCheckBox) { this.isShowCheckBox = isShowCheckBox; } public boolean isShowCheckBox() { return this.isShowCheckBox; } public void isShowMenuIcon(boolean isShowMenuIcon) { this.isShowMenuIcon = isShowMenuIcon; } public boolean isShowMenuIcon() { return this.isShowMenuIcon; } public boolean isEnabledCheckBox() { return isEnabledCheckBox; } public void isEnabledCheckBox(boolean isEnabledCheckBox) { this.isEnabledCheckBox = isEnabledCheckBox; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/DetailListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class DetailListWidget extends ListWidget { DetailListWidgetAdapter adapter; List itemCollection = new ArrayList(); public DetailListWidget(Context context) { this(context, null); } public DetailListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public DetailListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public DetailListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); List itemCollection = new ArrayList(); adapter = new DetailListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/DetailListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Typeface; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; @SuppressLint("NewApi") public class DetailListWidgetAdapter extends ListWidgetAdapter { public DetailListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } public static final int ID_HEADER_ITEM = 1001; public static final int ID_TITLE = 1020; public static final int ID_TEXE_LINE_ONE = 1030; public static final int ID_TEXE_LINE_TWO = 1040; public static final int ID_TEXE_LINE_THREE = 1050; public static final int ID_BUTTON = 1060; private View leftView; private View middleView; private View rightView; /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { return createView(position, convertView, parent); } public void setLeftView(View view) { this.leftView = view; } public void setMiddleView(View view) { this.middleView = view; } public void setRightView(View view) { this.rightView = view; } public View createView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { LinearLayout rootLinearLayout = new LinearLayout(context); rootLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout headerTextLayout = new LinearLayout(context); headerTextLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerTextLayout.setOrientation(LinearLayout.HORIZONTAL); headerTextLayout.setGravity(Gravity.CENTER); TextView headerTextView = new TextView(context); headerTextView.setId(ID_HEADER_ITEM); headerTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); headerTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); headerTextLayout.addView(headerTextView); rootLinearLayout.addView(headerTextLayout); LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); contentItemLayout.setBackgroundColor(color.white); contentItemLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); LinearLayout leftIconLinearLayout = new LinearLayout(context); leftIconLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0,0); leftIconLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; leftIconLinearLayoutParams.width = 0; leftIconLinearLayoutParams.height = LayoutParams.FILL_PARENT; leftIconLinearLayoutParams.weight = 0f; leftIconLinearLayout.setLayoutParams(leftIconLinearLayoutParams); if (leftView != null) { leftIconLinearLayoutParams.weight = 0.55f; leftIconLinearLayout.addView(leftView); } contentItemLayout.addView(leftIconLinearLayout); if (middleView != null) { contentItemLayout.addView(middleView); } else { contentItemLayout.addView(createMiddleLayout()); } LinearLayout buttonLinearLayout = new LinearLayout(context); buttonLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams buttonLinearLayoutParams = new LinearLayout.LayoutParams(LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); buttonLinearLayoutParams.gravity = Gravity.CENTER | Gravity.RIGHT; buttonLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; buttonLinearLayout.setLayoutParams(buttonLinearLayoutParams); if (rightView != null) { buttonLinearLayout.addView(rightView); } else { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.RIGHT | Gravity.CENTER_HORIZONTAL; endFrameLayout.setLayoutParams(endFrameParams); endFrameLayout.setBackgroundColor(color.holo_green_light); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setId(ID_BUTTON); endFrameLayout.addView(imageButton); buttonLinearLayout.addView(endFrameLayout); } contentItemLayout.addView(buttonLinearLayout); rootLinearLayout.addView(contentItemLayout); v = rootLinearLayout; } else { v = convertView; } bindView(position, v); return v; } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 3f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(25, 0, 0, 0); TextView titleTextView = new TextView(context); titleTextView.setId(ID_TITLE); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(titleTextView); TextView textLineOneTextView = new TextView(context); textLineOneTextView.setId(ID_TEXE_LINE_ONE); textLineOneTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineOneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineOneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineOneTextView.setEllipsize(TruncateAt.END); textLineOneTextView.setMaxLines(1); textLineOneTextView.setSingleLine(); textLineOneTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(textLineOneTextView); TextView textLineTwoTextView = new TextView(context); textLineTwoTextView.setId(ID_TEXE_LINE_TWO); textLineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineTwoTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(textLineTwoTextView); TextView textLineThreeTextView = new TextView(context); textLineThreeTextView.setId(ID_TEXE_LINE_THREE); textLineThreeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineThreeTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineThreeTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineThreeTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(textLineThreeTextView); return midLinearLayout; } public void bindView(int position, View view) { final DetailListWidgetItem dataSet = (DetailListWidgetItem)mData.get(position); if (dataSet == null) { return; } TextView headerTextView = (TextView) view.findViewById(ID_HEADER_ITEM); TextView titleTextView = (TextView) view.findViewById(ID_TITLE); TextView lineOneTextView = (TextView) view .findViewById(ID_TEXE_LINE_ONE); TextView lineTwoTextView = (TextView) view .findViewById(ID_TEXE_LINE_TWO); TextView lineThreeTextView = (TextView) view .findViewById(ID_TEXE_LINE_THREE); ImageButton imageButton = (ImageButton) view .findViewById(ID_BUTTON); setViewText(titleTextView, dataSet.getTitleText()); setViewText(lineOneTextView, dataSet.getStringLine1()); setViewText(lineTwoTextView, dataSet.getStringLine2()); if (null != lineThreeTextView) { setViewText(lineThreeTextView, dataSet.getStringLine3()); } if (dataSet.isShowEllipInEndOfText()) { titleTextView.setMaxLines(2); lineOneTextView.setMaxLines(1); lineTwoTextView.setMaxLines(1); titleTextView.setEllipsize(TruncateAt.END); lineOneTextView.setEllipsize(TruncateAt.END); lineTwoTextView.setEllipsize(TruncateAt.END); if (null != lineThreeTextView) { lineThreeTextView.setMaxLines(1); lineThreeTextView.setEllipsize(TruncateAt.END); } } if (null == imageButton) { return; } if (null != dataSet.getButtonImage()) { if (null != dataSet.getButtonImageTag()) { imageButton.setTag(dataSet.getButtonImageTag()); } imageButton.setBackground(dataSet.getButtonImage()); if (null != dataSet.getOnClickListener()) { imageButton.setOnClickListener(dataSet.getOnClickListener()); } imageButton.setFocusable(false); imageButton.setVisibility(View.VISIBLE); } else { imageButton.setVisibility(View.INVISIBLE); } if (dataSet.isShowRightLayout()) { LinearLayout linearLayout = (LinearLayout) imageButton.getParent().getParent(); linearLayout.setVisibility(View.VISIBLE); } else { LinearLayout linearLayout = (LinearLayout) imageButton.getParent().getParent(); linearLayout.setVisibility(View.GONE); } if(dataSet.getHeader() == null) { headerTextView.setVisibility(View.GONE); } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/DetailListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.drawable.Drawable; import android.view.View.OnClickListener; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * A item that has an icon on the left, a title, two lines of text and a image * button on the right. * * @author Xin * */ public class DetailListWidgetItem { private String header; private int headerBackgroundColor = LayoutUtils.DEFAULT_LIGHT_GRAY; private Drawable buttonImage = null; private String buttonImageTag; private String titleText; private String stringLine1; private String stringLine2; private String stringLine3; private boolean isShowEllipInTextEnd; private boolean isShowRightLayout = true; private OnClickListener onClickListener = null; private Object data; public String getTitleText() { return titleText; } public void setTitleText(String titleText) { this.titleText = titleText; } public String getStringLine1() { return stringLine1; } public void setStringLine1(String stringLine1) { this.stringLine1 = stringLine1; } public String getStringLine2() { return stringLine2; } public void setStringLine2(String stringLine2) { this.stringLine2 = stringLine2; } public String getStringLine3() { return stringLine3; } public void setStringLine3(String stringLine3) { this.stringLine3 = stringLine3; } public Drawable getButtonImage() { return buttonImage; } public void setButtonImage(Drawable buttonImage) { this.buttonImage = buttonImage; } public String getButtonImageTag() { return buttonImageTag; } public void setButtonImageTag(String buttonImageTag) { this.buttonImageTag = buttonImageTag; } public void isShowEllipInTextEnd(boolean isShowEllipInTextEnd) { this.isShowEllipInTextEnd = isShowEllipInTextEnd; } public boolean isShowEllipInEndOfText() { return isShowEllipInTextEnd; } public boolean isShowRightLayout() { return isShowRightLayout; } public void isShowRightLayout(boolean isShowRightLayout) { this.isShowRightLayout = isShowRightLayout; } public OnClickListener getOnClickListener() { return onClickListener; } public void setOnClickListener(OnClickListener onClickListener) { this.onClickListener = onClickListener; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public int getHeaderBackgroundColor() { return headerBackgroundColor; } public void setHeaderBackgroundColor(int headerBackgroundColor) { this.headerBackgroundColor = headerBackgroundColor; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/ImageListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class ImageListWidget extends ListWidget { public ImageListWidget(Context context) { this(context, null); } public ImageListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public ImageListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public ImageListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new ImageListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/ImageListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class ImageListWidgetAdapter extends ListWidgetAdapter { public static final int ID_DESCRIPTION = 2090; public static final int ID_TYPE = 2100; public static final int ID_STATUS = 2105; public static final int ID_IMAGE = 2110; public ImageListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { return createView(position, convertView, parent); } public View createView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { LinearLayout rootLinearLayout = new LinearLayout(context); rootLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); contentItemLayout.setBackgroundColor(color.white); contentItemLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING , LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING , LayoutUtils.DEFAULT_MIN_PADDING); contentItemLayout.addView(createMiddleLayout()); int height = 160; int width = 240; FrameLayout endFrameLayout = new FrameLayout(context); endFrameLayout.setBackgroundColor(color.holo_green_light); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); overlayParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL; overlayParams.height = height; overlayParams.width = width; endFrameLayout.setLayoutParams(overlayParams); ImageView image = new ImageView(context); image.setId(ID_IMAGE); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMinimumHeight(height); image.setMaxHeight(height); image.setMaxWidth(width); endFrameLayout.addView(image); contentItemLayout.addView(endFrameLayout); rootLinearLayout.addView(contentItemLayout); v = rootLinearLayout; } else { v = convertView; } bindView(position, v); return v; } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 2.5f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(5, 5, 5, 5); TextView descriptionTextView = new TextView(context); descriptionTextView.setId(ID_DESCRIPTION); descriptionTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); descriptionTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); descriptionTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); descriptionTextView.setEllipsize(TruncateAt.END); descriptionTextView.setMaxLines(3); midLinearLayout.addView(descriptionTextView); TextView typeTextView = new TextView(context); typeTextView.setId(ID_TYPE); typeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); typeTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); typeTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); typeTextView.setMaxLines(1); typeTextView.setSingleLine(); typeTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(typeTextView); TextView statusTextView = new TextView(context); statusTextView.setId(ID_STATUS); statusTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); statusTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); statusTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); statusTextView.setMaxLines(1); statusTextView.setSingleLine(); statusTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(statusTextView); return midLinearLayout; } public void bindView(int position, View view) { final ImageListWidgetItem dataSet = (ImageListWidgetItem)mData.get(position); if (dataSet == null) { return; } TextView desTextView = (TextView) view .findViewById(ID_DESCRIPTION); TextView typeTextView = (TextView) view .findViewById(ID_TYPE); TextView statusTextView = (TextView) view .findViewById(ID_STATUS); ImageView image = (ImageView) view .findViewById(ID_IMAGE); setViewText(desTextView, dataSet.getDescription()); setViewText(typeTextView, dataSet.getType()); setViewText(statusTextView, dataSet.getStatus()); if (null != dataSet.getImageBitmap()) { image.setImageBitmap(dataSet.getImageBitmap()); if (null != dataSet.getOnClickListener()) { image.setOnClickListener(dataSet.getOnClickListener()); } } desTextView.setMaxLines(2); typeTextView.setEllipsize(TruncateAt.END); statusTextView.setEllipsize(TruncateAt.END); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/ImageListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.Bitmap; public class ImageListWidgetItem extends DetailListWidgetItem{ private String description; private String type; private String status; private Bitmap imageBitmap; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Bitmap getImageBitmap() { return imageBitmap; } public void setImageBitmap(Bitmap imageBitmap) { this.imageBitmap = imageBitmap; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/ListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class ListWidget extends ListView { ListWidgetAdapter adapter; List itemCollection = new ArrayList(); public ListWidget(Context context) { this(context, null); } public ListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public ListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public ListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); adapter = new ListWidgetAdapter(context, itemCollection); this.setAdapter(adapter); } public void clean(){ itemCollection.clear(); adapter.notifyDataSetChanged(); } public void addItem(DetailListWidgetItem item){ itemCollection.add(item); adapter.notifyDataSetChanged(); } public void addItems(List items){ itemCollection.addAll(items); adapter.notifyDataSetChanged(); } public List getItems() { return itemCollection; } public void removeItem(int position){ itemCollection.remove(position); adapter.notifyDataSetChanged(); } public ListWidgetAdapter getAdapter() { return adapter; } public void setListWidgetAdapterAndCollection(ListWidgetAdapter adapter, List itemCollection) { this.adapter = adapter; this.itemCollection = itemCollection; } private OverScrollListener mOverScrollListener = null; @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { super.onOverScrolled(scrollX, scrollY, clampedX, clampedY); if (null != mOverScrollListener) { mOverScrollListener.onOverScrolled(scrollX, scrollY, clampedX, clampedY); } } public void setOnOverScrollListener(OverScrollListener listener) { mOverScrollListener = listener; } public interface OverScrollListener { void onOverScrolled(int scrollx, int scrollY, boolean clampedX, boolean clampedY); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/ListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.StringUtil; @SuppressLint("NewApi") public class ListWidgetAdapter extends BaseAdapter implements Filterable { public List mData; public List mDataTemp; public Context context; /** * Constructor * * @param context * The context where the View associated with this SimpleAdapter * is running * @param data * A List of Maps. Each entry in the List corresponds to one row * in the list. The Maps contain the data for each row, and * should include all the entries specified in "from" * @param resource * Resource identifier of a view layout that defines the views * for this list item. The layout file should include at least * those named views defined in "to" * @param from * A list of column names that will be added to the Map * associated with each item. * @param to * The views that should display column in the "from" parameter. * These should all be TextViews. The first N views in this list * are given the values of the first N columns in the from * parameter. */ public ListWidgetAdapter(Context context, List coll) { mData = coll; mDataTemp = coll; this.context = context; } /** * @see android.widget.Adapter#getCount() */ public int getCount() { return mData.size(); } /** * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return mData.get(position); } /** * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { return position; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { return null; } /** * Sets the {@link android.content.res.Resources.Theme} against which * drop-down views are inflated. *

* By default, drop-down views are inflated against the theme of the * {@link Context} passed to the adapter's constructor. * * @param theme * the theme against which to inflate drop-down views or * {@code null} to use the theme from the adapter's context * @see #getDropDownView(int, View, ViewGroup) */ @SuppressLint("NewApi") public void setDropDownViewTheme(Resources.Theme theme) { // New API } public Resources.Theme getDropDownViewTheme() { return null; } /** * Called by bindView() to set the text for a TextView but only if there is * no existing ViewBinder or if the existing ViewBinder cannot handle * binding to a TextView. * * @param v * TextView to receive text * @param text * the text to be set for the TextView */ public void setViewText(TextView v, String text) { v.setText(text); } public Filter getFilter() { return new ListWidgetAdapterFilter(); } /** * This class can be used by external clients of SimpleAdapter to bind * values to views. * * You should use this class to bind values to views that are not directly * supported by SimpleAdapter or to change the way binding occurs for views * supported by SimpleAdapter. * * @see SimpleAdapter#setViewImage(ImageView, int) * @see SimpleAdapter#setViewImage(ImageView, String) * @see SimpleAdapter#setViewText(TextView, String) */ public static interface ViewBinder { /** * Binds the specified data to the specified view. * * When binding is handled by this ViewBinder, this method must return * true. If this method returns false, SimpleAdapter will attempts to * handle the binding on its own. * * @param view * the view to bind the data to * @param data * the data to bind to the view * @param textRepresentation * a safe String representation of the supplied data: it is * either the result of data.toString() or an empty String * but it is never null * * @return true if the data was bound to the view, false otherwise */ boolean setViewValue(View view, Object data, String textRepresentation); } /** * The Filter For ListWidgetAdapter. * * @author nop */ private class ListWidgetAdapterFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { String queryTextLowerCase = constraint.toString().toLowerCase(); FilterResults results = new FilterResults(); ArrayList tempList = new ArrayList(); if (mData == null) { mData = new ArrayList(); } if (StringUtil.isNotEmpty(queryTextLowerCase)) { for (DetailListWidgetItem item : mDataTemp) { String content = (item.getTitleText() + item.getStringLine1() + item.getStringLine2()).toLowerCase(); if (content.contains(queryTextLowerCase)) { tempList.add(item); } } results.values = tempList; results.count = tempList.size(); } else { // add all objects synchronized (this) { results.values = mDataTemp; results.count = mDataTemp.size(); } } return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence contraint, FilterResults results) { mData = (ArrayList) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/MaterialListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class MaterialListWidget extends DetailListWidget { public MaterialListWidget(Context context) { this(context, null); } public MaterialListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public MaterialListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public MaterialListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new MaterialListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/MaterialListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.support.v7.widget.GridLayout; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class MaterialListWidgetAdapter extends DefaultListWidgetAdapter { public static final int ID_TEXT_PRICE = 2030; public static final int ID_TEXT_REPLACEMENT = 2035; public MaterialListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setMiddleView(createMiddleLayout()); return super.getView(position, convertView, parent); } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 3f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(25, 0, 0, 0); TextView titleTextView = new TextView(context); titleTextView.setId(ID_TITLE); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(titleTextView); GridLayout lineOneGridLayout = new GridLayout(context); RelativeLayout.LayoutParams lineOneGridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); lineOneGridLayoutParams.leftMargin = 0; lineOneGridLayoutParams.setMargins(0, 0, 0, 0); lineOneGridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); lineOneGridLayout.setLayoutParams(lineOneGridLayoutParams); lineOneGridLayout.setColumnCount(2); lineOneGridLayout.setUseDefaultMargins(true); TextView lineOneTextView = new TextView(context); lineOneTextView.setId(ID_TEXE_LINE_ONE); lineOneTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineOneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); lineOneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); lineOneTextView.setEllipsize(TruncateAt.END); lineOneTextView.setMaxLines(1); lineOneTextView.setSingleLine(); GridLayout.LayoutParams gridLayoutLineOneTextViewParams = new GridLayout.LayoutParams(); gridLayoutLineOneTextViewParams.width = 0; gridLayoutLineOneTextViewParams.height = LayoutParams.WRAP_CONTENT; gridLayoutLineOneTextViewParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.5f); lineOneTextView.setLayoutParams(gridLayoutLineOneTextViewParams); lineOneGridLayout.addView(lineOneTextView); RelativeLayout gridRelativeLayout = new RelativeLayout(lineOneGridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.5f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView lineOneColumnTwoTextView = new TextView(context); lineOneColumnTwoTextView.setId(ID_TEXT_PRICE); lineOneColumnTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineOneColumnTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); lineOneColumnTwoTextView.setLayoutParams(gridTextViewValueParams); gridRelativeLayout.addView(lineOneColumnTwoTextView); lineOneGridLayout.addView(gridRelativeLayout); midLinearLayout.addView(lineOneGridLayout); TextView lineTwoTextView = new TextView(context); lineTwoTextView.setId(ID_TEXE_LINE_TWO); lineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); lineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); lineTwoTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(lineTwoTextView); TextView lineThreeTextView = new TextView(context); lineThreeTextView.setId(ID_TEXT_REPLACEMENT); lineThreeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineThreeTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); lineThreeTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); lineThreeTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(lineThreeTextView); return midLinearLayout; } public void bindView(int position, View view) { super.bindView(position, view); final MaterialListWidgetItem dataSet = (MaterialListWidgetItem)mData.get(position); if (dataSet == null) { return; } TextView priceTextView = (TextView) view.findViewById(ID_TEXT_PRICE); priceTextView.setText(dataSet.getStringPrice()); TextView replaceMentTextView = (TextView) view.findViewById(ID_TEXT_REPLACEMENT); String replacement = dataSet.getReplacement(); if (replacement.isEmpty()) { replaceMentTextView.setVisibility(View.INVISIBLE); } else { replaceMentTextView.setVisibility(View.VISIBLE); replaceMentTextView.setText(replacement); } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/MaterialListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; public class MaterialListWidgetItem extends DefaultListWidgetItem{ private String stringPrice; private String replacement; public String getStringPrice() { return stringPrice; } public void setStringPrice(String stringPrice) { this.stringPrice = stringPrice; } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/RadioButtonListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class RadioButtonListWidget extends DetailListWidget { public RadioButtonListWidget(Context context) { this(context, null); } public RadioButtonListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public RadioButtonListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } @Override public void setChoiceMode(int choiceMode) { super.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } public RadioButtonListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); List itemCollection = new ArrayList(); adapter = new RadioButtonListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/RadioButtonListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RadioButton; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class RadioButtonListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_LEFT_RADIO = 1200; private Context context; public RadioButtonListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { FrameLayout endFrameLayout = new FrameLayout(context); LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; endFrameLayout.setLayoutParams(endFrameParams); final RadioButton radioButton = new RadioButton(context); radioButton.setId(ID_LEFT_RADIO); radioButton.setChecked(false); endFrameLayout.addView(radioButton); return endFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final RadioButtonListWidgetItem dataSet = (RadioButtonListWidgetItem) mData.get(position); if (dataSet == null) { return; } RadioButton leftRadioButton = (RadioButton) view.findViewById(ID_LEFT_RADIO); if (null != dataSet.getLeftRadioButtonTag()) { leftRadioButton.setTag(dataSet.getLeftRadioButtonTag()); } leftRadioButton.setOnClickListener(dataSet.getOnClickListener()); leftRadioButton.setFocusable(false); leftRadioButton.setChecked(dataSet.isCheck()); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/RadioButtonListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; public class RadioButtonListWidgetItem extends DetailListWidgetItem { private String leftRadioButtonTag; private boolean isCheck; public String getLeftRadioButtonTag() { return leftRadioButtonTag; } public void setLeftRadioButtonTag(String leftRadioButtonTag) { this.leftRadioButtonTag = leftRadioButtonTag; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/StatusListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class StatusListWidget extends DetailListWidget { public StatusListWidget(Context context) { this(context, null); } public StatusListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public StatusListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public StatusListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new StatusListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/StatusListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class StatusListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_BACKGROUND_ICON = 1000; private static final int ID_STATUS_TEXT = 1010; private static final int ID_OVERLAY_ICON = 1011; private Context context; public StatusListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { FrameLayout beginFrameLayout = new FrameLayout(context); LinearLayout.LayoutParams beginFrameParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); beginFrameParams.gravity = Gravity.LEFT; beginFrameLayout.setLayoutParams(beginFrameParams); beginFrameLayout.setBackgroundColor(color.holo_green_light); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams(LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL ; ImageView backgroundIcon = new ImageView(context); backgroundIcon.setId(ID_BACKGROUND_ICON); backgroundIcon.setLayoutParams(backgroundIconParams); backgroundIcon.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); beginFrameLayout.addView(backgroundIcon); FrameLayout.LayoutParams statusTextParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); statusTextParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL ; TextView statusText = new TextView(context); statusText.setId(ID_STATUS_TEXT); statusText.setLayoutParams(statusTextParams); statusText.setTextColor(Color.WHITE); statusText.setTypeface(CommonConstants.Font.getDefaultMediumFont()); beginFrameLayout.addView(statusText); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); overlayParams.gravity = Gravity.LEFT | Gravity.TOP; // overlayParams.leftMargin = -10; // overlayParams.topMargin = -10; overlayParams.height = 40; overlayParams.width = 40; ImageView overlayIcon = new ImageView(context); overlayIcon.setId(ID_OVERLAY_ICON); overlayIcon.setLayoutParams(overlayParams); beginFrameLayout.addView(overlayIcon); return beginFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final StatusListWidgetItem dataSet = (StatusListWidgetItem)mData.get(position); if (dataSet == null) { return; } ImageView backgroundIcon = (ImageView) view.findViewById(ID_BACKGROUND_ICON); ImageView overlayIcon = (ImageView) view.findViewById(ID_OVERLAY_ICON); TextView statusText = (TextView) view.findViewById(ID_STATUS_TEXT); ImageButton imageButton = (ImageButton) view .findViewById(ID_BUTTON); if (0 != dataSet.getStatusColor()) { GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(dataSet.getStatusColor()); gradientDrawable.setCornerRadius(LayoutUtils.convertDpToPixel(view.getContext(), 50)); gradientDrawable.setStroke(2, dataSet.getStatusColor()); backgroundIcon.setBackground(gradientDrawable); } if (null != dataSet.getStatusType()) { statusText.setText(dataSet.getStatusType()); } if (null != dataSet.getOverlayIcon()) { overlayIcon.setVisibility(View.VISIBLE); overlayIcon.setBackground(dataSet.getOverlayIcon()); } else { overlayIcon.setVisibility(View.INVISIBLE); } if (null == imageButton) { return; } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/StatusListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.drawable.BitmapDrawable; public class StatusListWidgetItem extends DetailListWidgetItem { private int statusColor; private String statusType = null; private BitmapDrawable overlayImage; public int getStatusColor() { return statusColor; } public void setStatusColor(int backgroundIcon) { this.statusColor = backgroundIcon; } public String getStatusType() { return statusType; } public void setStatusType(String statusType) { this.statusType = statusType; } public BitmapDrawable getOverlayIcon() { return overlayImage; } public void setOverlayIcon(BitmapDrawable bitmapDrawable) { this.overlayImage = bitmapDrawable; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/TimeListWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * */ public class TimeListWidget extends DetailListWidget { public TimeListWidget(Context context) { this(context, null); } public TimeListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public TimeListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public TimeListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new TimeListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/TimeListWidgetAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class TimeListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_Date_Title = 1090; private static final int ID_Date_Text = 1100; private Context context; public TimeListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); setRightView(createRightLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams buttonLinearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); buttonLinearLayoutParams.gravity = Gravity.TOP; // buttonLinearLayoutParams.width = 0; buttonLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; buttonLinearLayoutParams.weight = 0.75f; midLinearLayout.setLayoutParams(buttonLinearLayoutParams); LinearLayout headerTextLayout = new LinearLayout(context); headerTextLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerTextLayout.setOrientation(LinearLayout.HORIZONTAL); headerTextLayout.setGravity(Gravity.TOP); TextView headerTextView = new TextView(context); headerTextView.setId(ID_Date_Title); headerTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); headerTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); headerTextView.setPadding(0, -5, 0, 0); headerTextLayout.addView(headerTextView); midLinearLayout.addView(headerTextLayout); LinearLayout textLineTwoTextLayout = new LinearLayout(context); textLineTwoTextLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); textLineTwoTextLayout.setOrientation(LinearLayout.HORIZONTAL); textLineTwoTextLayout.setGravity(Gravity.VERTICAL_GRAVITY_MASK); TextView textLineTwoTextView = new TextView(context); textLineTwoTextView.setId(ID_Date_Text); textLineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineTwoTextLayout.addView(textLineTwoTextView); midLinearLayout.addView(textLineTwoTextLayout); return midLinearLayout; } private View createRightLayout() { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL; endFrameLayout.setLayoutParams(endFrameParams); endFrameLayout.setBackgroundColor(color.holo_green_light); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setId(ID_BUTTON); endFrameLayout.addView(imageButton); return endFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final TimeListWidgetItem dataSet = (TimeListWidgetItem) mData.get(position); if (dataSet == null) { return; } TextView titleTextView = (TextView) view.findViewById(ID_TITLE); TextView lineOneTextView = (TextView) view.findViewById(ID_TEXE_LINE_ONE); TextView lineTwoTextView = (TextView) view.findViewById(ID_TEXE_LINE_TWO); TextView headerTextView = (TextView) view.findViewById(ID_HEADER_ITEM); TextView dateTitleTextView = (TextView) view.findViewById(ID_Date_Title); TextView dateTextTextView = (TextView) view .findViewById(ID_Date_Text); lineTwoTextView.setVisibility(View.GONE); setViewText(dateTitleTextView, dataSet.getDateTitle()); setViewText(dateTextTextView, dataSet.getDateText()); dateTitleTextView.setTextColor(dataSet.getTextColor()); dateTextTextView.setTextColor(dataSet.getTextColor()); titleTextView.setTextColor(dataSet.getTextColor()); lineOneTextView.setTextColor(dataSet.getTextColor()); if(dataSet.getHeader() != null) { headerTextView.setVisibility(View.VISIBLE); setViewText(headerTextView, dataSet.getHeader()); ((LinearLayout) headerTextView.getParent()).setBackgroundColor(dataSet.getHeaderBackgroundColor()); } LinearLayout rootLayout = ((LinearLayout) ((LinearLayout) lineOneTextView.getParent()).getParent()); rootLayout.setBackgroundColor(dataSet.getBackgroundColor()); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/lists/TimeListWidgetItem.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class TimeListWidgetItem extends DetailListWidgetItem { private String dateTitle; private String dateText; private int backgroundColor; private int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; public String getDateTitle() { return dateTitle; } public void setDateTitle(String dateTitle) { this.dateTitle = dateTitle; } public String getDateText() { return dateText; } public void setDateText(String dateText) { this.dateText = dateText; } public int getTextColor() { return textColor; } public void setTextColor(int layoutUtils) { this.textColor = layoutUtils; } public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; } public int getBackgroundColor() { return backgroundColor; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MaterialSearchView.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Color; import android.provider.BaseColumns; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.Messages; public class MaterialSearchView extends SearchView { private SimpleCursorAdapter searchViewAdapter; private List suggessionList = new ArrayList(); private OnSuggestionListener onSuggestionListener; private onQueryTextListener queryTextListener; public MaterialSearchView(Context context) { super(context); // create SearchView setLayoutParams(new Toolbar.LayoutParams(Gravity.RIGHT)); setQueryHint(Messages.getString("search")); //$NON-NLS-1$ setFocusableInTouchMode(true); final String[] from = new String[] { "matNo", "matName" }; //$NON-NLS-1$ final int[] to = {android.R.id.text1, android.R.id.text2}; searchViewAdapter = new MyCursorAdapter(context, android.R.layout.simple_list_item_2, null , from, to, 0); setSuggestionsAdapter(searchViewAdapter); setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String query) { queryTextListener.onQueryTextChange(query); final MatrixCursor c = new MatrixCursor(new String[] { BaseColumns._ID, "matNo", "matName" }); //$NON-NLS-1$ for (int i = 0; i < suggessionList.size(); i++) { c.addRow(new Object[] { i, suggessionList.get(i).getNumber() , suggessionList.get(i).getName()}); } searchViewAdapter.changeCursor(c); if (suggessionList.size() == 1) { onSuggestionListener.onSuggestionClick(0); clearFocus(); setQuery("", false); //$NON-NLS-1$ } return true; } }); } @Override public void setOnSuggestionListener(OnSuggestionListener onSuggestionListener) { this.onSuggestionListener = onSuggestionListener; super.setOnSuggestionListener(onSuggestionListener); } public List getSuggessionItemList() { return suggessionList; } public void setQueryTextListener(onQueryTextListener queryTextListener) { this.queryTextListener = queryTextListener; } public interface onQueryTextListener { void onQueryTextChange(String query); } public static class SuggessionItem { private String number; private String name; public SuggessionItem(String number, String name) { setName(name); setNumber(number); } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } } private class MyCursorAdapter extends SimpleCursorAdapter{ public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) { super(context, layout, c, from, to, flags); } @Override public View getView(int position, View convertView, ViewGroup parent) { //get reference to the row View view = super.getView(position, convertView, parent); //check for odd or even to set alternate colors to the row background if(position % 2 == 0){ view.setBackgroundColor(Color.rgb(238, 233, 233)); } else { view.setBackgroundColor(Color.rgb(255, 255, 255)); } return view; } } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDAutoComplete.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatAutoCompleteTextView; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextWatcher; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomAutoCompleteItemAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * A view for easy creation and use of an {@link EditText} that is embedded in a * {@link TextInputLayout} which is the way input fields are created in Material * design. * * @author cyu */ public class MDAutoComplete extends AppCompatAutoCompleteTextView { private static Log log = LogFactory.getLog(MDAutoComplete.class); /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, boolean required) { return createDefaultAutoCompleteText(context, null, required); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, boolean required, TextWatcher textWatcher) { return createDefaultAutoCompleteText(context, null, required, textWatcher); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, boolean required) { return createDefaultAutoCompleteText(context, label, 0, required); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, boolean required, TextWatcher textWatcher) { return createDefaultAutoCompleteText(context, label, 0, required, textWatcher); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, int inputType, boolean required) { return createAutoCompleteText(context, label, inputType, required, null); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, int inputType, boolean required, TextWatcher textWatcher) { return createAutoCompleteText(context, label, inputType, required, textWatcher); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(ViewGroup parent, String label, int inputType, boolean required) { return createDefaultAutoCompleteText(parent, label, inputType, required, null); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(ViewGroup parent, String label, int inputType, boolean required, TextWatcher textWatcher) { if (parent == null) { return null; } Context context = parent.getContext(); MDAutoComplete editText = createAutoCompleteText(context, label, inputType, required, textWatcher); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } public MDAutoComplete(Context context) { super(context); InputFilter filter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { int type = Character.getType(source.charAt(i)); if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) { return ""; } } return null; } }; setFilters(new InputFilter[] { filter }); } public static TextInputLayout getTextInputLayout(MDAutoComplete editText) { TextInputLayout textInputLayout = new TextInputLayout(editText.getContext()); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); return textInputLayout; } private static MDAutoComplete createAutoCompleteText(Context context, final String label, final int inputType, boolean required, TextWatcher textWatcher) { final MDAutoComplete editText = new MDAutoComplete(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); if (inputType != 0) { editText.setInputType(inputType); } if (label != null) { editText.setHint(label); } if (required) { editText.setRequired(required); } if (textWatcher != null) { editText.addTextChangedListener(textWatcher); } else { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Auto-generated method stub } @Override public void afterTextChanged(Editable s) { editText.clearError(); } }); } editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (editText.getEditableText().toString().isEmpty()) { editText.showDropDown(); } } else { if (editText.getSelectedId().isEmpty()) { editText.getEditableText().clear(); } } } }); editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, // Mode.SRC_ATOP); return editText; } /** * Sets the error on the embedding {@link TextInputLayout} if it is the parent * of the receiver by calling {@link TextInputLayout#setError(CharSequence)}. * * @param error The error message to set or null to remove the * error text by calling * {@link TextInputLayout#setErrorEnabled(boolean)} with * false. */ @Override public void setError(CharSequence error) { TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { textInputLayout.setError(error); if (error == null) textInputLayout.setErrorEnabled(false); return; } super.setError(error); } /** * Returns the {@link TextInputLayout} in the views hierarchy or * null if the view is not wrapped within such a layout. * * @return */ public TextInputLayout getParentTextInputLayout() { ViewParent parent = getParent(); while (parent != null) { if (parent instanceof TextInputLayout) return (TextInputLayout) parent; parent = parent.getParent(); } return null; } /** * Clears an error. */ public void clearError() { setError(null); } private boolean required = false; /** * Adds an asterisk to the hint that was set to the receiver marking the input * field as 'required'. * * @param required */ public void setRequired(boolean required) { this.required = required; TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { String hint = textInputLayout.getHint().toString().replaceAll(" \\*", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (required) { hint = hint + " *"; //$NON-NLS-1$ } textInputLayout.setHint(hint); } } /** * Adds an asterisk to the hint that was set using * {@link MDAutoComplete#setText(CharSequence)} if {@link #setRequired(boolean)} was * set to true. * * @return */ @Override public CharSequence getHint() { return required ? super.getHint() + " *" : super.getHint(); //$NON-NLS-1$ } /** * Is required. * * @return */ public boolean isRequired() { return required; // $NON-NLS-1$ } @Override public void setEnabled(boolean enabled) { setFocusable(enabled); setClickable(enabled); setFocusableInTouchMode(enabled); super.setEnabled(enabled); // set Enabled/Disabled style. int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; if (!enabled) { textColor = LayoutUtils.DEFAULT_DISABLED_COLOR; } setTextColor(textColor); } @Override public void setFilters(InputFilter[] filters) { super.setFilters(filters); } /** * Gets selected item id. * * @return */ public String getSelectedId() { return this.selectedCustomSpinnerItem == null? "":this.selectedCustomSpinnerItem.getId(); } private CustomSpinnerItem selectedCustomSpinnerItem; private void setSelected(CustomSpinnerItem customSpinnerItem) { this.selectedCustomSpinnerItem = customSpinnerItem; } /** * Sets contents. * * @param list */ public void setContents(List list) { List customSpinnerItemList = new ArrayList(); if (list != null && list.isEmpty()) { customSpinnerItemList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, "")); } else { for (int i = 0; i < list.size(); i++) { CustomSpinnerItem item = list.get(i); if (item.getName().startsWith("Bitte w") && item.getName().endsWith("...")) { list.remove(item); if(customSpinnerItemList.isEmpty()) { customSpinnerItemList.add(item); } } } customSpinnerItemList.addAll(list); } if (this.getAdapter() != null) { this.setAdapter(null); } setThreshold(1); // handle click event and set desc on textview setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { CustomSpinnerItem customSpinnerItem = (CustomSpinnerItem) adapterView.getItemAtPosition(i); setSelected(customSpinnerItem); } }); CustomAutoCompleteItemAdapter adapter = new CustomAutoCompleteItemAdapter(this.getContext(), android.R.layout.simple_spinner_item, customSpinnerItemList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); setAdapter(adapter); setListSelection(0); } /** * Sets selection by id. * * @param id */ public void setSelectionById(String id) { CustomAutoCompleteItemAdapter adapter = (CustomAutoCompleteItemAdapter) this.getAdapter(); if (adapter == null) { return; } this.setText(adapter.getNameById(id), false); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDCalendar.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.graphics.Typeface; import android.support.v7.widget.AppCompatSpinner; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.adapters.SpinnerTextStyle; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.impl.android.ui.UIActivity; /** * A view for easy creation and use of an {@link AppCompatSpinner} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * @author cyu */ public class MDCalendar extends MDSpinner implements OnItemSelectedListener{ private int color = LayoutUtils.DEFAULT_LABEL_COLOR; private Typeface typeface = CommonConstants.Font.getDefaultRegularFont(Typeface.NORMAL); private int textSize = CommonConstants.Font.DEFAULT_FONT_SIZE; private int unit = TypedValue.COMPLEX_UNIT_SP; private boolean customTextStyle; private static SimpleDateFormat format = new SimpleDateFormat("MMMM yyyy"); private static MDCalendar mdCalendar; private static Calendar calendar; private static DatePickerDialog datePickerDialog; public MDCalendar(Context context) { super(context); setOnItemSelectedListener(this); setFocusable(false); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param required * @return */ public static MDCalendar createDefaultCalendar(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); MDCalendar calendar = createCalendar(context, label, required); LinearLayout linearLayout = (LinearLayout) calendar.getParent(); parent.addView(linearLayout); return calendar; } private static MDCalendar createCalendar(Context context, String label, boolean required) { mdCalendar = new MDCalendar(context); mdCalendar.createSpinnerView(context, mdCalendar); mdCalendar.setLabel(label); mdCalendar.setRequired(required); mdCalendar.setContents(new ArrayList()); // make clicking the view group the same as clicking the spinner // linearLayout.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // calendar.performClick(); // } // }); // // calendar.setOnItemSelectedListener(new OnItemSelectedListener() { // // @Override // public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { // calendar.clearError(); // } // // @Override // public void onNothingSelected(AdapterView arg0) { // // Auto-generated method stub // // } // }); mdCalendar.setFocusableInTouchMode(false); calendar = Calendar.getInstance(); datePickerDialog = createDatePickerDialog(); mdCalendar.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { mdCalendar.setEnabled(false); datePickerDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mdCalendar.setEnabled(true); mdCalendar.clearError(); } }); datePickerDialog.show(); return true; } }); return mdCalendar; } private static DatePickerDialog createDatePickerDialog() { return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); mdCalendar.setSelectedDate(calendar.getTime()); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { applyTextStyle(parent, view); } @Override public void setContents(List list) { super.setContents(list); applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } @Override protected CustomSpinnerAdapter createSpinnerAdapter(List customSpinnerItemList) { CustomSpinnerAdapter adapter = super.createSpinnerAdapter(customSpinnerItemList); if (isStyleChanged()) { adapter.setClosedViewTextStyle(getTextStyle()); } return adapter; } private TextView getSelectedTextView(AdapterView parent, View view) { if (view instanceof TextView) { return (TextView) view; } if (parent != null && parent.getSelectedView() instanceof TextView) { return (TextView) parent.getSelectedView(); } if (parent != null && parent.getChildAt(0) instanceof TextView) { return (TextView) parent.getChildAt(0); } return null; } private boolean isStyleChanged() { return customTextStyle; } @Override public void onNothingSelected(AdapterView parent) { // do nothing } public void setTextColor(int color) { this.color = color; customTextStyle = true; applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } public void setTypeface(Typeface typeface) { this.typeface = typeface; customTextStyle = true; applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } public void setTextSize(int unit, int textSize) { this.unit = unit; this.textSize = textSize; customTextStyle = true; applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } private void applyTextStyleToAdapter() { if (!isStyleChanged() || !(getAdapter() instanceof CustomSpinnerAdapter)) { return; } ((CustomSpinnerAdapter) getAdapter()).setClosedViewTextStyle(getTextStyle()); } private void applyTextStyle(AdapterView parent, View view) { if (!isStyleChanged()) { return; } getTextStyle().applyTo(getSelectedTextView(parent, view)); } private SpinnerTextStyle getTextStyle() { return SpinnerTextStyle.custom(color, typeface, unit, textSize); } public void setSelectedDate(Date select) { calendar.setTime(select); String date = format.format(calendar.getTime()); List dateTypeValueList = new ArrayList(); dateTypeValueList.add(new CustomSpinnerItem(date, date)); mdCalendar.setContents(dateTypeValueList); datePickerDialog = createDatePickerDialog(); } public Date getSelectedDate() { return calendar.getTime(); } public void setSimpleDateFormat(SimpleDateFormat simpleDateFormat) { format = simpleDateFormat; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDCheckBox.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatCheckBox; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * * A view for easy creation and use of an {@link AppCompatCheckBox} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * MDCheckBox structure: * LinearLayout * --AppCompatCheckBox * --View(Underline) * --TextView(Error message) * * * @author CYU * */ public class MDCheckBox extends AppCompatCheckBox { public MDCheckBox(Context context) { super(context); } /** * Creates a new {@link MDCheckBox} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @return */ public static MDCheckBox createDefaultCheckBox(Context context) { return createDefaultCheckBox(context, null); } /** * Creates a new {@link MDCheckBox} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @return */ public static MDCheckBox createDefaultCheckBox(Context context, String label) { return createCheckBox(context, label); } /** * Creates a new {@link MDCheckBox} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @return */ public static MDCheckBox createDefaultCheckBox(ViewGroup parent, String label) { if (parent == null) { return null; } Context context = parent.getContext(); MDCheckBox checkBox = createCheckBox(context, label); LinearLayout linearLayout = (LinearLayout) checkBox.getParent(); parent.addView(linearLayout); checkBox.setContentDescription(label); return checkBox; } private static MDCheckBox createCheckBox(Context context, final String label) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setOrientation(LinearLayout.VERTICAL); final MDCheckBox checkBox = new MDCheckBox(context); checkBox.setTag("CHECKBOX"); //$NON-NLS-1$ checkBox.setText(label); checkBox.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); checkBox.setTypeface(CommonConstants.Font.getDefaultRegularFont()); checkBox.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.addView(checkBox); View underline = new View(context); underline.setTag("UNDERLINE"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); underlineLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), LayoutUtils.convertDpToPixel(context, 8), LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); underline.setLayoutParams(underlineLinearLayout); underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); linearLayout.addView(underline); TextView errorText = new TextView(context); errorText.setTag("ERRORTEXT"); //$NON-NLS-1$ LinearLayout.LayoutParams errorTextLinearLayout = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); errorTextLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); errorText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); errorText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); errorText.setLayoutParams(errorTextLinearLayout); errorText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); errorText.setVisibility(View.GONE); linearLayout.addView(errorText); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { checkBox.clearError(); } }); return checkBox; } /** * Gets top parent. * * @return */ public View getTopParent() { return (View) this.getParent(); } /** * Sets an error. * * @param error */ @Override public void setError(CharSequence error) { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(error); errorText.setVisibility(View.VISIBLE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_ERROR_COLOR); underline.setVisibility(View.VISIBLE); } /** * Clears an error. */ public void clearError() { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(""); //$NON-NLS-1$ errorText.setVisibility(View.GONE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); } /** * Adds an asterisk to the hint that was set to the receiver marking the * input field as 'required'. * * @param required */ public void setRequired(boolean required) { MDCheckBox checkBox = getMDCheckBox(); String text = checkBox.getText().toString().replaceAll("\\*", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ checkBox.setText(text); if (required) { checkBox.setText(text + " *"); //$NON-NLS-1$ } } /** * Is required. * @return */ public boolean isRequired() { MDCheckBox checkBox = getMDCheckBox(); return checkBox.getText().toString().contains("*"); //$NON-NLS-1$ } public MDCheckBox getMDCheckBox() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(0); if (view instanceof MDCheckBox && "CHECKBOX".equals(view.getTag().toString())) { //$NON-NLS-1$ return (MDCheckBox) view; } return null; } private View getUnderline() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(1); if ("UNDERLINE".equals(view.getTag().toString())) { //$NON-NLS-1$ return view; } return null; } private TextView getErrorText() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(2); if (view instanceof TextView && "ERRORTEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDDialog.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnShowListener; import android.graphics.Typeface; import android.support.v7.app.AlertDialog; import android.util.TypedValue; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.impl.android.ui.UIActivity; /** * A view for easy creation and use of an {@link AlertDialog.Builder} * * @author nop */ public class MDDialog extends AlertDialog.Builder { public MDDialog(Context context) { super(context); } /** * Creates a new {@link MDDialog} * * @param title * @return */ public static MDDialog createDefaultSpinner(String title) { return createDefaultSpinner(title, null); } /** * Creates a new {@link MDDialog} * * @param title * @return */ public static MDDialog createDefaultSpinner(String title, String cancel) { return createSpinner(UIActivity.getInstance(), title, cancel); } private static MDDialog createSpinner(Context context, String title, String cancel) { TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setPadding(LayoutUtils.convertDpToPixel(context, LayoutUtils.DEFAULT_MAX_PADDING), LayoutUtils.convertDpToPixel(context, LayoutUtils.DEFAULT_MAX_PADDING), 0, 0); titleTextView.setText(title); MDDialog dialog = new MDDialog(context); dialog.setCustomTitle(titleTextView); dialog.setCancelable(false); if (StringUtil.isNotEmpty(cancel)) { dialog.setNegativeButton(cancel, new OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { dialog.dismiss(); } }); } return dialog; } private static void doKeepDialog(Dialog dialog){ WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.WRAP_CONTENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialog.getWindow().setAttributes(lp); } @Override public AlertDialog show() { final AlertDialog alert = this.create(); alert.setOnShowListener(new OnShowListener() { @Override public void onShow(android.content.DialogInterface dialog) { Button btnPositive = alert.getButton(Dialog.BUTTON_POSITIVE); btnPositive.setTextSize(CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); btnPositive.setTypeface(CommonConstants.Font.getDefaultMediumFont()); Button btnNegative = alert.getButton(Dialog.BUTTON_NEGATIVE); btnNegative.setTextSize(CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); btnNegative.setTypeface(CommonConstants.Font.getDefaultMediumFont()); } }); alert.show(); doKeepDialog(alert); return alert; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDEditText.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.Spanned; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.EditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.Watcher; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; /** * A view for easy creation and use of an {@link EditText} that is embedded in a * {@link TextInputLayout} which is the way input fields are created in Material * design. * * @author joerg */ public class MDEditText extends TextInputEditText { /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @return */ public static MDEditText createDefaultEditText(Context context, boolean required) { return createDefaultEditText(context, null, required); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(Context context, boolean required, TextWatcher textWatcher) { return createDefaultEditText(context, null, required, textWatcher); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @return */ public static MDEditText createDefaultEditText(Context context, String label, boolean required) { return createDefaultEditText(context, label, 0, required); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(Context context, String label, boolean required, TextWatcher textWatcher) { return createDefaultEditText(context, label, 0, required, textWatcher); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @return */ public static MDEditText createDefaultEditText(Context context, String label, int inputType, boolean required) { return createEditText(context, label, inputType, required, null); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(Context context, String label, int inputType, boolean required, TextWatcher textWatcher) { return createEditText(context, label, inputType, required, textWatcher); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @return */ public static MDEditText createDefaultEditText(ViewGroup parent, String label, int inputType, boolean required) { return createDefaultEditText(parent, label, inputType, required, null); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(ViewGroup parent, String label, int inputType, boolean required, TextWatcher textWatcher) { if (parent == null) { return null; } Context context = parent.getContext(); MDEditText editText = createEditText(context, label, inputType, required, textWatcher); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } public MDEditText(Context context) { super(context); InputFilter filter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { int type = Character.getType(source.charAt(i)); if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) { return ""; } } return null; } }; setFilters(new InputFilter[] { filter }); } public static TextInputLayout getTextInputLayout(MDEditText editText) { TextInputLayout textInputLayout = new TextInputLayout(editText.getContext()); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); return textInputLayout; } private static MDEditText createEditText(Context context, final String label, final int inputType, boolean required, TextWatcher textWatcher) { final MDEditText editText = new MDEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); if (inputType != 0) { editText.setInputType(inputType); } if (label != null) { editText.setHint(label); } if (required) { editText.setRequired(required); } if (textWatcher != null) { editText.addTextChangedListener(textWatcher); } else { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Auto-generated method stub } @Override public void afterTextChanged(Editable s) { editText.clearError(); } }); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, // Mode.SRC_ATOP); return editText; } /** * Sets the error on the embedding {@link TextInputLayout} if it is the parent * of the receiver by calling {@link TextInputLayout#setError(CharSequence)}. * * @param error The error message to set or null to remove the * error text by calling * {@link TextInputLayout#setErrorEnabled(boolean)} with * false. */ @Override public void setError(CharSequence error) { TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { textInputLayout.setError(error); if (error == null) textInputLayout.setErrorEnabled(false); return; } super.setError(error); } /** * Returns the {@link TextInputLayout} in the views hierarchy or * null if the view is not wrapped within such a layout. * * @return */ public TextInputLayout getParentTextInputLayout() { ViewParent parent = getParent(); while (parent != null) { if (parent instanceof TextInputLayout) return (TextInputLayout) parent; parent = parent.getParent(); } return null; } /** * Clears an error. */ public void clearError() { setError(null); } private boolean required = false; private boolean directionRight = false; /** * Adds an asterisk to the hint that was set to the receiver marking the input * field as 'required'. * * @param required */ public void setRequired(boolean required) { this.required = required; TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { String hint = textInputLayout.getHint().toString().replaceAll(" \\*", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (required) { hint = hint + " *"; //$NON-NLS-1$ } textInputLayout.setHint(hint); } } /** * Adds an asterisk to the hint that was set using * {@link MDEditText#setText(CharSequence)} if {@link #setRequired(boolean)} was * set to true. * * @return */ @Override public CharSequence getHint() { return required ? super.getHint() + " *" : super.getHint(); //$NON-NLS-1$ } /** * Is required. * * @return */ public boolean isRequired() { return required; // $NON-NLS-1$ } @Override public void setEnabled(boolean enabled) { setFocusable(enabled); setClickable(enabled); setFocusableInTouchMode(enabled); super.setEnabled(enabled); // set Enabled/Disabled style. int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; if (!enabled) { textColor = LayoutUtils.DEFAULT_DISABLED_COLOR; } setTextColor(textColor); } @Override public void setFilters(InputFilter[] filters) { super.setFilters(filters); } public void setDirectionRight(final boolean setFormattedDigitNumber) { directionRight = true; setGravity(Gravity.RIGHT); addTextChangedListener(new Watcher(this, null) { @Override public void afterTextChanged(Editable editText) { removeTextChangedListener(this); //00.00 if (beforeCharSequence < afterCharSequence) { setTextAndSelection(StringUtil.getFormattedDigitNumber(editText.toString(), setFormattedDigitNumber)); } else { // select all and enter new number if (editText.toString().length() == 1 && !editText.toString().equalsIgnoreCase("0")) { if (setFormattedDigitNumber) { setTextAndSelection("00.0" + editText.toString()); } } } addTextChangedListener(this); } }); } public void setSelection(int index) { Selection.setSelection(getText(), index); } public void setText(String text) { setTextAndSelection(text); } public void setTextAndSelection(String text) { // try to fix setSelection not working from softkey. getText().clear(); append(text); append(""); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDRadioButton.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.support.v7.widget.AppCompatRadioButton; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * A view for easy creation and use of an {@link AppCompatRadioButton} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * MDRadioButton structure: * LinearLayout * --AppCompatRadioButton * --View(Underline) * --TextView(Error message) * * @author nop */ public class MDRadioButton extends AppCompatRadioButton { public MDRadioButton(Context context) { super(context); } /** * Creates a new {@link MDRadioButton} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @return */ public static MDRadioButton createDefaultRadioButton(Context context) { return createDefaultRadioButton(context, null); } /** * Creates a new {@link MDRadioButton} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @return */ public static MDRadioButton createDefaultRadioButton(Context context, String label) { return createRadioButton(context, label); } /** * Creates a new {@link MDRadioButton} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @return */ public static MDRadioButton createDefaultRadioButton(ViewGroup parent, String label) { if (parent == null) { return null; } Context context = parent.getContext(); MDRadioButton radioButton = createRadioButton(context, label); LinearLayout linearLayout = (LinearLayout) radioButton.getParent(); parent.addView(linearLayout); radioButton.setContentDescription(label); return radioButton; } private static MDRadioButton createRadioButton(Context context, final String label) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setOrientation(LinearLayout.VERTICAL); final MDRadioButton radioButton = new MDRadioButton(context); radioButton.setTag("RADIOBUTTON"); //$NON-NLS-1$ radioButton.setText(label); radioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); radioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioButton.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.addView(radioButton); View underline = new View(context); underline.setTag("UNDERLINE"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); underlineLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), LayoutUtils.convertDpToPixel(context, 8), LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); underline.setLayoutParams(underlineLinearLayout); underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); linearLayout.addView(underline); TextView errorText = new TextView(context); errorText.setTag("ERRORTEXT"); //$NON-NLS-1$ LinearLayout.LayoutParams errorTextLinearLayout = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); errorTextLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); errorText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); errorText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); errorText.setLayoutParams(errorTextLinearLayout); errorText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); errorText.setVisibility(View.GONE); linearLayout.addView(errorText); radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { radioButton.clearError(); } }); return radioButton; } /** * Gets top parent. * * @return */ public View getTopParent() { return (View) this.getParent(); } /** * Sets an error. * * @param error */ @Override public void setError(CharSequence error) { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(error); errorText.setVisibility(View.VISIBLE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_ERROR_COLOR); underline.setVisibility(View.VISIBLE); } /** * Clears an error. */ public void clearError() { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(""); //$NON-NLS-1$ errorText.setVisibility(View.GONE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); } private View getUnderline() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(1); if ("UNDERLINE".equals(view.getTag().toString())) { //$NON-NLS-1$ return view; } return null; } private TextView getErrorText() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(2); if (view instanceof TextView && "ERRORTEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/MDSpinner.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.PorterDuff.Mode; import android.support.v7.widget.AppCompatSpinner; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; /** * A view for easy creation and use of an {@link AppCompatSpinner} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * MDSpinner structure: * LinearLayout * --TextView(label) * --AppCompatSpinner * --View(Underline) * --TextView(Error message) * * @author nop */ public class MDSpinner extends AppCompatSpinner { private TextView labelTextView; public MDSpinner(Context context) { super(context); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @return */ public static MDSpinner createDefaultSpinner(Context context, boolean required) { return createDefaultSpinner(context, null, required); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @return */ public static MDSpinner createDefaultSpinner(Context context, String label, boolean required) { return createSpinner(context, label, required); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param required * @return */ public static MDSpinner createDefaultSpinner(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); MDSpinner spinner = createSpinner(context, label, required); LinearLayout linearLayout = (LinearLayout) spinner.getParent(); parent.addView(linearLayout); return spinner; } private static MDSpinner createSpinner(Context context, final String label, boolean required) { final MDSpinner spinner = new MDSpinner(context); LinearLayout linearLayout = spinner.createSpinnerView(context, spinner); spinner.setLabel(label); spinner.setRequired(required); // make clicking the view group the same as clicking the spinner linearLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { spinner.performClick(); } }); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { spinner.clearError(); } @Override public void onNothingSelected(AdapterView arg0) { // Auto-generated method stub } }); return spinner; } public LinearLayout createSpinnerView(Context context, View view) { LinearLayout linearLayout = new LinearLayout(context); LinearLayout.LayoutParams linearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.VERTICAL); labelTextView = new TextView(context); labelTextView.setTag("TEXT"); //$NON-NLS-1$ labelTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); labelTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); textLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); labelTextView.setLayoutParams(textLayoutParams); labelTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(labelTextView); LinearLayout.LayoutParams viewLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); viewLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), 0, 0, 0); view.setLayoutParams(viewLayoutParams); view.getBackground().setColorFilter(LayoutUtils.DEFAULT_TEXT_COLOR, Mode.SRC_ATOP); linearLayout.addView(view); View underline = new View(context); underline.setTag("UNDERLINE"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); underlineLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4) , 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); underline.setLayoutParams(underlineLinearLayout); underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); linearLayout.addView(underline); TextView errorText = new TextView(context); errorText.setTag("ERRORTEXT"); //$NON-NLS-1$ errorText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); errorText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams errorTextLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); errorTextLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); errorText.setLayoutParams(errorTextLayoutParams); errorText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); errorText.setVisibility(View.GONE); linearLayout.addView(errorText); return linearLayout; } /** * Sets contents. * * @param list */ public void setContents(List list) { List customSpinnerItemList = new ArrayList(); if (list != null && list.isEmpty()) { customSpinnerItemList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, "")); } else { for (int i = 0; i < list.size(); i++) { CustomSpinnerItem item = list.get(i); if (item.getName().startsWith("Bitte w") && item.getName().endsWith("...")) { list.remove(item); if(customSpinnerItemList.isEmpty()) { customSpinnerItemList.add(item); } } } customSpinnerItemList.addAll(list); } if (this.getAdapter() != null) { this.setAdapter(null); } CustomSpinnerAdapter adapter = createSpinnerAdapter(customSpinnerItemList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); this.setAdapter(adapter); this.setSelection(0); // default } protected CustomSpinnerAdapter createSpinnerAdapter(List customSpinnerItemList) { return new CustomSpinnerAdapter(this.getContext(), android.R.layout.simple_spinner_item, customSpinnerItemList); } /** * Clears contents. */ public void clearContents() { if (this.getAdapter() != null) { this.setAdapter(null); } } /** * Sets selection by id. * * @param id */ public void setSelectionById(String id) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) this.getAdapter(); if (adapter == null) { return; } this.setSelection(adapter.getPositionById(id)); } /** * Sets selection by name. * * @param name */ public void setSelectionByName(String name) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) this.getAdapter(); this.setSelection(adapter.getPositionByName(name)); } /** * Sets selection by description. * * @param description */ public void setSelectionByDescription(String description) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) this.getAdapter(); this.setSelection(adapter.getPositionByDescription(description)); } /** * Sets an error. * * @param error */ public void setError(CharSequence error) { TextView errorText = getErrorText(); errorText.setText(error); errorText.setVisibility(View.VISIBLE); View underline = getUnderline(); underline.setBackgroundColor(LayoutUtils.DEFAULT_ERROR_COLOR); } /** * Gets top parent. * * @return */ public View getTopParent() { return (View) this.getParent(); } /** * Gets selected item id. * * @return */ public String getSelectedId() { CustomSpinnerItem customSpinnerItem = ((CustomSpinnerItem) this.getSelectedItem()); if (customSpinnerItem == null) { return ""; } return ((CustomSpinnerItem) this.getSelectedItem()).getId(); } /** * Gets selected item name. * * @return */ public String getSelectedName() { return ((CustomSpinnerItem) this.getSelectedItem()).getName(); } /** * Gets selected item Description. * * @return */ public String getSelectedDescription() { return ((CustomSpinnerItem) this.getSelectedItem()).getDescription(); } /** * Clears an error. */ public void clearError() { TextView errorText = getErrorText(); errorText.setText(""); //$NON-NLS-1$ errorText.setVisibility(View.GONE); View underline = getUnderline(); underline.setBackgroundColor(isEnabled() ? LayoutUtils.DEFAULT_UNDERLINE_COLOR : LayoutUtils.DEFAULT_UNDERLINE_DISABLED_COLOR); } /** * Adds an asterisk to the hint that was set to the receiver marking the * input field as 'required'. * * @param required */ public void setRequired(boolean required) { TextView textView = getTextView(); String text = textView.getText().toString().replaceAll("\\*", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ textView.setText(text); if (required) { textView.setText(text + " *"); //$NON-NLS-1$ } } /** * Is required. * @return */ public boolean isRequired() { TextView textView = getTextView(); return textView.getText().toString().contains("*"); //$NON-NLS-1$ } /** * Gets a text. * @return */ public TextView getTextView() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(0); if (view instanceof TextView && "TEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } /** * Gets an underline. * @return */ public View getUnderline() { int childIndex = 2; LinearLayout linearLayout = (LinearLayout) getTopParent(); if (linearLayout.getChildCount() == 3) { childIndex = 1; } View view = linearLayout.getChildAt(childIndex); if ("UNDERLINE".equals(view.getTag().toString())) { //$NON-NLS-1$ return view; } return null; } /** * Gets an error text. * @return */ public TextView getErrorText() { int childIndex = 3; LinearLayout linearLayout = (LinearLayout) getTopParent(); if (linearLayout.getChildCount() == 3) { childIndex = 2; } View view = linearLayout.getChildAt(childIndex); if (view instanceof TextView && "ERRORTEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); this.setClickable(enabled); // set Enabled/Disabled click event LinearLayout linearLayout = (LinearLayout) getTopParent(); linearLayout.setClickable(enabled); // set Enabled/Disabled style. int spinnerColor = LayoutUtils.DEFAULT_TEXT_COLOR; int underlineColor = LayoutUtils.DEFAULT_UNDERLINE_COLOR; if (!enabled) { spinnerColor = LayoutUtils.DEFAULT_DISABLED_COLOR; underlineColor = LayoutUtils.DEFAULT_UNDERLINE_DISABLED_COLOR; } TextView textView = (TextView) this.getSelectedView(); if (textView == null) { textView = (TextView) this.getChildAt(0); } if (textView != null) { textView.setTextColor(spinnerColor); textView.setEnabled(enabled); this.getBackground().setColorFilter(spinnerColor, Mode.SRC_ATOP); } View underlineView = getUnderline(); if (underlineView != null) { underlineView.setBackgroundColor(underlineColor); underlineView.setEnabled(enabled); } TextView labelView = getTextView(); if (labelView != null) { labelView.setTextColor(spinnerColor); labelView.setHintTextColor(spinnerColor); labelView.setEnabled(enabled); } } public void setLabel(String label) { labelTextView.setText(label); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/ReportContentWidget.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.ErrorCode; import ch.mfiles.kaba.kolibri.common.businessobjects.Incident; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.util.DateUtils; public class ReportContentWidget extends Form { private Application app; private DatabaseUtil dbutil; private Context context; private Job job; private TextView timeTitle; private GridLayout timesGridLayout; private TextView reportTitle; private GridLayout reportGridLayout; private TextView materialTitle; private GridLayout materialGridLayout; private TextView messageTitle; private GridLayout messageGridLayout; private TextView imageTitle; private GridLayout imageGridLayout; private ImagesUtil imagesUtil; private EnumUtil enumUtil; public ReportContentWidget(Application app, DatabaseUtil dbutil, Context context) { this.app = app; this.dbutil = dbutil; this.context = context; this.imagesUtil = ImagesUtil.getInstance(app); this.enumUtil = EnumUtil.getInstance(dbutil); } public CardView createTimesCard() { timesGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); timesGridLayout.setLayoutParams(gridLayoutParams); timesGridLayout.setColumnCount(2); timesGridLayout.setUseDefaultMargins(true); timeTitle = new TextView(context); return createCard(timeTitle, timesGridLayout); } public CardView createReportCard() { reportGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); reportGridLayout.setLayoutParams(gridLayoutParams); reportGridLayout.setColumnCount(2); reportGridLayout.setUseDefaultMargins(true); reportTitle = new TextView(context); return createCard(reportTitle, reportGridLayout); } public CardView createMaterialCard() { materialGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); materialGridLayout.setLayoutParams(gridLayoutParams); materialGridLayout.setColumnCount(2); materialGridLayout.setUseDefaultMargins(true); materialTitle = new TextView(context); return createCard(materialTitle, materialGridLayout); } public CardView createMessageCard() { messageGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); messageGridLayout.setLayoutParams(gridLayoutParams); messageGridLayout.setColumnCount(2); messageGridLayout.setUseDefaultMargins(true); messageTitle = new TextView(context); return createCard(messageTitle, messageGridLayout); } public CardView createImageCard() { imageGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); imageGridLayout.setLayoutParams(gridLayoutParams); imageGridLayout.setColumnCount(2); imageGridLayout.setUseDefaultMargins(true); imageTitle = new TextView(context); return createCard(imageTitle, imageGridLayout); } private CardView createCard(TextView title, GridLayout gridLayout) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 0, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MAX_PADDING); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); gradientDrawable.setCornerRadius(7f); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_CARD_VIEW_SHADOW_COLOR); // cardView.setBackground(gradientDrawable); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); RelativeLayout titleRrelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams relativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); relativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); titleRrelativeLayout.setLayoutParams(relativeLayoutParams); title.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); title.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); title.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); title.setPadding(5, 10, 5, 5); title.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); titleRrelativeLayout.addView(title); linearLayout.addView(titleRrelativeLayout); linearLayout.addView(gridLayout); cardView.addView(linearLayout); ((LayoutParams) cardView.getLayoutParams()).topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; return cardView; } public void loadTimes(boolean showDate) { job.loadReports(dbutil); Report report = job.getLatestReport(); timesGridLayout.removeAllViews(); report.loadTimes(dbutil); List reportTimeList = report.getTimes(); if (reportTimeList.isEmpty()) { createTextView(timesGridLayout, Messages.getString("noTimesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } else { for (int i = 0; i < reportTimeList.size(); i++) { JobReportTime reportTime = reportTimeList.get(i); if (i == 0) timeTitle.setText(Messages.getString("timesFrom") + " " + DateTimeUtil.showDate(reportTime.getDate())); WorkType WorkType = dbutil.selectWorkTypeByJobTypeAndWorkTypeCode(job.getJobType(), reportTime.getWorkTypeCode()); String workTypeText = (WorkType == null ? "" : WorkType.getText()); String dateString = ""; if(showDate) { dateString = DateTimeUtil.showDate(reportTime.getDate()) + " "; } String stopTime = ""; if (!DateUtils.getInitialDateTime().equals(reportTime.getStopTime())) { stopTime = DateTimeUtil.showTime(reportTime.getStopTime()); } createInfoTextView(timesGridLayout, dateString + DateTimeUtil.showTime(reportTime.getStartTime()) + "-" + stopTime, workTypeText); } } } public void loadReport() { job.loadReports(dbutil); Report report = job.getLatestReport(); reportGridLayout.removeAllViews(); String date = DateTimeUtil.showDate(report.getCreateDate()); reportTitle.setText(Messages.getString("reportsFrom") + " " + date); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (job.getCurrentReport().getReportStatus().isInitial()) { createTextView(reportGridLayout, Messages.getString("noReportRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } else { job.loadAddresses(dbutil); createInfoTextView(reportGridLayout, Messages.getString("location"), report.getCommissionNumber()); //$NON-NLS-1$ Address address = job.getObjectAddress(); createInfoTextView(reportGridLayout, "", address.getLocation()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, "", address.getStreet() + " " + address.getPostalCode() + " " + address.getCity()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ createInfoTextView(reportGridLayout, Messages.getString("orderNo"), report.getOrderNumber()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("billing"), report.getBilling()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("typeOfJob"), report.getWorkType()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("orderDate"), DateTimeUtil.showDate(report.getCreateDate())); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("jobState"), report.getReportStatus().toString()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("costumerReport"), report.getCustomerSupport()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("checkList"), report.getChecklist()); //$NON-NLS-1$ addFailure(); addError(); createInfoTextView(reportGridLayout, Messages.getString("installationError"), report.getSystemError()); //$NON-NLS-1$ addMaintanNance(); createInfoTextView(reportGridLayout, Messages.getString("signature"), report.isSignatureInfo()? report.getSignatureInfo():""); } } private void addFailure() { Report report = job.getLatestReport(); String incidentAText = ""; //$NON-NLS-1$ String incidentBText = ""; //$NON-NLS-1$ Incident incidentA = null; Incident incidentB = null; if(!report.getIncidentAB().isEmpty()) { incidentA = dbutil.selectIncidentByFCT(report.getIncidentAB().substring(0, 2), "A"); //$NON-NLS-1$ incidentB = dbutil.selectIncidentByFCT(report.getIncidentAB().substring(2), "B"); //$NON-NLS-1$ } if(incidentA != null) { incidentAText = incidentA.getErrorCode() + " / " +incidentA.getText(); //$NON-NLS-1$ } if(incidentB != null) { incidentBText = incidentB.getErrorCode() + " / " +incidentB.getText(); //$NON-NLS-1$ } createInfoTextViewWithIcon(reportGridLayout, Messages.getString("failure"), "1 " + incidentAText); //$NON-NLS-1$ //$NON-NLS-2$ createInfoTextView(reportGridLayout, "", "2 " + incidentBText); //$NON-NLS-1$ //$NON-NLS-2$ } private void addError() { Report report = job.getLatestReport(); String error = ""; //$NON-NLS-1$ String error2 = ""; //$NON-NLS-1$ if("000".equalsIgnoreCase(report.getErrorId1())){ //$NON-NLS-1$ ErrorCode errorCode1 = dbutil.selectErrorCodeByFc(report.getErrorId1()); if(errorCode1 != null) { error = errorCode1.getErrorCode() + " / " + errorCode1.getText(); //$NON-NLS-1$ } } if("000".equalsIgnoreCase(report.getErrorId2())){ //$NON-NLS-1$ ErrorCode errorCode2 = dbutil.selectErrorCodeByFc(report.getErrorId2()); if(errorCode2 != null) { error2 = errorCode2.getErrorCode() + " / " + errorCode2.getText(); //$NON-NLS-1$ } } createInfoTextView(reportGridLayout, Messages.getString("error"), "1: " + error); //$NON-NLS-1$ //$NON-NLS-2$ createInfoTextView(reportGridLayout, "", "2: " + error2); //$NON-NLS-1$ //$NON-NLS-2$ } private void addMaintanNance(){ Report report = job.getLatestReport(); String planed = report.getServicePlanMonth1() + " " + report.getServicePlanMonth2() + " " + report.getServicePlanMonth3() //$NON-NLS-1$ //$NON-NLS-2$ + " " + report.getServicePlanMonth4() + " " + report.getServicePlanMonth5() + " " + report.getServicePlanMonth6(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String done = ""; //$NON-NLS-1$ if (report.getMonthYear().length() > 2) { if(!CommonConstants.PLEASE_SELECT.equalsIgnoreCase(report.getMonthYear().substring(0, 2))){ //$NON-NLS-1$ done = report.getMonthYear().substring(0, 2); } if(!CommonConstants.PLEASE_SELECT.equalsIgnoreCase(report.getMonthYear().substring(2, 4))){ //$NON-NLS-1$ done += " " + report.getMonthYear().substring(2, 4); //$NON-NLS-1$ } } else { if(!CommonConstants.PLEASE_SELECT.equalsIgnoreCase(report.getMonthYear())){ //$NON-NLS-1$ done = report.getMonthYear(); } } createInfoTextView(reportGridLayout, Messages.getString("Service"), Messages.getString("Planed") + ": " + planed); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ createInfoTextView(reportGridLayout, "", Messages.getString("Done") + ": " + done); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void loadMaterial() { Report report = job.getLatestReport(); materialGridLayout.removeAllViews(); materialTitle.setText(Messages.getString("material")); //$NON-NLS-1$ // Verwendetes Material (nur wenn vorhanden) List reportMatList = dbutil.selectReportMaterialList(report.getGuId()); if (!reportMatList.isEmpty()) { for (int i = 0; i < reportMatList.size(); i++) { ReportMaterial reportMat = reportMatList.get(i); Material part = dbutil.selectMaterialByMatNo(reportMat.getSparePartNumber()); String material = ""; //$NON-NLS-1$ if (part == null) { material += " " + reportMat.getProductName(); //$NON-NLS-1$ } else { material += " " + part.getMaterialShortText(); //$NON-NLS-1$ } createInfoTextView(materialGridLayout, reportMat.getAmount() + " " + reportMat.getUnit(), material); //$NON-NLS-1$ } } else { createTextView(materialGridLayout, Messages.getString("noMaterialRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } } public void loadMessage() { Report report = job.getLatestReport(); messageGridLayout.removeAllViews(); messageTitle.setText(Messages.getString("messages")); //$NON-NLS-1$ String messageId = ""; //$NON-NLS-1$ List reportTextList = dbutil.selectJobMessageListByReport(report); boolean isEmptyMessage = true; for (int i = 0; i < reportTextList.size(); i++) { JobMessage jobMessage = reportTextList.get(i); if(!jobMessage.getMessageId().equalsIgnoreCase("01")) { String message = ""; ReportMessage reportMessage = null; if(job.getJobType().isMON()) { if (jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.PROJECT_MANAGER) || jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.DISPOSITION)) { continue; } JobMonText jobMonText = dbutil.selectReportMONMessageByMsgcAndLangu(jobMessage.getMessageCode(), ""); if(jobMonText != null) { message = jobMonText.getText(); } } else { reportMessage = dbutil.selectReportMessageByMsgc(jobMessage.getMessageCode()); if(reportMessage != null) { message = reportMessage.getMessage(); } } String messageIdTemp = jobMessage.getMessageId(); // Don't display text for supervisor and KDZ-text 3 if ((!(jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.HEAD_OF_DEPARTMENT) && (reportMessage != null && reportMessage.isABTL()))) && !messageIdTemp.equalsIgnoreCase(CommonConstants.Message.KDZ3)) { String key = ""; //$NON-NLS-1$ if (!messageId.equals(messageIdTemp)) { key = enumUtil.messageRecipientEnum.get(jobMessage.getMessageId()); } if(!message.isEmpty() || !jobMessage.getFullText().isEmpty()) { isEmptyMessage = false; createInfoTextViewWithBold(messageGridLayout, key, message); createInfoTextView(messageGridLayout, "", jobMessage.getFullText()); //$NON-NLS-1$ } } } } if (isEmptyMessage) { createTextView(messageGridLayout, Messages.getString("noMessagesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } } public void loadImage() { Report report = job.getLatestReport(); imageGridLayout.removeAllViews(); imageTitle.setText(Messages.getString("image")); //$NON-NLS-1$ // String messageId = ""; //$NON-NLS-1$ // List reportTextList = dbutil.selectJobMessageListByReport(report); boolean isEmptyImage = true; // for (int i = 0; i < reportTextList.size(); i++) { // JobMessage zkdmobmsg = reportTextList.get(i); // // String value = ""; // ReportMessage reportMessage = dbutil.selectReportMessageByMsgcAndLangu(zkdmobmsg.getMessageCode(), dbutil.getUser().getLanguage()); // if(reportMessage != null) { // value = reportMessage.getMessage(); // } // // String messageIdTemp = zkdmobmsg.getMessageId(); // // Don't display text for supervisor and KDZ-text 3 // if ((!(zkdmobmsg.getMessageId().equalsIgnoreCase(CommonConstants.ZKDMOBMSG.ABTEILUNGSLEITER) // && (reportMessage != null && reportMessage.isABTL()))) && !messageIdTemp.equalsIgnoreCase(CommonConstants.ZKDMOBMSG.KDZ3)) { // String key = ""; //$NON-NLS-1$ // if (!messageId.equals(messageIdTemp)) { // key = enumUtil.messageRecipientEnum.get(zkdmobmsg.getMessageId()); // } // // if(!value.isEmpty() || !zkdmobmsg.getFullText().isEmpty()) { // isEmptyImage = false; // createInfoTextViewWithBold(imageGridLayout, key, value); // createInfoTextView(imageGridLayout, "", zkdmobmsg.getFullText()); //$NON-NLS-1$ // } // } // } if (isEmptyImage) { createTextView(imageGridLayout, Messages.getString("noImageRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } } /** * Creates info text view. * * @param gridLayout * @param key * @param value */ private void createInfoTextView(GridLayout gridLayout, String key, final String value) { createInfoTextView(gridLayout, key, value, false, false); } private void createInfoTextViewWithBold(GridLayout gridLayout, String key, final String value) { createInfoTextView(gridLayout, key, value, true, false); } private void createInfoTextViewWithIcon(GridLayout gridLayout, String key, final String value) { createInfoTextView(gridLayout, key, value, false, true); } private void createInfoTextView(GridLayout gridLayout, String key, final String value , boolean isBold, boolean isShowIcon) { TextView gridTextViewKey = new TextView(gridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.4f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout gridRelativeLayout = new RelativeLayout(gridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.6f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(gridLayout.getContext()); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(value); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(gridTextViewValue); if (isShowIcon) { ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(imagesUtil.getImage(ImagesUtil.Images.PHONE_DISABLED, CommonConstants.Images.IMAGE_DPI))); if (value != null && !value.isEmpty()) { String phoneNumber = ""; if (StringUtil.findChar(value, ' ')) { String values[] = value.split(" "); if(values.length > 1) { phoneNumber = values[1].replaceAll("\\s+","").trim();//$NON-NLS-1$ //$NON-NLS-2$ } } final String tel = phoneNumber; if(!phoneNumber.isEmpty()) { gridImageView.setImageDrawable(getBitmanDrawable(imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, CommonConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + tel)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } }); } } gridRelativeLayout.addView(gridImageView); } gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } private void createTextView(GridLayout gridLayout, String text, int color) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(text); gridTextViewKey.setTextColor(color); gridLayout.addView(gridTextViewKey); } public TextView getTimeTitle() { return timeTitle; } public void setTimeTitle(TextView timeTitle) { this.timeTitle = timeTitle; } public GridLayout getTimesGridLayout() { return timesGridLayout; } public void setTimesGridLayout(GridLayout timesGridLayout) { this.timesGridLayout = timesGridLayout; } public TextView getReportTitle() { return reportTitle; } public void setReportTitle(TextView reportTitle) { this.reportTitle = reportTitle; } public GridLayout getReportGridLayout() { return reportGridLayout; } public void setReportGridLayout(GridLayout reportGridLayout) { this.reportGridLayout = reportGridLayout; } public TextView getMaterialTitle() { return materialTitle; } public void setMaterialTitle(TextView materialTitle) { this.materialTitle = materialTitle; } public GridLayout getMaterialGridLayout() { return materialGridLayout; } public void setMaterialGridLayout(GridLayout materialGridLayout) { this.materialGridLayout = materialGridLayout; } public TextView getMessageTitle() { return messageTitle; } public void setMessageTitle(TextView messageTitle) { this.messageTitle = messageTitle; } public GridLayout getMessageGridLayout() { return messageGridLayout; } public void setMessageGridLayout(GridLayout messageGridLayout) { this.messageGridLayout = messageGridLayout; } public void setJob(Job job) { this.job = job; } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/TimeEditText.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class TimeEditText extends MDEditText { private static Log log = LogFactory.getLog(TimeEditText.class); public TimeEditText(Context context) { super(context); } public static TimeEditText createDefaultEditText(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); TimeEditText editText = createEditText(context, label, required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private static TimeEditText createEditText(Context context, String label, final boolean required) { final TimeEditText editText = new TimeEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setRawInputType(InputType.TYPE_CLASS_NUMBER); if (required) { editText.setRequired(required); } if (label != null) { editText.setHint(label); } editText.addTextChangedListener(new TextWatcher() { private int beforeCharSequence; private int afterCharSequence; private Pattern pattern = Pattern.compile(CommonConstants.TimeSheet.TIME_REGEX); @Override public void afterTextChanged(Editable s) { String value = s.toString().trim(); editText.removeTextChangedListener(this); value = value.replace("-", ""); value = value.replace(" ", ""); value = value.replace(".", ""); value = value.replace(",", ""); if(!StringUtil.isNumeric(value)) { StringUtil.removeLetters(value); } editText.setText(value); try { if (value.length() == CommonConstants.TimeSheet.COLON_POSITION && beforeCharSequence < afterCharSequence) { if(Integer.parseInt(StringUtil.getOnlyDigits(value)) > 23){ value = "23"; //$NON-NLS-1$ } value = value + ":"; //$NON-NLS-1$ editText.setText(value); } if (value.length() == CommonConstants.TimeSheet.COLON_POSITION +1 && value.charAt(CommonConstants.TimeSheet.COLON_POSITION) != ':' && beforeCharSequence < afterCharSequence) { String hour = value.substring(0, CommonConstants.TimeSheet.COLON_POSITION); String minutes = value.substring(CommonConstants.TimeSheet.COLON_POSITION, value.length()); if(Integer.parseInt(StringUtil.getOnlyDigits(minutes)) > 59){ minutes = "59"; //$NON-NLS-1$ } value = hour + ":" + minutes; //$NON-NLS-1$ editText.setText(value); } if(value.indexOf(':') > -1) { if(value.length() > 5) { value = value.substring(0, 5); } } // remove ":" position if(value.indexOf(':') != CommonConstants.TimeSheet.COLON_POSITION) { value = value.replace(":", ""); } if (value.length() > CommonConstants.TimeSheet.COLON_POSITION+1) { if(value.charAt(value.length()-1) == ':') { value = value.substring(0, value.length()-1); } else { String values[] = value.split(":"); //$NON-NLS-1$ if(Integer.parseInt(StringUtil.getOnlyDigits(values[1])) > 59){ values[1] = "59"; //$NON-NLS-1$ } editText.setText(values[0] + ":" + values[1]); //$NON-NLS-1$ } } } catch (IndexOutOfBoundsException e) { editText.setText(""); } Matcher matcher = pattern.matcher(value); if (matcher.matches() || matcher.hitEnd()) { editText.setText(value); } editText.setSelection(editText.getText().length()); if (editText.hasFocus()) { editText.clearError(); } editText.addTextChangedListener(this); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } }); editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, Mode.SRC_ATOP); return editText; } public boolean isValid() { return isMatch(getText().toString()); } private boolean isMatch(String value) { Pattern pattern = Pattern.compile(CommonConstants.TimeSheet.TIME_REGEX); Matcher matcher = pattern.matcher(value); return matcher.matches(); } public void setText(String text) { super.setText(text); } public void setLabel(String label) { super.setHint(label); } }     common/src/ch/mfiles/kaba/kolibri/common/forms/widgets/ViewPageAdapter.java:   package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; /** * A PagerAdapter providing a static number of views. * * @author joerg * */ public class ViewPageAdapter extends PagerAdapter { private static class Page { String title; View view; Page(String title, View view) { this.view = view; this.title = title; } } private List viewPages = new ArrayList(); public void addPage(String title, View pageView) { viewPages.add(new Page(title, pageView)); notifyDataSetChanged(); } @Override public Object instantiateItem(ViewGroup container, int position) { View pageView = viewPages.get(position).view; container.addView(pageView); return pageView; } @Override public CharSequence getPageTitle(int position) { return viewPages.get(position).title; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return viewPages.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }     common/src/ch/mfiles/kaba/kolibri/common/net/CommSetupHelper.java:   package ch.mfiles.kaba.kolibri.common.net; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; public class CommSetupHelper { private static final String PROD_MIDDLEWARE_URL = "http://194.209.171.40:8080/trHandler/transport/mbcp2"; private static final String PROD_BACKEND_URL = "http://kgsssapwebdisp.gilgends.com:8080/mfl/mbcp2"; /** * Sets production communication data to the runtime's registry, if there is * currently no 'backendUrl' set. *

* If a 'backendUrl' is set, nothing is changed. */ public static void setupProductionEnvironment() { // always apply/reset common settings setCommonSettings(); Registry reg = Runtime.getApplicationManager().getRegistry(null); String backendUrl = reg.getProperty("framework.net.backendUrl"); //$NON-NLS-1$ // set backend settings only once if (backendUrl != null && backendUrl.length() > 0) return; reg.setProperty("framework.net.middlewareUrl", PROD_MIDDLEWARE_URL); //$NON-NLS-1$ reg.setProperty("framework.net.backendUrl", PROD_BACKEND_URL); //$NON-NLS-1$ } public static boolean isProductionEnvironment() { Registry reg = Runtime.getApplicationManager().getRegistry(null); String backendUrl = reg.getProperty("framework.net.backendUrl"); //$NON-NLS-1$ return PROD_BACKEND_URL.equals(backendUrl); } private static void setCommonSettings() { Registry reg = Runtime.getApplicationManager().getRegistry(null); reg.deleteProperty("framework.la.url"); //$NON-NLS-1$ reg.setProperty("framework.dm.deviceTypeId", "S60"); //$NON-NLS-1$ //$NON-NLS-2$ reg.setProperty("framework.net.notify.maxRetryTimeout", "120"); //$NON-NLS-1$ //$NON-NLS-2$ reg.setProperty("framework.dm.localCycle", "720"); } /** * Sets test communication data to the runtime's registry, replacing any configuration present before. */ public static void setupDevelopmentEnvironment() { Registry reg = Runtime.getApplicationManager().getRegistry(null); reg.setProperty("framework.net.middlewareUrl", "http://194.209.171.36:8080/trHandler/transport/mbcp2"); //$NON-NLS-1$ //$NON-NLS-2$ reg.setProperty("framework.net.backendUrl", "http://kgsssapwebdisptest.gilgends.com:8080/mfl/mbcp2"); //$NON-NLS-1$ //$NON-NLS-2$ setCommonSettings(); } /** * Called in {@link Application#onApplicationStart(Object)} to setup the UI * layout corresponding to the current communication environment. */ public static void setEnvironmentLayout() { if (!isProductionEnvironment()) LayoutUtils.setDevelopmentColors(); } }     common/src/ch/mfiles/kaba/kolibri/common/net/MasterDataDBHandler.java:   package ch.mfiles.kaba.kolibri.common.net; import java.io.File; import java.text.MessageFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMATPERS; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.gen.TableCursor; /** * Handler for the separately stored master data. * * @author joerg * @@deprecated The last remaining attached master data table was remigrated to * the runtime database in release 3.3.9. The remaining * implementation checks whether the attached master data db file * still exists and migrates the contained data to the * application's runtime db when an attempt is made to attache the * master data db. * */ public class MasterDataDBHandler { private final static Log log = LogFactory.getLog(MasterDataDBHandler.class); private static MasterDataDBHandler masterDataDBHandler; public static MasterDataDBHandler getInstance() { if (masterDataDBHandler == null) masterDataDBHandler = new MasterDataDBHandler(); return masterDataDBHandler; } private final static String PERSONAL_DATA = "PERSONAL_DATA"; //$NON-NLS-1$ private final static String DB_NAME = "GilgenPersonalData"; //$NON-NLS-1$ private MasterDataDBHandler() { // singleton } private boolean m_masterDataDBAttached = false; /** * Attaches the master data database to the runtime database if it still exists, * copies the data to the runtime db, detaches the database and deletes the * file. Does nothing if the database file doen't exist (any more). */ public void attach() { if (m_masterDataDBAttached) return; // no masterdata file no attachment necessary File mdFile = new File(getDBPath(PERSONAL_DATA) + ".db3"); if (!mdFile.exists()) { log.info("Master data db does not exist - not attached..."); return; } // temporarily attach the master data file and copy the existing data to the // runtime table log.info("Migrating master data db " + PERSONAL_DATA); //$NON-NLS-1$ DBSession dbSession = Runtime.getApplicationManager().getDBSession(); dbSession.executeSql("ATTACH DATABASE '" + getDBPath(PERSONAL_DATA) + ".db3" + "' AS " + DB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ ZKDMOBMATPERS attachedMD = new ZKDMOBMATPERS(dbSession); TableCursor cursor = ZKDMOBMATPERS.query(attachedMD, "SELECT * FROM " + DB_NAME + "." + DbConstants.MaterialPerson.MATERIAL_PERSON, true); int rowsInserted = 0; dbSession.startTransaction(); try { while (cursor.next()) { attachedMD.insert(); rowsInserted += 1; } dbSession.commit(); } finally { cursor.dispose(); if (dbSession.isTransactionPending()) dbSession.rollback(); } log.info(MessageFormat.format("Copied {0} rows of table ZKDMIBMATPERS from attached database.", rowsInserted)); // detach the master data db and delete its file log.info("Detaching master data db " + PERSONAL_DATA); //$NON-NLS-1$ dbSession.executeSql("DETACH DATABASE " + DB_NAME); //$NON-NLS-1$ mdFile.delete(); m_masterDataDBAttached = true; } /** * @param PERSONAL_DATA * @return Returns the absolute path to the db without the file extension '.db3' */ private String getDBPath(String masterDB) { return Runtime.getApplicationManager().getApplicationFolder(CommonConstants.Application.COMMON_APP) + File.separator + masterDB; } /** * Does nothing. */ public void detach() { return; } }     common/src/ch/mfiles/kaba/kolibri/common/net/PresenceState.java:   package ch.mfiles.kaba.kolibri.common.net; /** * Presence state to be used with remote transcation UPDATE_PRESENCE. * * @author joerg * */ public enum PresenceState { /** * Present, i.e. reachable at work. */ PRESENT, /** * Gone from work for today, i.e. no more reachable for today. */ GONE, /** * Gone from work for a short break, i.e. probably reachable again later that day. */ BREAK }     common/src/ch/mfiles/kaba/kolibri/common/net/RemoteTransactionHandler.java:   package ch.mfiles.kaba.kolibri.common.net; import java.io.File; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.db.FORMINSTANCE; import ch.mfiles.kaba.kolibri.common.db.LocalizedTexts; import ch.mfiles.kaba.kolibri.common.db.ZKDMOB; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.FatalApplicationException; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.net.Element; import ch.mfiles.kolibri.net.ElementTemplate; import ch.mfiles.kolibri.net.Request; import ch.mfiles.kolibri.net.Response; import ch.mfiles.kolibri.net.TableElement; import ch.mfiles.kolibri.net.Transaction; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.ProgressMonitor; public class RemoteTransactionHandler { private Log log = LogFactory.getLog(RemoteTransactionHandler.class); private DatabaseUtil dbutil; private TransactionHandler tr; /** * instantiates a new RemoteTransactionHandler * * @param application the application. * @param transactionHandler the transaction handler to be used for communication. */ public RemoteTransactionHandler() { this.dbutil = DatabaseUtil.getInstance(); this.tr = Runtime.getTransactionHandler(); } /** * Make sure we are *not* running on the UI thread. */ private void ensureAMThread() { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); if (appman.getContext().getMainLooper().getThread() == Thread.currentThread()) throw new FatalApplicationException(Messages.getString("RemoteTransactionHandler.0")); //$NON-NLS-1$ } public boolean runRefreshMasterdata(int perno, String tableName, String initalRequest, ProgressMonitor monitor) { ensureAMThread(); monitor.begin(Messages.getString("RemoteTransactionHandler.1"), 3); //$NON-NLS-1$ DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); try { // REFRESHED Flag bei allen Stammdatentabellen zur�cksetzten // (unabh�ngig davon, ob sie aktualisiert werden oder nicht) dbutil.updateRefreshFlag(); monitor.comment(Messages.getString("RemoteTransactionHandler.2")); //$NON-NLS-1$ monitor.worked(1); // Transaktion ausf�hren RemoteTransactionHandler rth = new RemoteTransactionHandler(); dbutil.deleteAllReason(); dbutil.deleteAllJobReason(); dbutil.deleteAllJobMonText(); dbutil.deleteAllIncident(); dbutil.deleteAllJobFormDesc(); dbutil.deleteAllJobNoForm(); dbutil.deleteAllReportMessage(); dbutil.deleteAllDrive(); dbutil.deleteAllBilling(); dbutil.deleteAllInvoice(); dbutil.deleteAllInternalWorkType(); dbutil.deleteAllAbsenceType(); dbutil.deleteAllServiceRefused(); dbutil.deleteAllChecklist(); dbutil.deleteAllProgress(); dbutil.deleteFormMetadata(); dbutil.deleteAllStateOfInstallation(); dbutil.deleteAllNextIntervention(); dbutil.deleteAllInventoryStock(); dbutil.deleteAllInventory(); dbutil.deleteAllReceiptOfGoods(); if (rth.refreshMasterdata(perno, tableName, initalRequest)) { monitor.comment(Messages.getString("RemoteTransactionHandler.3")); //$NON-NLS-1$ monitor.worked(1); // Records ohne REFRESHED Flag l�schen if ("X".equalsIgnoreCase(initalRequest)) { //$NON-NLS-1$ dbutil.deleteAllWorkTypeNonRefreshed(); dbutil.deleteAllErrorCodeNonRefreshed(); dbutil.deleteAllMaterialNonRefreshed(); dbutil.deleteAllEmployeeNonRefreshed(); dbutil.deleteAllReasonNonRefreshed(); dbutil.deleteAllJobDeleteReasonNonRefreshed(); dbutil.deleteAllJobMonTextNonRefreshed(); dbutil.deleteAllIncIdentNonRefreshed(); dbutil.deleteAllJobFormDescNonRefreshed(); dbutil.deleteAllJobNoFormNonRefreshed(); dbutil.deleteAllInvoiceNonRefreshed(); dbutil.deleteAllInternalWorkTypeNonRefreshed(); dbutil.deleteAllAbsenceTypeNonRefreshed(); dbutil.deleteAllServiceRefusedNonRefreshed(); dbutil.deleteAllChecklistNonRefreshed(); dbutil.deleteAllProgresstNonRefreshed(); dbutil.deleteAllStateOfInstallationNonRefreshed(); dbutil.deleteAllNextInterventionNonRefreshed(); dbutil.deleteAllInventoryNonRefreshed(); dbutil.deleteAllReceiptOfGoodsNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.WorkType.WORK_TYPE)) { dbutil.deleteAllWorkTypeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.ErrorCode.ERROR_CODE)) { dbutil.deleteAllErrorCodeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Material.MATERIAL)) { dbutil.deleteAllMaterialNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Employee.EMPLOYEE)) { dbutil.deleteAllEmployeeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.InternalWorkType.INTERNAL_WORK_TYPE)) { dbutil.deleteAllInternalWorkTypeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.AbsenceType.ABSENCE_TYPE)) { dbutil.deleteAllAbsenceTypeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.ServiceRefused.SERVICE_REFUSED)) { dbutil.deleteAllServiceRefusedNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Checklist.CHECK_LIST)) { dbutil.deleteAllChecklistNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Progress.PROGRESS)) { dbutil.deleteAllProgresstNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.StateOfInstallation.STATE_OF_INSTALLATION)) { dbutil.deleteAllStateOfInstallationNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.NextIntervention.NEXT_INVENTION)) { dbutil.deleteAllNextInterventionNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Inventory.INVENTORY)) { dbutil.deleteAllInventoryNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS)) { dbutil.deleteAllReceiptOfGoodsNonRefreshed(); } db.commit(); monitor.comment(Messages.getString("RemoteTransactionHandler.4")); //$NON-NLS-1$ monitor.worked(1); countFromTable("LocalizedTexts", LocalizedTexts.TABLE); countFromTable("Reason", DbConstants.Reason.REASON); countFromTable("Job return reason", DbConstants.JobReturnReason.JOB_RETURN_REASON); countFromTable("JobMon text", DbConstants.JobMonText.JOB_MON_TEXT); countFromTable("Incident", DbConstants.Incident.INCIDENT); countFromTable("Report message", DbConstants.ReportMessage.REPORT_MESSAGE); countFromTable("Drive", DbConstants.Drive.DRIVE); countFromTable("Billing", DbConstants.Billing.BILLING); countFromTable("Work type", DbConstants.WorkType.WORK_TYPE); countFromTable("Internal work type", DbConstants.InternalWorkType.INTERNAL_WORK_TYPE); countFromTable("Absence type", DbConstants.AbsenceType.ABSENCE_TYPE); countFromTable("Service Refused", DbConstants.ServiceRefused.SERVICE_REFUSED); countFromTable("Check list", DbConstants.Checklist.CHECK_LIST); countFromTable("PROGRESS", DbConstants.Progress.PROGRESS); countFromTable("FORM", DbConstants.Form.FORM); countFromTable("FORMITEM", DbConstants.FormItem.FORMITEM); countFromTable("FORMVALUELIST", DbConstants.FormValueList.FORMVALUELIST); countFromTable("State of installation", DbConstants.StateOfInstallation.STATE_OF_INSTALLATION); countFromTable("Next intervention", DbConstants.NextIntervention.NEXT_INVENTION); countFromTable("inventory", DbConstants.Inventory.INVENTORY); countFromTable("ReceiptOfGoods", DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS); // reload user profile (might have changed by master data refresh) // and update user's warehouse number from employee master data Person user = dbutil.getUser(true); user.setWarehouseNumber(""); Employee userEmployee = dbutil.selectEmployeeByPerNr(user.getPersonalNumber()); if (userEmployee != null) user.setWarehouseNumber(userEmployee.getWarehouseNumber()); dbutil.updateUser(user); } } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { db.rollback(); } } return true; } private void countFromTable(String name, String table) { int rowsCount = dbutil.selectCountFromTable(table, ""); log.info(name + " " + table + " -> " + rowsCount); //reduce number of toasts... //if (rowsCount == 0) { // MessageUtil.getInstance().showMessage(name + " not received from server."); //} } /** * runs the operation REFRESH_MASTERDATA in order to retrieve the entire set * of master data tables * * @param perno employee ID * @param tableName name of the requested master data table. * @param initalRequest flag that defines an initial download of all master data tables. * @return */ private boolean refreshMasterdata(int perno, String tableName, String initalRequest) { boolean result = true; Transaction transaction = tr.getSynchronousTransaction("REFRESH_MASTERDATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); // get generic form draft download flag from registry boolean genericFormsDraftDownload = RegistryUtil.isGenericFormsDraftDownload(); try { transaction.start(false) .addElement("PERNR", perno) //$NON-NLS-1$ .addElement("TABLENAME", tableName) //$NON-NLS-1$ .addElement("INIT", initalRequest) //$NON-NLS-1$ .addElement("DRAFT", genericFormsDraftDownload); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // String reason = response.getStringElement("ZKDMOBMVCAS"); //$NON-NLS-1$ // String plan = response.getStringElement("ZKDMOBMONTXT"); //$NON-NLS-1$ // success // if (log.isDebugEnabled()) log.info("REFRESH_MASTERDATA(TABLENAME=" + tableName + ", INIT=" + initalRequest + ") completed successfully"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // log.info("ZKDMOBMVCAS " + reason + " ZKDMOBMONTXT " + plan); } else { // error if (log.isDebugEnabled()) { log.error("communication error: ", transaction.getLastException().fillInStackTrace()); //$NON-NLS-1$ } android.util.Log.e("ERROR", Arrays.toString(transaction.getLastException().getStackTrace()), transaction.getLastException().fillInStackTrace()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * runs the operation REGISTER_USER in order to retrieve a new user record * * @param perno employee ID * @param pwd password * @return */ public boolean runRegisterUser(int perno, String pwd) { ensureAMThread(); boolean result = false; Transaction transaction = tr.getSynchronousTransaction("REGISTER_USER"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addElement("PERNR", perno).addElement("PWD", pwd); //$NON-NLS-1$ //$NON-NLS-2$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success String info = response.getStringElement("INFO"); //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("REGISTER_USER(PERNR=" + perno + ", PWD=" + pwd + ") completed successfully with info code " + info); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if ("01".equalsIgnoreCase(info)) { //$NON-NLS-1$ return true; } else if ("02".equalsIgnoreCase(info)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("invalidUsernameOrPassword")); //$NON-NLS-1$ } else if ("03".equalsIgnoreCase(info)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("userLocked")); //$NON-NLS-1$ } else if ("04".equalsIgnoreCase(info)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("userIsNotRegistred")); //$NON-NLS-1$ } } else { // error if (log.isDebugEnabled()) { log.debug("communication error: "); //$NON-NLS-1$ } showCommunicationErrorMessage(transaction.getLastException().getMessage()); } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); } finally { // clean up transaction.dispose(); } return result; } /** * runs the operation GET_ORDER in order to retrieve a certain order from * the server * * @param orderId the id of the order * @param orderType the type of the order * @param pernr the personal number of the order * @return */ public RemoteTransactionResult runGetOrder(String orderId, String orderType, int pernr) { ensureAMThread(); log.info("orderId " + orderId + " orderType " + orderType + " pernr " + pernr); Transaction transaction = tr.getSynchronousTransaction("GET_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false) .addElement("MLDNR", orderId) .addElement("AUART", orderType) .addElement("PERNR", pernr); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { String msgType = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String msg = response.getStringElement("MSG"); //$NON-NLS-1$ if ("E".equalsIgnoreCase(msgType)) { //$NON-NLS-1$ // error log.info("SAP error message: " + msg); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + msg); //$NON-NLS-1$ return new RemoteTransactionResult(RemoteTransactionResult.Status.error, msg, msgType); } else { // success if (log.isDebugEnabled()) { log.debug("GET_ORDER completed successfully"); //$NON-NLS-1$ } } if (log.isDebugEnabled()) { log.debug("MSGTYPE /" + msgType + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); return new RemoteTransactionResult(RemoteTransactionResult.Status.error); } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); return new RemoteTransactionResult(RemoteTransactionResult.Status.error); } finally { // clean up transaction.dispose(); } return new RemoteTransactionResult(RemoteTransactionResult.Status.success); } /** * runs the operation CREATE_ORDER in order to request SAP (the server) to * create a new order * * @param personalNumber * @param kommissionNumber * @return */ public Job runCreateOrder(int personalNumber, String kommissionNumber) { ensureAMThread(); Job newJob = null; Transaction transaction = tr.getSynchronousTransaction("CREATE_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("CREATE_ORDER (kommissionNumber=" + kommissionNumber + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { transaction.start(true).addElement("PERNR", personalNumber).addElement("VBELN", kommissionNumber.toUpperCase()); //$NON-NLS-1$ //$NON-NLS-2$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("CREATE_ORDER completed successfully"); //$NON-NLS-1$ } String msgtype = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String msg = response.getStringElement("MSG"); //$NON-NLS-1$ String mldnr = response.getStringElement("MLDNR"); //$NON-NLS-1$ String auart = response.getStringElement("AUART"); //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("MSGTYPE /" + msgtype + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MLDNR /" + mldnr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("AUART /" + auart + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } if ("S".equalsIgnoreCase(msgtype)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(msg); newJob = dbutil.selectJobByJobIdAndJobType(mldnr, auart); } else if ("E".equalsIgnoreCase(msgtype)) { //$NON-NLS-1$ // error log.info("SAP error message: " + msg); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + msg); //$NON-NLS-1$ // app.inform(Messages.getString("SAPErrorMessage") + msg); } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); } finally { // clean up transaction.dispose(); } return newJob; } /** * saves an order * * Note: the name of this transaction is misleading, it is used for two use * cases:

    *
  • inform SAP that an address or other order data has been edited (case 1)
  • *
  • inform SAP that a new job has been created (case 2)
  • *
* The two cases are only distinct with respect to the addresses to transfer. * * @param job the job * @param address the address edited, null otherwise * @return */ public boolean runSaveOrder(Job job, Address address) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("SAVE_ORDER"); //$NON-NLS-1$ } try { Request request = transaction.start(true) .addElement("PERNR", job.getPersonalNumber()) //$NON-NLS-1$ .addQuery("ZKDMOB", sqlQuerySelectJob(job.getJobNumber(), job.getJobType().getCode(), job.getPersonalNumber(), job.isDriveTypeUpdated()), jobElementTempLate()); //$NON-NLS-1$ if (address != null) { // add the address that has been edited request.addQuery("ZKDMOBADR", sqlQuerySelectAddress(address), addressElementTemplate()); //$NON-NLS-1$ } else if (job.isLocalJob() && !job.isDriveTypeUpdated()) { // add all addressed linked to this job if the job was created in the app request.addQuery("ZKDMOBADR", sqlQuerySelectAddress(job), addressElementTemplate()); //$NON-NLS-1$ } log.info(sqlQuerySelectAddress(job)); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("SAVE_ORDER completed successfully"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetOrderList(String orderId, int pernr, String auart, String vbeln, String street, String city1, String postCode1, String name4, String savOff) { ensureAMThread(); boolean result = true; log.info("pernr " + pernr + " jobType " + auart + " commission " + vbeln); Transaction transaction = tr.getSynchronousTransaction("GET_ORDER_LIST"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false) .addElement("PERNR", pernr) .addElement("AUART", auart) .addElement("MLDNR", orderId) .addElement("VBELN", vbeln.toUpperCase()) .addElement("STREET", street) .addElement("CITY1", city1) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ .addElement("POST_CODE1", postCode1) .addElement("NAME4", name4) .addElement("SAVOFF", savOff); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("GET_ORDER_LIST completed successfully"); //$NON-NLS-1$ } String msg = response.getStringElement("MSG"); //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } if (msg.length() > 0) { MessageUtil.getInstance().showMessage(msg); } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetShortMSG(int pernr, String tdName) { ensureAMThread(); boolean result = true; SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Transaction transaction = tr.getSynchronousTransaction("GET_SHORT_MSG"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runGetShortMSG - PERNR /" + pernr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.info("runGetShortMSG - TDNAME /" + tdName + "/"); //$NON-NLS-1$ //$NON-NLS-2$ transaction.start(false).addElement("PERNR", pernr).addElement("TDNAME", tdName); //$NON-NLS-1$ //$NON-NLS-2$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success ShortMessage newMsg = dbutil.selectShortMessageByPerNoAndTdName(pernr, tdName); newMsg.setReceiveDate(format.format(new Date())); newMsg.setReceiveTime(new Date()); dbutil.updateShortMessage(newMsg); if (log.isDebugEnabled()) { log.debug("GET_SHORT_MSG completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runComfirmShortMSG(ShortMessage shortMessage) { ensureAMThread(); boolean result = true; DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); Transaction transaction = tr.getAsynchronousTransaction("CONFIRM_SHORTMSG"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { shortMessage.setStatus(CommonConstants.ShortMessage.Status.CONFIRMED); dbutil.updateShortMessage(shortMessage); transaction.start(false).addQuery("ZSHORTMSG", //$NON-NLS-1$ "SELECT " + DbConstants.ShortMessage.MESSAGE_KEY + ", " + DbConstants.ShortMessage.PERSONAL_NUMBER + ", " + DbConstants.ShortMessage.CONFIRM + DbConstants.From.FROM_TEXT //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + DbConstants.ShortMessage.SHORT_MESSAGE + DbConstants.Where.WHERE_TEXT + DbConstants.ShortMessage.PERSONAL_NUMBER + " = " + shortMessage.getPersonalNumber() + " AND " + DbConstants.ShortMessage.MESSAGE_KEY //$NON-NLS-1$ //$NON-NLS-2$ + " ='" + shortMessage.getMessageKey() + "'", //$NON-NLS-1$ //$NON-NLS-2$ new ElementTemplate[] { Element.STRING(DbConstants.ShortMessage.MESSAGE_KEY), Element.INT(DbConstants.ShortMessage.PERSONAL_NUMBER), Element.STRING(DbConstants.ShortMessage.CONFIRM) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("CONFIRM_SHORTMSG queued"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up if (db.isTransactionPending()) { db.rollback(); } } return result; } private boolean runSaveReportWithSignatureFileAttachment(int perno, String orderId, String orderType, String guid, File file) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_REPORT"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addElement("PERNR", perno) //$NON-NLS-1$ .addQuery("ZKDMOBREP", sqlQuerySelectActivedReport(orderId, orderType), reportElementTemplate()) //$NON-NLS-1$ .addQuery("ZKDMOBMSG", sqlQuerySelectMessage(guid), jobMessageElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMATORD", sqlQuerySelectReportMaterial(guid), reportMaterialElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMOBRTIM", sqlQuerySelectJobReportTime(guid), jobTimeElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMOBMEAS", sqlQuerySelectReportMeasurements(guid), reportMeasurementElementTempLate()) //$NON-NLS-1$ .addQuery("FORMINSTANCE", sqlQuerySelectFormInstances(guid), reportFormInstancesElementTempLate()) //$NON-NLS-1$ .addAttachmentElement(DbConstants.Report.SIGNATURE, file); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSavePicture(JobFile jobFile) { boolean result = true; log.info("MLDNR " + jobFile.getJobNumber() + "\nAUART " + jobFile.getJobType().getCode() + "\nGUID " + jobFile.getGuid() + "\nATTCLAS " + jobFile.getType() + "\nIDX " + jobFile.getJobFileId() + "\nDESC " + jobFile.getDescription() + "\nSIGNPIC_AT " + (jobFile.getSignpicAt().length() > 20 ? jobFile.getSignpicAt().substring(0, 20) + "..." : "") + "\nFORMTYPE " + jobFile.getFormType().getCode() + "\nFORMDESC " + jobFile.getFormDesc() ); Transaction transaction = tr.getAsynchronousTransaction("SAVE_PICTURE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false) .addElement("MLDNR", jobFile.getJobNumber()) .addElement("AUART", jobFile.getJobType().getCode()) .addElement("GUID", jobFile.getGuid()) .addElement("ATTCLAS", jobFile.getType()) .addElement("IDX", jobFile.getJobFileId()) .addElement("DESC", jobFile.getDescription()) .addElement("SIGNPIC_AT", jobFile.getSignpicAt()) .addElement("FORMTYPE", jobFile.getFormType().getCode()) .addElement("FORMDESC", jobFile.getFormDesc()); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSavePicture(String orderId, String orderType, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PICTURE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addQuery(DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE, sqlQuerySelectJobFile(orderId, orderType, guid), pictureElementTempLate()); // $NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSavePersonalPicture(String orderId, String orderType, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_PICS"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addQuery("ZKDMOBMV", sqlQuerySelectJobFile(orderId, orderType, guid), pictureElementTempLate()); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSynchronize(int pernr) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("SYNCHRONIZE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runSynchronize - PERNR /" + pernr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ transaction.start(true).addElement("PERNR", pernr); //$NON-NLS-1$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success response.getDateElement("SERVER_TIME"); //$NON-NLS-1$ try { // app.appman.setSystemDateTime(srvTime); } catch (Exception e) { log.error("Setting system date and time failed: " + e.getMessage()); //$NON-NLS-1$ log.error(e); } if (log.isDebugEnabled()) { log.debug("SYNCHRONIZE completed successfully"); //$NON-NLS-1$ } } else { // error if (log.isDebugEnabled()) { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ } showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveAbsence(Date date, int pernr, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_ABSENCE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addQuery("ZKDMAABSENCE", sqlQuerySelectAbsenceNotification(date, pernr, guid), absenceNotificationElementTempLate()); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("save absence to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * Selects one single address * * @param address * @return */ private String sqlQuerySelectAddress(Address address) { return "SELECT " + DbConstants.Address.JOB_NUMBER + " ," + DbConstants.Address.JOB_TYPE + " ," + DbConstants.Address.PARTNER_NUMBER + " ," + DbConstants.Address.COMMISSION_NUMBER + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Address.CUSTOMER_NUMBER + " ," + DbConstants.Address.TITLE + " ," + DbConstants.Address.NAME1 + " ," + DbConstants.Address.NAME2 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.NAME3 + " ," + DbConstants.Address.LOCATION + " ," + DbConstants.Address.STREET + " ," + DbConstants.Address.CITY + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.PASTAL_CODE + " ," + DbConstants.Address.PHONE_1 + " ," + DbConstants.Address.PHONE_2 + " ," + DbConstants.Address.FAX + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.EMAIL + " FROM " + DbConstants.Address.ADDRESS + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + address.getJobNumber() + "'" + " AND " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Address.JOB_TYPE + " = '" + address.getJobType() + "'" + " AND " + DbConstants.Address.PARTNER_NUMBER + " = '" + address.getPartnerNummer() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } /** * selects all addresses linked to a job * * @param job * @return */ private String sqlQuerySelectAddress(Job job) { return "SELECT " + DbConstants.Address.JOB_NUMBER + " ," + DbConstants.Address.JOB_TYPE + " ," + DbConstants.Address.PARTNER_NUMBER + " ," + DbConstants.Address.COMMISSION_NUMBER + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Address.CUSTOMER_NUMBER + " ," + DbConstants.Address.TITLE + " ," + DbConstants.Address.NAME1 + " ," + DbConstants.Address.NAME2 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.NAME3 + " ," + DbConstants.Address.LOCATION + " ," + DbConstants.Address.STREET + " ," + DbConstants.Address.CITY + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.PASTAL_CODE + " ," + DbConstants.Address.PHONE_1 + " ," + DbConstants.Address.PHONE_2 + " ," + DbConstants.Address.FAX + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.EMAIL + " FROM " + DbConstants.Address.ADDRESS + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + job.getJobNumber() + "'" + " AND " + DbConstants.Address.JOB_TYPE //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + " = '" + job.getJobType() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ } private ElementTemplate[] addressElementTemplate() { return new ElementTemplate[] { Element.STRING(DbConstants.Address.JOB_NUMBER), Element.STRING(DbConstants.Address.JOB_TYPE), Element.STRING(DbConstants.Address.PARTNER_NUMBER), Element.STRING(DbConstants.Address.COMMISSION_NUMBER), Element.STRING(DbConstants.Address.CUSTOMER_NUMBER), Element.STRING(DbConstants.Address.TITLE), Element.STRING(DbConstants.Address.NAME1), Element.STRING(DbConstants.Address.NAME2), Element.STRING(DbConstants.Address.NAME3), Element.STRING(DbConstants.Address.LOCATION), Element.STRING(DbConstants.Address.STREET), Element.STRING(DbConstants.Address.CITY), Element.STRING(DbConstants.Address.PASTAL_CODE), Element.STRING(DbConstants.Address.PHONE_1), Element.STRING(DbConstants.Address.PHONE_2), Element.STRING(DbConstants.Address.FAX), Element.STRING(DbConstants.Address.EMAIL) }; } private String sqlQuerySelectJob(String MLDNR, String AUART, int pernr, boolean driveTypeUpdated) { StringBuilder sb = new StringBuilder(); sb.append("SELECT "); //$NON-NLS-1$ sb.append(DbConstants.Job.JOB_NUMBER); sb.append(" ," + DbConstants.Job.JOB_TYPE); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.PERSONAL_NUMBER); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.CUSTOMER_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.PARTNER_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.OBJECT_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.OWNER_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.COMMISSION_NUMBER); //$NON-NLS-1$ // send driver type only if entered/updated in app if (driveTypeUpdated) sb.append(" ," + DbConstants.Job.DRIVER_TYPE); //$NON-NLS-1$ sb.append(" FROM " + DbConstants.Job.JOB); //$NON-NLS-1$ sb.append(" WHERE " + DbConstants.Job.JOB_NUMBER + " = '" + MLDNR + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append(" AND " + DbConstants.Job.JOB_TYPE + " = '" + AUART + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append(" AND " + DbConstants.Job.PERSONAL_NUMBER + " = " + pernr + ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return sb.toString(); } private ElementTemplate[] jobElementTempLate() { return new ElementTemplate[] { Element.INT(DbConstants.Job.PERSONAL_NUMBER) }; } private String sqlQuerySelectActivedReport(String orderId, String orderType) { return "SELECT " + DbConstants.Report.GUID + " ," + DbConstants.Report.CREATE_DATE + " ," + DbConstants.Report.JOB_NUMBER + " ," + DbConstants.Report.JOB_TYPE + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Report.COMMISSION_NUMBER + " ," + DbConstants.Report.PERSONAL_NUMBER + " ," + DbConstants.Report.PARTICAL_REPAIR + " ," + DbConstants.Report.FINAL_REPAIR + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.REASONING + " ," + DbConstants.Report.INCIDENT_AB + " ," + DbConstants.Report.BILLING + " ," + DbConstants.Report.SAFETY_REPORT + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.CUSTOMER_SUPPORT + " ," + DbConstants.Report.CUSTOMRE_SUPPORT_TEXT + " ," + DbConstants.Report.CHECK_LIST + " ," + DbConstants.Report.ERROR_ID_1 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.ERROR_H_1 + " ," + DbConstants.Report.ERROR_FLAG_1 + " ," + DbConstants.Report.ERROR_ID_2 + " ," + DbConstants.Report.ERROR_H_2 + " ," + DbConstants.Report.ERROR_FLAG_2 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " ," + DbConstants.Report.ERROR_ID_3 + " ," + DbConstants.Report.ERROR_H_3 + " ," + DbConstants.Report.ERROR_FLAG_3 + " ," + DbConstants.Report.SYSTEM_ERROR + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Report.DISTANCE + " ," + DbConstants.Report.EXPENSES + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_1 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_2 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.SERVICE_PLAN_MENTH_3 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_4 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_5 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_6 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.MONTH_YEAR + " ," + DbConstants.Report.ORDER_NUMBER + " ," + DbConstants.Report.SIGNATURE_GUID + " ," + DbConstants.Report.SIGNATURE_FLAG + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.SIGNATURE_INFO + " ," //$NON-NLS-1$ // TODO Was erwartet Sven im Feld SIGNPIC? (sollte m. E. den // Dateinamen enthalten obder besser gar nicht �bermittelt // werden) + DbConstants.Report.SIGNATURE + " ," + DbConstants.Report.WORK_TYPE // MIG-513 CHANGE: NOMATUSED isn't necessary anymore in SAVE_REPORT // + " ," + DbConstants.Report.NO_MATERIAL + " ," + DbConstants.Report.CYCLE_OF_INSTALLATION + " ," + DbConstants.Report.NO_FORM1 + " ," + DbConstants.Report.NO_FORM2 + " ," + DbConstants.Report.NO_FORM3 + " ," + DbConstants.Report.SERVICE_REFUSED + " ," + DbConstants.Report.OPEN_PENDING + " ," + DbConstants.Report.GOVERNMENT_REPORT + " ," + DbConstants.Report.CHECKLIST_STATE + " ," + DbConstants.Report.CHECKLIST_SIA + " ," + DbConstants.Report.CHECKLIST_READY + " ," + DbConstants.Report.CHECKLIST_INSTRUCTION + " ," + DbConstants.Report.CHECKLIST_VKF + " ," + DbConstants.Report.CHECKLIST_TEST + " ," + DbConstants.Report.SIGNATURE_NAME + " ," + DbConstants.Report.MON_STK + " ," + DbConstants.Report.NEXT_INTERVENTION_DATE + " ," + DbConstants.Report.STATE_OF_INSTALLATION + " ," + DbConstants.Report.NEXT_INTERVENTION_CODE + " FROM " + DbConstants.Report.REPORT + " WHERE " + DbConstants.Report.JOB_NUMBER + " = '" + orderId //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + "'" + " AND " + DbConstants.Report.JOB_TYPE + " = '" + orderType + "'" + " AND " + DbConstants.Report.IDX + " = (" + "SELECT MAX(" + DbConstants.Report.IDX + ") " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + "FROM " + DbConstants.Report.REPORT + " WHERE MLDNR = '" + orderId + "'" + " AND AUART = '" + orderType + "' )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } private ElementTemplate[] reportElementTemplate() { return new ElementTemplate[] { Element.STRING(DbConstants.Report.GUID), Element.DATETIME(DbConstants.Report.CREATE_DATE), Element.STRING(DbConstants.Report.JOB_NUMBER), Element.STRING(DbConstants.Report.JOB_TYPE), Element.STRING(DbConstants.Report.COMMISSION_NUMBER), Element.INT(DbConstants.Report.PERSONAL_NUMBER), Element.STRING(DbConstants.Report.PARTICAL_REPAIR), Element.STRING(DbConstants.Report.FINAL_REPAIR), Element.STRING(DbConstants.Report.REASONING), Element.STRING(DbConstants.Report.INCIDENT_AB), Element.STRING(DbConstants.Report.BILLING), Element.STRING(DbConstants.Report.SAFETY_REPORT), Element.STRING(DbConstants.Report.CUSTOMER_SUPPORT), Element.STRING(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT), Element.STRING(DbConstants.Report.CHECK_LIST), Element.STRING(DbConstants.Report.ERROR_ID_1), Element.STRING(DbConstants.Report.ERROR_H_1), Element.STRING(DbConstants.Report.ERROR_FLAG_1), Element.STRING(DbConstants.Report.ERROR_ID_2), Element.STRING(DbConstants.Report.ERROR_H_2), Element.STRING(DbConstants.Report.ERROR_FLAG_2), Element.STRING(DbConstants.Report.ERROR_ID_3), Element.STRING(DbConstants.Report.ERROR_H_3), Element.STRING(DbConstants.Report.ERROR_FLAG_3), Element.STRING(DbConstants.Report.SYSTEM_ERROR), Element.STRING(DbConstants.Report.DISTANCE), Element.STRING(DbConstants.Report.EXPENSES), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_1), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_2), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_3), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_4), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_5), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_6), Element.STRING(DbConstants.Report.MONTH_YEAR), Element.STRING(DbConstants.Report.ORDER_NUMBER), Element.STRING(DbConstants.Report.SIGNATURE_GUID), Element.STRING(DbConstants.Report.SIGNATURE_FLAG), Element.STRING(DbConstants.Report.SIGNATURE_INFO), Element.STRING(DbConstants.Report.SIGNATURE), Element.STRING(DbConstants.Report.WORK_TYPE) , Element.STRING(DbConstants.Report.CYCLE_OF_INSTALLATION) , Element.STRING(DbConstants.Report.NO_FORM1), Element.STRING(DbConstants.Report.NO_FORM2), Element.STRING(DbConstants.Report.NO_FORM3), Element.STRING(DbConstants.Report.SERVICE_REFUSED), Element.STRING(DbConstants.Report.OPEN_PENDING),Element.STRING(DbConstants.Report.GOVERNMENT_REPORT), Element.STRING(DbConstants.Report.CHECKLIST_STATE), Element.STRING(DbConstants.Report.CHECKLIST_SIA), Element.STRING(DbConstants.Report.CHECKLIST_READY),Element.STRING(DbConstants.Report.CHECKLIST_INSTRUCTION), Element.STRING(DbConstants.Report.CHECKLIST_VKF), Element.STRING(DbConstants.Report.CHECKLIST_TEST), Element.STRING(DbConstants.Report.SIGNATURE_NAME), Element.STRING(DbConstants.Report.MON_STK), Element.DATETIME(DbConstants.Report.NEXT_INTERVENTION_DATE),Element.STRING(DbConstants.Report.STATE_OF_INSTALLATION),Element.STRING(DbConstants.Report.NEXT_INTERVENTION_CODE),}; } private String sqlQuerySelectReportMaterial(String guid) { return "SELECT " + DbConstants.ReportMaterial.GUID + " , " + DbConstants.ReportMaterial.IDX + " , " + DbConstants.ReportMaterial.NUMBER + " , " + DbConstants.ReportMaterial.PERSONAL_NUMBER + " , " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.ReportMaterial.COMMISSION_NUMBER + " , " + DbConstants.ReportMaterial.AMOUNT + " , " + DbConstants.ReportMaterial.DELIVERY + " , " + DbConstants.ReportMaterial.EXPRESS_DELIVERY + " , " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.ReportMaterial.ACCOUNT_CODE + " , " + DbConstants.ReportMaterial.NAME + " , " + DbConstants.ReportMaterial.PRICE + " , " + DbConstants.ReportMaterial.BARCODE + " , " + DbConstants.ReportMaterial.K14 + " , " + DbConstants.ReportMaterial.EXPLANATION_TEXT + " , " + DbConstants.ReportMaterial.OTHER_TYPE_FLAG + " FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.ReportMaterial.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ } private ElementTemplate[] reportMaterialElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.ReportMaterial.GUID), Element.INT(DbConstants.ReportMaterial.IDX), Element.STRING(DbConstants.ReportMaterial.NUMBER), Element.INT(DbConstants.ReportMaterial.PERSONAL_NUMBER), Element.STRING(DbConstants.ReportMaterial.COMMISSION_NUMBER), Element.STRING(DbConstants.ReportMaterial.AMOUNT), Element.STRING(DbConstants.ReportMaterial.DELIVERY), Element.STRING(DbConstants.ReportMaterial.EXPRESS_DELIVERY), Element.STRING(DbConstants.ReportMaterial.NAME), Element.STRING(DbConstants.ReportMaterial.PRICE), Element.STRING(DbConstants.ReportMaterial.BARCODE), Element.STRING(DbConstants.ReportMaterial.K14), Element.STRING(DbConstants.ReportMaterial.EXPLANATION_TEXT), Element.STRING(DbConstants.ReportMaterial.OTHER_TYPE_FLAG) }; } private String sqlQuerySelectMessage(String guid) { return "SELECT " + DbConstants.JobMessage.GUID + " ," + DbConstants.JobMessage.MESSAGE_ID + " ," + DbConstants.JobMessage.TEXT_1 + " ," + DbConstants.JobMessage.TEXT_2 + " ," + DbConstants.JobMessage.MoreText + " ," + DbConstants.JobMessage.MESSAGE_CODE + " FROM " + DbConstants.JobMessage.JOB_MESSAGE + " WHERE " + DbConstants.JobMessage.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } private ElementTemplate[] jobMessageElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.JobMessage.GUID) , Element.STRING(DbConstants.JobMessage.MESSAGE_ID) , Element.STRING(DbConstants.JobMessage.TEXT_1) , Element.STRING(DbConstants.JobMessage.TEXT_2) , Element.STRING(DbConstants.JobMessage.MoreText) , Element.STRING(DbConstants.JobMessage.MESSAGE_CODE) }; } private String sqlQuerySelectJobReportTime(String guid) { return "SELECT " + DbConstants.JobReportTime.GUID + " , " + DbConstants.JobReportTime.IDX + " , " + DbConstants.JobReportTime.START_TIME + " , " + DbConstants.JobReportTime.STOP_TIME + " , " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobReportTime.WORK_TYPE_CODE + " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } private ElementTemplate[] jobTimeElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.JobReportTime.GUID), Element.INT(DbConstants.JobReportTime.IDX), Element.DATETIME(DbConstants.JobReportTime.START_TIME), Element.DATETIME(DbConstants.JobReportTime.STOP_TIME), Element.STRING(DbConstants.JobReportTime.WORK_TYPE_CODE) }; } private String sqlQuerySelectJobFile(String orderId, String orderType, String guid) { return "SELECT " + DbConstants.JobFile.JOB_NUMBER + " ," + DbConstants.JobFile.JOB_TYPE + " ," + DbConstants.JobFile.GUID + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.TYPE + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.IDX + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.DESCRIPTION + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.SIGN_PIC_AT + " ," + DbConstants.JobFile.FORM_TYPE + " ," + DbConstants.JobFile.FORM_DESC + " ," + DbConstants.JobFile.SENT_DATE + " FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.JOB_NUMBER + " = '" + orderId + "'" + " AND " + DbConstants.JobFile.JOB_TYPE + " = '" + orderType + "'" + " AND " + DbConstants.JobFile.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } private ElementTemplate[] pictureElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.JobFile.JOB_NUMBER), Element.STRING(DbConstants.JobFile.JOB_TYPE), Element.STRING(DbConstants.JobFile.GUID), Element.STRING(DbConstants.JobFile.TYPE), Element.STRING(DbConstants.JobFile.IDX), Element.STRING(DbConstants.JobFile.DESCRIPTION), Element.STRING(DbConstants.JobFile.SIGN_PIC_AT), Element.STRING(DbConstants.JobFile.FORM_TYPE), Element.STRING(DbConstants.JobFile.FORM_DESC), Element.STRING(DbConstants.JobFile.SENT_DATE) }; } private String sqlQuerySelectReportMeasurements(String guid) { return "SELECT " + DbConstants.ReportMeasurement.GUID + " ," + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ," + DbConstants.ReportMeasurement.MEASURING_POINT + " ," + DbConstants.ReportMeasurement.MEASUREMENT + " ," + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ," + DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE + " ," + DbConstants.ReportMeasurement.DYNAMIC_TIME + " ," + DbConstants.ReportMeasurement.STATIC_END_POWER + " ," + DbConstants.ReportMeasurement.DEVICE_TYPE + " ," + DbConstants.ReportMeasurement.SN_OF_DEVICE + " ," + DbConstants.ReportMeasurement.CALIBRATION_DATE + " FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " = '" + guid + "'"; } private ElementTemplate[] reportMeasurementElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.ReportMeasurement.GUID), Element.STRING(DbConstants.ReportMeasurement.COMMISSION_NUMBER), Element.STRING(DbConstants.ReportMeasurement.MEASURING_POINT), Element.STRING(DbConstants.ReportMeasurement.MEASUREMENT), Element.STRING(DbConstants.ReportMeasurement.PERSONAL_NUMBER), Element.STRING(DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE), Element.STRING(DbConstants.ReportMeasurement.DYNAMIC_TIME), Element.STRING(DbConstants.ReportMeasurement.STATIC_END_POWER), Element.STRING(DbConstants.ReportMeasurement.DEVICE_TYPE), Element.STRING(DbConstants.ReportMeasurement.SN_OF_DEVICE), Element.DATETIME(DbConstants.ReportMeasurement.CALIBRATION_DATE) }; } private String sqlQuerySelectFormInstances(String guid) { return "SELECT " + FORMINSTANCE.COL_GUID + " ," + FORMINSTANCE.COL_FORMID + " ," + FORMINSTANCE.COL_FORMVERSION + " ," + FORMINSTANCE.COL_FORMITEMID + " ," + FORMINSTANCE.COL_VALUELISTID + " ," + FORMINSTANCE.COL_VALUEID + " ," + FORMINSTANCE.COL_FORMITEMTYPE + " ," + FORMINSTANCE.COL_STRINGVALUE + " ," + FORMINSTANCE.COL_BOOLEANVALUE + " ," + FORMINSTANCE.COL_FLOATVALUE + " ," + FORMINSTANCE.COL_ATTACHMENTVALUE + " FROM " + FORMINSTANCE.TABLE + " WHERE " + FORMINSTANCE.COL_GUID + " = '" + guid + "'"; } private ElementTemplate[] reportFormInstancesElementTempLate() { return new ElementTemplate[] { Element.STRING(FORMINSTANCE.COL_GUID), Element.STRING(FORMINSTANCE.COL_FORMID), Element.INT(FORMINSTANCE.COL_FORMVERSION), Element.STRING(FORMINSTANCE.COL_FORMITEMID), Element.STRING(FORMINSTANCE.COL_VALUELISTID), Element.STRING(FORMINSTANCE.COL_VALUEID), Element.STRING(FORMINSTANCE.COL_FORMITEMTYPE), Element.STRING(FORMINSTANCE.COL_STRINGVALUE), Element.BOOLEAN(FORMINSTANCE.COL_BOOLEANVALUE), Element.DOUBLE(FORMINSTANCE.COL_FLOATVALUE), Element.ATTACHMENT(FORMINSTANCE.COL_ATTACHMENTVALUE) }; } private String sqlQuerySelectAbsenceNotification(Date date, int pernr, String guid) { return "SELECT " + DbConstants.AbsenceNotification.GUID + " ," + DbConstants.AbsenceNotification.DATE + " ," + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " ," + DbConstants.AbsenceNotification.ABSENCE_TYPE + " ," + DbConstants.AbsenceNotification.DATE_FROM + " ," + DbConstants.AbsenceNotification.DATE_TO + " ," + DbConstants.AbsenceNotification.TIME_FROM + " ," + DbConstants.AbsenceNotification.TIME_TO + " ," + DbConstants.AbsenceNotification.TEXT + " FROM " + DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION + " WHERE " + DbConstants.AbsenceNotification.DATE + " = '" + date.getTime() + "'" + " AND " + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " = " + pernr + "" + " AND " + DbConstants.JobFile.GUID + " = '" + guid + "'"; } private ElementTemplate[] absenceNotificationElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.AbsenceNotification.GUID), Element.DATETIME(DbConstants.AbsenceNotification.DATE), Element.STRING(DbConstants.AbsenceNotification.PERSONAL_NUMBER), Element.STRING(DbConstants.AbsenceNotification.ABSENCE_TYPE), Element.DATE(DbConstants.AbsenceNotification.DATE_FROM), Element.DATE(DbConstants.AbsenceNotification.DATE_TO), Element.TIME(DbConstants.AbsenceNotification.TIME_FROM), Element.TIME(DbConstants.AbsenceNotification.TIME_TO), Element.STRING(DbConstants.AbsenceNotification.TEXT) }; } public boolean saveReport(DBSession db, Job job, String signaturePath) { ensureAMThread(); boolean result = true; Report report = job.getLatestReport(); db.startTransaction(); try { // assign value to objects if ((!report.isFinalRepair() && !report.isPartialRepair()) || report.isFinalRepair()) { job.setStatus(JobStatus.FINALIZED); } else if (report.isPartialRepair()) { job.setStatus(JobStatus.PARLTY_DONE); } job.setStatusEdit(new Date()); log.info("saveReport " + report.getGuId() + " job " + job.getJobNumber()); report.setReportStatus(ReportStatus.RECEIVED); // replace "U" with empty before send to server if (report.isChecklistStateUnselected()) { report.setChecklistState(false); } if (report.isChecklistSIAUnselected()) { report.setChecklistSIA(false); } if (report.isChecklistReadyUnselected()) { report.setChecklistReady(false); } if (report.isChecklistInstructionUnselected()) { report.setChecklistInstruction(false); } if (report.isChecklistVKFUnselected()) { report.setChecklistVKF(false); } if (report.isChecklistTestUnselected()) { report.setChecklistTest(false); } // update status dbutil.updateJob(job); // update report dbutil.updateReport(report); log.info("Next intervention date " + DateTimeUtil.showDate(report.getNextInterventionDate())); log.info("State of installation " + report.getStateOfInstallation()); log.info("Next intervention code " + report.getNextInterventionCode()); // Save report to backend (doing an implicit dbutil commit // on success) if(new RemoteTransactionHandler().runSaveReport(job.getPersonalNumber(), job.getJobNumber(), job.getJobType().getCode(), report, signaturePath)) { List reportImageAttachmentsList = dbutil.selectReportJobFileImageListByReport(report); for (JobFile image : reportImageAttachmentsList) { runSavePicture(image); image.setSentDate(new Date()); dbutil.updateJobFile(image); } List reportDocAttachmentsList = dbutil.selectReportJobFileListByReport(report); for (JobFile jobFile : reportDocAttachmentsList) { runSavePicture(jobFile); } List formImagesList = dbutil.selectFormImageListByReport(report); for (JobFile formImage : formImagesList) { runSavePicture(formImage); } } else { result = false; } } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { db.rollback(); } } return result; } public boolean runSaveReport(int perno, String orderId, String orderType, Report report, String signaturePath) { ensureAMThread(); String guid = report.getGuId(); if (StringUtil.isNotEmpty(report.getSignature())) { File att = new File(FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, signaturePath, report.getSignature(), false)); return runSaveReportWithSignatureFileAttachment(perno, orderId, orderType, guid, att); } else { return runSaveReportWithoutFile(perno, orderId, orderType, guid); } } private boolean runSaveReportWithoutFile(int perno, String orderId, String orderType, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_REPORT"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addElement("PERNR", perno).addQuery("ZKDMOBREP", sqlQuerySelectActivedReport(orderId, orderType), reportElementTemplate()) //$NON-NLS-1$ //$NON-NLS-2$ .addQuery("ZKDMOBMSG", sqlQuerySelectMessage(guid), jobMessageElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMATORD", sqlQuerySelectReportMaterial(guid), reportMaterialElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMOBRTIM", sqlQuerySelectJobReportTime(guid), jobTimeElementTempLate()) .addQuery("ZKDMOBMEAS", sqlQuerySelectReportMeasurements(guid), reportMeasurementElementTempLate()) .addQuery("FORMINSTANCE", sqlQuerySelectFormInstances(guid), reportFormInstancesElementTempLate()); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("update reports to remote server"); //$NON-NLS-1$ } else { // error if (log.isDebugEnabled()) { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * Updates job on SAP side in case that a wrong Kommissionnummer has been * sent with the job. * * In case that the transaction completes successfully then - the existing * job is deleted from the local database - the SAP returns a new job with * the very same primary key, but updated information * * In case that the transaction fails the existing job remains in the * database * * * @param job the job where the Kommissionummer has to be changed * @param user current user * @return true if successfully, false otherwise. */ public boolean runUpdateOrder(Job job, Person user) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("UPDATE_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); try { dbutil.deleteJob(job); transaction.start(false) .addElement("MLDNR", job.getJobNumber()) .addElement("AUART", job.getJobType().getCode()) .addElement("VBELN", job.getCommissionNumber().toUpperCase()) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ .addElement("PERNR", user.getPersonalNumber()); //$NON-NLS-1$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { String MSGTYPE = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String MSG = response.getStringElement("MSG"); //$NON-NLS-1$ if ("E".equalsIgnoreCase(MSGTYPE) && MSG.length() > 0) { //$NON-NLS-1$ // error log.info("SAP error message: " + MSG); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + MSG); //$NON-NLS-1$ result = false; } else { if (log.isDebugEnabled()) log.debug("MSG /" + MSG + "/"); //$NON-NLS-1$ //$NON-NLS-2$ // success if (log.isDebugEnabled()) log.debug("UPDATE_ORDER successfully"); //$NON-NLS-1$ db.commit(); } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { if (db.isTransactionPending()) { db.rollback(); } // clean up transaction.dispose(); } return result; } public boolean updateStatus(DBSession db, Job job, String status, String sapStatus, String reason) { ensureAMThread(); boolean result = true; db.startTransaction(); try { // update status job.setStatus(status); dbutil.updateJob(job); // send update status to backend (doing an implicit dbutil commit on // success) result = this.runUpdateStatus(job.getJobNumber(), job.getJobType().getCode(), sapStatus, job.getJobForward(), reason); } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { String logMsg = MessageFormat.format( "DB transaction is still pending after backend communication and will be rolled back! Tried to update job status: job = {0}/{1}, new job status = {2}, SAP status = {3}", //$NON-NLS-1$ new Object[] { job.getJobNumber(), job.getJobType(), status, sapStatus }); log.warn(logMsg); db.rollback(); } } return result; } private boolean runUpdateStatus(String orderId, String orderType, String orderStatus, int persno2, String reason) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("UPDATE_STATUS"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isInfoEnabled()) { log.info("UPDATE_STATUS (mldnr= " + orderId + ", auart= " + orderType + ", new status= " + orderStatus + ", if forwarded pernr= " + persno2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } try { transaction.start(true) .addElement("MLDNR", orderId) .addElement("AUART", orderType) .addElement("STATUS", orderStatus) .addElement("PERSNO2", persno2) .addElement("RETTXT", reason); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveTimeSheet(int perNr, CalendarTimeSheet calendar) { if (dbutil.getUser().getExpensesActive()) { return runSaveTimeSheetWitExpenses(perNr, calendar); } else { return runSaveTimeSheetWitoutExpenses(perNr, calendar); } } public boolean runSaveTimeSheetWitoutExpenses(int perNr, CalendarTimeSheet calendar) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_DATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("SAVE_PERSONAL_DATA (perNr=" + perNr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { String sqlTimeSheetE = "SELECT " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ," + DbConstants.TimeSheet.DATE + " ," + DbConstants.TimeSheet.START_TIME + " ," + DbConstants.TimeSheet.STOP_TIME + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.COST_CENTER + " ," + DbConstants.TimeSheet.WORK_TYPE_CODE + " ," + DbConstants.TimeSheet.CALL_FLAG + " FROM " + DbConstants.TimeSheet.TIME_SHEET + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.TimeSheet.START_TIME + " >='" + calendar.getDate().getTime() + "'" + " AND " + DbConstants.TimeSheet.START_TIME + " <='" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DateTimeUtil.getLateNight(calendar.getDate()).getTime().getTime() + "'" + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + perNr + "'" + " ORDER BY " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("Select ZKDMATIME for: '" + sqlTimeSheetE + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } transaction.start(true) .addQuery("ZKDMATIME", sqlTimeSheetE, //$NON-NLS-1$ new ElementTemplate[] { Element.INT(DbConstants.TimeSheet.PERSONAL_NUMBER), Element.DATETIME(DbConstants.TimeSheet.DATE), Element.DATETIME(DbConstants.TimeSheet.START_TIME), Element.DATETIME(DbConstants.TimeSheet.STOP_TIME), Element.STRING(DbConstants.TimeSheet.COST_CENTER), Element.STRING(DbConstants.TimeSheet.WORK_TYPE_CODE), Element.STRING(DbConstants.TimeSheet.CALL_FLAG) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveTimeSheetWitExpenses(int perNr, CalendarTimeSheet calendar) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_DATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("SAVE_PERSONAL_DATA (perNr=" + perNr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { String sqlTimeSheetE = "SELECT " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ," + DbConstants.TimeSheet.DATE + " ," + DbConstants.TimeSheet.START_TIME + " ," + DbConstants.TimeSheet.STOP_TIME + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.COST_CENTER + " ," + DbConstants.TimeSheet.WORK_TYPE_CODE + " ," + DbConstants.TimeSheet.CALL_FLAG + " FROM " + DbConstants.TimeSheet.TIME_SHEET + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.TimeSheet.START_TIME + " >='" + calendar.getDate().getTime() + "'" + " AND " + DbConstants.TimeSheet.START_TIME + " <='" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DateTimeUtil.getLateNight(calendar.getDate()).getTime().getTime() + "'" + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + perNr + "'" + " ORDER BY " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ String sqlExpenses = "SELECT " + DbConstants.Expenses.PERSONAL_NUMBER + " ," + DbConstants.Expenses.DATE + " ," + DbConstants.Expenses.EXPENSES_DATE + " ," + DbConstants.Expenses.DAILY_EXPENSES //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " ," + DbConstants.Expenses.VARIOUS_EXPENSES + " ," + DbConstants.Expenses.DECUCTION + " ," + DbConstants.Expenses.EXPENSES_KEY + " ," + DbConstants.Expenses.PIKETT_EXPENSES + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Expenses.EXPENSES_DESCRIPTION + " ," + DbConstants.Expenses.OPERATING_HOURS_OF + " ," + DbConstants.Expenses.OPERATION_HOURS_UP_TO + " ," + DbConstants.Expenses.OPERATION_HOURS_TOTAL + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Expenses.DEDUCTION_DESCRIPTION + " ," + DbConstants.Expenses.COMPENSTION + " FROM " + DbConstants.Expenses.EXPENSES + " WHERE " + DbConstants.Expenses.DATE + " = '" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + calendar.getDate().getTime() + "'" + " AND " + DbConstants.Expenses.PERSONAL_NUMBER + " = " + perNr + " ORDER BY " + DbConstants.Expenses.DATE + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ if (log.isDebugEnabled()) { log.debug("Select ZKDMATIME for: '" + sqlTimeSheetE + "'"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("Select ZKDMAEXPNS for: '" + sqlExpenses + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } transaction.start(true) .addQuery("ZKDMATIME", sqlTimeSheetE, //$NON-NLS-1$ new ElementTemplate[] { Element.INT(DbConstants.TimeSheet.PERSONAL_NUMBER), Element.DATETIME(DbConstants.TimeSheet.DATE), Element.DATETIME(DbConstants.TimeSheet.START_TIME), Element.DATETIME(DbConstants.TimeSheet.STOP_TIME), Element.STRING(DbConstants.TimeSheet.COST_CENTER), Element.STRING(DbConstants.TimeSheet.WORK_TYPE_CODE), Element.STRING(DbConstants.TimeSheet.CALL_FLAG) }) .addQuery("ZKDMAEXPNS", sqlExpenses, //$NON-NLS-1$ new ElementTemplate[] { Element.INT(DbConstants.Expenses.PERSONAL_NUMBER), Element.DATETIME(DbConstants.Expenses.DATE), Element.DATE(DbConstants.Expenses.EXPENSES_DATE), Element.STRING(DbConstants.Expenses.DAILY_EXPENSES), Element.STRING(DbConstants.Expenses.VARIOUS_EXPENSES), Element.STRING(DbConstants.Expenses.DECUCTION), Element.STRING(DbConstants.Expenses.EXPENSES_KEY), Element.STRING(DbConstants.Expenses.PIKETT_EXPENSES), Element.STRING(DbConstants.Expenses.EXPENSES_DESCRIPTION), Element.STRING(DbConstants.Expenses.OPERATING_HOURS_OF), Element.STRING(DbConstants.Expenses.OPERATION_HOURS_UP_TO), Element.STRING(DbConstants.Expenses.OPERATION_HOURS_TOTAL), Element.STRING(DbConstants.Expenses.DEDUCTION_DESCRIPTION), Element.STRING(DbConstants.Expenses.COMPENSTION) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean saveMaterial(int perNr, Order order) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_DATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); order.setStatus(CommonConstants.Order.Status.SENT_ORDER); order.setSentDate(DateTimeUtil.getTimestamp().getTime()); dbutil.updateOrder(order); if (log.isDebugEnabled()) { log.debug("SAVE_PERSONAL_DATA (perNr=" + perNr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { transaction.start(true).addQuery("ZKDMAMAT", //$NON-NLS-1$ "SELECT " + DbConstants.OrderMaterial.PERSONAL_NUMBER + ", " + DbConstants.OrderMaterial.DATE + ", " + DbConstants.OrderMaterial.AMOUNT + ", " + DbConstants.OrderMaterial.NUMBER + ", " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.OrderMaterial.EXPRESS_FLAG + ", " + DbConstants.OrderMaterial.VARIOUS_MATERIAL + " FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL + " WHERE " + DbConstants.OrderMaterial.PERSONAL_NUMBER + " = '" + perNr //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + "'" + " AND " + DbConstants.OrderMaterial.ORDER_DATE + " = '" + order.getCreateDate().getTime() + "'", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ new ElementTemplate[] { Element.INT(DbConstants.OrderMaterial.PERSONAL_NUMBER), Element.DATETIME(DbConstants.OrderMaterial.DATE), Element.STRING(DbConstants.OrderMaterial.AMOUNT), Element.STRING(DbConstants.OrderMaterial.NUMBER), Element.STRING(DbConstants.OrderMaterial.EXPRESS_FLAG), Element.STRING(DbConstants.OrderMaterial.VARIOUS_MATERIAL) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { if (db.isTransactionPending()) { db.rollback(); } // clean up transaction.dispose(); } return result; } private void showCommunicationErrorMessage(String message) { MessageUtil.getInstance().showMessage(Messages.getString("communicationErrorWithColon") + message); //$NON-NLS-1$ } public boolean runUpdateEdate(String orderId , String orderType , Date eDate , Date eDateTime , String reason) { boolean result = true; SimpleDateFormat dateFormate = new SimpleDateFormat("dd.MM.yyyy", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ SimpleDateFormat timeFormate = new SimpleDateFormat("HH:mm", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Transaction transaction = tr.getAsynchronousTransaction("UPDATE_EDATE"); //$NON-NLS-1$ transaction.setInsertOnly(false); String date = dateFormate.format(eDate); String time = timeFormate.format(eDateTime); log.info("EDATE_DT " + date + " EDATE_TI " + time); try { transaction.start(true) .addElement("MLDNR", orderId) .addElement("AUART", orderType) .addDateElement("EDATE", eDate) .addTimeElement("EDATE", eDateTime) .addElement("MVCASTXT", reason); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetInventryStock(int pernr, String wareHouseNumber, String language) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("SYNC_FZLG"); transaction.setInsertOnly(false); try { log.info("runSYNC_FZLG - PERNR /" + pernr + "/"); log.info("runSYNC_FZLG - LGORT /" + wareHouseNumber + "/"); transaction.start(false).addElement("PERNR", pernr).addElement("LGORT", wareHouseNumber).addElement("SPRAS", language); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success countFromTable("inventory Stock", DbConstants.VehicleInventory.VEHICLE_INVENTORY); if (log.isDebugEnabled()) { log.debug("SYNC_FZLG completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetMaterialMoveMent(String guid, int pernr, Date date) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("GET_MBEW"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runGetMaterialMoveMent - GUID /" + guid + "/ PERNR /" + pernr + "/"); transaction.start(false).addElement("GUID", guid).addElement("PERNR", pernr).addDateTimeElement("DATUM", date); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("GET_MBEW completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveMaterialMoveMent(MaterialMovement materialMovement) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_MBEW"); transaction.setInsertOnly(false); log.info("SAVE_MBEW (GUID= " + materialMovement.getGuid() + ", PERNR= " + materialMovement.getPersonalNumber() + ", MATNR= " + materialMovement.getMaterialNumber() + ", from= " + materialMovement.getFrom() + ", to= " + materialMovement.getTo() + ", ENTRY_QNT= " + materialMovement.getEntryCount() + ", ENTRY_UOM= " + materialMovement.getEntryUnit() + ", WEGRND= " + materialMovement.getReceiptOfGoods() + ", BARC= " + materialMovement.getBarcode() + ", BARCTXT= " + materialMovement.getBarcodeText() + ")"); try { dbutil.insertMaterialMovement(materialMovement); transaction.start(true).addQuery("ZKDMOBFZGMBEW", "SELECT " + DbConstants.MaterialMovement.GUID + ", " + DbConstants.MaterialMovement.PERSONAL_NUMBER + ", " + DbConstants.MaterialMovement.MATERIAL_NUMBER + ", " + DbConstants.MaterialMovement.FROM + ", " + DbConstants.MaterialMovement.TO + ", " + DbConstants.MaterialMovement.ENTRY_COUNT + ", " + DbConstants.MaterialMovement.ENTRY_UNIT + ", " + DbConstants.MaterialMovement.RECEIPT_OF_GOODS + ", " + DbConstants.MaterialMovement.BARCODE + ", " + DbConstants.MaterialMovement.BARCODE_TEXT + " FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + materialMovement.getGuid() + "'" + " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " = " + materialMovement.getPersonalNumber(), new ElementTemplate[] { Element.STRING(DbConstants.MaterialMovement.GUID), Element.INT(DbConstants.MaterialMovement.PERSONAL_NUMBER), Element.STRING(DbConstants.MaterialMovement.MATERIAL_NUMBER), Element.STRING(DbConstants.MaterialMovement.FROM), Element.STRING(DbConstants.MaterialMovement.TO), Element.STRING(DbConstants.MaterialMovement.ENTRY_COUNT), Element.STRING(DbConstants.MaterialMovement.ENTRY_UNIT), Element.STRING(DbConstants.MaterialMovement.RECEIPT_OF_GOODS), Element.STRING(DbConstants.MaterialMovement.BARCODE), Element.STRING(DbConstants.MaterialMovement.BARCODE_TEXT), }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("SAVE_MBEW queued"); //$NON-NLS-1$ } dbutil.deleteMaterialMovement(materialMovement); } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runConfirmMaterialMoveMent(MaterialMovement materialMovement) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("CONFIRM_MBEW"); transaction.setInsertOnly(false); log.info("CONF_MBEW (GUID= " + materialMovement.getGuid() + ", PERNR= " + materialMovement.getPersonalNumber() + ", EBELN= " + materialMovement.getOrderNumber() + ", EBELP= " + materialMovement.getOrderPosition() + ", ENTRY_QNT = " + materialMovement.getEntryCount() + ", ENTRY_UOM = " + materialMovement.getEntryUnit() + ")"); try { if (dbutil.selectMaterialMovement(materialMovement.getGuid()) != null) { dbutil.deleteMaterialMovement(materialMovement); } dbutil.insertMaterialMovement(materialMovement); transaction.start(true).addQuery("ZKDMOBFZGMBEW", "SELECT " + DbConstants.MaterialMovement.GUID + ", " + DbConstants.MaterialMovement.PERSONAL_NUMBER + ", " + DbConstants.MaterialMovement.ORDER_NUMBER + ", " + DbConstants.MaterialMovement.ORDER_POSITION + ", " + DbConstants.MaterialMovement.ENTRY_COUNT + ", " + DbConstants.MaterialMovement.ENTRY_UNIT + " FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + materialMovement.getGuid() + "'" + " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " = " + materialMovement.getPersonalNumber(), new ElementTemplate[] { Element.STRING(DbConstants.MaterialMovement.GUID), Element.INT(DbConstants.MaterialMovement.PERSONAL_NUMBER), Element.STRING(DbConstants.MaterialMovement.ORDER_NUMBER), Element.INT(DbConstants.MaterialMovement.ORDER_POSITION), Element.STRING(DbConstants.MaterialMovement.ENTRY_COUNT), Element.STRING(DbConstants.MaterialMovement.ENTRY_UNIT), }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("CONF_MBEW queued"); //$NON-NLS-1$ } dbutil.deleteMaterialMovement(materialMovement); } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetDeliveryList(int pernr, ProgressMonitor monitor) { ensureAMThread(); monitor.begin("run get Delivery list", 2); //$NON-NLS-1$ DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); try { // Transaktion ausf�hren RemoteTransactionHandler rth = new RemoteTransactionHandler(); monitor.comment(Messages.getString(("updatingDeliveryList"))); //$NON-NLS-1$ monitor.worked(1); dbutil.deleteAllDeliveryList(); if (rth.runGetDeliveryList(pernr)) { monitor.comment(Messages.getString(("deliveryListDownloaded"))); //$NON-NLS-1$ monitor.worked(1); // Records ohne REFRESHED Flag l�schen db.commit(); } } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { db.rollback(); } } return true; } public boolean runGetDeliveryList(int pernr) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("GET_DELVRY_LIST"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runGetDeliveryList - PERNR /" + pernr + "/"); dbutil.updateRefreshFlag(); // Transaktion ausf�hren transaction.start(false).addElement("PERNR", pernr); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("GET_DELVRY_LIST completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * Runs the operation SYNC_ORDER in order to synchronize local orders with * centrally dispatched orders from the server. As a result, new orders are * retrieved, present orders updated (regarding order schedule) and no more * dispatched orders deleted. * * @param pernr the personal number of the order * @return */ public boolean runSyncOrder(int pernr) { ensureAMThread(); log.info("SYNC_ORDER: pernr " + pernr); Transaction transaction = tr.getSynchronousTransaction("SYNC_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); TableElement withdrawnOrders = null; // lokal vorhandene Auftr�ge festhalten um sp�ter neu hinzugekommene // erkennen zu k�nnen HashSet localOrders = new HashSet(); DBSession db = Runtime.getApplicationManager().getDBSession(); ZKDMOB zkdmob = new ZKDMOB(db); TableCursor cursor = ZKDMOB.queryByPrimaryKey(zkdmob); try { while (cursor.next()) { localOrders.add(zkdmob.getAUART() + zkdmob.getMLDNR()); } } finally { cursor.dispose(); } try { transaction.start(false).addElement("PERNR", pernr) //$NON-NLS-1$ .addQuery("ZKDMOB", //$NON-NLS-1$ "SELECT " + DbConstants.Job.JOB_NUMBER + //$NON-NLS-1$ ", " + DbConstants.Job.JOB_TYPE + //$NON-NLS-1$ ", " + DbConstants.Job.STATUS + //$NON-NLS-1$ ", " + DbConstants.Job.APPOINTMENT_DATE + //$NON-NLS-1$ " FROM " + DbConstants.Job.JOB, //$NON-NLS-1$ new ElementTemplate[] { Element.DATETIME(DbConstants.Job.APPOINTMENT_DATE) }) .requestResponseTableElement("ZKDMOB_DEL"); //$NON-NLS-1$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { String msgType = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String msg = response.getStringElement("MSG"); //$NON-NLS-1$ if ("E".equalsIgnoreCase(msgType)) { //$NON-NLS-1$ // error log.info("SAP error message: " + msg); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + msg); //$NON-NLS-1$ return false; } else { // success if (log.isDebugEnabled()) { log.debug("SYNC_ORDER completed successfully"); //$NON-NLS-1$ } // extract withdrawn orders for later processing withdrawnOrders = response.getTableElement("ZKDMOB_DEL"); } if (log.isDebugEnabled()) { log.debug("MSGTYPE /" + msgType + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); return false; } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); return false; } finally { // clean up transaction.dispose(); } // delete withdrawn orders in state 00, 01 and 02 without further feedback db.startTransaction(); try { for (int i = 0; i < (withdrawnOrders != null ? withdrawnOrders.getSize() : 0); i++) { withdrawnOrders.readRow(i); String jobNumber = withdrawnOrders.getStringElement(DbConstants.Job.JOB_NUMBER); String jobType = withdrawnOrders.getStringElement(DbConstants.Job.JOB_TYPE); log.info("Withdrawing job " + jobNumber + ", type " + jobType); DatabaseUtil dbUtil = DatabaseUtil.getInstance(); Job job = dbUtil.selectJobByJobIdAndJobType(jobNumber, jobType); // check stop date for deletability: still a new not yet in progress or somehow completed order? JobStatus jobState = job.getStatus(); if (!(jobState.isInitial() || jobState.isNew() || jobState.isReceived())) { log.info("... not changed due to current state: " + jobState.getCode()); continue; } // check report data if (job.hasReportedData(dbUtil)) { log.info("... not changed due to existing report data."); continue; } dbUtil.deleteJob(job); log.info("... deleted"); } db.commit(); } finally { if (db.isTransactionPending()) db.rollback(); } // post update state for newly received orders cursor = ZKDMOB.queryByPrimaryKey(zkdmob); try { while (cursor.next()) { String jobNumber = zkdmob.getMLDNR(); String jobType = zkdmob.getAUART(); // new order? if (localOrders.contains(jobType + jobNumber)) continue; // no // update_status log.info("Confirming new job " + jobNumber + ", type " + jobType); Job job = dbutil.selectJobByJobIdAndJobType(zkdmob.getMLDNR(), zkdmob.getAUART()); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } } finally { cursor.dispose(); } return true; } /** * Send presence state to SAP. * @param pernr Currently logged in user for which the presence state is reported. * @param arba The work type associated with the presence update (optional). * @param state The new presence state. * @return true if successfully, false otherwise. */ public boolean runUpdatePresence(int pernr, String arba, PresenceState state) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("UPDATE_PRESENCE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { Request req = transaction.start(true); req.addElement("PERNR", pernr); req.addDateTimeElement("TIMESTAMP", new Date()); req.addElement("STATE", state.toString()); if (!StringUtil.isEmpty(arba)) req.addElement("ARBA", arba); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update presence to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } }     common/src/ch/mfiles/kaba/kolibri/common/net/RemoteTransactionResult.java:   package ch.mfiles.kaba.kolibri.common.net; public class RemoteTransactionResult { private String messageType = "S"; private String message = ""; private Status status; public enum Status { success, error } public RemoteTransactionResult(Status status, String message, String msgType) { this.message = message; this.status = status; this.messageType = msgType; } public RemoteTransactionResult(Status status) { this.status = status; } public String getMessage() { return message; } public Status getStatus() { return status; } public String getMessageType() { return messageType; } }     common/src/ch/mfiles/kaba/kolibri/common/NotificationTestMessage.java:   package ch.mfiles.kaba.kolibri.common; //used for testing only public class NotificationTestMessage { public String getContent() { // "SHORTMSG-78703-XMSG998877" // SHORTMSG-78702-XMSG3980 // SHORTMSG-78702-XMSG3981 // SHORTMSG-78702-XMSG3982 // SHORTMSG-78703-XMSG3983 // SHORTMSG-78703-XMSG3984 // SHORTMSG-78703-XMSG3985 // SHORTMSG-78702-XMSG3986 // SHORTMSG-78703-XMSG3987 return "SHORTMSG-78702-0000003980"; //$NON-NLS-1$ } }     common/src/ch/mfiles/kaba/kolibri/common/util/ActionUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.widget.PopupMenu; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ActionUtil { private static Log log = LogFactory.getLog(ActionUtil.class); public ApplicationManager appman; public Application app; public ActionUtil(Application app) { this.app = app; this.appman = (ApplicationManager) Runtime.getApplicationManager(); } public void showPopupMenu(Context context, final ActionResult cameraActionResult, final ActionResult galleryActionResult, final ActionResult pdfActionResult) { /* * Create the context menu. see "[MIG-67] Context menu for jobs doesn't work" */ PopupMenu popupMenu = new PopupMenu(context, app.getCurrentForm().getToolbar()); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); popupMenu.getMenu() .add(Menu.NONE, CommonConstants.Menu.CAMERA, Menu.NONE, ch.mfiles.kaba.kolibri.common.Messages.getString("camera")) .setIcon(app.getCurrentForm().getBitmanDrawable(ImagesUtil.getInstance(app) .getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); popupMenu.getMenu() .add(Menu.NONE, CommonConstants.Menu.GALLERY, Menu.NONE, ch.mfiles.kaba.kolibri.common.Messages.getString("gallery")) .setIcon(app.getCurrentForm().getBitmanDrawable(ImagesUtil.getInstance(app) .getImage(ImagesUtil.Images.PHOTO_LIBRARY_BLACK, CommonConstants.Images.IMAGE_DPI))); // popupMenu.getMenu() // .add(Menu.NONE, ServiceConstants.Index.THREE, Menu.NONE, ServiceMessages.getString("pdfFiles")) // .setIcon(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PICTURE_AS_PDF_BLACK, CommonConstants.Images.IMAGE_DPI))); // forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem, cameraActionResult, galleryActionResult, pdfActionResult); return true; } }); popupMenu.show(); } private void handleMenuItemClicked(MenuItem menuItem, final ActionResult cameraActionResult, final ActionResult galleryActionResult, final ActionResult pdfActionResult) { if (menuItem.getItemId() == CommonConstants.Menu.CAMERA) { actionCamera(cameraActionResult); } else if (menuItem.getItemId() == CommonConstants.Menu.GALLERY) { actionGallery(galleryActionResult); } else if (menuItem.getItemId() == CommonConstants.Menu.PDF) { } } public void actionCamera(final ActionResult actionResult) { int permissionCheck = ContextCompat.checkSelfPermission(appman.getContext(), Manifest.permission.CAMERA); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { appman.requestPermissions( new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, CommonConstants.PERMISSION_REQUEST_CODE); } else { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String timeStamp = Long.toString(new Date().getTime()); String imageName = "IMAGE_" + timeStamp; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ final String imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) .getAbsolutePath() + "/Camera/"; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File photo = new File(imagePath, imageName + ".jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, appman.getUriForFile(photo)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); if (appman.startActivityForResult(intent) != null) { loadBitmapFromUri(actionResult, photo.getAbsolutePath(), true); } else { photo.delete(); } return null; } }; } } public void actionGallery(final ActionResult actionResult) { int permissionCheck = ContextCompat.checkSelfPermission(appman.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { appman.requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, CommonConstants.PERMISSION_REQUEST_CODE); } else { new AsyncTask(app.getCurrentForm()) { private String filePath; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_PICK); Intent result = appman.startActivityForResult(intent); if (result == null) { return null; } Uri selectedImage = result.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = appman.getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); cursor.close(); return null; } @Override protected void runOnUIThread() { loadBitmapFromUri(actionResult, filePath, false); } }; } } private void loadBitmapFromUri(final ActionResult actionResult, final String filePath, boolean broadcast) { if (filePath == null) { return; } if (broadcast) // make the new image visible in gallery asap MediaScannerConnection.scanFile(appman.getContext(), new String[] { filePath }, new String[] { "image/jpeg" }, null); BitmapLoadUtils.decodeBitmapInBackground(appman.getContext(), Uri.fromFile(new File(filePath)), new BitmapLoadUtils.BitmapLoadCallback() { @Override public void onFailure(@NonNull Exception bitmapWorkerException) { actionResult.onActionResult(null); } public void onBitmapLoaded(Bitmap bitmap, int exifOrientation) { actionResult.onActionResult(bitmap); } }); } public interface ActionResult { void onActionResult(Bitmap bitmap); } }     common/src/ch/mfiles/kaba/kolibri/common/util/BackupHandler.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.File; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.os.AsyncTask; import ch.mfiles.kaba.kolibri.common.CommonApplication; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.SimpleUserInterface; import ch.mfiles.kolibri.bu.BackupManager; import ch.mfiles.kolibri.bu.BackupMonitor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.NotificationMessage; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.BusyUIRunnable; import ch.mfiles.kolibri.util.AlertManager; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Helper class dealing with scheduling and performing a daily runtime backup. * The backup will run on some random time during the night hours from 8pm to * 6am. * * @author Joerg * */ public class BackupHandler { private static Log log = LogFactory.getLog(BackupHandler.class); /** * Makes sure, the backup manager is setup as required and all (special) * application folders are present. */ public static void setupOnPostApplicationUpgrade(final Application app) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(null); boolean bmActive = false; try { bmActive = reg.getBooleanProperty("framework.bm.active"); //$NON-NLS-1$ } catch (IllegalArgumentException ex) { } if (!bmActive) { log.info("Activating runtime's backup manager..."); //$NON-NLS-1$ // activate backup manager reg.setProperty("framework.bm.active", true); //$NON-NLS-1$ reg.setProperty("framework.bm.hideBackupAction", true); //$NON-NLS-1$ reg.setProperty("framework.bm.hideRestoreAction", true); //$NON-NLS-1$ // restart framework to activate the changes appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { app.showMessageBox(Messages.getString("BackupHandler_5"), //$NON-NLS-1$ Messages.getString("BackupHandler_6"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_INFORMATION); return appman.exitFramework(); } }, false); } // check/create application folders checkCreateAppFolder(CommonConstants.Application.COMMON_APP); checkCreateAppFolder(CommonConstants.Application.LOGIN_APP); checkCreateAppFolder(CommonConstants.Application.MATERIAL_APP); checkCreateAppFolder(CommonConstants.Application.SERVICE_APP); checkCreateAppFolder(CommonConstants.Application.TIMESHEET_APP); } private static void checkCreateAppFolder(String appFolder) { File folder = new File(Runtime.getInstallationFolder(), appFolder); if (!folder.exists()) { log.info("Creating special app folder " + folder); //$NON-NLS-1$ folder.mkdir(); } } private static BackupHandler s_instance; public static BackupHandler getInstance() { if (s_instance == null) { s_instance = new BackupHandler(); } return s_instance; } private ApplicationManager m_appman; private AlertManager m_alertManager; private Random m_random = new Random(System.currentTimeMillis()); private int m_testIntervalS = 0; private BackupHandler() { m_appman = (ApplicationManager) Runtime.getApplicationManager(); m_alertManager = m_appman.getAlertManager(); m_testIntervalS = RegistryUtil.getTestBackupEveryS(); updateBackupJob(); } private static final String BACKUP_JOB_MESSAGE = "Daily backup run"; //$NON-NLS-1$ private static final String BACKUP_JOB_ID = "CommonBackupJob"; //$NON-NLS-1$ private void updateBackupJob() { // remove the current alert m_alertManager.cancelAlert(BACKUP_JOB_ID); // get hour offset to 8pm for the backup schedule int hourOffset = (int) (m_random.nextFloat() * 10); int minuteOffset = (int) (m_random.nextFloat() * 59); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); // if we currently are past 8pm run on next day if (cal.get(Calendar.HOUR_OF_DAY) >= 20) cal.add(Calendar.DATE, 1); // set (start) time to 8pm for the/that day cal.set(Calendar.HOUR_OF_DAY, 20); cal.set(Calendar.MINUTE, 0); // add the random offset to the start time cal.add(Calendar.HOUR_OF_DAY, hourOffset); cal.add(Calendar.MINUTE, minuteOffset); Date schedule = cal.getTime(); // allow for quicker test backups if (m_testIntervalS > 0) schedule = new Date(System.currentTimeMillis() + m_testIntervalS * 1000); log.info("Next backup run planned for " + schedule); //$NON-NLS-1$ m_alertManager.addAlert(schedule, CommonApplication.class.getName(), BACKUP_JOB_ID, BACKUP_JOB_MESSAGE); Application app = (Application) m_appman.getActiveApplication(); if (app != null) app.inform(MessageFormat.format(Messages.getString("BackupHandler_11"), schedule)); //$NON-NLS-1$ } /** * Processes received messages and starts a backup if apropriate. * * @param nm * @return Returns true if the notification message was handled * (i.e. consumed) */ public boolean processNotification(NotificationMessage nm) { if (!BACKUP_JOB_ID.equals(nm.getMessageId()) || !BACKUP_JOB_MESSAGE.equals(nm.getContent())) return false; log.info("Starting daily backup..."); //$NON-NLS-1$ // register a new backup job updateBackupJob(); // run the backup runBackup((Application) m_appman.getActiveApplication()); return true; } private void runBackup(final Application app) { m_appman.inject(new BusyUIRunnable() { @Override public ApplicationEvent runBusy(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { BackupManager bm = Runtime.getBackupManager(); final BackupMonitor buMonitor = bm.backup(Messages.getString("BackupHandler_13"), monitor); //$NON-NLS-1$ if (buMonitor.getErrorMessage() != null) { log.error("Backup failed: " + buMonitor.getErrorMessage()); //$NON-NLS-1$ if (app != null) app.inform(MessageFormat.format(Messages.getString("BackupHandler_15"), //$NON-NLS-1$ buMonitor.getErrorMessage())); } // if the runtime was started only to process the backup job, exit the runtime // at the end of the backup process if (m_appman.getActiveApplication() == null) waitForBackupAndExitRuntime(buMonitor); return null; } }, false); } protected void waitForBackupAndExitRuntime(final BackupMonitor buMonitor) { new AsyncTask() { @Override protected Void doInBackground(Void... params) { log.info("Waiting for backup process to end..."); //$NON-NLS-1$ try { buMonitor.join(); } catch (InterruptedException e) { return null; } m_appman.inject(new BusyUIRunnable() { @Override public ApplicationEvent runBusy(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { // before exiting check again, if nothing was started in the meantime... if (m_appman.getActiveApplication() == null) { log.info("Backup complete - exiting runtime since it was started for backup only..."); //$NON-NLS-1$ return appman.exitFramework(); } log.info("Backup complete - leaving to running application..."); //$NON-NLS-1$ return null; } }, false); return null; } }.execute(); } /** * Returns the hours past since the last (successful) backup run. * * @return Returns the hours since the last (successful) backup run or * -1 */ private int getHoursSinceLastBackup() { Date lastBackup = Runtime.getBackupManager().getLastBackupTS(); if (lastBackup == null) return -1; return (int) ((System.currentTimeMillis() - lastBackup.getTime()) / (1000 * 3600)); } /** Timestamp of last overdue check */ private long m_lastOverdueCheckMS = 0; /** * Check if the last successful backup is too old and ask to perform a backup if * the backup is older than 24 hours and force a backup run if older than 48 * hours. */ public void checkOverdueBackup(final Application app) { // only check every 1 hour if (System.currentTimeMillis() - m_lastOverdueCheckMS < 60 * 60 * 1000) return; m_appman.inject(new BusyUIRunnable() { @Override public ApplicationEvent runBusy(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { int hours = getHoursSinceLastBackup(); if (hours >= 0 && hours <= 24) return null; if (hours >= 24 && hours <= 48) { app.inform(Messages.getString("BackupHandler_19")); //$NON-NLS-1$ return null; } else { if (hours < 0) app.inform(Messages.getString("BackupHandler_21")); //$NON-NLS-1$ else app.inform(Messages.getString("BackupHandler_23")); //$NON-NLS-1$ } runBackup(app); return null; } }, false); } }     common/src/ch/mfiles/kaba/kolibri/common/util/BitmapConverterUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; public class BitmapConverterUtil { public static String bitMapToString(Bitmap bitmap) { // TODO compress ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String temp = Base64.encodeToString(b, Base64.DEFAULT); return temp; } public static Bitmap stringToBitMap(String encodedString) { try { byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); return bitmap; } catch (Exception e) { e.getMessage(); return null; } } }     common/src/ch/mfiles/kaba/kolibri/common/util/BitmapLoadUtils.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.ParcelFileDescriptor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; /** * Created by Oleksii Shliama (https://github.com/shliama). */ public class BitmapLoadUtils { private static final String TAG = "BitmapLoadUtils"; private static final int MAXIMUM_FILE_SIZE_K = 900; public interface BitmapLoadCallback { void onBitmapLoaded(@NonNull Bitmap bitmap, int exifOrientation); void onFailure(@NonNull Exception bitmapWorkerException); } public static void decodeBitmapInBackground(@NonNull Context context, @Nullable Uri uri, BitmapLoadCallback loadCallback) { new BitmapWorkerTask(context, uri, loadCallback).execute(); } static class BitmapWorkerResult { Bitmap mBitmapResult; int mExifOrientation; Exception mBitmapWorkerException; public BitmapWorkerResult(@Nullable Bitmap bitmapResult, int exifOrientation, @Nullable Exception bitmapWorkerException) { mBitmapResult = bitmapResult; mBitmapWorkerException = bitmapWorkerException; mExifOrientation = exifOrientation; } } /** * Creates and returns a Bitmap for a given Uri. * inSampleSize is calculated based on requiredWidth property. However can be adjusted if OOM occurs. * If any EXIF config is found - bitmap is transformed properly. */ static class BitmapWorkerTask extends AsyncTask { private final Context mContext; private final Uri mUri; private final BitmapLoadCallback mBitmapLoadCallback; public BitmapWorkerTask(@NonNull Context context, @Nullable Uri uri, BitmapLoadCallback loadCallback) { mContext = context; mUri = uri; mBitmapLoadCallback = loadCallback; } @Override @NonNull protected BitmapWorkerResult doInBackground(Void... params) { if (mUri == null) { return new BitmapWorkerResult(null, 0, new NullPointerException("Uri cannot be null")); } final ParcelFileDescriptor parcelFileDescriptor; try { parcelFileDescriptor = mContext.getContentResolver().openFileDescriptor(mUri, "r"); } catch (FileNotFoundException e) { return new BitmapWorkerResult(null, 0, e); } Bitmap decodeSampledBitmap = makeBitmap(mUri.getPath()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { close(parcelFileDescriptor); } int exifOrientation = getExifOrientation(mContext, mUri); int exifDegrees = exifToDegrees(exifOrientation); int exifTranslation = exifToTranslation(exifOrientation); Log.i(TAG, "Image EXIF Orientation: " + exifOrientation); Log.i(TAG, "Image EXIF Degrees: " + exifDegrees); Log.i(TAG, "Image EXIF Translation: " + exifTranslation); Matrix matrix = new Matrix(); if (exifDegrees != 0) { matrix.preRotate(exifDegrees); } if (exifTranslation != 1) { matrix.postScale(exifTranslation, 1); } if (decodeSampledBitmap == null) { return new BitmapWorkerResult(null, 0, new IllegalArgumentException("Source is not an image or not supported.")); } if (!matrix.isIdentity()) { decodeSampledBitmap = transformBitmap(decodeSampledBitmap, matrix); } // for test //writeToFile(decodeSampledBitmap); return new BitmapWorkerResult(decodeSampledBitmap, exifOrientation, null); } @Override protected void onPostExecute(@NonNull BitmapWorkerResult result) { if (result.mBitmapWorkerException == null) { mBitmapLoadCallback.onBitmapLoaded(result.mBitmapResult, result.mExifOrientation); } else { mBitmapLoadCallback.onFailure(result.mBitmapWorkerException); } } private void writeToFile(Bitmap bitmap) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 0, baos); String Path = mContext.getExternalFilesDir(null).getPath(); File dirFile = new File(Path); if (!dirFile.exists()) { dirFile.mkdir(); } File myCaptureFile = new File(Path +"/cache_" + System.currentTimeMillis() +".jpg"); FileOutputStream fi; fi = new FileOutputStream(myCaptureFile); baos.writeTo(fi); baos.flush(); baos.close(); int fileSize = baos.toByteArray().length / 1024; Log.i(TAG, "after compressed size: " + fileSize + "Kb"); Log.i(TAG, "path : " + myCaptureFile.getAbsolutePath()); } catch (FileNotFoundException e) { Log.i(TAG, e + ""); } catch (IOException e) { Log.i(TAG, e + ""); } } private Bitmap makeBitmap(String path) { long fileSize = new File(mUri.getPath()).length(); fileSize = (fileSize) / 1024;// in Kb now if (fileSize > MAXIMUM_FILE_SIZE_K) { Bitmap image = BitmapFactory.decodeFile(path); int width = image.getWidth(); int height = image.getHeight(); float bitmapRatio = (float)width / (float) height; if (bitmapRatio > 1) { width = MAXIMUM_FILE_SIZE_K; height = (int) (width / bitmapRatio); } else { height = MAXIMUM_FILE_SIZE_K; width = (int) (height * bitmapRatio); } return Bitmap.createScaledBitmap(image, width, height, true); } // Decode image size BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); final int IMAGE_MAX_SIZE = MAXIMUM_FILE_SIZE_K * 1024; // 1.2MP int scale = 1; while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) { scale++; } Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight); Bitmap pic = null; if (scale > 1) { scale--; // scale to max possible inSampleSize that still yields an image // larger than target options = new BitmapFactory.Options(); options.inSampleSize = scale; pic = BitmapFactory.decodeFile(path, options); // resize to desired dimensions int height = pic.getHeight(); int width = pic.getWidth(); float bitmapRatio = (float)width / (float) height; if (bitmapRatio > 1) { width = IMAGE_MAX_SIZE; height = (int) (width / bitmapRatio); } else { height = IMAGE_MAX_SIZE; width = (int) (height * bitmapRatio); } Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height); double y = Math.sqrt(IMAGE_MAX_SIZE / (((double) width) / height)); double x = (y / height) * width; Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true); pic.recycle(); pic = scaledBitmap; System.gc(); } else { pic = BitmapFactory.decodeFile(path); } Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight()); return pic; } } public static Bitmap transformBitmap(@NonNull Bitmap bitmap, @NonNull Matrix transformMatrix) { try { Bitmap converted = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), transformMatrix, true); if (bitmap != converted) { bitmap.recycle(); bitmap = converted; } } catch (OutOfMemoryError error) { Log.e(TAG, "transformBitmap: ", error); } return bitmap; } protected static int getExifOrientation(@NonNull Context context, @NonNull Uri imageUri) { int orientation = ExifInterface.ORIENTATION_UNDEFINED; try { InputStream stream = context.getContentResolver().openInputStream(imageUri); if (stream == null) { return orientation; } orientation = new ImageHeaderParser(stream).getOrientation(); close(stream); } catch (IOException e) { Log.e(TAG, "getExifOrientation: " + imageUri.toString(), e); } return orientation; } public static int exifToTranslation(int exifOrientation) { int translation; switch (exifOrientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: case ExifInterface.ORIENTATION_FLIP_VERTICAL: case ExifInterface.ORIENTATION_TRANSPOSE: case ExifInterface.ORIENTATION_TRANSVERSE: translation = -1; break; default: translation = 1; } return translation; } public static Bitmap rotateBitmap(@Nullable Bitmap bitmap, int degrees) { if (bitmap != null && degrees != 0) { Matrix rotateMatrix = new Matrix(); rotateMatrix.setRotate(degrees, bitmap.getWidth() / (float) 2, bitmap.getHeight() / (float) 2); Bitmap converted = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), rotateMatrix, true); if (bitmap != converted) { bitmap.recycle(); bitmap = converted; } } return bitmap; } @Nullable private static ExifInterface getExif(@NonNull Uri imageUri) { try { return new ExifInterface(imageUri.getPath()); } catch (IOException e) { Log.w(TAG, "getExif: ", e); } return null; } static int exifToDegrees(int exifOrientation) { if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; } return 0; } @SuppressWarnings("ConstantConditions") public static void close(@Nullable Closeable c) { if (c != null && c instanceof Closeable) { // java.lang.IncompatibleClassChangeError: interface not implemented try { c.close(); } catch (IOException e) { // silence } } } }     common/src/ch/mfiles/kaba/kolibri/common/util/CommonConstants.java:   package ch.mfiles.kaba.kolibri.common.util; import java.util.Random; import android.graphics.Typeface; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kolibri.ApplicationBase; import ch.mfiles.kolibri.ui.Image; public class CommonConstants { CommonConstants(){ } public static final int PERMISSION_REQUEST_CODE = 200; public static final int RETENTION_PERIOD_DAY = 180; public static Random r = new Random(); public static final String PLEASE_SELECT = "00"; public static final String KOLIBRI_ID = "framework.net.kolibriId"; public static final class Local { Local() { } public static final int EN = 0; public static final int GE = 1; public static final int FR = 2; public static final int IT = 3; } public static final class LocalizedTexts { LocalizedTexts() { } public static final String JOB_TYPE = "1"; //$NON-NLS-1$ public static final String JOB_STATUS = "2"; //$NON-NLS-1$ public static final String JOB_PRIORITY = "3"; //$NON-NLS-1$ public static final String ADDRESS_TITLE = "4"; //$NON-NLS-1$ public static final String ADDRESS_TYPE = "5"; //$NON-NLS-1$ public static final String REPORT_SIGNATURE = "6"; //$NON-NLS-1$ public static final String REPORT_CUSTOMER_SUPPORT = "7"; //$NON-NLS-1$ public static final String REPORT_CHCKLISTE = "8"; //$NON-NLS-1$ public static final String MONTH = "9"; //$NON-NLS-1$ public static final String MESSAGE_ID = "10"; //$NON-NLS-1$ public static final String VAREXP = "11"; //$NON-NLS-1$ public static final String INVOICE = "12"; //$NON-NLS-1$ public static final String WORK_TYPE = "13"; //$NON-NLS-1$ public static final String REGISTER_USER = "14"; //$NON-NLS-1$ } public static final class Font { Font() { } public static final int DEFAULT_FONT_SIZE = 13; public static final int DEFAULT_HERDER_FONT_SIZE = 16; public static final int DEFAULT_TITLE_FONT_SIZE = 24; // roboto regular public static Typeface getDefaultRegularFont() { return getDefaultRegularFont(Typeface.NORMAL); } public static Typeface getDefaultRegularFont(int typeface) { return Typeface.create("sans-serif", typeface); //$NON-NLS-1$ } // roboto light public static Typeface getDefaultLightFont() { return getDefaultLightFont(Typeface.NORMAL); } public static Typeface getDefaultLightFont(int typeface) { return Typeface.create("sans-serif-light", typeface); //$NON-NLS-1$ } // roboto condensed public static Typeface getDefaultCondensedFont() { return getDefaultCondensedFont(Typeface.NORMAL); } public static Typeface getDefaultCondensedFont(int typeface) { return Typeface.create("sans-serif-condensed", typeface); //$NON-NLS-1$ } // roboto thin (android 4.2) public static Typeface getDefaultThinFont() { return getDefaultThinFont(Typeface.NORMAL); } public static Typeface getDefaultThinFont(int typeface) { return Typeface.create("sans-serif-thin", typeface); //$NON-NLS-1$ } // roboto medium (android 5.0) public static Typeface getDefaultMediumFont() { return getDefaultMediumFont(Typeface.NORMAL); } public static Typeface getDefaultMediumFont(int typeface) { return Typeface.create("sans-serif-medium", typeface); //$NON-NLS-1$ } } public static class Address { Address() { } /* * * (2009-03-24) * INSERT INTO localizedTexts VALUES ("01","D","Objekt","5") * INSERT INTO localizedTexts VALUES ("02","D","Ansprechperson","5") * INSERT INTO localizedTexts VALUES ("03","D","Auftraggeber","5") * INSERT INTO localizedTexts VALUES ("04","D","Eigentümer","5") * INSERT INTO localizedTexts VALUES ("05","D","Verwaltung","5") * INSERT INTO localizedTexts VALUES ("06","D","Partner","5") * INSERT INTO localizedTexts VALUES ("07","D","Warenempfänger","5") * * OBJNR = 01 - OBJEKT * PARZSNR = 02 - ANSPRECHPERSON * PARANMNR = 03 - AUFTRAGGEBER * PARZANR = 04 - EIGENTUMER * * PARAPNR = 06 - PARTNER * PARZRNR = 07 - WARENEMPFANGER */ public static final String KdnJobNumber = "BSTKD"; //$NON-NLS-1$ /** * OBJEKT */ public static final String OBJECT_ADDRESS = "01"; //$NON-NLS-1$ /** * ANSPRECHPERSON */ public static final String CUSTOMER_ADDRESS = "02"; //$NON-NLS-1$ /** * AUFTRAGGEBER */ public static final String PARTNET_ADDRESS = "03"; //$NON-NLS-1$ /** * EIGENTUMER */ public static final String OWNER_ADDRESS = "04"; //$NON-NLS-1$ // public static final String VERWALTUNG = "05"; /** * PARTNER */ public static final String PARTNER_OF_INSTALLATION_ADDRESS = "06"; //$NON-NLS-1$ /** * WARENEMPFANGER */ public static final String KDN_SERVICE_ADDRESS = "07"; //$NON-NLS-1$ } public static class Report { Report() { } public static final String WORK_TYPE_SERVICE_CONTACT = "05"; //$NON-NLS-1$ public static final String WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA = "98"; public static final String WORK_TYPE_MAINTENANCE_VONOVIA = "99"; public static final String CUSTOMER_SUPPORT_FAX = "01"; //$NON-NLS-1$ public static final String CUSTOMER_SUPPORT_EMAIL = "02"; //$NON-NLS-1$ public static final String CUSTOMER_SUPPORT_FOMULAR = "03"; //$NON-NLS-1$ public static final String CUSTOMER_SUPPORT_WAIVER = "04"; //$NON-NLS-1$ public static final String WORK_TYPE_REPAIR = "01"; public static final String WORK_TYPE_ON_CALL = "02"; public static final String BILLING_GUARANTEE = "04"; public static final String BILLING_GOODWILL = "05"; public static final String WORKTYPE_INSTALLATION = "32"; public static final String FORM_VONOVIA = "VD10"; public static class Month { Month() { } public static final String JAN = "01"; //$NON-NLS-1$ public static final String FEB = "02"; //$NON-NLS-1$ public static final String MAR = "03"; //$NON-NLS-1$ public static final String APR = "04"; //$NON-NLS-1$ public static final String MAY = "05"; //$NON-NLS-1$ public static final String JUN = "06"; //$NON-NLS-1$ public static final String JUL = "07"; //$NON-NLS-1$ public static final String AUG = "08"; //$NON-NLS-1$ public static final String SEP = "09"; //$NON-NLS-1$ public static final String OCT = "10"; //$NON-NLS-1$ public static final String NOV = "11"; //$NON-NLS-1$ public static final String DEC = "12"; //$NON-NLS-1$ } } public static class Message { Message() { } // Abteilungsleiter Kunde KDZ 1 KDZ 2 KDZ 3 public static final String HEAD_OF_DEPARTMENT= "01"; //$NON-NLS-1$ public static final String CUSTOMER = "02"; //$NON-NLS-1$ public static final String KDZ1 = "03"; //$NON-NLS-1$ public static final String KDZ2 = "04"; //$NON-NLS-1$ public static final String KDZ3 = "05"; //$NON-NLS-1$ public static final String PROJECT_MANAGER = "06"; //$NON-NLS-1$ public static final String DISPOSITION = "07"; //$NON-NLS-1$ public static final String SYSTEM_IS_SAVE = "18"; //$NON-NLS-1$ public static final String SYSTEM_WITH_MINOR_DEFECTS = "19"; //$NON-NLS-1$ public static final String SYSTEM_EXHIBITS_DEFECTS = "20"; //$NON-NLS-1$ } // TODOO Replace "Status" with an enum public static class Order { Order() { } public static class Status { Status() { } public static final String NEW_ORDER = "0"; //$NON-NLS-1$ public static final String SENT_ORDER = "1"; //$NON-NLS-1$ } } public static class ShortMessage { ShortMessage() { } public static class Status { Status() { } public static final String RECEIVED = "01"; //$NON-NLS-1$ public static final String READ = "02"; //$NON-NLS-1$ public static final String CONFIRMED = "03"; //$NON-NLS-1$ } } public static class Application { Application() { } // app constants for storing app specific data in the filesystem public static final String COMMON = "CommonApplication"; //$NON-NLS-1$ public static final String SERVICE = "ServiceApplication"; //$NON-NLS-1$ // app constants for access to app classes public static final String COMMON_APP = "ch.mfiles.kaba.kolibri.common.CommonApplication"; //$NON-NLS-1$ public static final String LOGIN_APP = "ch.mfiles.kaba.kolibri.login.LoginApplication"; //$NON-NLS-1$ public static final String MATERIAL_APP = "ch.mfiles.kaba.kolibri.material.MaterialApplication"; //$NON-NLS-1$ public static final String SERVICE_APP = "ch.mfiles.kaba.kolibri.service.ServiceApplication"; //$NON-NLS-1$ public static final String TIMESHEET_APP = "ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication"; //$NON-NLS-1$ } public static class Regex { Regex() { } // eMail validation // public static final String EMAIL_VALIDATOR = "^[^\\s]+@[^\\s]+\\.[^\\s]{2,3}$"; // public static final String EMAIL_VALIDATOR = "^[\\w]+@[\\w]+\\.[\\w]{2,3}$"; // public static final String EMAIL_VALIDATOR = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[\\w]{2,4}$"; public static final String EMAIL_VALIDATOR = "^[\\w\\.\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]+@([\\w\\-]+\\.)+[\\w]{2,7}$"; //$NON-NLS-1$ public static final String EMAIL_VALIDATION_MSG = Messages.getString("FormatMailAddress"); //$NON-NLS-1$ // Tel. and fax number validation public static final String TEL_NR_VALIDATOR = "^[\\d\\s]{1,30}$"; //$NON-NLS-1$ public static final String TEL_NR_VALIDATION_MSG = Messages.getString("onlyNumberAndSpacesAllowedForTelephoneNumber"); //$NON-NLS-1$ // MLDNR number validation public static final String MLDNR_VALIDATOR = "^[\\d]{1,6}$"; //$NON-NLS-1$ public static final String MLDNRR_VALIDATION_MSG = Messages.getString("NumbersUpToSixDigitsAreAllowed"); //$NON-NLS-1$ // Validation of any string with max. length public static String getRegexMaxLength(int length) { return "^.{1," + length + "}$"; //$NON-NLS-1$ //$NON-NLS-2$ } public static String getValidationMsgMaxLength(int length) { return Messages.getString("valueMustNotBeLongerThen") + String.valueOf(length) + Messages.getString("characters"); //$NON-NLS-1$ //$NON-NLS-2$ } } public static class Images { Images() { } public enum Type { BMP, JPG, JPEG, PNG, WEBP } public static final int IMAGE_DPI = 200; public static final int IMAGE_MIN_DPI = 250; public static final int IMAGE_MAX_DPI = 95; public static final String NEW16 = "new16.png"; //$NON-NLS-1$ public static final String INPROGRESS16 = "inProgress16.png"; //$NON-NLS-1$ public static final String FINALIZE16 = "finalize16.png"; //$NON-NLS-1$ public static final String RECEIVE16 = "receive16.png"; //$NON-NLS-1$ public static final String FORWARD16 = "forward16.png"; //$NON-NLS-1$ public static final String MAKING16 = "making16.png"; //$NON-NLS-1$ public static final String CHECK16 = "check16.png"; //$NON-NLS-1$ public static final String REPAIR16 = "repair16.png"; //$NON-NLS-1$ public static final String INSTALL16 = "install16.png"; //$NON-NLS-1$ public static final String CALL = "call.png"; //$NON-NLS-1$ public static final String WARNING = "warning.png"; //$NON-NLS-1$ public static final String IMAGE_PACKAGE = "images"; //$NON-NLS-1$ public static Image getImageByJobType(ApplicationBase app, JobType jobType) { String prefixPath = "images/"; //$NON-NLS-1$ if (jobType.isREP()) { return app.getImage(prefixPath + REPAIR16); } else if (jobType.isSAV()) { return app.getImage(prefixPath + CHECK16); } else if (jobType.isMON()) { return app.getImage(prefixPath + INSTALL16); } else return null; } public static String getImageNameByStatus(JobStatus status) { String result; if (status.isNew()) { result = NEW16; } else if (status.isReceived()) { result = RECEIVE16; } else if (status.isForwarded()) { result = FORWARD16; } else if (status.isInProgress()) { result = INPROGRESS16; } else if (status.isFinalized()) { result = FINALIZE16; } else if (status.isPartlyDone()) { result = MAKING16; } else { result = CHECK16; } return result; } } public static class Prefix { Prefix() { } /* * The prefix for short message * * example: SHORTMSG-78702-0000003990 * * @see "[MIG-53] implement of "report messages"" */ public static final String SHORTMSG = "SHORTMSG"; //$NON-NLS-1$ /* * The prefix for transmit a job from backend to frontend * * example: AUFTR-12345-REP-BR * * @see "[MIG-120] Cannot transmit a job from backend to frontend (GET_ORDER)" */ public static final String AUFTR = "AUFTR"; //$NON-NLS-1$ /* * The prefix for transmit a vehicle inventory from backend to frontend * * example: MBEW-GUID-CONF * * @see "[MIG-818] Implement push message and transaction GET_MBEW for inventory" */ public static final String MBEW = "MBEW"; //$NON-NLS-1$ } public static String randomString(int length) { String tempString = "QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"; //$NON-NLS-1$ StringBuilder result = new StringBuilder(); Random r = new Random(); int te; for (int i = 1; i <= length; i++) { te = r.nextInt(62); result.append(tempString.charAt(te)); } return result.toString(); } public static String randomInt(int length) { String result = Integer.toString(Math.abs(r.nextInt())); if (result.length() > length) { result = result.substring(0, length); } else if (result.length() < length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length - result.length(); i++) { sb.append("0"); //$NON-NLS-1$ } result = sb.toString() + result; } return result; } public static final class CommissionNumber { CommissionNumber() { } public enum Type { CORRECT, UNKNOWN, INVALID } public static final String DEFAULT = "0459999-99"; //$NON-NLS-1$ public static final int DASH_POSITION = 7; public static final int LETTER_POSITION = 8; //CH -> REP, SAV -> 0xxxxxx-yy -> x: [0-9], y: [0-9][A-Z] public static final String REGX_REP_SAV_CH = "0\\d{6}\\-[A-Za-z0-9]{2}$"; //CH -> MON -> xxxxxx -> x: [0-9] public static final String REGX_MON_CH = "[0-9]{6}$"; //DE -> REP, SAV -> xxxxxxx-yy -> x: [0-9], y: [0-9][A-Z] public static final String REGX_REP_SAV_DE = "\\d{7}\\-[A-Za-z0-9]{2}$"; //DE -> MON -> xxxxxxxxxx -> x: [0-9] public static final String REGX_MON_DE = "[0-9]{10}$"; public static final String CH = "CH"; public static final String DE = "DE"; } public static final class Notification { Notification() { } public static final String BROADCAST_ACTION = "NfAction"; //$NON-NLS-1$ // note: notification id's < 100 are reserved by runtime notifications public static final int NEW_JOB = 100; public static final int SHORT_MESSAGE = 110; public static final int INCOMING_ARTICLE = 120; } public static final class MaxLength { MaxLength() { } public static final Integer ONE = 1; public static final Integer TWO = 2; public static final Integer THREE = 3; public static final Integer FOUR = 4; public static final Integer FIVE = 5; public static final Integer SIX = 6; public static final Integer SEVEN = 7; public static final Integer EIGHT = 8; public static final Integer NINE = 9; public static final Integer TEN = 10; public static final Integer ELEVEN = 11; public static final Integer TWELVE = 12; public static final Integer THIRTEEN = 13; public static final Integer FOURTEEN = 14; public static final Integer FIFTEEN = 15; public static final Integer SIXTEEN = 16; public static final Integer SEVENTEEN = 17; public static final Integer EIGHTTEEN = 18; public static final Integer NINETEEN = 19; public static final Integer TWENTY = 20; public static final Integer TWENTY_FIVE = 25; public static final Integer THIRTY = 30; public static final Integer THIRTY_FIVE = 35; public static final Integer FORTY = 40; public static final Integer FIFTY = 50; public static final Integer SIXTY = 60; public static final Integer SEVENTY = 70; public static final Integer EIGHTY = 80; public static final Integer EIGHTY_TWO = 82; public static final Integer NINETY = 90; public static final Integer ONE_HUNDRED = 100; public static final Integer FIVE_HUNDRED_AND_TEN = 510; public static final Integer ONE_HUNDRED_AND_FIFTY = 150; } public static final class Material { Material() { } public static final String REGEX = "^\\d{2}-\\d{4}-\\d{3}(\\/\\d{2})?$"; //$NON-NLS-1$ public static final String SEARCH_REGEX = "\\d{0,2}(-\\d{0,4})?(-\\d{0,3})?(\\/\\d{0,2})?"; //$NON-NLS-1$ public static final String NUMBER_PREFIX = "45"; //$NON-NLS-1$ } public static final class Mode { Mode() { } public static final String NEW = "NEW"; //$NON-NLS-1$ public static final String EDIT = "EDIT"; //$NON-NLS-1$ public static final String STOP = "STOP"; //$NON-NLS-1$ public static final String PLAYING = "PLAYING"; //$NON-NLS-1$ } public static final class TimeSheet { TimeSheet() { } public static final String REGEX = "^CHF \\d{1,3}\\.\\d{1,2}?$|^CHF \\d{1,3}\\,\\d{1,2}?$"; //$NON-NLS-1$ public static final String EXPENSES_PREFIX = "CHF "; //$NON-NLS-1$ public static final String VEHICLE_REGEX = "\\d{1,9}\\.\\d{1,2}?$"; //$NON-NLS-1$ public static final String TIME_REGEX = "^([0-1][0-9]|2[0-3]):[0-5][0-9]$"; //$NON-NLS-1$ public static final int COLON_POSITION = 2; } public static final class Menu { Menu() { } public static final Integer CAMERA = 1; public static final Integer GALLERY = 2; public static final Integer PDF = 2; } public static final class DeviceType { DeviceType() { } public static final String SMARTPHONE = "s"; public static final String TABLET = "t"; } }     common/src/ch/mfiles/kaba/kolibri/common/util/DatabaseUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Checklist; import ch.mfiles.kaba.kolibri.common.businessobjects.Billing; import ch.mfiles.kaba.kolibri.common.businessobjects.Drive; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.ErrorCode; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.History; import ch.mfiles.kaba.kolibri.common.businessobjects.Incident; import ch.mfiles.kaba.kolibri.common.businessobjects.InternalWorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Invoice; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormDependency; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.FormValueList; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenses; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenseFile; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Progress; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.businessobjects.ReceiptOfGoods; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.NextIntervention; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.ServerJob; import ch.mfiles.kaba.kolibri.common.businessobjects.ServiceRefused; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.JobNoForm; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReturnReason; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.StateOfInstallation; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.Warehouse; import ch.mfiles.kaba.kolibri.common.db.FORM; import ch.mfiles.kaba.kolibri.common.db.FORMDEPENDENCY; import ch.mfiles.kaba.kolibri.common.db.FORMITEM; import ch.mfiles.kaba.kolibri.common.db.FORMVALUELIST; import ch.mfiles.kaba.kolibri.common.db.LocalizedTexts; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceNotification; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceType; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.FatalApplicationException; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.LocalTransaction; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.DateUtils; public class DatabaseUtil { public static final Log log = LogFactory.getLog(DatabaseUtil.class); private static DatabaseUtil instance = null; private DBSession db; private DatabaseUtil() { db = Runtime.getApplicationManager().getDBSession(); } /** * Make sure we are *not* running on the UI thread. */ private void ensureAMThread() { ApplicationManager appman = (ApplicationManager)Runtime.getApplicationManager(); if (appman.getContext().getMainLooper().getThread() == Thread.currentThread()) throw new FatalApplicationException(Messages.getString("error")); //$NON-NLS-1$ } public static final DatabaseUtil getInstance() { if (instance == null) { instance = new DatabaseUtil(); } return instance; } private static Person mUser; public Person getUser() { return getUser(false); } public Person getUser(boolean reload) { if (reload) { mUser = null; } if (mUser == null) { mUser = selectActiveUser(); if (mUser == null) { throw new ApplicationException(Messages.getString("noUserActive")); //$NON-NLS-1$ } } return mUser; } public void setupFixedMasterData(boolean replace) { // reset some tables, if we have no localized texts (unclear, why...) boolean localizedTextsEmpty = LocalizedTexts.listByPrimaryKey(db, 1).length == 0; log.debug("localizedZextsEmpty=" + localizedTextsEmpty); //$NON-NLS-1$ if (localizedTextsEmpty) { db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.ReportMessage.REPORT_MESSAGE); db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.Incident.INCIDENT); db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.Drive.DRIVE); db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.Billing.BILLING); } if (!localizedTextsEmpty && !replace) // texts already loaded... nothing to do return; log.debug("Reloading localized texts"); // create a local transaction (speeding up operations if not transaction was already started) LocalTransaction trans = new LocalTransaction(db); try { LocalizedTexts.delete(db); List listSql = SQLFileConverter.readFile(FileUtils .getAbsoluteFilePathName(CommonConstants.Application.COMMON, FileUtils.Packages.DATA, //$NON-NLS-1$ FileUtils.FileNames.FIXED_MASTERDATA, false)); //$NON-NLS-1$ for (int i = 0; i < listSql.size(); i++) { String sql = listSql.get(i); if (sql.startsWith("INSERT") && sql.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sql); } } trans.commit(); if(log.isDebugEnabled()) log.debug(Messages.getString("insertComplete")); //$NON-NLS-1$ } catch (IOException e) { log.error("Error processing localized texts...", e); } finally { if (trans.isPending()) trans.rollback(); } } public void insertJob(Job job) { Iterator
itr = job.getAddresses().values().iterator(); while (itr.hasNext()) { Address address = itr.next(); insertAddress(address); } DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Job.JOB).in( DbConstants.Job.JOB_NUMBER, job.getJobNumber()).in( DbConstants.Job.JOB_TYPE, job.getJobType().getCode()).in( DbConstants.Job.PERSONAL_NUMBER, job.getPersonalNumber()).in( DbConstants.Job.STATUS, job.getStatus().getCode()).in( DbConstants.Job.PRIORITY, job.getPriority()).in( DbConstants.Job.JOB_FORWARD, job.getJobForward()).in( DbConstants.Job.COMMISSION_NUMBER, job.getCommissionNumber()).in( DbConstants.Job.STAFF_NAME, job.getStaffName()).in( DbConstants.Job.STAFF_PHONE, job.getStaffPhoneNumber()).in( DbConstants.Job.APPOINTMENT_DATE, job.getAppointmentDate()).in( DbConstants.Job.ACTIVE_DATE, job.getActiveJobDate()).in( DbConstants.Job.JOB_RESCHEDULE_DATE, job.getJobRescheduleDate()).in( DbConstants.Job.JOB_RESCHEDULE_TIME, job.getJobRescheduleTime()).in( DbConstants.Job.WEEK, job.getWeek()).in( DbConstants.Job.FIX, job.getFix()).in( DbConstants.Job.APPOINTMENT, job.getAppointment()).in( DbConstants.Job.ORDER_NUMBER, job.getOrderNumber()).in( DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID, job.getPartnerOfInstallAddressId()).in( DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID, job.getKdnServiceAddressId()).in( DbConstants.Job.CUSTOMER_ADDRESS_ID, job.getCustomerAddressId()).in( DbConstants.Job.PARTNER_ADDRESS_ID, job.getPartnerAddressId()).in( DbConstants.Job.OBJECT_ADDRESS_ID, job.getObjectAddressId()).in( DbConstants.Job.OWNER_ADDRESS_ID, job.getOwnerAddressId()).in( DbConstants.Job.NEW_JOB_DATE, job.getNewJobDate()).in( DbConstants.Job.ERROR_ID, job.getErrorId()).in( DbConstants.Job.CALL_SERVICE_FLAG, job.getCallServiceFlag()).in( DbConstants.Job.MAINTENANCE_CONTRACT_TYPE, job.getMaintenanceContractType()).in( DbConstants.Job.SERVICE_PLAN_MONTH_1, job.getServicePlanMonth1()).in( DbConstants.Job.SERVICE_PLAN_MONTH_2, job.getServicePlanMonth2()).in( DbConstants.Job.SERVICE_PLAN_MONTH_3, job.getServicePlanMonth3()).in( DbConstants.Job.SERVICE_PLAN_MONTH_4, job.getServicePlanMonth4()).in( DbConstants.Job.SERVICE_PLAN_MONTH_5, job.getServicePlanMonth5()).in( DbConstants.Job.SERVICE_PLAN_MONTH_6, job.getServicePlanMonth6()).in( DbConstants.Job.SERVICE_OPEN, job.getServiceOpen()).in( DbConstants.Job.CONTACT_NAME, job.getContactName()).in( DbConstants.Job.CONTACT_PHONE, job.getContactPhoneNumber()).in( DbConstants.Job.TECHNICAL_NAME, job.getTechnicalName()).in( DbConstants.Job.TECHNICAL_PHONE, job.getTechnicalPhoneNumber()).in( DbConstants.Job.SELLER_NAME, job.getSellerName()).in( DbConstants.Job.SELLER_PHONE, job.getSellerPhoneNumber()).in( DbConstants.Job.STATUS_EDIT, job.getStatusEdit()).in( DbConstants.Job.DRIVER_TYPE, job.getDriveType()).in( DbConstants.Job.DRIVER_TYPE_UPD, job.isDriveTypeUpdated() ? "X" : "").in( //$NON-NLS-1$ //$NON-NLS-2$ DbConstants.Job.DEFAULT_TIME, job.getDefaultTime()).in( DbConstants.Job.DESCRIPTION, job.getInformation()).in( DbConstants.Job.INFORMATION, job.getDescription()).in( DbConstants.Job.CYCLE_OF_INSTALLATIN_FLAG, job.getCycleOfInstallationFlag()).in( DbConstants.Job.FORM_DESC_1, job.getFormDesc1()).in( DbConstants.Job.FORM_DESC_2, job.getFormDesc2()).in( DbConstants.Job.FORM_DESC_3, job.getFormDesc3()).in( DbConstants.Job.SERVICE_REFUSED_FLAG, job.getServiceRefusedFlag()).in( DbConstants.Job.LINK, job.getLink()).in( DbConstants.Job.GUARANTEE, job.getGuarantee()).in( DbConstants.Job.MORE_INFORMARION_FLAG, job.getGuarantee()).in( DbConstants.Job.CURRENT_REPORT_GUID, job.getCurrentReportGuId(this)) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertAddress(Address address) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Address.ADDRESS).in( DbConstants.Address.JOB_TYPE, address.getJobType().getCode()).in( DbConstants.Address.CITY, address.getCity()).in( DbConstants.Address.EMAIL, address.getEmail()).in( DbConstants.Address.FAX, address.getFaxNumber()).in( DbConstants.Address.CUSTOMER_NUMBER, address.getCustomerNumber()).in( DbConstants.Address.JOB_NUMBER, address.getJobNumber()).in( DbConstants.Address.NAME1, address.getName1()).in( DbConstants.Address.NAME2, address.getName2()).in( DbConstants.Address.NAME3, address.getName3()).in( DbConstants.Address.LOCATION, address.getLocation()).in( DbConstants.Address.PARTNER_NUMBER, address.getPartnerNummer()).in( DbConstants.Address.PASTAL_CODE,address.getPostalCode()).in( DbConstants.Address.STREET, address.getStreet()).in( DbConstants.Address.PHONE_1, address.getTelNumber1()).in( DbConstants.Address.PHONE_2, address.getTelNumber2()).in( DbConstants.Address.TITLE, address.getTitle()).in( DbConstants.Address.CHANGE_FLAG, address.getChangeFlag()).in( DbConstants.Address.COMMISSION_NUMBER, address.getCommissionNumber()).in( DbConstants.Address.DIRTY_FLAG, address.getDirtyFlag()).in( DbConstants.Address.TYPE, address.getType()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertEmail(Email email) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Email.EMAIL).in( DbConstants.Email.PARTNER_NUMBER, email.getPartnerNummer()).in( DbConstants.Email.JOB_TYPE, email.getJobType().getCode()).in( DbConstants.Email.TEXT, email.getEmail()).in( DbConstants.Email.JOB_NUMBER, email.getJobNumber()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } private void insertReplaceExpenses(Expenses expenses) { expenses.setExpenseCompensation(); DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Expenses.EXPENSES) .in(DbConstants.Expenses.DECUCTION ,expenses.getDeduction() ) .in(DbConstants.Expenses.DEDUCTION_DESCRIPTION ,expenses.getDeductionDescription() ) .in(DbConstants.Expenses.OPERATION_HOURS_UP_TO ,expenses.getOperatingHoursUpTo() ) .in(DbConstants.Expenses.OPERATION_HOURS_TOTAL ,expenses.getOperatingHoursTotal() ) .in(DbConstants.Expenses.OPERATING_HOURS_OF ,expenses.getOperatingHoursOf() ) .in(DbConstants.Expenses.DATE ,expenses.getDate() ) .in(DbConstants.Expenses.NO_EXPENSES ,expenses.getNoExpenses()) .in(DbConstants.Expenses.VARIOUS_EXPENSES ,expenses.getVariousExpenses() ) .in(DbConstants.Expenses.PERSONAL_NUMBER ,expenses.getPersonalNumber() ) .in(DbConstants.Expenses.PIKETT_EXPENSES ,expenses.getPikettExpenses() ) .in(DbConstants.Expenses.EXPENSES_KEY ,expenses.getExpensesKey() ) .in(DbConstants.Expenses.EXPENSES_DESCRIPTION ,expenses.getExpensesDescription() ) .in(DbConstants.Expenses.EXPENSES_DATE ,expenses.getExpensesDate() ) .in(DbConstants.Expenses.DAILY_EXPENSES ,expenses.getDailyExpenses() ) .in(DbConstants.Expenses.COMPENSTION ,expenses.getCompensation() ) .toString(); sqlStmt = sqlStmt.substring(0, 6) + " OR REPLACE " + sqlStmt.substring(7, sqlStmt.length()); //$NON-NLS-1$ int result = db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("Number of inserted records:'" + result + "' (SQL Statemant:/" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void insertOrderMaterial(OrderMaterial orderMaterial) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.OrderMaterial.ORDER_MATERIAL).in( DbConstants.OrderMaterial.DATE, orderMaterial.getDate()).in( DbConstants.OrderMaterial.EXPRESS_FLAG, orderMaterial.getExpressFlag()).in( DbConstants.OrderMaterial.VARIOUS_MATERIAL, orderMaterial.getVariousMaterial()).in( DbConstants.OrderMaterial.NUMBER, orderMaterial.getMaterialNumber()).in( DbConstants.OrderMaterial.PERSONAL_NUMBER, orderMaterial.getPersonalNumber()).in( DbConstants.OrderMaterial.AMOUNT, orderMaterial.getAmount()).in( DbConstants.OrderMaterial.UNIT, orderMaterial.getUnit()).in( DbConstants.OrderMaterial.ORDER_DATE, orderMaterial.getOrderDate()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } private void insertTimeSheet(TimeSheet timeSheet) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.TimeSheet.TIME_SHEET).in( DbConstants.TimeSheet.IDX, timeSheet.getIdx()).in( DbConstants.TimeSheet.PERSONAL_NUMBER, timeSheet.getPersonalNumber()).in( DbConstants.TimeSheet.DATE, timeSheet.getDate()).in( DbConstants.TimeSheet.START_TIME, timeSheet.getStartTime()).in( DbConstants.TimeSheet.STOP_TIME, timeSheet.getStopTime()).in( DbConstants.TimeSheet.COST_CENTER, timeSheet.getCostCenter()).in( DbConstants.TimeSheet.WORK_TYPE_CODE, timeSheet.getWorkTypeCode()).in( DbConstants.TimeSheet.CALL_FLAG, timeSheet.getCallFlag()) .toString(); int result = db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("Number of inserted records:'" + result + "' (SQL Statemant:/" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } static int getNextReportMaterialIdx(int requestedIdx, ReportMaterial maxReportMaterial) { if (maxReportMaterial == null) { return requestedIdx; } if (requestedIdx <= maxReportMaterial.getIdx()) { return maxReportMaterial.getIdx() + 1; } return requestedIdx; } public void insertNewReportMaterial(ReportMaterial reportMaterial) { ReportMaterial maxReportMaterial = selectMaxReportMaterial(reportMaterial.getGuId()); reportMaterial.setIdx(getNextReportMaterialIdx(reportMaterial.getIdx(), maxReportMaterial)); try { insertReportMaterial(reportMaterial); } catch (DBException e) { if (!isReportMaterialPrimaryKeyConstraint(e)) { throw e; } maxReportMaterial = selectMaxReportMaterial(reportMaterial.getGuId()); reportMaterial.setIdx(getNextReportMaterialIdx(reportMaterial.getIdx(), maxReportMaterial)); insertReportMaterial(reportMaterial); } } private boolean isReportMaterialPrimaryKeyConstraint(DBException exception) { String message = exception.getMessage(); return message != null && message.indexOf("ZKDMATORD.GUID") >= 0 //$NON-NLS-1$ && message.indexOf("ZKDMATORD.IDX") >= 0; //$NON-NLS-1$ } public void insertReportMaterial(ReportMaterial reportMaterial) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.ReportMaterial.REPORT_MATERIAL).in( DbConstants.ReportMaterial.IDX, reportMaterial.getIdx()).in( DbConstants.ReportMaterial.EXPRESS_DELIVERY, reportMaterial.getExpressDelivery()).in( DbConstants.ReportMaterial.GUID, reportMaterial.getGuId()).in( DbConstants.ReportMaterial.NUMBER, reportMaterial.getSparePartNumber()).in( DbConstants.ReportMaterial.DELIVERY, reportMaterial.getDelivery()).in( DbConstants.ReportMaterial.PERSONAL_NUMBER, reportMaterial.getPersonalNumber()).in( DbConstants.ReportMaterial.AMOUNT, reportMaterial.getAmount()).in( DbConstants.ReportMaterial.COMMISSION_NUMBER, reportMaterial.getCommissionNumber()).in( DbConstants.ReportMaterial.ACCOUNT_CODE, reportMaterial.getAccountCode()).in( DbConstants.ReportMaterial.UNIT, reportMaterial.getUnit()).in( DbConstants.ReportMaterial.NAME, reportMaterial.getProductName()).in( DbConstants.ReportMaterial.PRICE, reportMaterial.getPrice()).in( DbConstants.ReportMaterial.BARCODE, reportMaterial.getBarcode()).in( DbConstants.ReportMaterial.K14, reportMaterial.getK14()).in( DbConstants.ReportMaterial.EXPLANATION_TEXT, reportMaterial.getExplanationText()).in( DbConstants.ReportMaterial.OTHER_TYPE_FLAG, reportMaterial.getOtherTypeFlag()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertMaterialPerson(MaterialPerson materialOfPerson) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.MaterialPerson.MATERIAL_PERSON).in( DbConstants.MaterialPerson.NUMBER, materialOfPerson.getMaterialNumber()).in( DbConstants.MaterialPerson.TEXT, materialOfPerson.getMaterialShortText()).in( DbConstants.MaterialPerson.CUSTOMER_SERVICE_FLAG, materialOfPerson.getCustomerServiceFlag()).in( DbConstants.MaterialPerson.MOUNTING_FLAG, materialOfPerson.getMountingFlag()) .toString(); // if (log.isDebugEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ try { db.executeSql(sqlStmt); } catch (final Exception e) { ApplicationManager appman = (ApplicationManager)Runtime.getApplicationManager(); final Application app = (appman != null) ? (Application)appman.getActiveApplication() : null; if (app != null) appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase paramApplicationManagerBase, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry) { app.inform(e.getMessage()); return null; } }, false); } } public void insertServerJob( ServerJob serverJob) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.ServerJob.SERVER_JOB).in( DbConstants.ServerJob.JOB_TYPE, serverJob.getJobType().getCode()).in( DbConstants.ServerJob.CITY, serverJob.getCity()).in( DbConstants.ServerJob.JOB_NUMBER, serverJob.getJobNumber()).in( DbConstants.ServerJob.LOCATION, serverJob.getLocation()).in( DbConstants.ServerJob.PASTAL_CODE, serverJob.getPostalCode()).in( DbConstants.ServerJob.SERVICE_CONTRACT_TYPE, serverJob.getServiceContractType()).in( DbConstants.ServerJob.MONTH_YEAR, serverJob.getMonthYear()).in( DbConstants.ServerJob.STREET, serverJob.getStreet()).in( DbConstants.ServerJob.COMMISSION_NUMBER, serverJob.getCommissionNumber()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public boolean insertJobMessage(JobMessage jobMessage) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.JobMessage.JOB_MESSAGE).in( DbConstants.JobMessage.GUID, jobMessage.getGuId()).in( DbConstants.JobMessage.MESSAGE_ID, jobMessage.getMessageId()).in( DbConstants.JobMessage.MESSAGE_CODE, jobMessage.getMessageCode()).in( DbConstants.JobMessage.TEXT_1, jobMessage.getMessageCodeText()).in( DbConstants.JobMessage.TEXT_2, jobMessage.geText()).in( DbConstants.JobMessage.MoreText, jobMessage.getMoreText()) .toString(); try { if (log.isDebugEnabled()){ log.debug("sql /" + sqlStmt + "/");} //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMOBMSG:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public boolean insertReportMeasurement(ReportMeasurement reportMeasurement) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.ReportMeasurement.REPORT_MEASUREMENT).in( DbConstants.ReportMeasurement.GUID, reportMeasurement.getGuId()).in( DbConstants.ReportMeasurement.COMMISSION_NUMBER, reportMeasurement.getCommissionNumber()).in( DbConstants.ReportMeasurement.MEASURING_POINT, reportMeasurement.getMeasurementPoint()).in( DbConstants.ReportMeasurement.PERSONAL_NUMBER, reportMeasurement.getPersonalNumber()).in( DbConstants.ReportMeasurement.MEASUREMENT, reportMeasurement.getMeasurement()).in( DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE, reportMeasurement.getDynamicPowerPeakValue()).in( DbConstants.ReportMeasurement.DYNAMIC_TIME, reportMeasurement.getDynamicTime()).in( DbConstants.ReportMeasurement.STATIC_END_POWER, reportMeasurement.getStaticEndPower()).in( DbConstants.ReportMeasurement.DEVICE_TYPE, reportMeasurement.getDeviceType()).in( DbConstants.ReportMeasurement.SN_OF_DEVICE, reportMeasurement.getSNOfDevice()).in( DbConstants.ReportMeasurement.CALIBRATION_DATE, reportMeasurement.getCalibrationDate()) .toString(); try { if (log.isDebugEnabled()){ log.debug("sql /" + sqlStmt + "/");} //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMOBMEAS:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public boolean insertVariousExpenses(VariousExpenses variousExpenses) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.VariousExpenses.VARIOUS_EXPENSES).in( DbConstants.VariousExpenses.PERSONAL_NUMBER, variousExpenses.getPersonalNumber()).in( DbConstants.VariousExpenses.DATE, variousExpenses.getDate().getTime()).in( DbConstants.VariousExpenses.IDX, variousExpenses.getVariousExpensesId()).in( DbConstants.VariousExpenses.AMOUNT, variousExpenses.getAmount()).in( DbConstants.VariousExpenses.EXPENSES_CODE, variousExpenses.getExpensesCode()) .toString(); try { log.info("sql /" + sqlStmt + "/"); if (log.isDebugEnabled()){ log.debug("sql /" + sqlStmt + "/");} //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMOBMEAS:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public boolean insertVariousExpenseFile(VariousExpenseFile variousExpenseFile) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE).in( DbConstants.VariousExpenseFile.PERSONAL_NUMBER, variousExpenseFile.getPersonalNumber()).in( DbConstants.VariousExpenseFile.DATE, variousExpenseFile.getDate().getTime()).in( DbConstants.VariousExpenseFile.IDX, variousExpenseFile.getVariousExpensesFileId()).in( DbConstants.VariousExpenseFile.DESCRIPTION, variousExpenseFile.getDescription()).in( DbConstants.VariousExpenseFile.SIGN_PIC_AT, variousExpenseFile.getSignpicAt()).in( DbConstants.VariousExpenseFile.FORM_TYPE, variousExpenseFile.getFormType().getCode()) .toString(); try { // if (log.isDebugEnabled()){ log.info("sql /" + sqlStmt + "/"); // } //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMAEXPNSPICS:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public void insertReplaceReport(Report report) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Report.REPORT) .in(DbConstants.Report.IDX, report.getIdx()) .in(DbConstants.Report.JOB_TYPE, report.getJobType().getCode()) .in(DbConstants.Report.COMMISSION_NUMBER, report.getCommissionNumber()) .in(DbConstants.Report.CHECK_LIST, report.getChecklist()) .in(DbConstants.Report.FINAL_REPAIR, report.getFinalRepair()) .in(DbConstants.Report.CREATE_DATE, report.getCreateDate()) .in(DbConstants.Report.ERROR_FLAG_1, report.getErrorFlag1()) .in(DbConstants.Report.ERROR_FLAG_2, report.getErrorFlag2()) .in(DbConstants.Report.ERROR_FLAG_3, report.getErrorFlag3()) .in(DbConstants.Report.SYSTEM_ERROR, report.getSystemError()) .in(DbConstants.Report.ERROR_ID_1, report.getErrorId1()) .in(DbConstants.Report.ERROR_ID_2, report.getErrorId2()) .in(DbConstants.Report.ERROR_ID_3, report.getErrorId3()) .in(DbConstants.Report.ERROR_H_1, report.getErrorH1()) .in(DbConstants.Report.ERROR_H_2, report.getErrorH2()) .in(DbConstants.Report.ERROR_H_3, report.getErrorH3()) .in(DbConstants.Report.REASONING, report.getReasoning()) .in(DbConstants.Report.GUID, report.getGuId()) .in(DbConstants.Report.DISTANCE, report.getDistance()) .in(DbConstants.Report.JOB_NUMBER, report.getJobNumber()) .in(DbConstants.Report.PERSONAL_NUMBER, report.getPersonalNumber()) .in(DbConstants.Report.SIGNATURE_GUID, report.getSignatureGuId()) .in(DbConstants.Report.CUSTOMER_SUPPORT, report.getCustomerSupport()) .in(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT, report.getCustomerSupportText()) .in(DbConstants.Report.REPORT_STATUS,report.getReportStatus().getCode()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_1, report.getServicePlanMonth1()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_2, report.getServicePlanMonth2()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_3, report.getServicePlanMonth3()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_4, report.getServicePlanMonth4()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_5, report.getServicePlanMonth5()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_6, report.getServicePlanMonth6()) .in(DbConstants.Report.MONTH_YEAR, report.getMonthYear()) .in(DbConstants.Report.SAFETY_REPORT, report.getSafetyReport()) .in(DbConstants.Report.SIGNATURE_FLAG, report.getSignatureFlag()) .in(DbConstants.Report.ORDER_NUMBER, report.getOrderNumber()) .in(DbConstants.Report.SIGNATURE, report.getSignature()) .in(DbConstants.Report.SIGNATURE_INFO, report.getSignatureInfo()) .in(DbConstants.Report.EXPENSES, report.getExpenses()) .in(DbConstants.Report.INCIDENT_AB, report.getIncidentAB()) .in(DbConstants.Report.PARTICAL_REPAIR, report.getPartialRepair()) .in(DbConstants.Report.BILLING, report.getBilling()) .in(DbConstants.Report.WORK_TYPE, report.getWorkType()) .in(DbConstants.Report.COLLECTIVELY, report.getCollectively()) .in(DbConstants.Report.NO_MATERIAL, report.getNoMaterial()) .in(DbConstants.Report.CYCLE_OF_INSTALLATION, report.getCycleOfInstallation()) .in(DbConstants.Report.NO_FORM1, report.getNoForm1()) .in(DbConstants.Report.NO_FORM2, report.getNoForm2()) .in(DbConstants.Report.NO_FORM3, report.getNoForm3()) .in(DbConstants.Report.SERVICE_REFUSED, report.getServiceRefused()) .in(DbConstants.Report.OPEN_PENDING, report.getOpenPending()) .in(DbConstants.Report.GOVERNMENT_REPORT, report.getGovernmentReport()) .in(DbConstants.Report.CHECKLIST_STATE, report.getChecklistState()) .in(DbConstants.Report.CHECKLIST_SIA, report.getChecklistSIA()) .in(DbConstants.Report.CHECKLIST_READY, report.getChecklistReady()) .in(DbConstants.Report.CHECKLIST_INSTRUCTION, report.getChecklistInstruction()) .in(DbConstants.Report.CHECKLIST_VKF, report.getChecklistVKF()) .in(DbConstants.Report.CHECKLIST_TEST, report.getChecklistTest()) .in(DbConstants.Report.SIGNATURE_NAME, report.getSignatureName()) .in(DbConstants.Report.MON_STK, report.getMonStk()) .in(DbConstants.Report.NEXT_INTERVENTION_DATE, report.getNextInterventionDate()) .in(DbConstants.Report.STATE_OF_INSTALLATION, report.getStateOfInstallation()) .in(DbConstants.Report.NEXT_INTERVENTION_CODE, report.getNextInterventionCode()) .toString(); sqlStmt = sqlStmt.substring(0, 6) + " OR REPLACE " + sqlStmt.substring(7, sqlStmt.length()); //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } /** * Saves the list of job times and updates the job status to 'in arbeit' * * @param zkdmob * @param zkdmobrtimList */ public void insertJobReportTimeList(Report report) { List jobReportTimeList = report.getTimes(); boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); deleteJobReportTimeByGUID(report.getGuId()); Iterator itr = jobReportTimeList.iterator(); while (itr.hasNext()) { JobReportTime jobReportTime = itr.next(); String sql = "INSERT OR REPLACE INTO " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " (" //$NON-NLS-1$ + DbConstants.JobReportTime.IDX + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.GUID + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.DATE + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.START_TIME + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.STOP_TIME + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.WORK_TYPE_CODE + ") " //$NON-NLS-1$ + " VALUES (" //$NON-NLS-1$ + "'" + jobReportTime.getIdx() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getGuId() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getDate().getTime() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getStartTime().getTime() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getStopTime().getTime() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getWorkTypeCode() + "') "; //$NON-NLS-1$ //$NON-NLS-2$ int affectedRows = db.executeSql(sql); // if (log.isDebugEnabled()) log.info("affected rows:'" + affectedRows + "'/ sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); } public void insertJobReportTime(JobReportTime jobReportTime) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.JobReportTime.JOB_REPORT_TIME) .in(DbConstants.JobReportTime.IDX, jobReportTime.getIdx()) .in(DbConstants.JobReportTime.GUID, jobReportTime.getGuId()) .in(DbConstants.JobReportTime.DATE, jobReportTime.getDate()) .in(DbConstants.JobReportTime.START_TIME, jobReportTime.getStartTime()) .in(DbConstants.JobReportTime.STOP_TIME, jobReportTime.getStopTime()) .in(DbConstants.JobReportTime.WORK_TYPE_CODE, jobReportTime.getWorkTypeCode()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertOrder(Order order) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Order.ORDER).in( DbConstants.Order.PERSONAL_NUMBER, order.getPersonalNumber()).in( DbConstants.Order.STATUS, order.getStatus()).in( DbConstants.Order.ANZ, order.getANZ()).in( DbConstants.Order.CREATED_DATE, order.getCreateDate()).in( DbConstants.Order.SENT_DATE, order.getSentDate()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertJobFile(JobFile jobFile) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.JobFile.JOB_FILE).in( DbConstants.JobFile.IDX, jobFile.getJobFileId()).in( DbConstants.JobFile.GUID, jobFile.getGuid()).in( DbConstants.JobFile.JOB_NUMBER, jobFile.getJobNumber()).in( DbConstants.JobFile.JOB_TYPE, jobFile.getJobType().getCode()).in( DbConstants.JobFile.TYPE, jobFile.getType()).in( DbConstants.JobFile.DESCRIPTION, jobFile.getDescription()).in( DbConstants.JobFile.SIGN_PIC_AT, jobFile.getSignpicAt()).in( DbConstants.JobFile.FORM_TYPE, jobFile.getFormType().getCode()).in( DbConstants.JobFile.FORM_DESC, jobFile.getFormDesc()).in( DbConstants.JobFile.SENT_DATE, jobFile.getSentDate()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); // remove image data from memory after update (lazy load; MIG-988) jobFile.setSignPicAt(null); } public void insertAbsenceNotification(AbsenceNotification absenceNotification) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION).in( DbConstants.AbsenceNotification.GUID, absenceNotification.getGuId()).in( DbConstants.AbsenceNotification.PERSONAL_NUMBER, absenceNotification.getPersonalNumber()).in( DbConstants.AbsenceNotification.DATE, absenceNotification.getAbsenceDate()).in( DbConstants.AbsenceNotification.DATE_FROM, absenceNotification.getDateFrom()).in( DbConstants.AbsenceNotification.TIME_FROM, absenceNotification.getTimeFrom()).in( DbConstants.AbsenceNotification.DATE_TO, absenceNotification.getDateTo()).in( DbConstants.AbsenceNotification.TIME_TO, absenceNotification.getTimeTo()).in( DbConstants.AbsenceNotification.ABSENCE_TYPE, absenceNotification.getAbsenceType()).in( DbConstants.AbsenceNotification.TEXT, absenceNotification.getText()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } /** * Saves the list of report form instances * */ public void insertOrReplaceJobReportFormInstanceList(List formInstances) { boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); Iterator itr = formInstances.iterator(); while (itr.hasNext()) { FormInstance formInstance = itr.next(); DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.FormInstance.FORMINSTANCE ).in( DbConstants.FormInstance.GUID, formInstance.getGuid()).in( DbConstants.FormInstance.FORM_ID, formInstance.getFormId()).in( DbConstants.FormInstance.FORM_VERSION, formInstance.getFormVersion()).in( DbConstants.FormInstance.FORM_ITEM_ID, formInstance.getFormItemId()).in( DbConstants.FormInstance.VALUE_LIST_ID, formInstance.getValueListId()).in( DbConstants.FormInstance.VALUE_ID, formInstance.getValueId()).in( DbConstants.FormInstance.FORM_ITEM_TYPE, formInstance.getFormItemType().getCode()).in( DbConstants.FormInstance.STRING_VALUE, formInstance.getStringValue()).in( DbConstants.FormInstance.BOOLEAN_VALUE, formInstance.isBooleanValue()).in( DbConstants.FormInstance.FLOAT_VALUE, formInstance.getFloatValue()).in( DbConstants.FormInstance.ATTACHMENT_VALUE, formInstance.getAttachmentValue()) .toString(); sqlStmt = sqlStmt.substring(0, 6) + " OR REPLACE " + sqlStmt.substring(7, sqlStmt.length()); //$NON-NLS-1$ db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); } public void insertMaterialMovement(MaterialMovement materialMovement) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.MaterialMovement.MATRIAL_MOVEMENT).in( DbConstants.MaterialMovement.GUID, materialMovement.getGuid()).in( DbConstants.MaterialMovement.ORDER_NUMBER, materialMovement.getOrderNumber()).in( DbConstants.MaterialMovement.ORDER_POSITION, materialMovement.getOrderPosition()).in( DbConstants.MaterialMovement.PERSONAL_NUMBER, materialMovement.getPersonalNumber()).in( DbConstants.MaterialMovement.MATERIAL_NUMBER, materialMovement.getMaterialNumber()).in( DbConstants.MaterialMovement.FROM, materialMovement.getFrom()).in( DbConstants.MaterialMovement.TO, materialMovement.getTo()).in( DbConstants.MaterialMovement.ENTRY_COUNT, materialMovement.getEntryCount()).in( DbConstants.MaterialMovement.ENTRY_UNIT, materialMovement.getEntryUnit()).in( DbConstants.MaterialMovement.RECEIPT_OF_GOODS, materialMovement.getReceiptOfGoods()).in( DbConstants.MaterialMovement.BARCODE, materialMovement.getBarcode()).in( DbConstants.MaterialMovement.BARCODE_TEXT, materialMovement.getBarcodeText()).in( DbConstants.MaterialMovement.PERSONAL_NUMBER_CONFIRMED, materialMovement.getPersonalNumberConfirmed()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } /** * Selects count (number of records) from a table. * * @param table * the table * @return the row count of the table, 0 if it contains no records */ public int selectCountFromTable(String table, String criteria) { RecordSet rs = db.getRecordSet(); try { String sql = "SELECT COUNT(*) FROM " + table; //$NON-NLS-1$ if (!"".equalsIgnoreCase(criteria)) { //$NON-NLS-1$ sql += criteria; } rs.setQuery(sql); if (log.isDebugEnabled()) log.debug("sql / " + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.moveNext(); return rs.getInt(0); } finally { rs.dispose(); } } public LocalizedTexts[] selectLocalizedTextsList(String textType) { return LocalizedTexts.listByPrimaryKey(db, "%", true, setDefaultLanguage(getUser().getLanguage()), false, textType, false, Integer.MAX_VALUE); } public enum JobStatusFilter { active, planned, finalized } public List selectJobList() { // ensureAMThread(); List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String order = " ORDER BY CASE " + DbConstants.Job.STATUS + " WHEN '" + JobStatus.IN_PROGRESS + "' THEN 1" + " WHEN '" + JobStatus.NEW + "' THEN 2" + " WHEN '" + JobStatus.RECEIVED + "' THEN 3" + " WHEN '" + JobStatus.PARLTY_DONE + "' THEN 4" + " ELSE 5 END"; //$NON-NLS-1$ String sql = "SELECT * FROM " + DbConstants.Job.JOB; //$NON-NLS-1$ order += ", " + DbConstants.Job.NEW_JOB_DATE + " DESC" + ", " + DbConstants.Job.APPOINTMENT_DATE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sql = sql + order; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } public List selectJobList( JobStatusFilter jobStatusFilter , boolean filterRep , boolean filterSav , boolean filterMon) { ensureAMThread(); List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String auartList = ""; //$NON-NLS-1$ if (filterRep) { auartList = auartList.concat("'" + JobType.REP + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } if (filterSav && StringUtil.isNotEmpty(auartList)) { auartList = auartList.concat(","); //$NON-NLS-1$ } if (filterSav) { auartList = auartList.concat("'" + JobType.SAV + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } if (filterMon && StringUtil.isNotEmpty(auartList)) { auartList = auartList.concat(","); //$NON-NLS-1$ } if (filterMon) { auartList = auartList.concat("'" + JobType.MON + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } String sortingAuart = "CASE " + DbConstants.Job.JOB_TYPE + " WHEN '" + JobType.MON + "' THEN 1 WHEN '" + JobType.SAV + "' THEN 2 ELSE 3 END"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ String eDate = ""; //$NON-NLS-1$ String activeDate = ""; //$NON-NLS-1$ String statusList = ""; //$NON-NLS-1$ String order = " ORDER BY CASE " + DbConstants.Job.STATUS + " WHEN '" + JobStatus.IN_PROGRESS + "' THEN 1" + " WHEN '" + JobStatus.NEW + "' THEN 2" + " WHEN '" + JobStatus.RECEIVED + "' THEN 3" + " WHEN '" + JobStatus.PARLTY_DONE + "' THEN 4" + " ELSE 5 END"; //$NON-NLS-1$ // String todayDate = "(SELECT CAST(strftime('%s', date('now')) * 1000 AS INT))";//20.09.17 00.00.00->1505860000000 // String tomorrow = "(SELECT CAST(strftime('%s', date('now','+1 day')) * 1000 AS INT))";//21.09.17 00.00.00->1505952000000 String twoDaysInTheFuture = "(SELECT CAST(strftime('%s', date('now','+2 day')) * 1000 AS INT))";//22.09.17 00.00.00->1560384000000 String eightyNightDaysInTheFuture = "(SELECT CAST(strftime('%s', date('now','+2 day')) * 1000 AS INT))";//22.09.17 00.00.00->1560384000000 String timeCount = "SELECT COUNT(" + DbConstants.JobReportTime.GUID + ") FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.JOB_REPORT_TIME + "." + DbConstants.JobReportTime.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String reportCount = "SELECT COUNT(" + DbConstants.Report.GUID + ") FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.REPORT + "." + DbConstants.Report.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String matCount = "SELECT COUNT(" + DbConstants.ReportMaterial.GUID + ") FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.REPORT_MATERIAL + "." + DbConstants.ReportMaterial.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String messageCount = "SELECT COUNT(" + DbConstants.JobMessage.GUID + ") FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.JOB_MESSAGE + "." + DbConstants.JobMessage.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String reports = ""; switch (jobStatusFilter) { case active: statusList = "'" + JobStatus.NEW + "'," + "'" + JobStatus.RECEIVED + "'," + "'" + JobStatus.IN_PROGRESS + "'," + "'" + JobStatus.PARLTY_DONE + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //STATUS = NEW OR ZKDMOB.EDATE <= 1 day ( in the past , today and tomorrow) // MON, REP edate - 3 days <= current date // SAV edate - 90 days <= current date eDate = " AND " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " <= " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " <= " + eightyNightDaysInTheFuture + ")" + ")" ; // MON, REP active date - 3 days <= current date // SAV active date - 90 days <= current date activeDate = " AND " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.ACTIVE_DATE + " <= " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.ACTIVE_DATE + " <= " + eightyNightDaysInTheFuture + ")" + ")" ; // check if job active //- report is not empty //- time is not empty //- material is not empty //- message is not empty reports = "" + " OR (" + "(" + timeCount + ") > 0" + " OR (" + reportCount + ") > 0" + " OR (" + matCount + ") > 0" + " OR (" + messageCount + ") > 0" + ") AND ("+ DbConstants.Job.STATUS + " NOT IN ('" + JobStatus.FORWARDED + "', '" + JobStatus.FINALIZED + "'))"; order += ", " + sortingAuart; //$NON-NLS-1$ break; case planned: statusList = "'" + JobStatus.RECEIVED + "'," + "'" + JobStatus.PARLTY_DONE + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //ZKDMOB.EDATE > 1 day ( pass tomorrow and more than 2 days in the future) // MON, REP edate - 3 days >= current date // SAV edate - 90 days >= current date eDate = " AND " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " > " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " > " + eightyNightDaysInTheFuture + ")" + ")" ; // MON, REP active date - 3 days ><= current date // SAV active date - 90 days >= current date activeDate = " OR " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.ACTIVE_DATE + " > " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.ACTIVE_DATE + " > " + eightyNightDaysInTheFuture + ")" + ")" ; // no reports. reports = "" + " AND (" + "(" + matCount + ") = 0" + " AND (" + timeCount + ") = 0" + " AND (" + reportCount + ") = 0" + " AND (" + messageCount + ") = 0" + ")"; ; break; case finalized: statusList = "'" + JobStatus.FORWARDED + "'," + "'" + JobStatus.FINALIZED + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ order = " ORDER BY " + DbConstants.Job.STATUS_EDIT + " DESC"; break; } order += ", " + DbConstants.Job.NEW_JOB_DATE + " DESC" + ", " + DbConstants.Job.APPOINTMENT_DATE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String sql = "SELECT * FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + DbConstants.Job.STATUS + " IN (" + statusList + ")" + " AND " + DbConstants.Job.JOB_TYPE + " IN (" + auartList + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ if (StringUtil.isNotEmpty(eDate)) { sql = sql + eDate; //$NON-NLS-1$ } if (StringUtil.isNotEmpty(activeDate)) { sql = sql + activeDate; //$NON-NLS-1$ } if (StringUtil.isNotEmpty(reports)) { sql = sql + reports; //$NON-NLS-1$ } sql = sql + order; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } public List selectFinalizedJobList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String statusList = "'" + JobStatus.REJECTED + "'," //$NON-NLS-1$ //$NON-NLS-2$ + "'" + JobStatus.FINALIZED + "'," //$NON-NLS-1$ //$NON-NLS-2$ + "'" + JobStatus.DELETED + "' "; //$NON-NLS-1$ //$NON-NLS-2$ String sql = "SELECT * FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + DbConstants.Job.STATUS + " IN (" + statusList + ")" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.Job.STATUS + ",rowid"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } public Job selectJobByJobIdAndJobType( String jobId, String jobType) { Job result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Job.JOB + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.Job.JOB_NUMBER + " = '" + jobId + "'" + " AND " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + DbConstants.Job.JOB_TYPE + " = '" + jobType + "'"; //$NON-NLS-1$ //$NON-NLS-2$ // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Job(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple /" + jobId + "/ and /" + jobType + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } finally { rs.dispose(); } return result; } public List
selectAddressListByJobIdAndJobType(String jobId, String jobType) { List
result = new ArrayList
(); String sql = "SELECT * FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + jobType + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info(sql); if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); if (rs.isEmpty()) { result.add(new Address()); } else { while (rs.moveNext()) { result.add(new Address(rs)); } } } finally { rs.dispose(); } return result; } public List selectEmailListByJobIdAndJobType(String jobId, String jobType) { List result = new ArrayList(); String sql = "SELECT * FROM " + DbConstants.Email.EMAIL //$NON-NLS-1$ + " WHERE " + DbConstants.Email.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Email.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER By " + DbConstants.Email.TEXT + " ASC"; log.info(sql); if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); while (rs.moveNext()) { result.add(new Email(rs)); } } finally { rs.dispose(); } return result; } public Address selectAddressByJobIdAndJobTypeAndPerNo( String jobId, String jobType, String perNo) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.PARTNER_NUMBER + " = '" + perNo + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Address result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug(DbConstants.Address.JOB_NUMBER + " = " + jobId //$NON-NLS-1$ + " AND " + DbConstants.Address.JOB_TYPE + " = " //$NON-NLS-1$ //$NON-NLS-2$ + jobId + " AND " + DbConstants.Address.PARTNER_NUMBER //$NON-NLS-1$ + " = " + perNo + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Address(rs); } } finally { rs.dispose(); } return result; } public Email selectEmailByJobIdAndJobTypeAndPerNo( String jobId, String jobType, String perNo) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Email.EMAIL //$NON-NLS-1$ + " WHERE " + DbConstants.Email.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Email.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Email.PARTNER_NUMBER + " = '" + perNo + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Email result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug(DbConstants.Email.JOB_NUMBER + " = " + jobId //$NON-NLS-1$ + " AND " + DbConstants.Email.JOB_TYPE + " = " //$NON-NLS-1$ //$NON-NLS-2$ + jobId + " AND " + DbConstants.Email.PARTNER_NUMBER //$NON-NLS-1$ + " = " + perNo + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Email(rs); } } finally { rs.dispose(); } return result; } public WorkType selectWorkTypeByJobTypeAndWorkTypeCode(JobType jobType, String workTypeCode) { RecordSet rs = db.getRecordSet(); String frm = ""; //$NON-NLS-1$ if (jobType.isREP() || jobType.isSAV()) frm = "04"; //$NON-NLS-1$ else if (jobType.isMON()) frm = "03"; //$NON-NLS-1$ String sql = "SELECT * FROM " + DbConstants.WorkType.WORK_TYPE //$NON-NLS-1$ + " WHERE " + DbConstants.WorkType.GROUP + " ='" + frm + "'" + " AND " + DbConstants.WorkType.CODE + " ='" + workTypeCode + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); WorkType result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new WorkType(rs); } } finally { rs.dispose(); } return result; } public List selectWorkTypeListByJobType(JobType jobType) { RecordSet rs = db.getRecordSet(); List result = new ArrayList(); String frm = ""; //$NON-NLS-1$ if (jobType.isREP() || jobType.isSAV()) frm = "04"; //$NON-NLS-1$ else if (jobType.isMON()) frm = "03"; //$NON-NLS-1$ String sql = "SELECT * FROM " + DbConstants.WorkType.WORK_TYPE //$NON-NLS-1$ + " WHERE " + DbConstants.WorkType.GROUP + " ='" + frm + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new WorkType(rs)); } } finally { rs.dispose(); } return result; } public List selectStateOfInstallation() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.StateOfInstallation.STATE_OF_INSTALLATION; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new StateOfInstallation(rs)); } } finally { rs.dispose(); } return result; } public List selectNextIntervention() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.NextIntervention.NEXT_INVENTION; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new NextIntervention(rs)); } } finally { rs.dispose(); } return result; } public ErrorCode selectErrorCodeByFc( String fc) { RecordSet rs = db.getRecordSet(); ErrorCode result = null; String sql = "SELECT * FROM " + DbConstants.ErrorCode.ERROR_CODE + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.ErrorCode.CODE + " ='" + fc + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result = new ErrorCode(rs); } } finally { rs.dispose(); } return result; } public List selectErrorCodeList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ErrorCode.ERROR_CODE //$NON-NLS-1$ + " ORDER BY " + DbConstants.ErrorCode.CODE; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ErrorCode(rs)); } } finally { rs.dispose(); } return result; } public List selectShortMessageListbyPerNo( int pernr) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.ShortMessage.RECEIVED_TIME + " DESC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ShortMessage(rs)); } } finally { rs.dispose(); } return result; } public ShortMessage selectShortMessageByPerNoAndTdName( int pernr, String tdName) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ShortMessage.MESSAGE_KEY + " ='" + tdName + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); ShortMessage result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ShortMessage(rs); } } finally { rs.dispose(); } return result; } public List selectInternalWorkTypeList() { RecordSet rs = db.getRecordSet(); List result = new ArrayList(); String sql = "SELECT * FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new InternalWorkType(rs)); } } finally { rs.dispose(); } return result; } public InternalWorkType selectInternalWorkTypeByWorkTypeCode(String workTypeCode) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE //$NON-NLS-1$ + " WHERE " + DbConstants.InternalWorkType.CODE + " ='" + workTypeCode + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); InternalWorkType result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new InternalWorkType(rs); } } finally { rs.dispose(); } return result; } public List selectServiceRefusedList() { RecordSet rs = db.getRecordSet(); List result = new ArrayList(); String sql = "SELECT * FROM " + DbConstants.ServiceRefused.SERVICE_REFUSED; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ServiceRefused(rs)); } } finally { rs.dispose(); } return result; } public void updateShortMessage( ShortMessage shortMessage) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.ShortMessage.SHORT_MESSAGE) .in(DbConstants.ShortMessage.SUBJECT, shortMessage.getSubject()) .in(DbConstants.ShortMessage.CONFIRM, shortMessage.getConfirm()) .in(DbConstants.ShortMessage.MESSAGE, shortMessage.getMessage()) .in(DbConstants.ShortMessage.STATUS, shortMessage.getStatus()) .in(DbConstants.ShortMessage.RECEIVED_DATE, shortMessage.getReceiveDate()) .in(DbConstants.ShortMessage.RECEIVED_TIME, shortMessage.getReceiveTime()) + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " = '" + shortMessage.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ShortMessage.MESSAGE_KEY + " = '" + shortMessage.getMessageKey() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void updateVariousExpenses(VariousExpenses variousExpenses) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.VariousExpenses.VARIOUS_EXPENSES) .in(DbConstants.VariousExpenses.PERSONAL_NUMBER, variousExpenses.getPersonalNumber()) .in(DbConstants.VariousExpenses.DATE, variousExpenses.getDate().getTime()) .in(DbConstants.VariousExpenses.IDX, variousExpenses.getVariousExpensesId()) .in(DbConstants.VariousExpenses.AMOUNT, variousExpenses.getAmount()) .in(DbConstants.VariousExpenses.EXPENSES_CODE, variousExpenses.getExpensesCode()) + " WHERE " + DbConstants.VariousExpenses.PERSONAL_NUMBER + " = '" + variousExpenses.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenses.DATE + " ='" + variousExpenses.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenses.IDX + " ='" + variousExpenses.getVariousExpensesId() + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void updateVariousExpenseFile(VariousExpenseFile variousExpenseFile) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE) .in(DbConstants.VariousExpenseFile.PERSONAL_NUMBER, variousExpenseFile.getPersonalNumber()) .in(DbConstants.VariousExpenseFile.DATE, variousExpenseFile.getDate().getTime()) .in(DbConstants.VariousExpenseFile.IDX, variousExpenseFile.getVariousExpensesFileId()) .in(DbConstants.VariousExpenseFile.DESCRIPTION, variousExpenseFile.getDescription()) .in(DbConstants.VariousExpenseFile.SIGN_PIC_AT, variousExpenseFile.getSignpicAt()) .in(DbConstants.VariousExpenseFile.FORM_TYPE, variousExpenseFile.getFormType().getCode()) + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " = '" + variousExpenseFile.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenseFile.DATE + " ='" + variousExpenseFile.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenseFile.IDX + " ='" + variousExpenseFile.getVariousExpensesFileId() + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public ReportMessage selectReportMessageByMsgc( String msgc) { ReportMessage result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMessage.REPORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMessage.CODE + " = '" + msgc + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ReportMessage(rs); } } finally { rs.dispose(); } return result; } public JobMonText selectReportMONMessageByMsgcAndLangu( String msgc, String langu) { JobMonText result = null; // TODO "ZKDMOBMONTXT" missing "Language" from server. langu=""; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMonText.JOB_MON_TEXT //$NON-NLS-1$ + " WHERE " + DbConstants.JobMonText.CODE + " = '" + msgc + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobMonText.LANGUAGE + " = '" + langu + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobMonText(rs); } } finally { rs.dispose(); } return result; } public List selectReportMessage() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMessage.REPORT_MESSAGE; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMessage(rs)); } } finally { rs.dispose(); } return result; } public List selectJobMonMessageByLangu( String langu) { List result = new ArrayList(); // TODO "ZKDMOBMONTXT" missing "Language" from server. langu =""; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMonText.JOB_MON_TEXT//$NON-NLS-1$ + " WHERE " + DbConstants.JobMonText.LANGUAGE + " = '" + langu + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobMonText.CODE + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMonText(rs)); } } finally { rs.dispose(); } return result; } // public Incident selectIncidentByZiff( String strc, String ziff, String langu) { // Incident result = null; // // RecordSet rs = db.getRecordSet(); // // String sql = "SELECT * FROM " + DbConstants.Incident.Incident //$NON-NLS-1$ // + " WHERE " + DbConstants.Incident.ErrorCode + " ='" + strc //$NON-NLS-1$ //$NON-NLS-2$ // + "'" + " AND " + DbConstants.Incident.ZIFF + " ='" + ziff //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // + "'" + " AND " + DbConstants.Incident.Language + " ='" + langu //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // + "'"; //$NON-NLS-1$ // // if (log.isDebugEnabled()) // log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ // // rs.setQuery(sql); // // try { // while (rs.moveNext()) { // result = new Incident(rs); // } // } finally { // rs.dispose(); // } // return result; // } public Incident selectIncidentByFCT( String errorCode, String fct) { Incident result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Incident.INCIDENT //$NON-NLS-1$ + " WHERE " + DbConstants.Incident.CODE + " ='" + errorCode //$NON-NLS-1$ //$NON-NLS-2$ + "'" + " AND " + DbConstants.Incident.FCT + " ='" + fct //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "'"; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result = new Incident(rs); } } finally { rs.dispose(); } return result; } public List selectIncidentList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Incident.INCIDENT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Incident(rs)); } } finally { rs.dispose(); } return result; } public List selectHistoryList(String mldnr, String auart) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.History.HISTORY //$NON-NLS-1$ + " WHERE " + DbConstants.History.JOB_NUMBER + " = '" + mldnr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.History.JOB_TYPE + " = '" + auart + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new History(rs)); } } finally { rs.dispose(); } return result; } public List selectCheckList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Checklist.CHECK_LIST; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Checklist(rs)); } } finally { rs.dispose(); } return result; } public List selectProgress() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Progress.PROGRESS; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Progress(rs)); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ public List selectPersonList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Person.PERSON; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Person(rs)); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectExpensesList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Expenses(rs)); } } finally { rs.dispose(); } return result; } public List selectOrderMaterialList(Order order) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.OrderMaterial.ORDER_DATE + " ='" + order.getCreateDate().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new OrderMaterial(rs)); } } finally { rs.dispose(); } return result; } /** * @param von * @param pernr * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private TimeSheet selectActiveTimeSheetByFromDate(Date von, int pernr) { RecordSet rs = db.getRecordSet(); Date earlyMorning = DateTimeUtil.getDate(von).getTime(); Date lateNight = DateTimeUtil.getLateNight(von).getTime(); String sql = "SELECT * FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = " + pernr //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.IDX + " = " + //$NON-NLS-1$ //$NON-NLS-2$ "(SELECT MAX(" + DbConstants.TimeSheet.IDX + ") FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = '" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); TimeSheet result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new TimeSheet(rs); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private JobReportTime selectActiveJobReportTime() { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE ( rowid " + " = (SELECT MAX(rowid) FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + ")) " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " OR (" + DbConstants.JobReportTime.STOP_TIME + " ='" + DateUtils.getInitialDateTime().getTime() + "'" + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } else { /** * in case that there is some record has not been stopped yet * but it is not the latest record this will select the opened * entry instead of the latest record */ while (rs.moveNext()) { JobReportTime jobReportTime = new JobReportTime(rs); if (jobReportTime.getStopTime().equals(DateUtils.getInitialDateTime())) { result = jobReportTime; } } } } finally { rs.dispose(); } return result; } /** * @param guid Report ID * @return Last entry of the report time sheet. */ public JobReportTime selectLatestJobReportTimeByGUID(String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.START_TIME + " = " //$NON-NLS-1$ //$NON-NLS-2$ + "(SELECT MAX(" + DbConstants.JobReportTime.START_TIME + ") " + //$NON-NLS-1$ //$NON-NLS-2$ " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + //$NON-NLS-1$ " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } } finally { rs.dispose(); } return result; } public int selectNextIDXFromJobReportTimeByGUID(String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.JobReportTime.IDX + " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " = " //$NON-NLS-1$ //$NON-NLS-2$ + "(SELECT MAX(" + DbConstants.JobReportTime.IDX + ") " + //$NON-NLS-1$ //$NON-NLS-2$ " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + //$NON-NLS-1$ " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); int result = 1; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = rs.getInt(DbConstants.JobReportTime.IDX) + 1; } } finally { rs.dispose(); } return result; } /** * @param von * @param pernr * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectTimeSheetListByFromDate(Date von, int pernr) { List result = new ArrayList(); Date earlyMorning = DateTimeUtil.getDate(von).getTime(); Date lateNight = DateTimeUtil.getLateNight(von).getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new TimeSheet(rs)); } } finally { rs.dispose(); } return result; } /** * @param datum * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private Expenses selectExpenses(Date datum) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.DATE + " = '" + datum.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Expenses result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Expenses(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } /** * Searches the last entered value for the operation hour counter. * @param datum date form where the search is started into the past * @param pernr * @return Last available (not highest!) value of the operation hour counter (attribute BBIS) */ public Expenses selectLastAvailableBToDate(Date datum, int pernr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.DATE + " < " + datum.getTime() //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.Expenses.OPERATION_HOURS_UP_TO + " <> ''" //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.Expenses.DATE + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Expenses result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Expenses(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ rs.moveNext(); result = new Expenses(rs); } } finally { rs.dispose(); } return result; } public ReportMaterial selectMaxReportMaterial(String guid) { RecordSet rs = db.getRecordSet(); String sql = ("SELECT * FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = (SELECT MAX (" //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.ReportMaterial.IDX + ") FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + guid + "' )"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); ReportMaterial result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ReportMaterial(rs); } } finally { rs.dispose(); } return result; } public List selectReportMaterialList(String guid) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { ReportMaterial reportMaterial = new ReportMaterial(rs); if(!reportMaterial.isK14()){ Material part = selectMaterialByMatNo(reportMaterial.getSparePartNumber()); if (part != null) { reportMaterial.setProductName(part.getMaterialShortText()); } else { MaterialPerson materialPerson = selectMaterialPersonByMatNo(reportMaterial.getSparePartNumber()); if (materialPerson != null) { reportMaterial.setProductName(materialPerson.getMaterialShortText()); } } } result.add(reportMaterial); } } finally { rs.dispose(); } return result; } public List selectReportMaterialListByLimit(String guid, int limit) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String innerSql = "SELECT * FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.ReportMaterial.GUID + " = '" + guid + "'" + " ORDER BY " + DbConstants.ReportMaterial.IDX //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " DESC " + " LIMIT " + limit; //$NON-NLS-1$ //$NON-NLS-2$ String sql = "SELECT * FROM ( " + innerSql + " ) " + " ORDER BY " + DbConstants.ReportMaterial.IDX; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMaterial(rs)); } } finally { rs.dispose(); } return result; } public Job selectJobByGUID(String guid) { Job result = new Job(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Job.JOB + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.Job.CURRENT_REPORT_GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Job(rs); } } finally { rs.dispose(); } return result; } public List selectJobBySignGUID(String signguid) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT mob.* " //$NON-NLS-1$ + " FROM " + DbConstants.Job.JOB + " mob " //$NON-NLS-1$ //$NON-NLS-2$ + " JOIN " + DbConstants.Report.REPORT + " rep " //$NON-NLS-1$ //$NON-NLS-2$ + " ON mob." + DbConstants.Job.JOB_NUMBER + " = rep." + DbConstants.Report.JOB_NUMBER //$NON-NLS-1$ //$NON-NLS-2$ + " AND mob." + DbConstants.Job.JOB_TYPE + " = rep." + DbConstants.Report.JOB_TYPE //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE rep." + DbConstants.Report.SIGNATURE_GUID + " = '" + signguid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else { while (rs.moveNext()) { result.add(new Job(rs)); } } } finally { rs.dispose(); } return result; } public List selectReportListOfSignFiles() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT DISTINCT " + DbConstants.Report.SIGNATURE //$NON-NLS-1$ + " FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.SIGNATURE + " <> ''"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else { while (rs.moveNext()) { String signpic = rs.getString(DbConstants.Report.SIGNATURE); result.add(signpic); } } } finally { rs.dispose(); } return result; } public List selectReportListOfSignBundle() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.COLLECTIVELY + " <> ''" //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.Report.CREATE_DATE + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else { while (rs.moveNext()) { result.add(new Report(rs)); } } } finally { rs.dispose(); } return result; } public List selectMaterialPersonListByMatNoAndMatName( String matNr, String makTx) { List result = new ArrayList(); int pos = 0; while ((pos = makTx.indexOf('\'', pos)) != -1) { makTx = makTx.substring(0, pos) + '\'' + makTx.substring(pos++); pos++; } if (matNr.contains("'")) { matNr = matNr.replace("'", ""); } String cond = " OR "; if(matNr.isEmpty()) { cond = " AND "; } RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " //$NON-NLS-1$ + DbConstants.MaterialPerson.MATERIAL_PERSON + " WHERE " + DbConstants.MaterialPerson.TEXT + " LIKE '%" + makTx + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + cond + DbConstants.MaterialPerson.NUMBER + " LIKE '%" + matNr + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.MaterialPerson.TEXT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new MaterialPerson(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectMaterialListByMatNrAndMatName( String matNr, String makTx) { List result = new ArrayList(); int pos = 0; while ((pos = makTx.indexOf('\'', pos)) != -1) { makTx = makTx.substring(0, pos) + '\'' + makTx.substring(pos++); pos++; }if (matNr.contains("'")) { matNr = matNr.replace("'", ""); } String cond = " OR "; if(matNr.isEmpty()) { cond = " AND "; } RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Material.MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.Material.TEXT + " LIKE '%" + makTx + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + cond + DbConstants.Material.NUMBER + " LIKE '%" + matNr + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.Material.TEXT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Material(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public Material selectMaterialByMatNo( String matnr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Material.MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.Material.NUMBER + " = '" + matnr + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Material result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Material(rs); } else { if (log.isDebugEnabled()) log.debug("multiple matnr/" + matnr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public MaterialPerson selectMaterialPersonByMatNo( String matnr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " //$NON-NLS-1$ + DbConstants.MaterialPerson.MATERIAL_PERSON + " WHERE " //$NON-NLS-1$ + DbConstants.MaterialPerson.NUMBER + " = '" + matnr + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); MaterialPerson result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new MaterialPerson(rs); } else { if (log.isDebugEnabled()) log.debug("multiple matnr/" + matnr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } @Nullable public ServerJob selectServerJob(String jobNumber) { ServerJob result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ServerJob.SERVER_JOB //$NON-NLS-1$ + DbConstants.Where.WHERE_TEXT + " " + DbConstants.ServerJob.JOB_NUMBER + " ='" + jobNumber + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ServerJob(rs); } else { log.warn(MessageFormat.format("multiple entries in table ServerJob for job number {0} found, jobNumber", new Object[] { jobNumber})); return null; } } finally { rs.dispose(); } return result; } public List selectServerJobList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ServerJob.SERVER_JOB //$NON-NLS-1$ + " ORDER BY " + DbConstants.ServerJob.MONTH_YEAR + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ServerJob(rs)); } } finally { rs.dispose(); } return result; } public List selectServerJobNotInJobList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ServerJob.SERVER_JOB + " c " //$NON-NLS-1$ //$NON-NLS-2$ + "WHERE NOT EXISTS (" //$NON-NLS-1$ + " SELECT * FROM " + DbConstants.Job.JOB + " j " //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + "c." + DbConstants.ServerJob.JOB_NUMBER + "=" + "j." + DbConstants.Job.JOB_NUMBER //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " AND " + "c." + DbConstants.ServerJob.JOB_TYPE + "=" + "j." + DbConstants.Job.JOB_TYPE //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " )" //$NON-NLS-1$ + " ORDER BY " + "c." + DbConstants.ServerJob.MONTH_YEAR + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ServerJob(rs)); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectJobMessageList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMessage.JOB_MESSAGE; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMessage(rs)); } } finally { rs.dispose(); } return result; } public List selectJobMessageListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobMessage.MESSAGE_ID; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMessage(rs)); } } finally { rs.dispose(); } return result; } public List selectReportMeasurementListByReport(Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + report.getGuId() + "'" // + " AND " + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ='" + report.getCommissionNumber() + "'" // + " AND " + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ='" + report.getPersonalNumber() + "'" + " ORDER BY " + DbConstants.ReportMeasurement.MEASURING_POINT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMeasurement(rs)); } } finally { rs.dispose(); } return result; } public List selectReportMeasurementListByMeasuringPoint(Report report, String measuringPoint) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + report.getGuId() + "'" // + " AND " + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ='" + report.getCommissionNumber() + "'" // + " AND " + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ='" + report.getPersonalNumber() + "'" + " AND " + DbConstants.ReportMeasurement.MEASURING_POINT + " ='" + measuringPoint + "'" + " ORDER BY ROWID"; //$NON-NLS-1$ // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMeasurement(rs)); } } finally { rs.dispose(); } return result; } public int selectNextMeasurementFromReportMeasurement(Report report, String measuringPoint) { RecordSet rs = db.getRecordSet(); String sql = "select MAX(CAST( " + DbConstants.ReportMeasurement.MEASUREMENT + " AS INT)) AS " + DbConstants.ReportMeasurement.MEASUREMENT + " FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + report.getGuId() + "'" + " AND " + DbConstants.ReportMeasurement.MEASURING_POINT + " ='" + measuringPoint + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); int result = 1; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = rs.getInt(DbConstants.ReportMeasurement.MEASUREMENT) + 1; } } finally { rs.dispose(); } return result; } public List selectVariousExpenses(Date date, int perNo) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VariousExpenses.VARIOUS_EXPENSES + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " =" + perNo + "" + " AND " + DbConstants.VariousExpenseFile.DATE + "='" + date.getTime() + "'" ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new VariousExpenses(rs)); } } finally { rs.dispose(); } return result; } public VariousExpenseFile selectVariousExpensesFile(Date date, int perNo, String id) { VariousExpenseFile result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " =" + perNo + "" + " AND " + DbConstants.VariousExpenseFile.DATE + "='" + date.getTime() + "'" + " AND " + DbConstants.VariousExpenseFile.IDX + "='" + id + "'" + " ORDER BY " + DbConstants.VariousExpenseFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new VariousExpenseFile(rs); } } finally { rs.dispose(); } return result; } public JobMessage selectJobMessageListByreportAndMsgId( Report report, String msgId) { JobMessage result = null; if( report != null && msgId != null) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobMessage.MESSAGE_ID + "='" + msgId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobMessage.MESSAGE_ID; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobMessage(rs); } } finally { rs.dispose(); } } return result; } public List selectReportJobFileListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectReportJobFileDocumentListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectReportJobFileImageListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" + " AND " + DbConstants.JobFile.TYPE + " ='I'" + " ORDER BY " + DbConstants.JobFile.IDX; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectFormImageListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" + " AND " + DbConstants.JobFile.TYPE + " ='G'" + " ORDER BY " + DbConstants.JobFile.IDX; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public JobFile selectFormImageByGuidAndFileName(String guid, String fileName) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'" + " AND " + DbConstants.JobFile.IDX + " ='" + fileName + "'" + " AND " + DbConstants.JobFile.TYPE + " ='G'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); JobFile result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobFile(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ rs.moveNext(); result = new JobFile(rs); } } finally { rs.dispose(); } return result; } public Map> selectDocumentListByReport( Report report) { Map> result = new HashMap>(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " ORDER BY " + DbConstants.JobFile.FORM_DESC; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { String formDesc = ""; while (rs.moveNext()) { JobFile jobFile = new JobFile(rs); if (!formDesc.isEmpty() && formDesc.equalsIgnoreCase(jobFile.getFormDesc())) { result.get(formDesc).add(jobFile); } else { formDesc = jobFile.getFormDesc(); List files = new ArrayList(); files.add(jobFile); result.put(formDesc, files); } } } finally { rs.dispose(); } return result; } public List selectDocumentFileListByReport( Report report, String formDesc) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " AND " + DbConstants.JobFile.SIGN_PIC_AT + " <>''" + " AND " + DbConstants.JobFile.FORM_DESC + " ='" + formDesc + "'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectDocumentFileNoFormListByReportAndDormDesc( Report report, String formDesc) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " AND " + DbConstants.JobFile.SIGN_PIC_AT + " =''" + " AND " + DbConstants.JobFile.FORM_DESC + " ='" + formDesc + "'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectAbsencesNotificationList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION + " WHERE " + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " =" + selectActiveUser().getPersonalNumber() + "" + " ORDER BY " + DbConstants.AbsenceNotification.DATE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { AbsenceNotification absenceNotification = new AbsenceNotification(rs); Calendar absencesDeleteExpiredDate = DateTimeUtil.getDate(absenceNotification.getAbsenceDate()); absencesDeleteExpiredDate.add(Calendar.DAY_OF_YEAR, CommonConstants.PERMISSION_REQUEST_CODE); if (DateTimeUtil.getToday().after(absencesDeleteExpiredDate)) { log.info("Absences older than " + CommonConstants.PERMISSION_REQUEST_CODE + " days -> delete."); deleteAbsenceNotification(absenceNotification); } else { result.add(absenceNotification); } } } finally { rs.dispose(); } return result; } public List
selectFormList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Form.FORM + " ORDER BY " + DbConstants.Form.ID; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { Form form = new Form(rs); result.add(form); } } finally { rs.dispose(); } return result; } public List selectValidFormList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); // Form Modernisierung Schiebet�re GDS status F valid from 28/02/2023 07:00 valid to 31/12/9999 07:00 // Form Testformular 1 status F valid from 21/09/2022 07:00 valid to 31/12/9999 07:00 Date date = new Date(); String sql = "SELECT * FROM " + DbConstants.Form.FORM + " WHERE " + DbConstants.Form.STATUS + " ='F'" + " AND '" + date.getTime() + "' >= " + DbConstants.Form.VALID_FROM + " AND '" + date.getTime() + "' <= " + DbConstants.Form.VALID_TO + " ORDER BY " + DbConstants.Form.ID; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { Form form = new Form(rs); result.add(form); } } finally { rs.dispose(); } return result; } public Form selectFormByIdAndVersion(String formId, int version) { Form result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Form.FORM + " WHERE " + DbConstants.Form.ID + " ='" + formId + "'" + " AND " + DbConstants.Form.VERSION + " =" + version; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); } else if (rs.getCount() == 1) { rs.moveNext(); result = new Form(rs); } else { log.error("multiple Form in table FORM found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectFormItemListByFormId(String formId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormItem.FORMITEM + " WHERE " + DbConstants.FormItem.FORM_ID + " ='" + formId + "'" + " ORDER BY " + DbConstants.FormItem.FORM_VERSION + ", " + DbConstants.FormItem.SEQUENCE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormItem formItem = new FormItem(rs); result.add(formItem); } } finally { rs.dispose(); } return result; } public List selectFormItemListByFormIdAndFormVersion(String formId, int formVersion) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormItem.FORMITEM + " WHERE " + DbConstants.FormItem.FORM_ID + " ='" + formId + "'" + " AND " + DbConstants.FormItem.FORM_VERSION + " =" + formVersion + " ORDER BY " + DbConstants.FormItem.FORM_VERSION + ", " + DbConstants.FormItem.SEQUENCE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormItem formItem = new FormItem(rs); result.add(formItem); } } finally { rs.dispose(); } return result; } public List selectDependencyListByFormIdFormVersionAndFormItemId(String formId, int formVersion, String formItemId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormDependency.FORMDEPENDENCY + " WHERE " + DbConstants.FormDependency.FORM_ID + " ='" + formId + "'" + " AND " + DbConstants.FormDependency.FORM_VERSION + " =" + formVersion + "" + " AND " + DbConstants.FormDependency.FORM_ITEM_ID + " ='" + formItemId + "'" + " ORDER BY " + DbConstants.FormDependency.FORM_VERSION; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormDependency dependency = new FormDependency(rs); result.add(dependency); log.info("FormDependency --> FormId :" + dependency.getFormId() + " FormVersion :" + dependency.getFormVersion() + " FormItemId :" + dependency.getFormItemId() + " Dependency :" + dependency.getDependency() + " CheckboxFormItemId :" + dependency.getCheckBoxFormItemId() + " ValueListId :" + dependency.getValueListId() + " ValueId :" + dependency.getValueId() ); } } finally { rs.dispose(); } return result; } public List selectValueListsByValueListId(String valueListId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormValueList.FORMVALUELIST + " WHERE " + DbConstants.FormValueList.VALUE_LIST_ID + " ='" + valueListId + "'" + " ORDER BY " + DbConstants.FormValueList.VALUE_LIST_ID; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormValueList formValueList = new FormValueList(rs); result.add(formValueList); } } finally { rs.dispose(); } return result; } public FormValueList selectFormValueListByValueListId(String valueListId, String ValueId) { FormValueList result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormValueList.FORMVALUELIST + " WHERE " + DbConstants.FormValueList.VALUE_LIST_ID + " ='" + valueListId + "'" + " AND " + DbConstants.FormValueList.VALUE_ID + " ='" + ValueId + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); } else if (rs.getCount() == 1) { rs.moveNext(); result = new FormValueList(rs); } else { log.error("multiple ValueList in table FORMVALUELIST found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public void getFormInstanceList(String guid) { List formInstances = selectFormInstanceListByGuid(guid); Map> formMap = new HashMap>(); for (FormInstance formInstance : formInstances) { if (formMap.containsKey(formInstance.getFormId())) { formMap.get(formInstance.getFormId()).add(formInstance); } else { List newList = new ArrayList(); newList.add(formInstance); formMap.put(formInstance.getFormId(), newList); } } } public List selectFormInstanceListByGuid(String guid) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'" + " ORDER BY " + DbConstants.FormInstance.FORM_VERSION; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormInstance formInstance = new FormInstance(rs); result.add(formInstance); } } finally { rs.dispose(); } return result; } public List selectFormInstanceListByGuidAndFormId(String guid, String formId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'" + " AND " + DbConstants.FormInstance.FORM_ID + " ='" + formId + "'" + " ORDER BY " + DbConstants.FormInstance.FORM_VERSION; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormInstance formInstance = new FormInstance(rs); result.add(formInstance); } } finally { rs.dispose(); } return result; } public FormInstance selectFormInstanceByGuidFormIdAndFormItemId(String guid, String formId, String formItemId) { FormInstance result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'" + " AND " + DbConstants.FormInstance.FORM_ID + " ='" + formId + "'" + " AND " + DbConstants.FormInstance.FORM_ITEM_ID + " ='" + formItemId + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); } else if (rs.getCount() == 1) { rs.moveNext(); result = new FormInstance(rs); } else { log.error("multiple Form in table FORMINSTANCE found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public int countUnsavedAddresses() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.CHANGE_FLAG + " ='X'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int countUnsavedReport() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.REPORT_STATUS + " = 0"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int countNotConfirmedSHortMSG() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.CONFIRM + " ='X'" //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.ShortMessage.STATUS + " != '3'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int cntJobs_InArbeit() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + DbConstants.Job.STATUS + " = '" + JobStatus.IN_PROGRESS + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } private Person selectActiveUser() { Person result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Person.PERSON; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Person(rs); } else { log.error("multiple users in table ZKDMOBMA found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectReportListByJobIdAndJobType(String kobId, String jobType) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.JOB_NUMBER + " ='" + kobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " ='" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.Report.IDX + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Report(rs)); } } finally { rs.dispose(); } return result; } /** * @param table * @param column * @param criteria * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private int selectMax( String table, String column, String criteria) { RecordSet rs = db.getRecordSet(); String sql = "SELECT MAX(" + column + ") FROM " + table; //$NON-NLS-1$ //$NON-NLS-2$ if (!"".equalsIgnoreCase(criteria)) { //$NON-NLS-1$ sql = sql + " " + criteria; //$NON-NLS-1$ } if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); int result = 0; try { rs.moveNext(); result = rs.getInt(0); } finally { rs.dispose(); } return result; } public JobReportTime selectJobReportTimeByGuid( String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " >= (" //$NON-NLS-1$ //$NON-NLS-2$ + " SELECT MAX(" + DbConstants.JobReportTime.IDX + ") FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "' )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } } finally { rs.dispose(); } return result; } public List selectJobReportTimeListByReport(Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReportTime(rs)); } } finally { rs.dispose(); } return result; } public JobReportTime selectPlayingJobReportTimeByReport(Report report) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.STOP_TIME + " = '0'" //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } } finally { rs.dispose(); } return result; } public List selectJobWithOpenTimesheet() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT j.* FROM " //$NON-NLS-1$ + DbConstants.Job.JOB + " j, " //$NON-NLS-1$ + DbConstants.JobReportTime.JOB_REPORT_TIME + " t " //$NON-NLS-1$ + " WHERE j." + DbConstants.Job.CURRENT_REPORT_GUID + " = t." + DbConstants.JobReportTime.GUID //$NON-NLS-1$ //$NON-NLS-2$ + " AND t." + DbConstants.JobReportTime.STOP_TIME + " = '" + DateUtils.getInitialDateTime().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } /** * @param guid * @param datum * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectJobReportTimeList(String guid, Date datum) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (!datum.equals(DateUtils.getInitialDateTime())) { sql += " AND " + DbConstants.JobReportTime.DATE + " = '" + datum.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } sql += " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReportTime(rs)); } } finally { rs.dispose(); } return result; } public Employee selectEmployeeByPerNr( int perNo) { Employee result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Employee.EMPLOYEE //$NON-NLS-1$ + " WHERE " + DbConstants.Employee.PERSONAL_NUMBER + " = " + perNo + ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Employee(rs); } else { log.error("multiple person in table ZKDSMOBMA found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectEmployeeList(String criteria) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Employee.EMPLOYEE; //$NON-NLS-1$ //$NON-NLS-2$ if (criteria.length() > 0) { sql += " AND " + DbConstants.Employee.LAST_NAME + " LIKE '" + criteria + "%'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } sql += " ORDER BY " + DbConstants.Employee.LAST_NAME; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Employee(rs)); } } finally { rs.dispose(); } return result; } public List selectEmployeeList(Person person, String criteria) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Employee.EMPLOYEE //$NON-NLS-1$ + " WHERE " + DbConstants.Employee.PERSONAL_NUMBER + " != " + person.getPersonalNumber(); //$NON-NLS-1$ //$NON-NLS-2$ if (criteria.length() > 0) { sql += " AND " + DbConstants.Employee.LAST_NAME + " LIKE '" + criteria + "%'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } sql += " ORDER BY " + DbConstants.Employee.LAST_NAME; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Employee(rs)); } } finally { rs.dispose(); } return result; } public List selectJobReportTimeListByDate(Date date) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.DATE + " = '" + date.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReportTime(rs)); } } finally { rs.dispose(); } return result; } public Drive selectDriveByText(String text) { Drive result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Drive.DRIVE //$NON-NLS-1$ + " WHERE " + DbConstants.Drive.TEXT + " = '" + text + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Drive(rs); } } finally { rs.dispose(); } return result; } public List selectDriveList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Drive.DRIVE; //$NON-NLS-1$; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Drive(rs)); } } finally { rs.dispose(); } return result; } public List selectOrderListByPerNo( int perNr) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Order.ORDER //$NON-NLS-1$ + " WHERE " + DbConstants.Order.PERSONAL_NUMBER + " = " + perNr //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.Order.CREATED_DATE + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Order(rs)); } } finally { rs.dispose(); } return result; } public List selectInvoiceList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Invoice.INVOICE; //$NON-NLS-1$; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Invoice(rs)); } } finally { rs.dispose(); } return result; } public List selectBillingTypeListByJobType(JobType jobType) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Billing.BILLING //$NON-NLS-1$ + " WHERE " + DbConstants.Billing.JOB_TYPE + " = '" + jobType.getCode() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " OR " + DbConstants.Billing.JOB_TYPE + " = ''" + " ORDER BY " + DbConstants.Billing.CODE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Billing(rs)); } } finally { rs.dispose(); } return result; } public Billing selectBillingTypeByJobTypeAndCode(JobType jobType, String code) { Billing result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Billing.BILLING //$NON-NLS-1$ + " WHERE " + DbConstants.Billing.JOB_TYPE + " = '" + jobType.getCode() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Billing.CODE + " = '" + code + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Billing(rs); } } finally { rs.dispose(); } return result; } public List selectCalendarDatesOlderThan(Date date) throws ApplicationException { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.CalendarTimeSheet.DATE + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " < '" + date.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.STATUS + " IN ('" + CalendarStatus.INITIAL + "', '" + CalendarStatus.SENT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { Date calDate = rs.getDate(DbConstants.CalendarTimeSheet.DATE); result.add(calDate); } } finally { rs.dispose(); } return result; } public CalendarTimeSheet loadCalendar(Date date, int pernr) { CalendarTimeSheet calendar = selectCalendarTimeSheet(date, pernr); calendar.setExpense(selectExpenses(date, pernr)); calendar.setTimeSheets(selectTimeSheetList(date, pernr)); return calendar; } public boolean saveCALENDAR(CalendarTimeSheet calendar) { if (calendar.getStatus().isINITIAL()) return insertCalendarTimeSheet(calendar); else return updateCalendarTimeSheet(calendar); } private CalendarTimeSheet selectCalendarTimeSheet(Date date, int pernr) throws ApplicationException { // Make sure that date is a date value and not a time value! // if(!DateTimeUtil.isDate(date)) { // throw new ApplicationException(Messages.getString("loadCALENDARObjectWithDatetime") + date + ")"); //$NON-NLS-1$ //$NON-NLS-2$ // } CalendarTimeSheet result = new CalendarTimeSheet(date, pernr); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " = '" + date.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.moveNext()) { result = new CalendarTimeSheet(rs); } } finally { rs.dispose(); } return result; } public List selectReasonList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Reason.REASON //$NON-NLS-1$ + " ORDER BY " + DbConstants.Reason.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Reason(rs)); } } finally { rs.dispose(); } return result; } public List selectJobDeleteReasonList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReturnReason.JOB_RETURN_REASON //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobReturnReason.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReturnReason(rs)); } } finally { rs.dispose(); } return result; } public List selectJobMonTextList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMonText.JOB_MON_TEXT //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobMonText.TEXT + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMonText(rs)); } } finally { rs.dispose(); } return result; } public List selectJobFormDescList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobFormDesc.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFormDesc(rs)); } } finally { rs.dispose(); } return result; } public JobFormDesc selectJobFormDescByFormDesc(String formDesc) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC //$NON-NLS-1$ + " WHERE " + DbConstants.JobFormDesc.CODE + " = '" + formDesc + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobFormDesc result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobFormDesc(rs); } else { log.warn(MessageFormat.format("multiple entries in table " + DbConstants.JobFormDesc.CODE + " for formDesc {0} found", new Object[] { formDesc})); return null; } } finally { rs.dispose(); } return result; } public List selectJobNoFormList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobNoForm.JOB_NO_FORM //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobNoForm.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobNoForm(rs)); } } finally { rs.dispose(); } return result; } public JobNoForm selectJobNoFormByNoForm(String noForm) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobNoForm.JOB_NO_FORM //$NON-NLS-1$ + " WHERE " + DbConstants.JobNoForm.CODE + " = '" + noForm + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobNoForm result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobNoForm(rs); } else { log.warn(MessageFormat.format("multiple entries in table " + DbConstants.JobNoForm.CODE + " for noForm {0} found", new Object[] { noForm})); return null; } } finally { rs.dispose(); } return result; } public List selectAbsenceTypeList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.AbsenceType.ABSENCE_TYPE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new AbsenceType(rs)); } } finally { rs.dispose(); } return result; } public List selectReceiptOfGoodsList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReceiptOfGoods(rs)); } } finally { rs.dispose(); } return result; } public AbsenceType selectAbsenceType(String code) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.AbsenceType.ABSENCE_TYPE + " WHERE " + DbConstants.AbsenceType.ABWGRND + " = '" + code + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); AbsenceType result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new AbsenceType(rs); } else { log.warn(MessageFormat.format("multiple entries in table " + DbConstants.AbsenceType.ABWGRND + " for noForm {0} found", new Object[] { code})); return null; } } finally { rs.dispose(); } return result; } private boolean insertCalendarTimeSheet(CalendarTimeSheet calendarTimeSheet) throws ApplicationException { // Make shure that date is a date value and not a time value! if(!DateTimeUtil.isDate(calendarTimeSheet.getDate())) { throw new ApplicationException(Messages.getString("saveCALENDARObjectWithDatetime") + calendarTimeSheet.getDate() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); try { DBSqlHelper sql = new DBSqlHelper(db); calendarTimeSheet.setStatus(CalendarStatus.SAVED); String sqlStmt = sql.INSERT(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET) .in(DbConstants.CalendarTimeSheet.DATE, calendarTimeSheet.getDate()) .in(DbConstants.CalendarTimeSheet.DATE_STRING, calendarTimeSheet.getDateString()) .in(DbConstants.CalendarTimeSheet.PERSONAL_NUMBER, calendarTimeSheet.getPersonalNumber()) .in(DbConstants.CalendarTimeSheet.STATUS, calendarTimeSheet.getStatus().getCode()) .toString(); int result = db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("Number of inserted records:'" + result + "' (SQL Statemant:/" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ insertReplaceExpenses(calendarTimeSheet.getExpense()); deleteAllTimeSheetByDate(calendarTimeSheet.getDate()); TreeSet timesheets = calendarTimeSheet.getTimeSheets(); Iterator itr = timesheets.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = itr.next(); insertTimeSheet(timeSheet); } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e); db.rollback(); } // termination with errors return false; } private boolean updateCalendarTimeSheet(CalendarTimeSheet calendar) { boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); DBSqlHelper sql = new DBSqlHelper(db); try { db.executeSql(sql.UPDATE(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET) .in(DbConstants.CalendarTimeSheet.DATE, calendar.getDate()) .in(DbConstants.CalendarTimeSheet.DATE_STRING, calendar.getDateString()) .in(DbConstants.CalendarTimeSheet.PERSONAL_NUMBER, calendar.getPersonalNumber()) .in(DbConstants.CalendarTimeSheet.STATUS, calendar.getStatus().getCode()) + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " = " + calendar.getDate().getTime()); //$NON-NLS-1$ //$NON-NLS-2$ Expenses expenses = calendar.getExpense(); insertReplaceExpenses(expenses); deleteAllTimeSheetByDate(calendar.getDate()); TreeSet timesheets = calendar.getTimeSheets(); Iterator itr = timesheets.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = itr.next(); insertTimeSheet(timeSheet); } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e); db.rollback(); } // termination with errors return false; } public boolean deleteCalendarTimeSheet(CalendarTimeSheet calendar) { boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); try { Expenses expenses = calendar.getExpense(); deleteExpenses(expenses); deleteAllTimeSheetByDate(calendar.getDate()); int cnt = db.executeSql("DELETE FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " = '" + calendar.getDate().getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.PERSONAL_NUMBER + " = '" + calendar.getPersonalNumber() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug(cnt + " CALENDAR Record(s) deleted for date " + calendar.getDateString() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e); db.rollback(); } // termination with errors return false; } /** * Finds the oldest open (status != sent) time sheet in the database. * @param pernr * @return The date of the oldest time sheet which has not been sent. Time * sheets younger than 3 days are are ignored. If no open time sheets * can be found, the current day (time: 00:00:00.000) is returned. */ public Date selectOldestUnsavedCalendarDate(int pernr) { Calendar today = DateTimeUtil.getToday(); // If no older CALENDAR can be found, return the current day Date result = today.getTime(); today.add(Calendar.DAY_OF_YEAR, -3); Date threeDaysAgo = today.getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.CalendarTimeSheet.DATE //$NON-NLS-1$ + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " < '" + threeDaysAgo.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.STATUS + " <> '" + CalendarStatus.SENT + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.CalendarTimeSheet.DATE + " ASC" //$NON-NLS-1$ //$NON-NLS-2$ ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() > 0) { rs.moveNext(); result = rs.getDate(DbConstants.CalendarTimeSheet.DATE); } } finally { rs.dispose(); } return result; } public int countUnsavedCalendar(int pernr) { int result = 0; Date yesterday = DateTimeUtil.getYesterday().getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT COUNT(*)" + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " < '" + yesterday.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.STATUS + " <> '" + CalendarStatus.SENT + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() > 0) { rs.moveNext(); result = rs.getInt(0); } } finally { rs.dispose(); } return result; } private Expenses selectExpenses(Date date, int perNo) { Expenses result = new Expenses(date, perNo); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.DATE + " = '" + date.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Expenses(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } private TreeSet selectTimeSheetList(Date date, int perNo) { TreeSet result = new TreeSet(); Date earlyMorning = DateTimeUtil.getDate(date).getTime(); Date lateNight = DateTimeUtil.getLateNight(date).getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + perNo + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new TimeSheet(rs)); } } finally { rs.dispose(); } return result; } public List selectVehicleInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { VehicleInventory inventoryStock = new VehicleInventory(rs); result.add(inventoryStock); } } finally { rs.dispose(); } return result; } public VehicleInventory selectVehicleInventoryByMatNr(String matNr) { VehicleInventory result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY + " WHERE " + DbConstants.VehicleInventory.MATERIAL_NUMBER + " = '" + matNr + "'" + " AND " + DbConstants.VehicleInventory.STORAGE_LOCATION + " = '" + getUser().getWarehouseNumber() + "'"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new VehicleInventory(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectVehicleInventoryListByMatNrAndMatName( String matNr, String makTx) { List result = new ArrayList(); int pos = 0; while ((pos = makTx.indexOf('\'', pos)) != -1) { makTx = makTx.substring(0, pos) + '\'' + makTx.substring(pos++); pos++; } String cond = " OR "; if(matNr.isEmpty()) { cond = " AND "; } RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY //$NON-NLS-1$ + " WHERE " + DbConstants.VehicleInventory.MATERIAL_NAME + " LIKE '%" + makTx + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + cond + DbConstants.VehicleInventory.MATERIAL_NUMBER + " LIKE '%" + matNr + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.VehicleInventory.MATERIAL_NAME; //$NON-NLS-1$ if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new VehicleInventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY // + " WHERE " + DbConstants.Inventory.PERSONAL_NUMBER + " = " + getUser().getPersonalNumber() ; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectNotExternalInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE + " <> '" + Warehouse.EXTERNAL + "'" + " AND " + DbConstants.Inventory.NAME + " <> ''"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectExternalInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE + " = '" + Warehouse.EXTERNAL + "'" + " AND " + DbConstants.Inventory.NAME + " <> ''"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectNotMainInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE + " <> '" + Warehouse.MAIN + "'" + " AND " + DbConstants.Inventory.NAME + " <> ''"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public Inventory selectInventoryByPersonalNrAndWarehouseNr() { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE_NUMBER + " = '" + getUser().getWarehouseNumber() + "'" + " AND " + DbConstants.Inventory.PERSONAL_NUMBER + " = " + getUser().getPersonalNumber() ; rs.setQuery(sql); log.info("sql /" + sql + "/"); Inventory result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Inventory(rs); } else { if (log.isDebugEnabled()) log.debug("multiple " + DbConstants.Inventory.PERSONAL_NUMBER +"/" + getUser().getPersonalNumber() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public DeliveryList selectArticleByMatnr(String orderNr, String matnr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.DeliveryList.DELIVERY_LIST + " WHERE " + DbConstants.DeliveryList.TO + " = '" + getUser().getWarehouseNumber() + "'" + " AND " + DbConstants.DeliveryList.ORDER_NUMBER + " = '" + orderNr + "'" + " AND " + DbConstants.DeliveryList.MATERIAL_NUMBER + " = '" + matnr + "'" + " AND " + DbConstants.DeliveryList.PERSONAL_NUMBER + " = " + getUser().getPersonalNumber() ; rs.setQuery(sql); log.info("sql /" + sql + "/"); DeliveryList result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new DeliveryList(rs); } else { if (log.isDebugEnabled()) log.debug("multiple " + DbConstants.DeliveryList.PERSONAL_NUMBER +"/" + getUser().getPersonalNumber() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public List selectArticleList(boolean isOpen) { //Open ZKDMOBFZGDELVRY.KNZDLVRY = O //Transit ZKDMOBFZGDELVRY.KNZDLVRY = T, G List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.DeliveryList.DELIVERY_LIST + " WHERE " + DbConstants.DeliveryList.TO + " = '" + getUser().getWarehouseNumber() + "'" + " AND (" + (isOpen ? DbConstants.DeliveryList.STATUS + " = 'O'" : (DbConstants.DeliveryList.STATUS + " = 'T'" + " OR " + DbConstants.DeliveryList.STATUS + " = 'G'")) + ") ORDER BY " + DbConstants.DeliveryList.DATE + " DESC, " + DbConstants.DeliveryList.MATERIAL_NAME; // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { DeliveryList article = new DeliveryList(rs); result.add(article); } } finally { rs.dispose(); } return result; } public List selectOutgoingArticleList() { //Receipt ZKDMOBFZGDELVRY.LGORT_TO = ZKDMOBMA.LGORT from user (ZKDMOBA.PERNR = active user) //isBooked ZKDMOBFZGDELVRY.LGORT_FROM = ZKDMOBMA.LGORT from user (ZKDMOBA.PERNR = active user) List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.DeliveryList.DELIVERY_LIST + " WHERE " + DbConstants.DeliveryList.FROM + " = '" + getUser().getWarehouseNumber() + "'" + " ORDER BY " + DbConstants.DeliveryList.DATE + " DESC, " + DbConstants.DeliveryList.MATERIAL_NAME; // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { DeliveryList article = new DeliveryList(rs); result.add(article); } } finally { rs.dispose(); } return result; } public MaterialMovement selectMaterialMovement(String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT //$NON-NLS-1$ + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + guid + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); MaterialMovement result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new MaterialMovement(rs); } else { if (log.isDebugEnabled()) log.debug("multiple guid/" + guid + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public MaterialMovement selectMaterialMovement( String guid, int pernr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT //$NON-NLS-1$ + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + guid + "'" + (pernr == -1? "" : " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " = " + pernr); if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); MaterialMovement result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new MaterialMovement(rs); } else { if (log.isDebugEnabled()) log.debug("multiple guid/" + guid + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public void deleteNewUser(int newUserPernr) { db.executeSql("DELETE FROM " + DbConstants.Person.PERSON //$NON-NLS-1$ + " WHERE " + DbConstants.Person.PERSONAL_NUMBER + " = " + newUserPernr); //$NON-NLS-1$ //$NON-NLS-2$ } public void deleteOldUser(Person oldUser) { deleteOldUser(oldUser.getPersonalNumber()); } public void deleteOldUser(int oldPernr) { mUser = null; // trigger reload of user on next request db.executeSql("DELETE FROM " + DbConstants.Person.PERSON //$NON-NLS-1$ + " WHERE " + DbConstants.Person.PERSONAL_NUMBER + " = " //$NON-NLS-1$ //$NON-NLS-2$ + oldPernr); } public void deleteAllJob() { db.executeSql("DELETE FROM " + DbConstants.Job.JOB); //$NON-NLS-1$ } public void deleteAllAddress() { db.executeSql("DELETE FROM " + DbConstants.Address.ADDRESS); //$NON-NLS-1$ } public void deleteAllEmail() { db.executeSql("DELETE FROM " + DbConstants.Email.EMAIL); //$NON-NLS-1$ } public void deleteAllHistory() { db.executeSql("DELETE FROM " + DbConstants.History.HISTORY); //$NON-NLS-1$ } public void deleteAllReport() { db.executeSql("DELETE FROM " + DbConstants.Report.REPORT); //$NON-NLS-1$ } public void deleteAllJobMessage() { db.executeSql("DELETE FROM " + DbConstants.JobMessage.JOB_MESSAGE); //$NON-NLS-1$ } public void deleteAllReportMaterial() { db.executeSql("DELETE FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL); //$NON-NLS-1$ } public void deleteAllJobReportTime() { db.executeSql("DELETE FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME); //$NON-NLS-1$ } public void deleteAllTimeSheet() { db.executeSql("DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET); //$NON-NLS-1$ } private void deleteAllTimeSheetByDate(Date date) { Date earlyMorning = DateTimeUtil.getDate(date).getTime(); Date lateNight = DateTimeUtil.getLateNight(date).getTime(); int cnt = db.executeSql("DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("Number of deleted ZKDMATIME Records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } public void deleteAllExpenses() { db.executeSql("DELETE FROM " + DbConstants.Expenses.EXPENSES); //$NON-NLS-1$ } public void deleteAllOrderMaterial() { db.executeSql("DELETE FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL); //$NON-NLS-1$ } public void deleteAllOrder() { db.executeSql("DELETE FROM " + DbConstants.Order.ORDER); //$NON-NLS-1$ } public void deleteAllShortMessage() { db.executeSql("DELETE FROM " + DbConstants.ShortMessage.SHORT_MESSAGE); //$NON-NLS-1$ } public void deleteAllWorkTypeT() { db.executeSql("DELETE FROM " + DbConstants.WorkType.WORK_TYPE); //$NON-NLS-1$ } public void deleteAllErrorCode() { db.executeSql("DELETE FROM " + DbConstants.ErrorCode.ERROR_CODE); //$NON-NLS-1$ } public void deleteAllMaterial() { db.executeSql("DELETE FROM " + DbConstants.Material.MATERIAL); //$NON-NLS-1$ } public void deleteAllEmployee() { db.executeSql("DELETE FROM " + DbConstants.Employee.EMPLOYEE); //$NON-NLS-1$ } public void deleteAllMaterialOfPerson() { db.executeSql("DELETE FROM " //$NON-NLS-1$ + DbConstants.MaterialPerson.MATERIAL_PERSON); } public void deleteAllPerson() { db.executeSql("DELETE FROM " + DbConstants.Person.PERSON); //$NON-NLS-1$ } public void deleteAllServerJob() { db.executeSql("DELETE FROM " + DbConstants.ServerJob.SERVER_JOB); //$NON-NLS-1$ } public void deleteAllJobFile() { db.executeSql("DELETE FROM " + DbConstants.JobFile.JOB_FILE); //$NON-NLS-1$ } public void deleteAllReason() { db.executeSql("DELETE FROM " + DbConstants.Reason.REASON); //$NON-NLS-1$ } public void deleteAllJobReason() { db.executeSql("DELETE FROM " + DbConstants.JobReturnReason.JOB_RETURN_REASON); //$NON-NLS-1$ } public void deleteAllJobMonText() { db.executeSql("DELETE FROM " + DbConstants.JobMonText.JOB_MON_TEXT); //$NON-NLS-1$ } public void deleteAllIncident() { db.executeSql("DELETE FROM " + DbConstants.Incident.INCIDENT); //$NON-NLS-1$ } public void deleteAllJobFormDesc() { db.executeSql("DELETE FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC); //$NON-NLS-1$ } public void deleteAllJobNoForm() { db.executeSql("DELETE FROM " + DbConstants.JobNoForm.JOB_NO_FORM); //$NON-NLS-1$ } public void deleteAllReportMessage() { db.executeSql("DELETE FROM " + DbConstants.ReportMessage.REPORT_MESSAGE); //$NON-NLS-1$ } public void deleteAllDrive() { db.executeSql("DELETE FROM " + DbConstants.Drive.DRIVE); //$NON-NLS-1$ } public void deleteAllBilling() { db.executeSql("DELETE FROM " + DbConstants.Billing.BILLING); //$NON-NLS-1$ } public void deleteAllInvoice() { db.executeSql("DELETE FROM " + DbConstants.Invoice.INVOICE); //$NON-NLS-1$ } public void deleteAllInternalWorkType() { db.executeSql("DELETE FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE); //$NON-NLS-1$ } public void deleteAllAbsenceType() { db.executeSql("DELETE FROM " + DbConstants.AbsenceType.ABSENCE_TYPE); //$NON-NLS-1$ } public void deleteAllServiceRefused() { db.executeSql("DELETE FROM " + DbConstants.ServiceRefused.SERVICE_REFUSED); //$NON-NLS-1$ } public void deleteAllChecklist() { db.executeSql("DELETE FROM " + DbConstants.Checklist.CHECK_LIST); //$NON-NLS-1$ } public void deleteAllProgress() { db.executeSql("DELETE FROM " + DbConstants.Progress.PROGRESS); //$NON-NLS-1$ } public void deleteFormMetadata() { FORM.delete(db); FORMITEM.delete(db); FORMDEPENDENCY.delete(db); FORMVALUELIST.delete(db); } public void deleteAllStateOfInstallation() { db.executeSql("DELETE FROM " + DbConstants.StateOfInstallation.STATE_OF_INSTALLATION); //$NON-NLS-1$ } public void deleteAllNextIntervention() { db.executeSql("DELETE FROM " + DbConstants.NextIntervention.NEXT_INVENTION); //$NON-NLS-1$ } public void deleteAllInventoryStock() { db.executeSql("DELETE FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY); //$NON-NLS-1$ } public void deleteAllInventory() { db.executeSql("DELETE FROM " + DbConstants.Inventory.INVENTORY); //$NON-NLS-1$ } public void deleteAllReceiptOfGoods() { db.executeSql("DELETE FROM " + DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS); //$NON-NLS-1$ } public void deleteAllDeliveryList() { db.executeSql("DELETE FROM " + DbConstants.DeliveryList.DELIVERY_LIST); //$NON-NLS-1$ } public void deleteAllFormInstance() { db.executeSql("DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE); //$NON-NLS-1$ } public int deleteFormInstancesWithoutReport() { String sqlStmt = "DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE //$NON-NLS-1$ + " WHERE NOT EXISTS (" //$NON-NLS-1$ + "SELECT 1 FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.REPORT + "." + DbConstants.Report.GUID //$NON-NLS-1$ + " = " + DbConstants.FormInstance.FORMINSTANCE + "." + DbConstants.FormInstance.GUID //$NON-NLS-1$ + ")"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } /** * L�scht den ganzen Auftrag inkl. aller dazugeh�rigen Datens�tzen aus der Datenbank. * @param app * @param job */ public boolean deleteJob( Job job) { boolean pendingTransactionUsed = startTransaction(db); try{ String sqlStmt = "DELETE FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + "MLDNR = '" + job.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + "AUART = '" + job.getJobType() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ int cnt = db.executeSql(sqlStmt); if (log.isInfoEnabled()) { log.info("Number of deleted ZKDMOB Records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } // address // cnt = deleteZKDMOBADRByMLDNRAndAUART(job.getMLDNR_OrderNumber(), job.getAUART().getCode()); // history deleteHistoryByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); List reportList = selectReportListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); // report time without existing report deleteJobReportTimeByGUID(job.getCurrentReportGuId(this)); for (int i = 0; i < reportList.size(); i++) { Report report = (Report) reportList.get(i); // report msg deleteJobMessage(report.getGuId()); // report time deleteJobReportTimeByGUID(report.getGuId()); // report parts deleteReportMaterialByGUID(report.getGuId()); // report files deleteReportFileByGUID(report.getGuId()); // form instance deleteReportFormInstanceByGUID(report.getGuId()); // report deleteReport(report); } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e.getMessage()); if (!pendingTransactionUsed) db.rollback(); else throw e; } return false; } public boolean deleteCompleteReport(Report report) { boolean pendingTransactionUsed = startTransaction(db); try{ // report time without existing report deleteJobReportTimeByGUID(report.getGuId()); // report deleteReport(report); // report parts deleteReportMaterialByGUID(report.getGuId()); // report msg deleteJobMessage(report.getGuId()); // delete images deleteReportImage(report.getGuId()); // delete documents deleteReportDocument(report.getGuId()); // delete Measurements deleteReportMeasurement(report.getGuId()); // delete form instance deleteReportFormInstanceByGUID(report.getGuId()); // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e.getMessage()); if (!pendingTransactionUsed) db.rollback(); else throw e; } return false; } /** * @param expenses */ private void deleteExpenses( Expenses expenses) { String sql = "DELETE FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.PERSONAL_NUMBER + " = '" + expenses.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Expenses.DATE + " = '" + expenses.getDate().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ int cnt = db.executeSql(sql); if (log.isDebugEnabled()) log.debug("Number of deleted ZKDMATIME Records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } private int deleteHistoryByJobIdAndJobType( String jobId, String jobType) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.History.HISTORY //$NON-NLS-1$ + " WHERE " + DbConstants.History.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.History.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ; return executeDataManipulationStmt(sqlStmt); } private int deleteJobReportTimeByGUID( String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } public void deleteMaterialPerson(MaterialPerson materialPerson) { db.executeSql("DELETE FROM " + DbConstants.MaterialPerson.MATERIAL_PERSON //$NON-NLS-1$ + " WHERE " + DbConstants.MaterialPerson.NUMBER + " = '" + materialPerson.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.MaterialPerson.TEXT + " = '" + materialPerson.getMaterialShortText() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private int deleteJobMessage(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportImage(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " <>'F'"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportDocument(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportMeasurement(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + guid + "'"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } public int deleteFormInstanceByGuidAndFormId( String guid, String formid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " = '" + guid + "'" + " AND " + DbConstants.FormInstance.FORM_ID + " = '" + formid + "'" ; return executeDataManipulationStmt(sqlStmt); } /** * @param part * @deprecated */ @Deprecated @SuppressWarnings("unused") private void deleteMaterial(Material part) { db.executeSql("DELETE FROM " + DbConstants.Material.MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.Material.NUMBER + " = '" + part.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Material.TEXT + " = '" + part.getMaterialShortText() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void deleteReportMaterial(ReportMaterial reportMaterial) { db.executeSql("DELETE FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + reportMaterial.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = " + reportMaterial.getIdx()); //$NON-NLS-1$ //$NON-NLS-2$ } private int deleteReportMaterialByGUID(String guid) { String sqlStmt = "DELETE FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportFileByGUID(String guid) { String sqlStmt = "DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportFormInstanceByGUID(String guid) { String sqlStmt = "DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE //$NON-NLS-1$ + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } /** * @param jobid * @param jobType * @deprecated */ @Deprecated @SuppressWarnings("unused") private void deleteReportByJobidAndJobType( String jobid, String jobType) { db.executeSql("DELETE FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.JOB_NUMBER + " = '" + jobid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " = '" + jobType + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private int deleteReport(Report report) { String sqlStmt = "DELETE FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.JOB_NUMBER + " = '" + report.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " = '" + report.getJobType() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.GUID + " = '" + report.getGuId() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } public void deleteReportByGUID(String guid) { db.executeSql("DELETE FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.GUID + " = '" + guid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * @param timeSheets * @deprecated */ @Deprecated @SuppressWarnings("unused") private void deleteTimeSheetList(List timeSheets) { for (int i = 0; i < timeSheets.size(); i++) { deleteTimeSheet((TimeSheet) timeSheets.get(i)); } } private void deleteTimeSheet(TimeSheet timeSheet) { db.executeSql("DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = '" + timeSheet.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.IDX + " = '" + timeSheet.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.DATE + " = '" + timeSheet.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void deleteOrder(Order order) { db.executeSql("DELETE FROM " + DbConstants.Order.ORDER //$NON-NLS-1$ + " WHERE " + DbConstants.Order.IDX + " = " + order.getIdx() + "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } public void deleteOrderMaterial(OrderMaterial orderMaterial) { String sql = "DELETE FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.OrderMaterial.PERSONAL_NUMBER + " = " + orderMaterial.getPersonalNumber() + "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.NUMBER + " ='" + orderMaterial.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.DATE + " ='" + orderMaterial.getDate().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ db.executeSql(sql); } public void deleteShortMessage(ShortMessage shortMessage) { db.executeSql("DELETE FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " ='" + shortMessage.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ShortMessage.MESSAGE_KEY + " ='" + shortMessage.getMessageKey() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void deleteJobFile(JobFile jobFile) { db.executeSql("DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.IDX + " ='" + jobFile.getJobFileId() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // remove image data from memory after delete (lazy load; MIG-988) jobFile.setSignPicAt(null); } public void deleteReportMeasurement(ReportMeasurement reportMeasurement) { String sql = "DELETE FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + reportMeasurement.getGuId() + "'" + " AND " + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ='" + reportMeasurement.getCommissionNumber() + "'" + " AND " + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ='" + reportMeasurement.getPersonalNumber() + "'" + " AND " + DbConstants.ReportMeasurement.MEASURING_POINT + " ='" + reportMeasurement.getMeasurementPoint() + "'" + " AND " + DbConstants.ReportMeasurement.MEASUREMENT + " ='" + reportMeasurement.getMeasurement() + "'"; db.executeSql(sql ); log.info(sql); } public void deleteVariousExpense(VariousExpenses variousExpenses) { String sql = "DELETE FROM " + DbConstants.VariousExpenses.VARIOUS_EXPENSES + " WHERE " + DbConstants.VariousExpenses.PERSONAL_NUMBER + " ='" + variousExpenses.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenses.DATE + " ='" + variousExpenses.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenses.IDX + " ='" + variousExpenses.getVariousExpensesId() + "'"; db.executeSql(sql ); log.info(sql); } public void deleteVariousExpenseFile(VariousExpenseFile variousExpenseFile) { String sql = "DELETE FROM " + DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " ='" + variousExpenseFile.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenseFile.DATE + " ='" + variousExpenseFile.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenseFile.IDX + " ='" + variousExpenseFile.getVariousExpensesFileId() + "'"; db.executeSql(sql ); log.info(sql); } public void deleteAbsenceNotification(AbsenceNotification absenceNotification) { db.executeSql("DELETE FROM " + DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION + " WHERE " + DbConstants.AbsenceNotification.GUID + " ='" + absenceNotification.getGuId() + "'" + " AND " + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " ='" + absenceNotification.getPersonalNumber() + "'" + " AND " + DbConstants.AbsenceNotification.DATE + " = '" + absenceNotification.getAbsenceDate().getTime() + "'"); } public void deleteMaterialMovement(MaterialMovement materialMovement) { db.executeSql("DELETE FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT + " WHERE " + DbConstants.MaterialMovement.GUID + " ='" + materialMovement.getGuid() + "'" + " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " ='" + materialMovement.getPersonalNumber() + "'"); } public void updateReport(Report report) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.Report.REPORT) .in(DbConstants.Report.COMMISSION_NUMBER, report.getCommissionNumber()) .in(DbConstants.Report.CHECK_LIST, report.getChecklist()) .in(DbConstants.Report.ORDER_NUMBER, report.getOrderNumber()) .in(DbConstants.Report.FINAL_REPAIR, report.getFinalRepair()) .in(DbConstants.Report.CREATE_DATE, report.getCreateDate()) .in(DbConstants.Report.ERROR_FLAG_1, report.getErrorFlag1()) .in(DbConstants.Report.ERROR_FLAG_2, report.getErrorFlag2()) .in(DbConstants.Report.ERROR_FLAG_3, report.getErrorFlag3()) .in(DbConstants.Report.SYSTEM_ERROR, report.getSystemError()) .in(DbConstants.Report.ERROR_ID_1, report.getErrorId1()) .in(DbConstants.Report.ERROR_ID_2, report.getErrorId2()) .in(DbConstants.Report.ERROR_ID_3, report.getErrorId3()) .in(DbConstants.Report.ERROR_H_1, report.getErrorH1()) .in(DbConstants.Report.ERROR_H_2, report.getErrorH2()) .in(DbConstants.Report.ERROR_H_3, report.getErrorH3()) .in(DbConstants.Report.REASONING, report.getReasoning()) .in(DbConstants.Report.DISTANCE, report.getDistance()) .in(DbConstants.Report.PERSONAL_NUMBER, report.getPersonalNumber()) .in(DbConstants.Report.SIGNATURE_GUID,report.getSignatureGuId()) .in(DbConstants.Report.CUSTOMER_SUPPORT, report.getCustomerSupport()) .in(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT,report.getCustomerSupportText()) .in(DbConstants.Report.REPORT_STATUS,report.getReportStatus().getCode()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_1, report.getServicePlanMonth1()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_2, report.getServicePlanMonth2()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_3, report.getServicePlanMonth3()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_4, report.getServicePlanMonth4()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_5, report.getServicePlanMonth5()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_6, report.getServicePlanMonth6()) .in(DbConstants.Report.MONTH_YEAR, report.getMonthYear()) .in(DbConstants.Report.SAFETY_REPORT, report.getSafetyReport()) .in(DbConstants.Report.SIGNATURE_FLAG, report.getSignatureFlag()) .in(DbConstants.Report.SIGNATURE_INFO, report.getSignatureInfo()) .in(DbConstants.Report.SIGNATURE, report.getSignature()) .in(DbConstants.Report.EXPENSES, report.getExpenses()) .in(DbConstants.Report.INCIDENT_AB, report.getIncidentAB()) .in(DbConstants.Report.PARTICAL_REPAIR, report.getPartialRepair()) .in(DbConstants.Report.BILLING, report.getBilling()) .in(DbConstants.Report.WORK_TYPE, report.getWorkType()) .in(DbConstants.Report.NO_MATERIAL, report.getNoMaterial()) .in(DbConstants.Report.CYCLE_OF_INSTALLATION, report.getCycleOfInstallation()) .in(DbConstants.Report.NO_FORM1, report.getNoForm1()) .in(DbConstants.Report.NO_FORM2, report.getNoForm2()) .in(DbConstants.Report.NO_FORM3, report.getNoForm3()) .in(DbConstants.Report.SERVICE_REFUSED, report.getServiceRefused()) .in(DbConstants.Report.OPEN_PENDING, report.getOpenPending()) .in(DbConstants.Report.GOVERNMENT_REPORT, report.getGovernmentReport()) .in(DbConstants.Report.CHECKLIST_STATE, report.getChecklistState()) .in(DbConstants.Report.CHECKLIST_SIA, report.getChecklistSIA()) .in(DbConstants.Report.CHECKLIST_READY, report.getChecklistReady()) .in(DbConstants.Report.CHECKLIST_INSTRUCTION, report.getChecklistInstruction()) .in(DbConstants.Report.CHECKLIST_VKF, report.getChecklistVKF()) .in(DbConstants.Report.CHECKLIST_TEST, report.getChecklistTest()) .in(DbConstants.Report.SIGNATURE_NAME, report.getSignatureName()) .in(DbConstants.Report.MON_STK, report.getMonStk()) + " WHERE " + DbConstants.Report.IDX + " = " + report.getIdx() + "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_NUMBER + " = '" + report.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " = '" + report.getJobType() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.GUID + " = '" + report.getGuId() + "'"; db.executeSql(sqlStmt); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isInfoEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } public void updateJobMessage(JobMessage jobMessage) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobMessage.JOB_MESSAGE) .in(DbConstants.JobMessage.MESSAGE_CODE, jobMessage.getMessageCode()) .in(DbConstants.JobMessage.TEXT_1, jobMessage.getMessageCodeText()) .in(DbConstants.JobMessage.TEXT_2, jobMessage.geText()) .in(DbConstants.JobMessage.MoreText, jobMessage.getMoreText()) + " WHERE " + DbConstants.JobMessage.GUID + " = '" + jobMessage.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobMessage.MESSAGE_ID + " = '" + jobMessage.getMessageId() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void updateJobFile(JobFile jobFile) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobFile.JOB_FILE) .in(DbConstants.JobFile.IDX, jobFile.getJobFileId()) .in(DbConstants.JobFile.GUID, jobFile.getGuid()) .in(DbConstants.JobFile.JOB_NUMBER, jobFile.getJobNumber()) .in(DbConstants.JobFile.JOB_TYPE, jobFile.getJobType().getCode()) .in(DbConstants.JobFile.TYPE, jobFile.getType()) .in(DbConstants.JobFile.DESCRIPTION, jobFile.getDescription()) .in(DbConstants.JobFile.SIGN_PIC_AT, jobFile.getSignpicAt()) .in(DbConstants.JobFile.FORM_TYPE, jobFile.getFormType().getCode()) .in(DbConstants.JobFile.FORM_DESC, jobFile.getFormDesc()) .in(DbConstants.JobFile.SENT_DATE, jobFile.getSentDate()) + " WHERE " + DbConstants.JobFile.GUID + " = '" + jobFile.getGuid() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.IDX + " = '" + jobFile.getJobFileId() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // remove image data from memory after update (lazy load; MIG-988) jobFile.setSignPicAt(null); } private String getSqlUpdateJob(Job job) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = (sql.UPDATE(DbConstants.Job.JOB) .in(DbConstants.Job.CURRENT_REPORT_GUID,job.getCurrentReportGuId(this)) .in(DbConstants.Job.PERSONAL_NUMBER,job.getPersonalNumber()) .in(DbConstants.Job.STATUS,job.getStatus().getCode()) .in(DbConstants.Job.PRIORITY,job.getPriority()) .in(DbConstants.Job.JOB_FORWARD,job.getJobForward()) .in(DbConstants.Job.COMMISSION_NUMBER,job.getCommissionNumber()) .in(DbConstants.Job.STAFF_NAME, job.getStaffName()) .in(DbConstants.Job.STAFF_PHONE, job.getStaffPhoneNumber()) .in(DbConstants.Job.APPOINTMENT_DATE, job.getAppointmentDate()) .in(DbConstants.Job.ACTIVE_DATE, job.getActiveJobDate()) .in(DbConstants.Job.JOB_RESCHEDULE_DATE, job.getJobRescheduleDate()) .in(DbConstants.Job.JOB_RESCHEDULE_TIME, job.getJobRescheduleTime()) .in(DbConstants.Job.WEEK, job.getWeek()) .in(DbConstants.Job.FIX, job.getFix()) .in(DbConstants.Job.APPOINTMENT, job.getAppointment()) .in(DbConstants.Job.ORDER_NUMBER, job.getOrderNumber()) .in(DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID, job.getPartnerOfInstallAddressId()) .in(DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID, job.getKdnServiceAddressId()) .in(DbConstants.Job.CUSTOMER_ADDRESS_ID, job.getCustomerAddressId()) .in(DbConstants.Job.PARTNER_ADDRESS_ID, job.getPartnerAddressId()) .in(DbConstants.Job.OBJECT_ADDRESS_ID, job.getObjectAddressId()) .in(DbConstants.Job.OWNER_ADDRESS_ID, job.getOwnerAddressId()) .in(DbConstants.Job.NEW_JOB_DATE, job.getNewJobDate()) .in(DbConstants.Job.ERROR_ID, job.getErrorId()) .in(DbConstants.Job.CALL_SERVICE_FLAG, job.getCallServiceFlag()) .in(DbConstants.Job.MAINTENANCE_CONTRACT_TYPE, job.getMaintenanceContractType()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_1, job.getServicePlanMonth1()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_2, job.getServicePlanMonth2()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_3, job.getServicePlanMonth3()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_4, job.getServicePlanMonth4()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_5, job.getServicePlanMonth5()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_6, job.getServicePlanMonth6()) .in(DbConstants.Job.SERVICE_OPEN, job.getServiceOpen()) .in(DbConstants.Job.CONTACT_NAME, job.getContactName()) .in(DbConstants.Job.CONTACT_PHONE, job.getContactPhoneNumber()) .in(DbConstants.Job.TECHNICAL_NAME, job.getTechnicalName()) .in(DbConstants.Job.TECHNICAL_PHONE, job.getTechnicalPhoneNumber()) .in(DbConstants.Job.SELLER_NAME, job.getSellerName()) .in(DbConstants.Job.SELLER_PHONE, job.getSellerPhoneNumber()) .in(DbConstants.Job.STATUS_EDIT, job.getStatusEdit()) .in(DbConstants.Job.DRIVER_TYPE, job.getDriveType()) .in(DbConstants.Job.DRIVER_TYPE_UPD, job.isDriveTypeUpdated() ? "X" : "") //$NON-NLS-1$ //$NON-NLS-2$ .in(DbConstants.Job.DEFAULT_TIME, job.getDefaultTime()) .in(DbConstants.Job.DESCRIPTION, job.getInformation()) .in(DbConstants.Job.INFORMATION, job.getDescription()) .in(DbConstants.Job.CYCLE_OF_INSTALLATIN_FLAG, job.getCycleOfInstallationFlag()) .in(DbConstants.Job.FORM_DESC_1, job.getFormDesc1()) .in(DbConstants.Job.FORM_DESC_2, job.getFormDesc2()) .in(DbConstants.Job.FORM_DESC_3, job.getFormDesc3()) .in(DbConstants.Job.SERVICE_REFUSED_FLAG, job.getServiceRefusedFlag()) .in(DbConstants.Job.LINK, job.getLink()) .in(DbConstants.Job.GUARANTEE, job.getGuarantee()) .in(DbConstants.Job.MORE_INFORMARION_FLAG, job.getMoreInformationsFlag()) + " WHERE " + DbConstants.Job.JOB_NUMBER + " = '" + job.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Job.JOB_TYPE + " = '" + job.getJobType() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info("sql /" + sqlStmt + "/"); return sqlStmt; } /** * Updates the job, addresses and reports with the new KomNr * @param job The job, where the KomNr needs to be updated * @param comNo The new KomNr */ public void updateJobByComNo(Job job, String comNo) { if (!job.getCommissionNumber().equalsIgnoreCase(comNo)) { job.setCommissionNumber(comNo); updateJob(job); updateAddressComNo(job.getJobNumber(), job.getJobType().getCode(), comNo); if (!job.getCurrentReport().getReportStatus().isInitial()) { job.getCurrentReport().setCommissionNumber(comNo); updateReport(job.getCurrentReport()); } updateReportMaterialComNo(job.getCurrentReportGuId(this), comNo); } } public void updateJob(Job job) { Iterator
itr = job.getAddresses().values().iterator(); while (itr.hasNext()) { Address address = itr.next(); updateAddress(address); } db.executeSql(getSqlUpdateJob(job)); } public int updateAddress(Address address) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = (sql.UPDATE(DbConstants.Address.ADDRESS) .in(DbConstants.Address.JOB_TYPE, address.getJobType().getCode()) .in(DbConstants.Address.CITY, address.getCity()) .in(DbConstants.Address.TYPE, address.getType()) .in(DbConstants.Address.EMAIL, address.getEmail()) .in(DbConstants.Address.FAX, address.getFaxNumber()) .in(DbConstants.Address.CUSTOMER_NUMBER, address.getCustomerNumber()) .in(DbConstants.Address.JOB_NUMBER, address.getJobNumber()) .in(DbConstants.Address.NAME1, address.getName1()) .in(DbConstants.Address.NAME2, address.getName2()) .in(DbConstants.Address.NAME3, address.getName3()) .in(DbConstants.Address.LOCATION, address.getLocation()) .in(DbConstants.Address.PARTNER_NUMBER, address.getPartnerNummer()) .in(DbConstants.Address.PASTAL_CODE, address.getPostalCode()) .in(DbConstants.Address.STREET, address.getStreet()) .in(DbConstants.Address.PHONE_1, address.getTelNumber1()) .in(DbConstants.Address.PHONE_2, address.getTelNumber2()) .in(DbConstants.Address.TITLE, address.getTitle()) .in(DbConstants.Address.CHANGE_FLAG, address.getChangeFlag()) .in(DbConstants.Address.COMMISSION_NUMBER, address.getCommissionNumber()) .in(DbConstants.Address.DIRTY_FLAG, address.getDirtyFlag()) + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + address.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + address.getJobType() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.PARTNER_NUMBER + " = '" + address.getPartnerNummer() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isInfoEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ int cnt = db.executeSql(sqlStmt); if (log.isInfoEnabled()) log.info("Number of affected records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ return cnt; } public void updateAddressComNo(String jobId, String jobType, String newComNo) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Address.ADDRESS) .in(DbConstants.Address.COMMISSION_NUMBER, newComNo) + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } /** * @param timeSheet * @param newIdx * @deprecated */ @Deprecated @SuppressWarnings("unused") private void updateTimeSheetIdx(TimeSheet timeSheet, int newIdx) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.TimeSheet.TIME_SHEET) .in(DbConstants.TimeSheet.IDX, newIdx) + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = " + timeSheet.getPersonalNumber() //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.TimeSheet.IDX + " = '" + timeSheet.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.DATE + " ='" + timeSheet.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * @param jobReportTime * @param newIdx * @deprecated */ @Deprecated @SuppressWarnings("unused") private void updateJobReportTimeIdx( JobReportTime jobReportTime, int newIdx) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobReportTime.JOB_REPORT_TIME) .in(DbConstants.JobReportTime.IDX, newIdx) + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + jobReportTime.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " = '" + jobReportTime.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.DATE + " = '" + jobReportTime.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * @param jobReportTime * @deprecated */ @Deprecated @SuppressWarnings("unused") private void updateJobReportTime( JobReportTime jobReportTime) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobReportTime.JOB_REPORT_TIME) .in(DbConstants.JobReportTime.START_TIME, jobReportTime.getStartTime()) .in(DbConstants.JobReportTime.STOP_TIME, jobReportTime.getStopTime()) .in(DbConstants.JobReportTime.WORK_TYPE_CODE, jobReportTime.getWorkTypeCode()) + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + jobReportTime.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " = '" + jobReportTime.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.DATE + " = '" + jobReportTime.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void updateUser(Person person) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Person.PERSON).in( DbConstants.Person.WAREHOUSE_NUMBER, person.getWarehouseNumber()).in( DbConstants.Person.COMMISSION_NUMBER_FORMAT, person.getCommunicationNumberFormat()).in( DbConstants.Person.EXPENSES_ACTIVE, person.getExpensesActive()).in( DbConstants.Person.PROFILE_TEXT, person.getProfileText()) + " WHERE " + DbConstants.Person.PERSONAL_NUMBER + " = " + person.getPersonalNumber()); } public void switchUser(Person person) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Person.PERSON).in( DbConstants.Person.PERSONAL_NUMBER, person.getPersonalNumber()).in( DbConstants.Person.LAST_NAME, person.getLastName()).in( DbConstants.Person.FIRST_NAME, person.getFirstName()).in( DbConstants.Person.INITIAL, person.getInitial()).in( DbConstants.Person.PERSONAL_NUMBER_DEPUTY, person.getPersonalNumberDeputy()).in( DbConstants.Person.PHONE, person.getPhoneNumber()).in( DbConstants.Person.NUM01, person.getNUM01()).in( DbConstants.Person.SALES_OFFICE, person.getSalesOffice()).in( DbConstants.Person.ABSENT_FROM, person.getAbsentFrom()).in( DbConstants.Person.ABSENT_TO, person.getAbsentTo()).in( DbConstants.Person.LANGUAGE, person.getLanguage()).in( DbConstants.Person.DEVICE_ID, person.getDeviceId()).in( DbConstants.Person.PASSWORD, person.getPassword()).in( DbConstants.Person.REFRESH_FLAG, person.getRefreshFlag()).in( DbConstants.Person.WAREHOUSE_NUMBER, person.getWarehouseNumber()).in( DbConstants.Person.COMMISSION_NUMBER_FORMAT, person.getCommunicationNumberFormat()).in( DbConstants.Person.EXPENSES_ACTIVE, person.getExpensesActive()).in( DbConstants.Person.PROFILE_TEXT, person.getProfileText()) .toString(); db.executeSql(sqlStmt); } public void updateReportMaterialIdx(ReportMaterial reportMaterial, int newIdx) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.ReportMaterial.REPORT_MATERIAL) .in(DbConstants.ReportMaterial.IDX, newIdx) + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + reportMaterial.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = " + reportMaterial.getIdx()); //$NON-NLS-1$ //$NON-NLS-2$ } public void updateReportMaterial(ReportMaterial reportMaterial) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.ReportMaterial.REPORT_MATERIAL).in( DbConstants.ReportMaterial.PERSONAL_NUMBER, reportMaterial.getPersonalNumber()).in( DbConstants.ReportMaterial.COMMISSION_NUMBER, reportMaterial.getCommissionNumber()).in( DbConstants.ReportMaterial.AMOUNT, reportMaterial.getAmount()).in( DbConstants.ReportMaterial.DELIVERY, reportMaterial.getDelivery()).in( DbConstants.ReportMaterial.EXPRESS_DELIVERY, reportMaterial.getExpressDelivery()).in( DbConstants.ReportMaterial.ACCOUNT_CODE, reportMaterial.getAccountCode()).in( DbConstants.ReportMaterial.UNIT, reportMaterial.getUnit()).in( DbConstants.ReportMaterial.NAME, reportMaterial.getProductName()).in( DbConstants.ReportMaterial.PRICE, reportMaterial.getPrice()).in( DbConstants.ReportMaterial.BARCODE, reportMaterial.getBarcode()).in( DbConstants.ReportMaterial.K14, reportMaterial.getK14()).in( DbConstants.ReportMaterial.EXPLANATION_TEXT, reportMaterial.getExplanationText()).in( DbConstants.ReportMaterial.OTHER_TYPE_FLAG, reportMaterial.getOtherTypeFlag()) + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + reportMaterial.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = " + reportMaterial.getIdx() //$NON-NLS-1$ //$NON-NLS-2$ ); } public void updateArticleEntryCount(String guid, String entryCount) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.DeliveryList.DELIVERY_LIST) .in(DbConstants.DeliveryList.ENTRY_COUNT, entryCount) + " WHERE " + DbConstants.DeliveryList.GUID + " = '" + guid + "'" ); } public void updateArticleEntryCount(String orderNr, String matnr, String entryCount) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.DeliveryList.DELIVERY_LIST) .in(DbConstants.DeliveryList.ENTRY_COUNT, entryCount) + " WHERE " + DbConstants.DeliveryList.TO + " = '" + getUser().getWarehouseNumber() + "'" + " AND " + DbConstants.DeliveryList.ORDER_NUMBER + " = '" + orderNr + "'" + " AND " + DbConstants.DeliveryList.MATERIAL_NUMBER + " = '" + matnr + "'" ); } public void updateReportMaterialComNo(String guid, String newConNo) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.ReportMaterial.REPORT_MATERIAL) .in(DbConstants.ReportMaterial.COMMISSION_NUMBER, newConNo) + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + guid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void updateOrder(Order order) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Order.ORDER).in( DbConstants.Order.STATUS, order.getStatus()).in( DbConstants.Order.ANZ, order.getANZ()).in( DbConstants.Order.CREATED_DATE, order.getCreateDate()).in( DbConstants.Order.SENT_DATE, order.getSentDate()) + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = '" + order.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.IDX + " = " + order.getIdx()); //$NON-NLS-1$ //$NON-NLS-2$ } public void updateOrderMaterial(OrderMaterial orderMaterial) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.OrderMaterial.ORDER_MATERIAL) .in(DbConstants.OrderMaterial.AMOUNT, orderMaterial.getAmount()) .in(DbConstants.OrderMaterial.UNIT, orderMaterial.getUnit()) .in(DbConstants.OrderMaterial.EXPRESS_FLAG, orderMaterial.getExpressFlag()) + " WHERE " + DbConstants.OrderMaterial.PERSONAL_NUMBER + " = '" + orderMaterial.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.NUMBER + " = '" + orderMaterial.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.DATE + " = '" + orderMaterial.getDate().getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } public int cntJobid( String jobId) { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.Job.JOB_NUMBER + " FROM " + DbConstants.Job.JOB //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.Job.JOB_NUMBER + " = '" + jobId + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int cntPerNo( String perNo) { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT " //$NON-NLS-1$ + DbConstants.Address.JOB_NUMBER + ", " //$NON-NLS-1$ + DbConstants.Address.JOB_TYPE + ", " //$NON-NLS-1$ + DbConstants.Address.PARTNER_NUMBER + " FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.PARTNER_NUMBER + " = '" + perNo + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public void updateRefreshFlag() { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Employee.EMPLOYEE).in(DbConstants.Employee.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.WorkType.WORK_TYPE).in(DbConstants.WorkType.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.ErrorCode.ERROR_CODE).in(DbConstants.ErrorCode.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Material.MATERIAL).in(DbConstants.Material.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Reason.REASON).in(DbConstants.Reason.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobReturnReason.JOB_RETURN_REASON).in(DbConstants.JobReturnReason.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobMonText.JOB_MON_TEXT).in(DbConstants.JobMonText.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.InternalWorkType.INTERNAL_WORK_TYPE).in(DbConstants.InternalWorkType.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Incident.INCIDENT).in(DbConstants.Incident.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobFormDesc.JOB_FORM_DESC).in(DbConstants.JobFormDesc.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobNoForm.JOB_NO_FORM).in(DbConstants.JobNoForm.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Invoice.INVOICE).in(DbConstants.Invoice.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.AbsenceType.ABSENCE_TYPE).in(DbConstants.AbsenceType.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.ServiceRefused.SERVICE_REFUSED).in(DbConstants.ServiceRefused.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Checklist.CHECK_LIST).in(DbConstants.Checklist.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Progress.PROGRESS).in(DbConstants.Progress.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.StateOfInstallation.STATE_OF_INSTALLATION).in(DbConstants.StateOfInstallation.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.NextIntervention.NEXT_INVENTION).in(DbConstants.NextIntervention.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Inventory.INVENTORY).in(DbConstants.Inventory.REFRESH_FLAG, " ").toString()); } public void deleteAllWorkTypeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.WorkType.WORK_TYPE + " WHERE " + DbConstants.WorkType.REFRESH_FLAG + " = ' '"); } public void deleteAllErrorCodeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.ErrorCode.ERROR_CODE + " WHERE " + DbConstants.ErrorCode.REFRESH_FLAG + " = ' '"); } public void deleteAllMaterialNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Material.MATERIAL + " WHERE " + DbConstants.Material.REFRESH_FLAG + " = ' '"); } public void deleteAllEmployeeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Employee.EMPLOYEE + " WHERE " + DbConstants.Employee.REFRESH_FLAG + " = ' '"); } public void deleteAllReasonNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Reason.REASON + " WHERE " + DbConstants.Reason.REFRESH_FLAG + " = ' '"); } public void deleteAllJobDeleteReasonNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobReturnReason.JOB_RETURN_REASON + " WHERE " + DbConstants.JobReturnReason.REFRESH_FLAG + " = ' '"); } public void deleteAllJobMonTextNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobMonText.JOB_MON_TEXT + " WHERE " + DbConstants.JobMonText.REFRESH_FLAG + " = ' '"); } public void deleteAllIncIdentNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Incident.INCIDENT + " WHERE " + DbConstants.Incident.REFRESH_FLAG + " = ' '"); } public void deleteAllJobFormDescNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC + " WHERE " + DbConstants.Incident.REFRESH_FLAG + " = ' '"); } public void deleteAllJobNoFormNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobNoForm.JOB_NO_FORM + " WHERE " + DbConstants.Incident.REFRESH_FLAG + " = ' '"); } public void deleteAllInvoiceNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Invoice.INVOICE + " WHERE " + DbConstants.Invoice.REFRESH_FLAG + " = ' '"); } public void deleteAllInternalWorkTypeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE + " WHERE " + DbConstants.InternalWorkType.REFRESH_FLAG + " = ' '"); } public void deleteAllAbsenceTypeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.AbsenceType.ABSENCE_TYPE + " WHERE " + DbConstants.AbsenceType.REFRESH_FLAG + " = ' '"); } public void deleteAllServiceRefusedNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.ServiceRefused.SERVICE_REFUSED + " WHERE " + DbConstants.ServiceRefused.REFRESH_FLAG + " = ' '"); } public void deleteAllChecklistNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Checklist.CHECK_LIST + " WHERE " + DbConstants.Checklist.REFRESH_FLAG + " = ' '"); } public void deleteAllProgresstNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Progress.PROGRESS + " WHERE " + DbConstants.Progress.REFRESH_FLAG + " = ' '"); } public void deleteAllStateOfInstallationNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.StateOfInstallation.STATE_OF_INSTALLATION + " WHERE " + DbConstants.StateOfInstallation.REFRESH_FLAG + " = ' '"); } public void deleteAllNextInterventionNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.NextIntervention.NEXT_INVENTION + " WHERE " + DbConstants.NextIntervention.REFRESH_FLAG + " = ' '"); } public void deleteAllInventoryNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.REFRESH_FLAG + " = ' '"); } public void deleteAllReceiptOfGoodsNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS + " WHERE " + DbConstants.ReceiptOfGoods.REFRESH_FLAG + " = ' '"); } public List selectCalendarDateWithRunningTimeCapturing(int pernr) { // Date result = null; List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT c." + DbConstants.CalendarTimeSheet.DATE //$NON-NLS-1$ + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET + " c, " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.TimeSheet.TIME_SHEET + " t " //$NON-NLS-1$ + " WHERE t." + DbConstants.TimeSheet.START_TIME + " >= c." + DbConstants.CalendarTimeSheet.DATE //$NON-NLS-1$ //$NON-NLS-2$ + " AND t." + DbConstants.TimeSheet.START_TIME + " < c." + DbConstants.CalendarTimeSheet.DATE + " + 86400000 " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND t." + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND t." + DbConstants.TimeSheet.STOP_TIME + " ='" + DateUtils.getInitialDateTime().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); Date date = rs.getDate(DbConstants.CalendarTimeSheet.DATE); result.add(date); } else { while (rs.moveNext()) { Date date = rs.getDate(DbConstants.CalendarTimeSheet.DATE); result.add(date); } log.error("Multiple CALENDAR objects with running time capturing found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } private boolean startTransaction(DBSession session) { if (session.isTransactionPending()) return true; else { session.startTransaction(); return false; } } private int executeDataManipulationStmt(String sqlStmt) throws DBException { int result = -1; boolean pendingTransactionUsed = startTransaction(db); try{ if (log.isInfoEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ result = db.executeSql(sqlStmt); if (log.isInfoEnabled()) { log.info("Number of affected records:'" + result + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return result; } catch (DBException e) { log.error(e.getMessage()); if (!pendingTransactionUsed) db.rollback(); else throw e; } // termination with errors return result; } private String setDefaultLanguage(String language) { String result = language; if (StringUtil.isEmpty(result)) { result = "D"; //$NON-NLS-1$ } return result; } }     common/src/ch/mfiles/kaba/kolibri/common/util/DateTimeConverter.jpage:   java.lang.System.out.println(new java.util.Date().getTime()); java.lang.System.out.println(new java.util.Date(1326447011991L)); java.lang.System.out.println(new java.util.Date(1323959280000L)); java.lang.System.out.println("DATUM " + new java.util.Date(1347552978795L)); java.lang.System.out.println("DATUM " + new java.util.Date(1335304800000L)); java.lang.System.out.println("VON " + new java.util.Date(1323876420000L)); java.lang.System.out.println("VON " + new java.util.Date(1323959280000L)); java.lang.System.out.println("BIS " + new java.util.Date(1323876420000L)); java.lang.System.out.println("BIS " + new java.util.Date(1323959280000L));     common/src/ch/mfiles/kaba/kolibri/common/util/DateTimeUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DateTimeUtil { private static Log log = LogFactory.getLog(CommonConstants.class); public static final long SECONDS_IN_MILLI = 1000; public static final long MINUTES_IN_MILLI = SECONDS_IN_MILLI * 60; public static final long HOURS_IN_MILLI = MINUTES_IN_MILLI * 60; public static final long DAYS_IN_MILLI = HOURS_IN_MILLI * 24; public static final String SHOW_TABLE_DATE_FORMAT = "dd.MM.yy"; //$NON-NLS-1$ public static final String SHOW_TIME_FORMAT = "HH:mm"; //$NON-NLS-1$ public static final String DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm"; //$NON-NLS-1$ public static final String DATE_FORMAT = "dd.MM.yyyy"; //$NON-NLS-1$ public static final String SHOW_HTML_DATE_TIME_FORMAT = "dd.MM.yyyy HH:mm"; //$NON-NLS-1$ DateTimeUtil() { } /** * Creates a Calendar Object with the current date and time including seconds and milliseconds * @return a Calendar */ public static Calendar getTimestamp() { return Calendar.getInstance(); } /** * Creates a Calendar Object with the current date and time with 00.000s * @return a Calendar */ public static Calendar getNow() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); return cal; } /** * Creates a Calendar Object with the current date and time with 00.000s * @return a Calendar */ public static Calendar getTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); return cal; } /** * Creates a Calendar Object with the current date and time from datetime with 00.000s * @return a Calendar */ public static Calendar getTime(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); return cal; } /** * Creates a Calendar Object with the current date and time 00:00:00.000 * @return a Calendar */ public static Calendar getToday() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); return cal; } /** * Creates a Calendar Object with the date from yesterday and time 00:00:00.000 * @return a Calendar */ public static Calendar getYesterday() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.add(Calendar.DAY_OF_YEAR, -1); return cal; } /** * Creates a Calendar Object with the preceding date from date and time 00:00:00.000 * @return a Calendar */ public static Calendar getYesterday(Date date) { Calendar cal = getDate(date); cal.add(Calendar.DAY_OF_YEAR, -1); return cal; } /** * Creates a Calendar Object with the date from the day before yesterday and time 00:00:00.000 * @return a Calendar */ public static Calendar getDayBeforeYesterday() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.add(Calendar.DAY_OF_YEAR, -2); return cal; } /** * Creates a Calendar Object with the consecutively (next) date from date and time 00:00:00.000 * @return a Calendar */ public static Calendar getTomorrow(Date date) { Calendar cal = getDate(date); cal.add(Calendar.DAY_OF_YEAR, 1); return cal; } /** * Creates a Calendar Object with the date from datetime and time 00:00:00.000 * @return a Calendar */ public static Calendar getDate(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); return cal; } /** * Creates a Calendar Object with the date from today and time 00:01:00.000 * @return a Calendar */ public static Calendar getTodayEarlyMorning() { Calendar cal = getToday(); cal.set(Calendar.MINUTE, 01); return cal; } /** * Creates a Calendar Object with the date from yesterday and time 23:59:00.000 * @return a Calendar */ public static Calendar getYesterdayLateNight() { Calendar cal = getYesterday(); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.HOUR_OF_DAY, 23); return cal; } /** * Creates a Calendar Object with the date from datetime and time 23:59:00.000 * @return a Calendar */ public static Calendar getLateNight(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.HOUR_OF_DAY, 23); return cal; } /** * Creates a Calendar Object with the current date and time hourOfDay : minute:00.000 * @return a Calendar */ public static Calendar setTimeOfDate(Date date, int hourOfDay, int minute) { Calendar cal = getDate(date); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.HOUR_OF_DAY, hourOfDay); return cal; } /** * Checks is datetime is a date value. Condition for a date value is time = 00:00:00.000 * @param datetime * @return true if datetime is a date. */ public static boolean isDate(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); return cal.get(Calendar.HOUR_OF_DAY) == 0 && cal.get(Calendar.MINUTE) == 0 && cal.get(Calendar.SECOND) == 0 && cal.get(Calendar.MILLISECOND) == 0; } /** * Checks if start and stop are within the same day * @param start * @param stop * @return true/code> if start and stop are within the same day */ public static boolean isSameDay(Date start, Date stop) { int startDay = DateTimeUtil.getDate(start).get(Calendar.DAY_OF_YEAR); int stopDay = DateTimeUtil.getDate(stop).get(Calendar.DAY_OF_YEAR); return startDay == stopDay; } /** * @param start * @param stop * @return */ public static Date calcTimeDiff(Date start, Date stop) { Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); long startDateTime = cal.getTime().getTime(); cal.setTime(stop); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); long stopDateTime = cal.getTime().getTime(); return new Date(stopDateTime - startDateTime); } /** * Gets time difference is use for calculate the difference between two Dates. * * @param start * @param stop * @return */ public static long getTimeDifference(Date start, Date stop) { if (start.getTime() == 0 || stop.getTime() == 0) return 0; Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.MILLISECOND, 0); long startDateTime = cal.getTimeInMillis(); cal.setTime(stop); cal.set(Calendar.MILLISECOND, 0); long stopDateTime = cal.getTimeInMillis(); return startDateTime - stopDateTime; } public static Date parseDateFromHHmm(String time, Date currentDate) { Date result = null; try { int hours = Integer.parseInt(time.substring(0, 2)); int minutes = Integer.parseInt(time.substring(3, 5)); result = DateTimeUtil.setTimeOfDate(currentDate, hours, minutes).getTime(); } catch (Exception e) { log.error("Error while parsing time string '" + time + "', message is: '" + e.getMessage() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(e); } return result; } public static Date parseDateFromddMMyyyy(String date) { SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, new Locale("de", "CH")); try { return format.parse(date); } catch (ParseException e) { log.info("parse date fail"); return null; } } public static String tableDate(Date date) { SimpleDateFormat format = new SimpleDateFormat(SHOW_TABLE_DATE_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String HtmlDateTime(Date date) { SimpleDateFormat format = new SimpleDateFormat(SHOW_HTML_DATE_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String showTime(long time) { if (time == 0) return "00:00"; //$NON-NLS-1$ //long diffSeconds = time / SECONDS_IN_MILLI % 60; long minutes = time / (MINUTES_IN_MILLI) % 60; long hours = time / (HOURS_IN_MILLI) % 24; //long diffDays = time / (DAYS_IN_MILLI); return String.format("%02d", hours) + ":" + String.format("%02d", minutes); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public static String showTime(Date date) { SimpleDateFormat format = new SimpleDateFormat(SHOW_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } // public static String showRoundTime(Date date) { // Calendar calendar = Calendar.getInstance(); // calendar.setTime(date); // // if(calendar.get(Calendar.SECOND) > 0) { // calendar.add(Calendar.SECOND, 1); // } // SimpleDateFormat format = new SimpleDateFormat(SHOW_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ // return format.format(calendar.getTime()); // } public static String showDate(Date date) { SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String showDateTime(Date date) { SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String fileNameDate(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return format.format(date); } public static String fileNameTime(Date date) { SimpleDateFormat format = new SimpleDateFormat("HHmmss", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return format.format(date); } public static String showTimeGMT(Date date) { SimpleDateFormat format = new SimpleDateFormat("HH:mm"); //$NON-NLS-1$ return format.format(date); } public static String showDayOfMonth(Date date) { SimpleDateFormat format = new SimpleDateFormat("dd"); //$NON-NLS-1$ return format.format(date); } public static String showDayOfWeek(Date date) { SimpleDateFormat format = new SimpleDateFormat("EE"); //$NON-NLS-1$ return format.format(date); } public static String showDayMonth(Date date) { SimpleDateFormat format = new SimpleDateFormat("dd.MM"); //$NON-NLS-1$ return format.format(date); } public static String showMonthNameYear(Date date) { SimpleDateFormat format = new SimpleDateFormat("MMMM yyyy"); //$NON-NLS-1$ return format.format(date); } public static String showHHmmss(Date date) { SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$ return format.format(date); } }     common/src/ch/mfiles/kaba/kolibri/common/util/DbConstants.java:   package ch.mfiles.kaba.kolibri.common.util; public class DbConstants { DbConstants() { } public static final class From { From() { } public static final String FROM_TEXT = " FROM "; } public static final class DeleteFrom { DeleteFrom() { } public static final String DELETE_FROM = "DELETE " + From.FROM_TEXT; } public static final class Where { Where() { } public static final String WHERE_TEXT = " WHERE "; } public static final class Settings { Settings() { } public static final String T_SETTINGS = "kaba_service_Setting"; } public static final class Job { Job() { } public static final String JOB = "ZKDMOB"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String STATUS = "STATUS"; public static final String PRIORITY = "PRIO"; public static final String JOB_FORWARD = "PERSNO2"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String STAFF_NAME = "ERNAM"; public static final String STAFF_PHONE = "ERNAMTEL"; public static final String APPOINTMENT_DATE = "EDATE"; public static final String ACTIVE_DATE = "ACTIVE_DATE"; public static final String JOB_RESCHEDULE_DATE = "EDATE_DT"; public static final String JOB_RESCHEDULE_TIME = "EDATE_TI"; public static final String WEEK = "KW"; public static final String FIX = "FIX"; public static final String APPOINTMENT = "TVRB"; public static final String OBJECT_ADDRESS_ID = "OBJNR"; public static final String CUSTOMER_ADDRESS_ID = "PARZSNR"; public static final String PARTNER_ADDRESS_ID = "PARANMNR"; public static final String OWNER_ADDRESS_ID = "PARZANR"; public static final String PARTNER_OF_INSTALL_ADDRESS_ID = "PARAPNR"; public static final String CUSTOMER_SERVICE_ADDRESS_ID = "PARZRNR"; public static final String ORDER_NUMBER = "BSTKD"; public static final String NEW_JOB_DATE = "ERDAT"; public static final String ERROR_ID = "FC"; public static final String CALL_SERVICE_FLAG = "PIKETT"; public static final String MAINTENANCE_CONTRACT_TYPE = "SAVC"; public static final String SERVICE_PLAN_MONTH_1 = "SAVLFD1"; public static final String SERVICE_PLAN_MONTH_2 = "SAVLFD2"; public static final String SERVICE_PLAN_MONTH_3 = "SAVLFD3"; public static final String SERVICE_PLAN_MONTH_4 = "SAVLFD4"; public static final String SERVICE_PLAN_MONTH_5 = "SAVLFD5"; public static final String SERVICE_PLAN_MONTH_6 = "SAVLFD6"; public static final String SERVICE_OPEN = "SAVOFF"; public static final String CONTACT_NAME = "USER_SAV"; public static final String CONTACT_PHONE = "USER_SAVTEL"; public static final String TECHNICAL_NAME = "ZMNAM"; public static final String TECHNICAL_PHONE = "ZMTEL1"; public static final String SELLER_NAME = "ZVNAM"; public static final String SELLER_PHONE = "ZVTEL1"; public static final String DRIVER_TYPE = "ANTRTXT"; public static final String DRIVER_TYPE_UPD = "ANTRTXT_UPD"; public static final String DEFAULT_TIME = "ZKDINDZEIT"; public static final String INFORMATION = "LTXT2"; public static final String DESCRIPTION = "LTXT1"; public static final String CURRENT_REPORT_GUID = "CURRENTRAPPORTGUID"; public static final String STATUS_EDIT = "STEDTDATE"; public static final String CYCLE_OF_INSTALLATIN_FLAG = "ZYKFLG"; public static final String FORM_DESC_1 = "FORMDESC1"; public static final String FORM_DESC_2 = "FORMDESC2"; public static final String FORM_DESC_3 = "FORMDESC3"; public static final String SERVICE_REFUSED_FLAG = "KNZSAVPFL"; public static final String LINK = "LINK"; public static final String GUARANTEE = "KNZGARANT"; public static final String MORE_INFORMARION_FLAG = "KNZERWKOM"; } public static final class Address { Address() { } public static final String ADDRESS = "ZKDMOBADR"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String TYPE = "TYPE"; public static final String PARTNER_NUMBER = "PARNR"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String CUSTOMER_NUMBER = "KUNNR"; public static final String TITLE = "TITLE"; public static final String NAME1 = "NAME1"; public static final String NAME2 = "NAME2"; public static final String NAME3 = "NAME3"; public static final String LOCATION = "NAME4"; public static final String STREET = "STREET"; public static final String CITY = "CITY1"; public static final String PASTAL_CODE = "POST_CODE1"; public static final String PHONE_1 = "TEL_NUMBER1"; public static final String PHONE_2 = "TEL_NUMBER2"; public static final String FAX = "FAX_NUMBER1"; public static final String EMAIL = "EMAIL"; public static final String CHANGE_FLAG = "UPD"; public static final String DIRTY_FLAG = "DIRTYFLG"; } public static final class History { History() { } public static final String HISTORY = "ZKDHIST"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String IDX = "IDX"; public static final String Text = "TEXT"; } public static final class Report { Report() { } public static final String REPORT = "ZKDMOBREP"; public static final String IDX = "IDX"; public static final String GUID = "GUID"; public static final String CREATE_DATE = "ERDAT"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String COMMISSION_NUMBER = "ANLNR"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String PARTICAL_REPAIR = "TEILREP"; public static final String FINAL_REPAIR = "ENDREP"; public static final String REASONING = "FOLGEREP"; public static final String INCIDENT_AB = "STORC"; public static final String BILLING = "VERRC"; public static final String SAFETY_REPORT = "SECRAP"; public static final String CUSTOMER_SUPPORT = "RAPSEND"; public static final String CUSTOMRE_SUPPORT_TEXT = "RAPSENDCOM"; public static final String REPORT_STATUS = "REPORTSTATUS"; public static final String CHECK_LIST = "CHCKLISTE"; public static final String ERROR_ID_1 = "FMC1"; public static final String ERROR_H_1 = "FMH1"; public static final String ERROR_FLAG_1 = "FM1"; public static final String ERROR_ID_2 = "FMC2"; public static final String ERROR_H_2 = "FMH2"; public static final String ERROR_FLAG_2 = "FM2"; public static final String ERROR_ID_3 = "FMC3"; public static final String ERROR_H_3 = "FMH3"; public static final String ERROR_FLAG_3 = "FM3"; public static final String SYSTEM_ERROR = "FMB"; public static final String DISTANCE = "KM"; public static final String EXPENSES = "SPESEN"; public static final String SERVICE_PLAN_MENTH_1 = "SAVLFD1"; public static final String SERVICE_PLAN_MENTH_2 = "SAVLFD2"; public static final String SERVICE_PLAN_MENTH_3 = "SAVLFD3"; public static final String SERVICE_PLAN_MENTH_4 = "SAVLFD4"; public static final String SERVICE_PLAN_MENTH_5 = "SAVLFD5"; public static final String SERVICE_PLAN_MENTH_6 = "SAVLFD6"; public static final String MONTH_YEAR = "SAVERL"; public static final String ORDER_NUMBER = "BSTKD"; public static final String SIGNATURE_GUID = "SIGNGUID"; public static final String SIGNATURE_FLAG = "SIGNFLG"; public static final String SIGNATURE = "SIGNPIC"; public static final String SIGNATURE_INFO = "SIGNINFO"; public static final String WORK_TYPE = "ARBA"; public static final String COLLECTIVELY = "SIGNBUNDLE"; public static final String NO_MATERIAL = "NOMATUSED"; public static final String CYCLE_OF_INSTALLATION = "ZYKINT"; public static final String NO_FORM1 = "NO_FORM1"; public static final String NO_FORM2 = "NO_FORM2"; public static final String NO_FORM3 = "NO_FORM3"; public static final String SERVICE_REFUSED = "BGRSAV"; public static final String OPEN_PENDING = "PEND"; public static final String GOVERNMENT_REPORT = "REGIE"; public static final String CHECKLIST_STATE = "IBSSTATE"; public static final String CHECKLIST_SIA = "IBSSIA"; public static final String CHECKLIST_READY = "IBSREADY"; public static final String CHECKLIST_INSTRUCTION = "IBSINSTR"; public static final String CHECKLIST_VKF = "IBSVKF"; public static final String CHECKLIST_TEST = "IBSTEST"; public static final String SIGNATURE_NAME = "SIGNNAME"; public static final String MON_STK = "MONSTK"; public static final String NEXT_INTERVENTION_DATE = "EDATE"; public static final String STATE_OF_INSTALLATION = "BTRBZUST"; public static final String NEXT_INTERVENTION_CODE = "FLGVRG"; } public static final class JobMessage { JobMessage() { } public static final String JOB_MESSAGE = "ZKDMOBMSG"; public static final String GUID = "GUID"; public static final String MESSAGE_ID = "MSGID"; public static final String MESSAGE_CODE = "MSGC"; public static final String TEXT_1 = "TXT1"; public static final String TEXT_2 = "TXT2"; public static final String MoreText = "TXT3"; } public static final class ReportMaterial { ReportMaterial() { } public static final String REPORT_MATERIAL = "ZKDMATORD"; public static final String IDX = "IDX"; public static final String GUID = "GUID"; public static final String NUMBER = "MATNR"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String AMOUNT = "STCK"; public static final String DELIVERY = "MLIF"; public static final String EXPRESS_DELIVERY = "EXPR"; public static final String ACCOUNT_CODE = "VERRC"; public static final String UNIT = "MAUNIT"; public static final String NAME = "MAKTX"; public static final String PRICE = "PRICE"; public static final String BARCODE = "BARC"; public static final String K14 = "K14"; public static final String EXPLANATION_TEXT = "BARCTXT"; public static final String OTHER_TYPE_FLAG = "BARCFLG"; } public static final class JobReportTime { JobReportTime() { } public static final String JOB_REPORT_TIME = "ZKDMOBRTIM"; public static final String GUID = "GUID"; public static final String IDX = "IDX"; public static final String DATE = "DATUM"; public static final String START_TIME = "VON"; public static final String STOP_TIME = "BIS"; public static final String WORK_TYPE_CODE = "ARBA"; } public static final class CalendarTimeSheet { CalendarTimeSheet() { } public static final String CALENDAR_TIME_SHEET = "CALENDAR"; public static final String DATE = "DATUM"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String STATUS = "STATUS"; public static final String DATE_STRING = "DATUM_TXT"; } public static final class TimeSheet { TimeSheet() { } public static final String TIME_SHEET = "ZKDMATIME"; public static final String IDX = "IDX"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String START_TIME = "VON"; public static final String STOP_TIME = "BIS"; // public static final String C_VBELN = "VBELN"; public static final String COST_CENTER = "KOSTL"; public static final String WORK_TYPE_CODE = "ARBA"; public static final String CALL_FLAG = "PIKETT"; } public static final class Expenses { Expenses() { } public static final String EXPENSES = "ZKDMAEXPNS"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String NO_EXPENSES = "KEINESPSSEN"; public static final String EXPENSES_DATE = "SPSNDAT"; public static final String DAILY_EXPENSES = "TGSPSN"; public static final String VARIOUS_EXPENSES = "DIVSPNS"; public static final String DECUCTION = "ABZG"; public static final String EXPENSES_KEY = "SPNSKEY"; public static final String PIKETT_EXPENSES = "PIKETT"; public static final String EXPENSES_DESCRIPTION = "SPNSTXT"; public static final String OPERATING_HOURS_OF = "BVON"; public static final String OPERATION_HOURS_UP_TO = "BBIS"; public static final String OPERATION_HOURS_TOTAL = "BTOT"; public static final String DEDUCTION_DESCRIPTION = "ABZGTXT"; public static final String COMPENSTION = "VERG"; } public static final class OrderMaterial { OrderMaterial() { } public static final String ORDER_MATERIAL = "ZKDMAMAT"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String AMOUNT = "STCK"; public static final String NUMBER = "MATNR"; public static final String EXPRESS_FLAG = "EXPR"; public static final String VARIOUS_MATERIAL = "MAKTX"; public static final String UNIT = "MAUNIT"; public static final String ORDER_DATE = "BESTDAT"; } public static final class ShortMessage { ShortMessage() { } public static final String SHORT_MESSAGE = "ZSHORTMSG"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String MESSAGE_KEY = "TDNAME"; public static final String SUBJECT = "BETREFF"; public static final String CONFIRM = "BESTAETIGT"; public static final String MESSAGE = "LTEXT"; public static final String STATUS = "STATUS"; public static final String RECEIVED_DATE = "ERHALTEN"; public static final String RECEIVED_TIME = "EINGANG"; } // public static final class ZSHORTMSGREC { // public static final String T_ZSHORTMSGREC = "ZSHORTMSGREC"; // public static final String C_PERNR = "PERNR"; // public static final String C_TDNAME = "TDNAME"; // public static final String C_ERHALTEN = "ERHALTEN"; // } public static final class ServerJob { ServerJob() { } public static final String SERVER_JOB = "ZKDMOBMC"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String STREET = "STREET"; public static final String CITY = "CITY1"; public static final String PASTAL_CODE = "POST_CODE1"; public static final String LOCATION = "NAME4"; public static final String SERVICE_CONTRACT_TYPE = "SAVC"; public static final String MONTH_YEAR = "SAVOFF"; public static final String PERSONAL_NUMBER = "LKDPERNR"; } // public static final class Incident { // Incident() { // } // public static final String Incident = "ZKDCSTORC"; // public static final String ErrorCode = "STORC"; // public static final String ZIFF = "ZIFF"; // public static final String Language = "LANGU"; // public static final String Description = "TEXT"; // } public static final class WorkType { WorkType() { } public static final String WORK_TYPE = "ZARBEITSART"; public static final String CODE = "ARBA"; public static final String GROUP = "FRM"; public static final String TEXT = "TEXT"; public static final String REFRESH_FLAG = "REFRESHED"; public static final String GUARANTEE = "KNZGARENT"; } public static final class ErrorCode { ErrorCode() { } public static final String ERROR_CODE = "ZFCODE"; public static final String CODE = "FC"; public static final String TEXT = "TEXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ReportMessage { ReportMessage() { } public static final String REPORT_MESSAGE = "ZKDMOBMSGC"; public static final String CODE = "MSGC"; public static final String TEXT = "TXT"; public static final String KND = "KND"; public static final String KDZ = "KDZ"; public static final String ABTL = "ABTL"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Material { Material() { } public static final String MATERIAL = "ZKDMOBMAT"; public static final String NUMBER = "MATNR"; public static final String TEXT = "MAKTX"; public static final String CUSTOMER_SERVICE_FLAG = "KDMAT"; public static final String MOUNTING_FLAG = "MONMAT"; public static final String UNIT = "MAUNIT"; public static final String SIZE = "VPME"; public static final String NEW_PRICE = "KBETR_NP"; public static final String SUBSTITUE_PRICE = "KBETR_AP"; public static final String CALCULATION_NEW_PRICE = "KPEIN_NP"; public static final String CALCULATION_SUBSTITUE_PRICE = "KPEIN_AP"; public static final String UNIT_NEW_PRICE = "KMEIN_NP"; public static final String UNIT_SUBSTITUE_PRICE = "KMEIN_AP"; public static final String CURRENCY_NEW_PRICE = "WAERK_NP"; public static final String CURRENCY_SUBSTITUE_PRICE = "WAERK_AP"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class MaterialPerson { MaterialPerson() { } public static final String MATERIAL_PERSON = "ZKDMOBMATPERS"; public static final String NUMBER = "MATNR"; public static final String TEXT = "MAKTX"; public static final String CUSTOMER_SERVICE_FLAG = "KDMAT"; public static final String MOUNTING_FLAG = "MONMAT"; } public static final class Person { Person() { } public static final String PERSON = "ZKDMOBMA"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String LAST_NAME = "NACHN"; public static final String FIRST_NAME = "VORNA"; public static final String INITIAL = "INITS"; public static final String PERSONAL_NUMBER_DEPUTY = "STVPERNR"; public static final String PHONE = "TELNR"; public static final String NUM01 = "NUM01"; public static final String SALES_OFFICE = "VKBUR"; public static final String ABSENT_FROM = "ABWVON"; public static final String ABSENT_TO = "ABWBIS"; public static final String LANGUAGE = "COMLANGU"; public static final String DEVICE_ID = "GID"; public static final String PASSWORD = "PWD"; public static final String REFRESH_FLAG = "REFRESHED"; public static final String WAREHOUSE_NUMBER = "LGORT"; public static final String COMMISSION_NUMBER_FORMAT = "ANLFORMAT"; public static final String EXPENSES_ACTIVE = "SPESENERF"; public static final String PROFILE_TEXT = "IBSTEXT"; } public static final class Employee { Employee() { } public static final String EMPLOYEE = "ZKDSMOBMA"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String LAST_NAME = "NACHN"; public static final String FIRST_NAME = "VORNA"; public static final String INITIAL = "INITS"; public static final String PERSONAL_NUMBER_DEPUTY = "STVPERNR"; public static final String PHONE = "TELNR"; public static final String COMMUNICATION_NUMBER = "NUM01"; public static final String SALES_OFFICE = "VKBUR"; public static final String ABSENT_FROM = "ABWVON"; public static final String ABSENT_TO = "ABWBIS"; public static final String LANGUAGE = "COMLANGU"; public static final String DEVICE_ID = "GID"; public static final String PASSOWRD = "PWD"; public static final String SPECIFIC_FUNCTION = "FKT"; public static final String WAREHOUSE_NUMBER = "LGORT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Drive { Drive() { } public static final String DRIVE = "ZKDMOBANTRTYP"; public static final String CODE = "ANTRC"; public static final String TEXT = "TXT"; public static final String LONG_TEXT = "LTEXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Billing { Billing() { } public static final String BILLING = "ZKDMOBVRCINT"; public static final String CODE = "VRCD"; public static final String TEXT = "TXT"; public static final String JOB_TYPE = "AUART"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Order { Order() { } public static final String ORDER = "ZKSMABEST"; public static final String IDX = "IDX"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String STATUS = "STATUS"; public static final String ANZ = "ANZ"; public static final String CREATED_DATE = "ERFASST"; public static final String SENT_DATE = "GESENDET"; } public static final class JobFile { JobFile() { } public static final String JOB_FILE = "ZKDMOBMV"; public static final String IDX = "IDX"; public static final String GUID = "GUID"; public static final String JOB_NUMBER = "MDLNR"; public static final String JOB_TYPE = "AUART"; public static final String TYPE = "ATTCLAS"; public static final String DESCRIPTION = "DESC"; public static final String SIGN_PIC_AT = "SIGNPIC_AT"; public static final String FORM_TYPE = "FORMTYPE"; public static final String FORM_DESC = "FORMDESC"; public static final String SENT_DATE = "SENTDATE"; } public static final class Reason { Reason() { } public static final String REASON = "ZKDMOBMVCASE"; public static final String CODE = "MVCASETXT"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobReturnReason { JobReturnReason() { } public static final String JOB_RETURN_REASON= "ZKDMOBRETURN"; public static final String CODE = "RETTXT"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobMonText { JobMonText() { } public static final String JOB_MON_TEXT = "ZKDMOBMONTXT"; public static final String CODE = "MONTXT"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobFormDesc { JobFormDesc() { } public static final String JOB_FORM_DESC = "ZKDMOBFORMDESC"; public static final String CODE = "FORMDESC"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobNoForm{ JobNoForm() { } public static final String JOB_NO_FORM = "ZKDMOBNOFORM"; public static final String CODE = "NO_FORM"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Incident{ Incident() { } public static final String INCIDENT = "ZKDMOBSTORC"; public static final String CODE = "STORC"; public static final String TEXT = "TXT"; public static final String FCT = "FCT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Email { Email() { } public static final String EMAIL = "ZKDSMOBEMAIL"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String PARTNER_NUMBER = "PARNR"; public static final String TEXT = "EMAIL"; } public static final class Invoice{ Invoice() { } public static final String INVOICE = "ZKDMOBVERRC"; public static final String CODE = "VERRC"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class InternalWorkType { InternalWorkType() { } public static final String INTERNAL_WORK_TYPE = "ZKDMOBARBA"; public static final String CODE = "ARBA"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ReportMeasurement { ReportMeasurement() { } public static final String REPORT_MEASUREMENT = "ZKDMOBMEAS"; public static final String GUID = "GUID"; public static final String MEASURING_POINT = "PNT"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String MEASUREMENT = "MEAS"; public static final String DYNAMIC_POWER_PEAK_VALUE = "FDYN"; public static final String DYNAMIC_TIME = "TDYN"; public static final String STATIC_END_POWER = "FEND"; public static final String DEVICE_TYPE = "DEVTYPE"; public static final String SN_OF_DEVICE = "SNUMBER"; public static final String CALIBRATION_DATE = "CALDAT"; } public static final class VariousExpenses { VariousExpenses() { } public static final String VARIOUS_EXPENSES = "ZKDMAEXPNSDIV"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String IDX = "IDX"; public static final String AMOUNT = "DIVSPNS"; public static final String EXPENSES_CODE = "SPNSTXT"; } public static final class VariousExpenseFile { VariousExpenseFile() { } public static final String VARIOUS_EXPENSE_FILE = "ZKDMAESPNSPICS"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String IDX = "IDX"; public static final String DESCRIPTION = "DESC"; public static final String FORM_TYPE = "FORMTYP"; public static final String SIGN_PIC_AT = "SIGNPIC_AT"; } public static final class AbsenceNotification { AbsenceNotification() { } public static final String ABSENCE_NOTIFICATION = "ZKDMAABSENCE"; public static final String GUID = "GUID"; public static final String DATE = "ERFDT"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String ABSENCE_TYPE = "ABWGRND"; public static final String DATE_FROM = "DATUMVON"; public static final String DATE_TO = "DATUMBIS"; public static final String TIME_FROM = "ZEITVON"; public static final String TIME_TO = "ZEITBIS"; public static final String TEXT = "TEXT"; } public static final class AbsenceType { AbsenceType() { } public static final String ABSENCE_TYPE = "ZKDMOBABSC"; public static final String ABWGRND = "ABWGRND"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ServiceRefused { ServiceRefused() { } public static final String SERVICE_REFUSED = "ZKDMOBBEGRSAV"; public static final String SAVRET = "SAVRET"; public static final String LANGUAGE = "SPRAS"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Checklist { Checklist() { } public static final String CHECK_LIST = "ZKDMOBCHKLIST"; public static final String CODE = "CHCKLISTE"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Progress { Progress() { } public static final String PROGRESS = "ZKDMOBMONSTK"; public static final String CODE = "MONSTK"; public static final String SPRAS = "SPRAS"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Form { Form() { } public static final String FORM = "FORM"; public static final String ID = "Id"; public static final String VERSION = "Version"; public static final String STATUS = "Status"; public static final String VALID_FROM = "ValidFrom"; public static final String VALID_TO = "ValidTo"; public static final String NAME = "Name"; public static final String DESCRIPTION = "Description"; } public static final class FormItem { FormItem() { } public static final String FORMITEM = "FORMITEM"; public static final String FORM_ID = "FormId"; public static final String FORM_VERSION = "FormVersion"; public static final String ID = "Id"; public static final String FORM_ITEM_TYPE = "FormItemType"; public static final String SEQUENCE = "Sequence"; public static final String LABEL = "Label"; public static final String MANDATORY = "Mandatory"; public static final String CARD_NAME = "CardName"; public static final String OBSOLETE = "Obsolete"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String EMPTY_TEXT = "EmptyText"; public static final String GROUP_NAME = "GroupName"; public static final String MAX_STRING_SIZE = "MaxStringSize"; public static final String VALIDATION_REGEX = "ValidationRegex"; public static final String MULTILINE = "Multiline"; public static final String FORMAT = "Format"; public static final String MIN_VALUE = "MinValue"; public static final String MAX_VALUE = "MaxValue"; } public static final class FormDependency { FormDependency() { } public static final String FORMDEPENDENCY = "FORMDEPENDENCY"; public static final String FORM_ID = "FormId"; public static final String FORM_VERSION = "FormVersion"; public static final String FORM_ITEM_ID = "FormItemId"; public static final String DEPENDENCY = "Dependency"; public static final String CHECKBOX_FORM_ITEM_ID = "CheckboxFormItemId"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String VALUE_ID = "ValueId"; } public static final class FormValueList { FormValueList() { } public static final String FORMVALUELIST = "FORMVALUELIST"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String VALUE_ID = "ValueId"; // public static final String NAME = "Name"; public static final String SEQUENCE = "Sequence"; public static final String DEFAULT_VALUE = "DefaultValue"; public static final String VALUE = "Value"; } public static final class FormInstance { FormInstance() { } public static final String FORMINSTANCE = "FORMINSTANCE"; public static final String GUID = "GUID"; public static final String FORM_ID = "FormId"; public static final String FORM_VERSION = "FormVersion"; public static final String FORM_ITEM_ID = "FormItemId"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String VALUE_ID = "ValueId"; public static final String FORM_ITEM_TYPE = "FormItemType"; public static final String STRING_VALUE = "StringValue"; public static final String BOOLEAN_VALUE = "BooleanValue"; public static final String FLOAT_VALUE = "FloatValue"; public static final String ATTACHMENT_VALUE = "AttachmentValue"; } public static final class StateOfInstallation { StateOfInstallation() { } public static final String STATE_OF_INSTALLATION = "ZKDMOBBTRBZUST"; public static final String CODE = "BTRBZUST"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class NextIntervention { NextIntervention() { } public static final String NEXT_INVENTION = "ZKDMOBFLGVRG"; public static final String CODE = "FLGVRG"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class VehicleInventory { VehicleInventory() { } public static final String VEHICLE_INVENTORY = "ZKDMOBFZLGSYNC"; public static final String STORAGE_LOCATION = "LGORT"; public static final String MATERIAL_NUMBER = "MATNR"; public static final String MATERIAL_NAME = "MAKTX"; public static final String STOCK_OF_MATERIAL = "LABST"; public static final String UNIT = "MEINS"; } public static final class Inventory { Inventory() { } public static final String INVENTORY = "ZKDMOBFZLG"; public static final String WAREHOUSE_NUMBER = "LGORT"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String NAME = "NAME_TEXT"; public static final String WAREHOUSE = "LGKNZ"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ReceiptOfGoods { ReceiptOfGoods() { } public static final String RECEIPT_OF_GOODS = "ZKDMOBWERET"; public static final String CODE = "WEGRND"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class MaterialMovement { MaterialMovement() { } public static final String MATRIAL_MOVEMENT = "ZKDMOBFZGMBEW"; public static final String GUID = "GUID"; public static final String ORDER_NUMBER = "EBELN"; public static final String ORDER_POSITION = "EBELP"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String MATERIAL_NUMBER = "MATNR"; public static final String FROM = "LGORT_FROM"; public static final String TO = "LGORT_TO"; public static final String ENTRY_COUNT = "ENTRY_QNT"; public static final String ENTRY_UNIT = "ENTRY_UOM"; public static final String RECEIPT_OF_GOODS = "WEGRND"; public static final String BARCODE = "BARC"; public static final String BARCODE_TEXT = "BARCTXT"; public static final String PERSONAL_NUMBER_CONFIRMED = "CONF_PERNR"; } public static final class DeliveryList { DeliveryList() { } public static final String DELIVERY_LIST = "ZKDMOBDELVRYLIST"; public static final String GUID = "GUID"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String ORDER_NUMBER = "EBELN"; public static final String ORDER_POSITION = "EBELP"; public static final String MATERIAL_NUMBER = "MATNR"; public static final String MATERIAL_NAME = "MAKTX"; public static final String FROM = "LGORT_FROM"; public static final String TO = "LGORT_TO"; public static final String WAREHOUSE = "LGKNZ"; public static final String ENTRY_COUNT = "ENTRY_QNT"; public static final String ENTRY_UNIT = "ENTRY_UOM"; public static final String DATE = "WADAK"; public static final String STATUS = "KNZDLVRY"; } }     common/src/ch/mfiles/kaba/kolibri/common/util/DeviceMirrorringHandler.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.IOException; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.util.Base64; import ch.mfiles.kaba.kolibri.common.CommonApplication; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.SimpleUserInterface; import ch.mfiles.kolibri.bu.BackupManager; import ch.mfiles.kolibri.bu.BackupMonitor; import ch.mfiles.kolibri.bu.RestoreMonitor; import ch.mfiles.kolibri.bu.RestorePoint; import ch.mfiles.kolibri.db.LocalTransaction; import ch.mfiles.kolibri.net.NotificationHandler; import ch.mfiles.kolibri.net.NotificationHandler.Token; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.SubProgressMonitor; /** * The coordinator (singleton) for device mirroring. * * @author Joerg * */ public class DeviceMirrorringHandler { private static final Log log = LogFactory.getLog(DeviceMirrorringHandler.class); /** singleton */ private static DeviceMirrorringHandler instance = null; public static DeviceMirrorringHandler getInstance() { if (instance == null) instance = new DeviceMirrorringHandler(); return instance; } private Registry m_reg; private DeviceMirrorringHandler() { m_reg = Runtime.getApplicationManager().getRegistry(CommonApplication.class.getName()); } private static final String MIRROR_STATE_ACTIVE = "active"; //$NON-NLS-1$ private static final String MIRROR_STATE_INACTIVE = "inactive"; //$NON-NLS-1$ private static final String MIRROR_STATE_NOT_SET = ""; //$NON-NLS-1$ public static interface DeleteAppDataFunction { /** * Delete all (user dependent) application data. * * @param ui UI to use to present dialogs (if any) * @return Returns true if data was deleted, false * otherwise (e.g. after user cancelled the deletion) */ public boolean deleteApplicationData(SimpleUserInterface ui); } /** * Returns the mirror state from the registry. * * @return */ private String getMirrorState() { return m_reg.getProperty("mirrorState"); //$NON-NLS-1$ } /** * Sets the mirror state in the registry. * * @param mirrorState */ private void setMirrorState(String mirrorState) { m_reg.setProperty("mirrorState", mirrorState); //$NON-NLS-1$ } /** * Returns true if the last activated user's data has been * destroyed since the device was released by the user, i.e. the device data * have changed since the last backup. * * @return */ private boolean isMirrorUserdataDeleted() { return m_reg.getBooleanProperty("mirrorUserdataState"); //$NON-NLS-1$ } /** * Sets the last acitve user's data to invalid, i.e. the user's backup * * @param deleted */ private void setMirrorUserdataDeleted(boolean deleted) { m_reg.setProperty("mirrorUserdataState", deleted); //$NON-NLS-1$ } /** * Informs the mirror handler, that the last active user's data have definitly * been destroyed. */ public void setMirrorUserdataDeleted() { setMirrorUserdataDeleted(true); } /** * Get the personal token id for the given username. * * @param username * @return */ private String getPersonalTokenId(String username) { return "P@" + username; //$NON-NLS-1$ } /** * Get the username from the given personal token id. * * @param tokenId * @return */ private String getUsername(String tokenId) { return tokenId.substring(2); } /** * Returns true if the given token id is used for personal push * tokens. * * @param tokenId * @return */ private boolean isPersonalTokenId(String tokenId) { return tokenId != null && tokenId.length() > 2 && tokenId.startsWith("P@"); //$NON-NLS-1$ } /** * Returns the given restorepoint encoded as a string for use in the token * remark. * * @param restorePoint * @return */ private String getRemarkFromRP(RestorePoint restorePoint) { StringBuilder sb = new StringBuilder(); sb.append("SNAPSHOT~"); //$NON-NLS-1$ sb.append(encodeBase64(restorePoint.getKolibriId())); sb.append('~'); sb.append(encodeBase64(restorePoint.getClientId())); sb.append('~'); sb.append(restorePoint.getBackupTime().getTime()); sb.append('~'); sb.append(encodeBase64(restorePoint.getTag())); return sb.toString(); } private String encodeBase64(String data) { byte[] encoded = Base64.encode(data.getBytes(Charset.forName("utf-8")), Base64.NO_WRAP); //$NON-NLS-1$ return new String(encoded, Charset.forName("ascii")); //$NON-NLS-1$ } private String decodeBase64(String data) { byte[] decoded = Base64.decode(data.getBytes(Charset.forName("ascii")), Base64.NO_WRAP); //$NON-NLS-1$ return new String(decoded, Charset.forName("utf-8")); //$NON-NLS-1$ } /** * Returns a restore point from the given token remark. * * @param remark * @return Returns the restore point corresponding to the given token remark or * null if the remark did not contain a restore point. * * @throws IllegalArgumentException Thrown if the the remark started with the * magic word but could not be successfully * decoded into a restore point. */ private RestorePoint getRPFromRemark(String remark) throws IllegalArgumentException { if (remark == null || !remark.startsWith("SNAPSHOT~")) //$NON-NLS-1$ return null; String tokens[] = remark.split("~"); //$NON-NLS-1$ if (tokens.length != 5) throw new IllegalArgumentException(Messages.getString("DeviceMirrorringHandler.0")); //$NON-NLS-1$ String kolibriId = decodeBase64(tokens[1]); String clientId = decodeBase64(tokens[2]); Date backupTime = new Date(Long.valueOf(tokens[3])); String tag = decodeBase64(tokens[4]); return newRestorePoint(backupTime, kolibriId, clientId, tag); } private RestorePoint newRestorePoint(final Date backupTime, final String kolibriId, final String clientId, final String tag) { return new RestorePoint() { @Override public String getTag() { return tag; } @Override public Date getBackupTime() { return backupTime; } @Override public String getKolibriId() { return kolibriId; } @Override public String getClientId() { return clientId; } @Override public String toString() { StringBuilder sb = new StringBuilder("RestorePoint[kolibriId=").append(kolibriId).append(", clientId=") //$NON-NLS-1$ //$NON-NLS-2$ .append(clientId).append(", backupTime=").append(backupTime).append(", tag=").append(tag) //$NON-NLS-1$ //$NON-NLS-2$ .append("]"); //$NON-NLS-1$ return sb.toString(); } }; } /** * Process the user login. *

* Must only be called on the AM thread! * * @param username * @param ui * @return Returns true if the application can be started. */ public boolean processLogin(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { String mirrorState = getMirrorState(); if (MIRROR_STATE_ACTIVE.equals(mirrorState)) return processLoginActive(username, ui, monitor, deleteApplicationData); else if (MIRROR_STATE_NOT_SET.equals(mirrorState)) return processLoginInitial(username, ui, monitor, deleteApplicationData); return processLoginInactive(username, ui, monitor, deleteApplicationData); } /** * Process the user login in state 'initial'. * * @param username * @param deleteApplicationData * @return Returns true if the application can be started. */ private boolean processLoginInitial(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { monitor.begin(Messages.getString("DeviceMirrorringHandler.1"), 6); //$NON-NLS-1$ log.info("Processing initial user login for user " + username); //$NON-NLS-1$ // synchronize push tokens with middleware monitor.comment(Messages.getString("DeviceMirrorringHandler.2")); //$NON-NLS-1$ NotificationHandler nh = Runtime.getNotificationHandler(); String syncError = nh.synchronizeAssignedTokens(); if (syncError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.3") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", syncError); //$NON-NLS-1$//$NON-NLS-2$ log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // set state to inactive and switch to inactive login if personal push tokens // are already assigned if (PersonalTokenState.NONE_ASSIGNED != getTokenState()) { log.info("Already tokens assigned -> switching to mirror state 'inactive' and inactive login"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); return processLoginInactive(username, ui, new SubProgressMonitor(monitor, 5), deleteApplicationData); } // retrieve the personal token attributes from middleware String userTokenId = getPersonalTokenId(username); monitor.comment(Messages.getString("DeviceMirrorringHandler.5")); //$NON-NLS-1$ Token userToken = null; try { userToken = nh.getToken(userTokenId); } catch (IOException e) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.7") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", e.getLocalizedMessage()); //$NON-NLS-1$//$NON-NLS-2$ log.error(msg, e); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // create the token if it doesn't exist and assign it to the runtime if (userToken == null) { log.info("Creating and assigning personal push token"); //$NON-NLS-1$ monitor.comment(Messages.getString("DeviceMirrorringHandler.8")); //$NON-NLS-1$ String createError = nh.requestToken(userTokenId, "created on login request"); //$NON-NLS-1$ if (createError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.10") //$NON-NLS-1$ + "\n(" + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", createError); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully created personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); monitor.completed(); return true; } // bail out if the personal token is assigned to another runtime if (!userToken.isAssignable()) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.11"), //$NON-NLS-1$ username, userToken.getKolibriId()); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // restore runtime if the token remark contains a restore point RestorePoint rp = null; try { rp = getRPFromRemark(userToken.getRemark()); } catch (IllegalArgumentException ex) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.13") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") //$NON-NLS-1$ + " ''{0}''", ex.getLocalizedMessage()); //$NON-NLS-1$ log.error(msg); log.info("Token remark: " + userToken.getRemark()); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // if personal user token contains a restore point, confirm possible data loss, // switch // to mirror state inactive and continue with inactive login if (rp != null) { log.info("Personal push token restore point: " + rp); //$NON-NLS-1$ if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox( Messages.getString("DeviceMirrorringHandler.15") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.16"), //$NON-NLS-1$ Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_WARNING)) { log.info("User aborted initial login"); //$NON-NLS-1$ return false; } log.info("User confirmed -> switching to mirror state 'inactive' and inactive login"); //$NON-NLS-1$ // set preliminary state 'inactive' setMirrorState(MIRROR_STATE_INACTIVE); return processLoginInactive(username, ui, new SubProgressMonitor(monitor, 3), deleteApplicationData); } monitor.worked(2); // request personal user token and set mirror state to active in a single db // transaction monitor.comment(Messages.getString("DeviceMirrorringHandler.17")); //$NON-NLS-1$ LocalTransaction trans = new LocalTransaction(Runtime.getApplicationManager().getDBSession()); try { String requestError = nh.requestToken(userTokenId, "requested by login"); //$NON-NLS-1$ if (requestError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.18") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", //$NON-NLS-1$ //$NON-NLS-2$ requestError); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully requested personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); trans.commit(); monitor.worked(1); } finally { if (trans.isPending()) trans.rollback(); } return true; } /** * Process the user login in state 'inactive'. * * @param username * @param deleteApplicationData * @return Returns true if the application can be started. */ private boolean processLoginInactive(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { monitor.begin(Messages.getString("DeviceMirrorringHandler.1"), 4); //$NON-NLS-1$ log.info("Processing inactive user login for user " + username); //$NON-NLS-1$ // synchronize push tokens with middleware monitor.comment(Messages.getString("DeviceMirrorringHandler.2")); //$NON-NLS-1$ NotificationHandler nh = Runtime.getNotificationHandler(); String syncError = nh.synchronizeAssignedTokens(); if (syncError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.20") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", syncError); //$NON-NLS-1$//$NON-NLS-2$ log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // handle already assigned tokens List assignedUsernames = getAssignedPersonalTokenUsernames(); // issue error if more than one personal token is assigned if (assignedUsernames.size() > 1) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.24"), //$NON-NLS-1$ getAssignedPersonalTokenUsernames()); log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // issue error if device seems to belong to another user if (assignedUsernames.size() == 1 && !assignedUsernames.get(0).equalsIgnoreCase(username)) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.26"), //$NON-NLS-1$ assignedUsernames.get(0)); log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // set state to active if logged in user is already assigned if (assignedUsernames.size() == 1) { log.info("User token already assigned -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); return true; } // retrieve the personal token attributes from middleware monitor.comment(Messages.getString("DeviceMirrorringHandler.28")); //$NON-NLS-1$ String userTokenId = getPersonalTokenId(username); Token userToken = null; try { userToken = nh.getToken(userTokenId); } catch (IOException e) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.23") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", e.getLocalizedMessage()); //$NON-NLS-1$//$NON-NLS-2$ log.error(msg, e); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // create the token if it doesn't exist and assign it to the runtime if (userToken == null) { log.info("Creating and assigning personal push token"); //$NON-NLS-1$ monitor.comment(Messages.getString("DeviceMirrorringHandler.31")); //$NON-NLS-1$ String createError = nh.requestToken(userTokenId, "created on login request"); //$NON-NLS-1$ if (createError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.27") //$NON-NLS-1$ + "\n(" + Messages.getString("DeviceMirrorringHandler.29") + " ''{0}'')", createError); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully created personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); monitor.completed(); return true; } // bail out if the personal token is already assigned (to another runtime) if (!userToken.isAssignable()) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.35"), //$NON-NLS-1$ userToken.getKolibriId()); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // restore runtime if the token remark contains a restore point RestorePoint rp = null; try { rp = getRPFromRemark(userToken.getRemark()); } catch (IllegalArgumentException ex) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.30") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") //$NON-NLS-1$ + " ''{0}''", ex.getLocalizedMessage()); //$NON-NLS-1$ log.error(msg); log.info("Token remark: " + userToken.getRemark()); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // trigger runtime restore if token remark contains a restore point otherwise // set mirror state to active if (rp == null) { log.info( "No restore point mentioned in user token remark -> deleting application data and skipping restore..."); //$NON-NLS-1$ if (!deleteApplicationData.deleteApplicationData(ui)) return false; monitor.worked(1); } else { // check if restore point corresponds to the last backup of the runtime -> // restore not necessary; otherwise restore to the remark's restore point BackupManager bm = Runtime.getBackupManager(); log.info("Personal push token restore point: " + rp); //$NON-NLS-1$ // set preliminary state 'inactive' log.info("preliminariliy switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); if (rp.getKolibriId().equals(Runtime.getTransactionHandler().getKolibriId()) && rp.getBackupTime().equals(bm.getLastBackupTS()) && !isMirrorUserdataDeleted()) { log.info("Restore point equals last backup snapshot -> no restore necessary"); //$NON-NLS-1$ monitor.worked(1); } else { // check restore point availability boolean rpAvailable = false; List availableRestorePoints; try { availableRestorePoints = bm.getRestorePoints(rp.getKolibriId()); } catch (IOException ex) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.34") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", ex.getLocalizedMessage()); //$NON-NLS-1$//$NON-NLS-2$ log.error(msg, ex); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } for (RestorePoint restorePoint : availableRestorePoints) { if (restorePoint.getBackupTime().equals(rp.getBackupTime())) { rpAvailable = true; break; } } // perform restore if restore point exists, delete application data otherwise if (!rpAvailable) { log.info( "Restore point doen't exist any more -> deleting application data and skipping restore..."); //$NON-NLS-1$ if (!deleteApplicationData.deleteApplicationData(ui)) return false; monitor.worked(1); } else { log.info("Restoring to restore point: " + rp); //$NON-NLS-1$ if (!restoreRuntime(rp, ui, new SubProgressMonitor(monitor, 1))) return false; } } } // request personal user token and set mirror state to active in a single db // transaction monitor.comment(Messages.getString("DeviceMirrorringHandler.41")); //$NON-NLS-1$ LocalTransaction trans = new LocalTransaction(Runtime.getApplicationManager().getDBSession()); try { String requestError = nh.requestToken(userTokenId, "requested by login"); //$NON-NLS-1$ if (requestError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.37") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", //$NON-NLS-1$ //$NON-NLS-2$ requestError); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully requested personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); trans.commit(); monitor.worked(1); } finally { if (trans.isPending()) trans.rollback(); } return true; } private boolean m_mirrorRestoreActive = false; private boolean restoreRuntime(RestorePoint rp, SimpleUserInterface ui, ProgressMonitor monitor) { String restoreMsg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.39") //$NON-NLS-1$ + "\n\n" + Messages.getString("DeviceMirrorringHandler.16"), //$NON-NLS-1$ //$NON-NLS-2$ rp.getKolibriId(), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(rp.getBackupTime())); if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox(restoreMsg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, SimpleUserInterface.MBOX_ICON_QUESTION)) { log.info("User canceled restore to personal push token restore point"); //$NON-NLS-1$ return false; } BackupManager bm = Runtime.getBackupManager(); try { // set mirror restore flag m_mirrorRestoreActive = true; RestoreMonitor rmon = bm.restore(rp, monitor); if (rmon.getErrorMessage() != null) { String msg; if (rmon.getMissingAppAD() != null) msg = Messages.getString("DeviceMirrorringHandler.9") + " " //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.14"); //$NON-NLS-1$ else if (rmon.getVersionMismatchAppAD() != null) msg = Messages.getString("DeviceMirrorringHandler.19") + " " //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.14"); //$NON-NLS-1$ else msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.42") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", //$NON-NLS-1$ //$NON-NLS-2$ rmon.getErrorMessage()); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } ui.inform(Messages.getString("DeviceMirrorringHandler.50")); //$NON-NLS-1$ return true; } finally { m_mirrorRestoreActive = false; } } /** * Set mirror state to 'inactive' if restoring in the context of a device * migration. * * @param monitor * @param restoredTables */ public void onDbRestored(RestoreMonitor monitor, Set restoredTables) { if (m_mirrorRestoreActive) { log.info("DB restore complete -> switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); } } /** * Process the user login in state 'active'. * * @param username * @param deleteApplicationData * @return Returns true if the application can be started. */ private boolean processLoginActive(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { log.info("Processing active user login for user " + username); //$NON-NLS-1$ // check if the authenticated user's personal push token is currently assigned NotificationHandler nh = Runtime.getNotificationHandler(); String userTokenId = getPersonalTokenId(username); List assignedTokens = nh.getAssignedTokens(); boolean userTokenAssigned = false; String assignedUser = null; for (Token token : assignedTokens) { if (isPersonalTokenId(token.getTokenId())) { assignedUser = getUsername(token.getTokenId()); if (userTokenId.equals(token.getTokenId())) { // user token already assigned userTokenAssigned = true; break; } } } if (!userTokenAssigned) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.51") + "\n\n" //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.53"), //$NON-NLS-1$ username, assignedUser); if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, SimpleUserInterface.MBOX_ICON_QUESTION)) { return false; } // release currently assigned user and do an inactive login for the logged in // user if (assignedUser != null) { log.info("Releasing currently assigned user " + assignedUser); //$NON-NLS-1$ monitor.begin(2); if (!releaseDevice(assignedUser, ui, new SubProgressMonitor(monitor, 1))) return false; } else { log.info("No user currently assigned!? -> switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); monitor.begin(1); } log.info("Performing inactive login for user " + username); //$NON-NLS-1$ return processLoginInactive(username, ui, new SubProgressMonitor(monitor, 1), deleteApplicationData); } log.info("Personal push token already assigned -> starting normal"); //$NON-NLS-1$ return true; } /** * Process the device release on behalv of the logged in user. * * @param username * @param ui * @return Returns true if the application was released * successfully. */ public boolean releaseDevice(String username, SimpleUserInterface ui, ProgressMonitor monitor) { log.info("Processing device release for user " + username); //$NON-NLS-1$ monitor.begin(Messages.getString("DeviceMirrorringHandler.55"), 4); //$NON-NLS-1$ // synchronize the push token list and make sure, that the authenticated // user's personal push token is still assigned monitor.comment(Messages.getString("DeviceMirrorringHandler.56")); //$NON-NLS-1$ NotificationHandler nh = Runtime.getNotificationHandler(); String syncError = nh.synchronizeAssignedTokens(); if (syncError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.44") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", //$NON-NLS-1$ //$NON-NLS-2$ syncError); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } List assignedTokens = nh.getAssignedTokens(); String personalTokenId = getPersonalTokenId(username); boolean personalTokenFound = false; for (Token token : assignedTokens) { if (personalTokenId.equalsIgnoreCase(token.getTokenId())) { personalTokenFound = true; break; } } if (!personalTokenFound || PersonalTokenState.MULTIPLE_ASSIGNED == getTokenState()) { String msg; if (!personalTokenFound) msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.59"), username); //$NON-NLS-1$ else msg = Messages.getString("DeviceMirrorringHandler.60"); //$NON-NLS-1$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // stop push notification delivery nh.stopReception(); try { // backup the runtime monitor.comment(Messages.getString("DeviceMirrorringHandler.62")); //$NON-NLS-1$ RestorePoint rp = backupRuntime(username, ui, monitor); if (rp == null) return false; monitor.worked(1); // release push tokens of other users monitor.comment(Messages.getString("DeviceMirrorringHandler.63")); //$NON-NLS-1$ // release the personal push token of the logged in user and // set mirror state to inactive in a single db transaction String userTokenId = getPersonalTokenId(username); LocalTransaction trans = new LocalTransaction(Runtime.getApplicationManager().getDBSession()); try { String remark = getRemarkFromRP(rp); String releaseError = nh.releaseToken(userTokenId, remark); setMirrorUserdataDeleted(false); log.info("Personal push token released -> switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); trans.commit(); if (releaseError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.48") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", releaseError); //$NON-NLS-1$ //$NON-NLS-2$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return true; } monitor.worked(1); monitor.completed(); return true; } finally { if (trans.isPending()) trans.rollback(); } } finally { // restart push notification reception nh.startReception(); } } private enum PersonalTokenState { /** * No personal push token assigned. */ NONE_ASSIGNED, /** * Exactly one personal push token assigned. */ ONE_ASSIGNED, /** * Multiple personal push tokens assigned. */ MULTIPLE_ASSIGNED } private PersonalTokenState getTokenState() { NotificationHandler nh = Runtime.getNotificationHandler(); List assignedTokens = nh.getAssignedTokens(); boolean tokenFound = false; for (Token token : assignedTokens) { if (!isPersonalTokenId(token.getTokenId())) continue; if (tokenFound) return PersonalTokenState.MULTIPLE_ASSIGNED; tokenFound = true; } if (tokenFound) return PersonalTokenState.ONE_ASSIGNED; return PersonalTokenState.NONE_ASSIGNED; } private List getAssignedPersonalTokenUsernames() { NotificationHandler nh = Runtime.getNotificationHandler(); ArrayList result = new ArrayList(); List assignedTokens = nh.getAssignedTokens(); for (Token token : assignedTokens) { if (isPersonalTokenId(token.getTokenId())) result.add(getUsername(token.getTokenId())); } return result; } private RestorePoint backupRuntime(String username, SimpleUserInterface ui, ProgressMonitor monitor) { if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox( MessageFormat.format(Messages.getString("DeviceMirrorringHandler.66") //$NON-NLS-1$ + "\n\n" + Messages.getString("DeviceMirrorringHandler.68"), //$NON-NLS-1$ //$NON-NLS-2$ username), Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_QUESTION)) { log.info("User canceled backup"); //$NON-NLS-1$ return null; } BackupManager bm = Runtime.getBackupManager(); String tag = "application release / device mirroring"; //$NON-NLS-1$ final BackupMonitor bmon = bm.backup(tag, new SubProgressMonitor(monitor, 1)); try { bmon.join(); } catch (InterruptedException e) { return null; } if (bmon.getErrorMessage() != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.52") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", //$NON-NLS-1$ //$NON-NLS-2$ bmon.getErrorMessage()); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return null; } ui.inform(Messages.getString("DeviceMirrorringHandler.72")); //$NON-NLS-1$ return newRestorePoint(bmon.getBackupStart(), Runtime.getTransactionHandler().getKolibriId(), Runtime.getLicenseAdapter().getClientId(), tag); } /** * Abort the running backup if the application is not in mirror state 'active'. * * @param monitor */ public void onCreateSnapshot(BackupMonitor monitor) { if (MIRROR_STATE_ACTIVE.equals(getMirrorState())) return; monitor.abort(Messages.getString("DeviceMirrorringHandler.73")); //$NON-NLS-1$ } }     common/src/ch/mfiles/kaba/kolibri/common/util/EnumUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.AddressType; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.InvoiceCode; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.JobPriority; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.JobStatusName; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.LoginMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.MessageRecipient; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.Month; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.NoSignatureReason; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.ReportSendType; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.Titel; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.VariousExpens; public class EnumUtil { public static final Log log = LogFactory.getLog(EnumUtil.class); private static EnumUtil instance = null; private DatabaseUtil dbutil; private EnumUtil() { } public static final EnumUtil getInstance(DatabaseUtil dbutil) { if (instance == null) { instance = new EnumUtil(); } instance.dbutil = dbutil; instance.initializeLocalizedTexts(); return instance; } public JobType jobTypeEnum; public JobStatusName jobStatusNameEnum; public JobPriority jobPriorityEnum; public Titel titelEnum; public AddressType addressTypeEnum; public NoSignatureReason noSignatureReasonEnum; public ReportSendType reportSendTypeEnum; public Month monthEnum; public MessageRecipient messageRecipientEnum; public VariousExpens variousExpensEnum; public InvoiceCode invoiceCodeEnum; public LoginMessage loginMessageEnum; private void initializeLocalizedTexts() { jobTypeEnum = new JobType(dbutil); jobStatusNameEnum = new JobStatusName(dbutil); jobPriorityEnum = new JobPriority(dbutil); titelEnum = new Titel(dbutil); addressTypeEnum = new AddressType(dbutil); noSignatureReasonEnum = new NoSignatureReason(dbutil); reportSendTypeEnum = new ReportSendType(dbutil); monthEnum = new Month(dbutil); messageRecipientEnum = new MessageRecipient(dbutil); variousExpensEnum = new VariousExpens(dbutil); invoiceCodeEnum = new InvoiceCode(dbutil); loginMessageEnum = new LoginMessage(dbutil); } }     common/src/ch/mfiles/kaba/kolibri/common/util/EvalTimeGenerator.jpage:   java.lang.String timeStamp = java.lang.String.valueOf(new java.util.Date().getTime()); java.lang.String time = ""; for (int i = 0; i < timeStamp.length(); i++) { time = time.concat("3").concat(timeStamp.substring(i, i+1)); } System.out.println(timeStamp + " / " + time);     common/src/ch/mfiles/kaba/kolibri/common/util/FileUtils.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Bitmap; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.Runtime; public class FileUtils { public static final Log log = LogFactory.getLog(FileUtils.class); /** * Gets the absolute folder path name for the given application. * @param applicationName * * @return absolute file path name */ public static String getAbsoluteAppPathName(String applicationName) { return Runtime.getInstallationFolder() + "/" //$NON-NLS-1$ + applicationName; } /** * Gets the absolute file path name. * * @param packageName * the package name * @param fileName * the file name * * @param createDir * set to True in order to automatically create the directory if * it doesn't exist yet * * * @return absolute file path name */ public static String getAbsoluteFilePathName(String applicationName, String packageName, String fileName, boolean createDir) { if (!createDir) { return getAbsoluteAppPathName(applicationName) + "/" //$NON-NLS-1$ + packageName + "/" + fileName; //$NON-NLS-1$ } else { String absoluteImagePathName = getAbsoluteAppPathName(applicationName) + "/" //$NON-NLS-1$ + packageName + "/" + fileName; //$NON-NLS-1$ FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(absoluteImagePathName); } catch (FileNotFoundException e) { log.error(e); if(log.isDebugEnabled()) log.debug("directory not found"); //$NON-NLS-1$ absoluteImagePathName = createDirectory(applicationName,packageName, fileName); if(log.isDebugEnabled()) log.debug("new directory /" //$NON-NLS-1$ + absoluteImagePathName + "/ created"); //$NON-NLS-1$ } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // ignore log.error(e); } } } return absoluteImagePathName; } } /** * Create all needed sub-directories and return CanonicalPath * * @param packageName * package name to be create the directory * @param fileName * file name to be create * @return the full file path name */ public static String createDirectory(String applicationName, String packageName, String fileName) { String destinationPath = getAbsoluteAppPathName(applicationName); // create the destination root directory if it doesn't exist yet File destinationRootDirectory = new File(destinationPath); destinationRootDirectory.mkdir(); File destinationFileDir = new File(destinationRootDirectory + "/" //$NON-NLS-1$ + packageName); // create all needed sub-directories destinationFileDir.mkdirs(); File destinationFile = null; try { destinationFile = new File(destinationFileDir.getCanonicalPath() + "/" + fileName); } catch (IOException e) { throw new ApplicationException(e); } try { destinationPath = destinationFile.getCanonicalPath(); } catch (IOException e) { throw new ApplicationException(e); } return destinationPath; } public static void writeFile(String filePath, String data) throws IOException { BufferedWriter writer = null; FileWriter fr = null; try { fr = new FileWriter(filePath); writer = new BufferedWriter(fr); writer.write(data); } finally { try { if (writer != null) { writer.close(); } if (fr != null) { fr.close(); } } catch (IOException e) { log.error(e); } } } /** * Extracts a file from the classpath and saves it to the filesystem in a * path relative to the installation directory. * * Each application has it's own base directory (Application) * * Note: Use getAbsoluteFilePathName to get the absolute path to the file * * @param Application * the base directory of the application * * @param packageName * the name of the package where the file is located * @param fileName * the relative name of the file */ public void extractFileFromJar(String Application, String packageName, String fileName) { if(log.isDebugEnabled()) log.debug("extractFileFromJar/" + packageName + "/" + fileName + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ InputStream inputStream = getClass().getClassLoader() .getResourceAsStream(packageName + "/" + fileName); //$NON-NLS-1$ if (inputStream == null) throw new ApplicationException(MessageFormat.format( Messages.getString("FileUtils_0"), //$NON-NLS-1$ new Object[] { packageName + "/" + fileName })); //$NON-NLS-1$ FileOutputStream outputStream = null; try { String absoluteFilePathName = getAbsoluteFilePathName(Application, packageName, fileName, true); outputStream = new FileOutputStream(absoluteFilePathName); if(log.isDebugEnabled()) log.debug(MessageFormat.format("extracting {0} to {1}", //$NON-NLS-1$ new Object[] { packageName + "/" + fileName, //$NON-NLS-1$ absoluteFilePathName })); int aByte = 0; // write byte by byte while ((aByte = inputStream.read()) != -1) { outputStream.write(aByte); } } catch (IOException e) { throw new ApplicationException(e); } finally { try { inputStream.close(); } catch (IOException e) { log.error(e); // ignore } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { log.error(e); // ignore } } } } public static class Packages { public static final String DATA = "data"; //$NON-NLS-1$ } public static class FileNames { public static final String FIXED_MASTERDATA = "fixed-master-data.txt"; //$NON-NLS-1$ } public static void writeBitmapToFile(String imagePath, Bitmap bitmap) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); File myCaptureFile = new File(imagePath); FileOutputStream fi; fi = new FileOutputStream(myCaptureFile); baos.writeTo(fi); baos.flush(); baos.close(); int fileSize = baos.toByteArray().length / 1024; log.info("after compressed size: " + fileSize + " Kb"); log.info("path : " + myCaptureFile.getAbsolutePath()); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } } }     common/src/ch/mfiles/kaba/kolibri/common/util/FormUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import android.R; import android.content.Context; import android.content.res.TypedArray; public class FormUtil { private Context context; public FormUtil(Context context) { this.context = context; } public int getDisplayHeight() { return context.getResources().getDisplayMetrics().heightPixels; } public int getDisplayWidth() { return context.getResources().getDisplayMetrics().widthPixels; } public int getFormHeight() { return getDisplayHeight() - getStatusBarHeight() - getToolBarHeight(); } public int getStatusBarHeight() { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } public int getToolBarHeight() { int[] attrs = new int[] { R.attr.actionBarSize }; TypedArray ta = context.obtainStyledAttributes(attrs); int toolBarHeight = ta.getDimensionPixelSize(0, -1); ta.recycle(); return toolBarHeight; } public int getNavigationBarHeight() { int navigationBarHeight = 0; int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navigationBarHeight = context.getResources().getDimensionPixelSize(resourceId); } return navigationBarHeight; } }     common/src/ch/mfiles/kaba/kolibri/common/util/GuidGenerator.java:   package ch.mfiles.kaba.kolibri.common.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.os.StrictMode; /** * * Just a temporary solution, not sure if there is a better approach for this ... * * 1. (0-7) IPAddress as HEX - 8 bytes * 2. (8-19) CurrentTimeMillis() as HEX - Display all 12 bytes * 3. (20-23) SecureRandom() as HEX - Keep only 4 significant bytes. Since this is "random" it doesn't really matter how many bytes you keep or eliminate * 4. (24-31) System.identityHashCode as Hex - 8 bytes * * * @author Administrator * */ public class GuidGenerator { private static Log log = LogFactory.getLog(GuidGenerator.class); /** * Generates a 32 byte GUID * @return * @throws UnknownHostException * @throws NoSuchAlgorithmException */ public String generate() throws UnknownHostException, NoSuchAlgorithmException { String result = ""; //$NON-NLS-1$ String temp; /* * for solve exception: * android.os.NetworkOnMainThreadException * android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303) * * see "[MIG-52] implement of "search job"" also * see this link:"http://stackoverflow.com/questions/13136539/caused-by-android-os-networkonmainthreadexception" */ if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Get IPAddress Segment InetAddress addr = InetAddress.getLocalHost(); if(log.isDebugEnabled()) log.debug("IP /" + addr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ byte[] ipaddr = addr.getAddress(); for (int i = 0; i < ipaddr.length; i++) { Byte b = new Byte(ipaddr[i]); temp = Integer.toHexString(b.intValue() & 0x000000ff); while (temp.length() < 2) { temp = '0' + temp; } result += temp; } // Get CurrentTimeMillis() segment temp = Long.toHexString(System.currentTimeMillis()); while (temp.length() < 12) { temp = '0' + temp; } result += temp; // Get Random Segment SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$ temp = Integer.toHexString(prng.nextInt()); while (temp.length() < 8) { temp = '0' + temp; } result += temp.substring(4); // Get IdentityHash() segment temp = Long.toHexString(System.identityHashCode((Object) this)); while (temp.length() < 8) { temp = '0' + temp; } result += temp; return result.toUpperCase(); } public String getIP() throws UnknownHostException{ return InetAddress.getLocalHost().toString(); } public static void main(String[] args) throws Exception { log.info(new GuidGenerator().generate()); } }     common/src/ch/mfiles/kaba/kolibri/common/util/HTMLEncode.java:   package ch.mfiles.kaba.kolibri.common.util; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.ApplicationException; /* * Java HTML Tidy - JTidy * HTML parser and pretty printer * * Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts * Institute of Technology, Institut National de Recherche en * Informatique et en Automatique, Keio University). All Rights * Reserved. * * Contributing Author(s): * * Dave Raggett * Andy Quick (translation to Java) * Gary L Peskin (Java development) * Sami Lempinen (release management) * Fabrizio Giustina * Vlad Skarzhevskyy (JTidy servlet development) * * The contributing author(s) would like to thank all those who * helped with testing, bug fixes, and patience. This wouldn't * have been possible without all of you. * * COPYRIGHT NOTICE: * * This software and documentation is provided "as is," and * the copyright holders and contributing author(s) make no * representations or warranties, express or implied, including * but not limited to, warranties of merchantability or fitness * for any particular purpose or that the use of the software or * documentation will not infringe any third party patents, * copyrights, trademarks or other rights. * * The copyright holders and contributing author(s) will not be * liable for any direct, indirect, special or consequential damages * arising out of any use of the software or documentation, even if * advised of the possibility of such damage. * * Permission is hereby granted to use, copy, modify, and distribute * this source code, or portions hereof, documentation and executables, * for any purpose, without fee, subject to the following restrictions: * * 1. The origin of this source code must not be misrepresented. * 2. Altered versions must be plainly marked as such and must * not be misrepresented as being the original source. * 3. This Copyright notice may not be removed or altered from any * source or altered source distribution. * * The copyright holders and contributing author(s) specifically * permit, without fee, and encourage the use of this source code * as a component for supporting the Hypertext Markup Language in * commercial products. If you use this source code in a product, * acknowledgment is not required but would be appreciated. * */ /** * Converts a String to HTML by converting all special characters to HTML-entities. * @author Vlad Skarzhevskyy skarzhevskyy@gmail.com * @version $Revision: 1.2 $ ($Author: bpauli $) */ public class HTMLEncode { /** * j2se 1.4 encode method, used by reflection if available. */ private static Method encodeMethod14; public static final Log log = LogFactory.getLog(HTMLEncode.class); static { // URLEncoder.encode(String) has been deprecated in J2SE 1.4. // Take advantage of the new method URLEncoder.encode(String, enc) if J2SE 1.4 is used. try { Class urlEncoderClass = Class.forName("java.net.URLEncoder"); //$NON-NLS-1$ encodeMethod14 = urlEncoderClass.getMethod("encode", new Class[]{String.class, String.class}); //$NON-NLS-1$ } catch (Exception ex) { // encodeMethod14 will be null if exception log.error(ex); } } /** * Utility class, don't instantiate. */ private HTMLEncode() { // unused } private static final String[] ENTITIES = { ">", //$NON-NLS-1$ ">", //$NON-NLS-1$ "<", //$NON-NLS-1$ "<", //$NON-NLS-1$ "&", //$NON-NLS-1$ "&", //$NON-NLS-1$ "\"", //$NON-NLS-1$ """, //$NON-NLS-1$ "'", //$NON-NLS-1$ "'", //$NON-NLS-1$ "\\", //$NON-NLS-1$ "\", //$NON-NLS-1$ "\u00a9", //$NON-NLS-1$ "©", //$NON-NLS-1$ "\u00ae", //$NON-NLS-1$ "®"}; //$NON-NLS-1$ private static HashMap entityTableEncode = null; protected static synchronized void buildEntityTables() { entityTableEncode = new HashMap(ENTITIES.length); for (int i = 0; i < ENTITIES.length; i += 2) { if (!entityTableEncode.containsKey(ENTITIES[i])) { entityTableEncode.put(ENTITIES[i], ENTITIES[i + 1]); } } } /** * Converts a String to HTML by converting all special characters to HTML-entities. */ public final static String encode(String s) { return encode(s, "\n"); //$NON-NLS-1$ } /** * Converts a String to HTML by converting all special characters to HTML-entities. */ public final static String encode(String s, String cr) { if (entityTableEncode == null) { buildEntityTables(); } if (s == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(s.length() * 2); char ch; for (int i = 0; i < s.length(); ++i) { ch = s.charAt(i); if ((ch >= 63 && ch <= 90) || (ch >= 97 && ch <= 122) || (ch == ' ')) { sb.append(ch); } else if (ch == '\n') { sb.append(cr); } else { String chEnc = encodeSingleChar(String.valueOf(ch)); if (chEnc != null) { sb.append(chEnc); } else { // Not 7 Bit use the unicode system sb.append("&#"); //$NON-NLS-1$ sb.append(ch); sb.append(';'); } } } return sb.toString(); } /** * Converts a single character to HTML */ private static String encodeSingleChar(String ch) { return entityTableEncode.get(ch); } /** * Converts a String to valid HTML HREF by converting all special characters to HTML-entities. * @param url url to be encoded * @return encoded url. */ protected static String encodeHREFParam(String url) { if (encodeMethod14 != null) { Object[] methodArgs = new Object[2]; methodArgs[0] = url; methodArgs[1] = "UTF8"; //$NON-NLS-1$ try { return (String) encodeMethod14.invoke(null, methodArgs); } catch (Exception e) { log.error(e); throw new ApplicationException(Messages.getString("HTMLEncode_0") + e); //$NON-NLS-1$ } } // must use J2SE 1.3 version return URLEncoder.encode(url); } protected static String encodeHREFParamJava13(String value) { return URLEncoder.encode(value); } public static String encodeQuery(String url, String[] args) { return encodeHREFQuery(url, args, false); } public static String encodeHREFQuery(String url, String[] args) { return encodeHREFQuery(url, args, true); } public static String encodeHREFQuery(String url, String[] args, boolean forHtml) { StringBuilder out = new StringBuilder(128); out.append(url); if ((args != null) && (args.length > 0)) { out.append("?"); //$NON-NLS-1$ for (int i = 0; i < (args.length + 1) / 2; i++) { int k = i * 2; if (k != 0) { if (forHtml) { out.append("&"); //$NON-NLS-1$ } else { out.append("&"); //$NON-NLS-1$ } } out.append(encodeHREFParam(args[k])); if (k + 1 < args.length) { out.append("="); //$NON-NLS-1$ out.append(encodeHREFParam(args[k + 1])); } } } return out.toString(); } public static String encodeHREFQuery(String url, Map args, boolean forHtml) { StringBuilder out = new StringBuilder(128); out.append(url); if ((args != null) && (args.size() > 0)) { out.append("?"); //$NON-NLS-1$ int k = 0; for (Iterator i = args.keySet().iterator(); i.hasNext();) { if (k != 0) { if (forHtml) { out.append("&"); //$NON-NLS-1$ } else { out.append("&"); //$NON-NLS-1$ } } String name = (String) i.next(); out.append(encodeHREFParam(name)); out.append("="); //$NON-NLS-1$ out.append(encodeHREFParam((String) args.get(name))); k++; } } return out.toString(); } }     common/src/ch/mfiles/kaba/kolibri/common/util/HtmlUtil.java:   package ch.mfiles.kaba.kolibri.common.util; public class HtmlUtil { private StringBuilder mHeadStringBuilder = new StringBuilder(); private StringBuilder mCSSStringBuilder = new StringBuilder(); private StringBuilder mHtmlStringBuilder = new StringBuilder(); private StringBuilder mTableStringBuilder = new StringBuilder(); private StringBuilder mRowsStringBuilder = new StringBuilder(); private StringBuilder mBodyStringBuilder = new StringBuilder(); private String mTitle=""; //$NON-NLS-1$ private String mBackgroundColour=""; //$NON-NLS-1$ private String mTextcolour=""; //$NON-NLS-1$ private int mFontSize; public HtmlUtil(){ this.setBackgroundColour("#2554C7"); //$NON-NLS-1$ this.setFontSize(10); this.setTextColour("white"); //$NON-NLS-1$ } public HtmlUtil(HtmlUtil htmlUtil) { this.setBackgroundColour(htmlUtil.getBackgroundColour()); this.setFontSize(htmlUtil.getFontSize()); this.setTextColour(htmlUtil.getTextcolour()); this.setTitle(htmlUtil.getTitle()); } public int getFontSize() { return mFontSize; } public void setFontSize(int fontSize) { mFontSize = fontSize; } private void generateHtml(){ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""+mTitle+""); //$NON-NLS-1$ //$NON-NLS-2$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(HTMLEncode.encode(mHeadStringBuilder.toString())); mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ } private void endHtml(){ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ } public void setbody(String body){ mBodyStringBuilder.append(body); } public void generateTable(String width, int border, int cellspacing, int cellpadding){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ mTableStringBuilder.append(mRowsStringBuilder.toString()); mHtmlStringBuilder.append(""); //$NON-NLS-1$ } public void generateTable(String width, int border, int cellspacing, int cellpadding, String option){ mTableStringBuilder.append("
"); //$NON-NLS-1$ mTableStringBuilder.append(mRowsStringBuilder.toString()); mHtmlStringBuilder.append(""); //$NON-NLS-1$ } public void appendRow(String option ){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ } public void appendRow(){ mTableStringBuilder.append(""); //$NON-NLS-1$ } public void endRow(){ mTableStringBuilder.append(""); //$NON-NLS-1$ } public void appendColumn(String text, String option ){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void appendColumn(String text){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ } public void endTable(){ mTableStringBuilder.append("
" + text + "" + text + "
"); //$NON-NLS-1$ mBodyStringBuilder.append(mTableStringBuilder.toString()); } public String getHtml(){ generateHtml(); mHtmlStringBuilder.append(mBodyStringBuilder.toString()); endHtml(); return mHtmlStringBuilder.toString(); } public void setTitle(String title){ mTitle = title; } public String getTitle(){ return mTitle; } public String getTextcolour() { return mTextcolour; } public void setTextColour(String textcolour) { mTextcolour = textcolour; } public String getBackgroundColour() { return mBackgroundColour; } public void setBackgroundColour(String backgroundColour) { mBackgroundColour = backgroundColour; } public StringBuilder getCSSStringBuilder() { return mCSSStringBuilder; } public void setCSSStringBuilder(StringBuilder StringBuilder) { mCSSStringBuilder = StringBuilder; } public StringBuilder getHeadStringBuilder() { return mHeadStringBuilder; } public void setHeadStringBuilder(StringBuilder headStringBuilder) { mHeadStringBuilder = headStringBuilder; } public String replaceHtmlWhiteSpace(String text){ if(text.length() == 0){ return " "; //$NON-NLS-1$ }else{ return text; } } }     common/src/ch/mfiles/kaba/kolibri/common/util/ImageHeaderParser.java:   package ch.mfiles.kaba.kolibri.common.util; import android.media.ExifInterface; import android.text.TextUtils; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; /** * A class for parsing the exif orientation from an image header. */ public class ImageHeaderParser { private static final String TAG = "ImageHeaderParser"; /** * A constant indicating we were unable to parse the orientation from the image either because * no exif segment containing orientation data existed, or because of an I/O error attempting to * read the exif segment. */ public static final int UNKNOWN_ORIENTATION = -1; private static final int EXIF_MAGIC_NUMBER = 0xFFD8; // "MM". private static final int MOTOROLA_TIFF_MAGIC_NUMBER = 0x4D4D; // "II". private static final int INTEL_TIFF_MAGIC_NUMBER = 0x4949; private static final String JPEG_EXIF_SEGMENT_PREAMBLE = "Exif\0\0"; private static final byte[] JPEG_EXIF_SEGMENT_PREAMBLE_BYTES = JPEG_EXIF_SEGMENT_PREAMBLE.getBytes(Charset.forName("UTF-8")); private static final int SEGMENT_SOS = 0xDA; private static final int MARKER_EOI = 0xD9; private static final int SEGMENT_START_ID = 0xFF; private static final int EXIF_SEGMENT_TYPE = 0xE1; private static final int ORIENTATION_TAG_TYPE = 0x0112; private static final int[] BYTES_PER_FORMAT = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; private final Reader reader; public ImageHeaderParser(InputStream is) { reader = new StreamReader(is); } /** * Parse the orientation from the image header. If it doesn't handle this image type (or this is * not an image) it will return a default value rather than throwing an exception. * * @return The exif orientation if present or -1 if the header couldn't be parsed or doesn't * contain an orientation * @throws IOException */ public int getOrientation() throws IOException { final int magicNumber = reader.getUInt16(); if (!handles(magicNumber)) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Parser doesn't handle magic number: " + magicNumber); } return UNKNOWN_ORIENTATION; } else { int exifSegmentLength = moveToExifSegmentAndGetLength(); if (exifSegmentLength == -1) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Failed to parse exif segment length, or exif segment not found"); } return UNKNOWN_ORIENTATION; } byte[] exifData = new byte[exifSegmentLength]; return parseExifSegment(exifData, exifSegmentLength); } } private int parseExifSegment(byte[] tempArray, int exifSegmentLength) throws IOException { int read = reader.read(tempArray, exifSegmentLength); if (read != exifSegmentLength) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to read exif segment data" + ", length: " + exifSegmentLength + ", actually read: " + read); } return UNKNOWN_ORIENTATION; } boolean hasJpegExifPreamble = hasJpegExifPreamble(tempArray, exifSegmentLength); if (hasJpegExifPreamble) { return parseExifSegment(new RandomAccessReader(tempArray, exifSegmentLength)); } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Missing jpeg exif preamble"); } return UNKNOWN_ORIENTATION; } } private boolean hasJpegExifPreamble(byte[] exifData, int exifSegmentLength) { boolean result = exifData != null && exifSegmentLength > JPEG_EXIF_SEGMENT_PREAMBLE_BYTES.length; if (result) { for (int i = 0; i < JPEG_EXIF_SEGMENT_PREAMBLE_BYTES.length; i++) { if (exifData[i] != JPEG_EXIF_SEGMENT_PREAMBLE_BYTES[i]) { result = false; break; } } } return result; } /** * Moves reader to the start of the exif segment and returns the length of the exif segment or * {@code -1} if no exif segment is found. */ private int moveToExifSegmentAndGetLength() throws IOException { short segmentId, segmentType; int segmentLength; while (true) { segmentId = reader.getUInt8(); if (segmentId != SEGMENT_START_ID) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unknown segmentId=" + segmentId); } return -1; } segmentType = reader.getUInt8(); if (segmentType == SEGMENT_SOS) { return -1; } else if (segmentType == MARKER_EOI) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Found MARKER_EOI in exif segment"); } return -1; } // Segment length includes bytes for segment length. segmentLength = reader.getUInt16() - 2; if (segmentType != EXIF_SEGMENT_TYPE) { long skipped = reader.skip(segmentLength); if (skipped != segmentLength) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to skip enough data" + ", type: " + segmentType + ", wanted to skip: " + segmentLength + ", but actually skipped: " + skipped); } return -1; } } else { return segmentLength; } } } private static int parseExifSegment(RandomAccessReader segmentData) { final int headerOffsetSize = JPEG_EXIF_SEGMENT_PREAMBLE.length(); short byteOrderIdentifier = segmentData.getInt16(headerOffsetSize); final ByteOrder byteOrder; if (byteOrderIdentifier == MOTOROLA_TIFF_MAGIC_NUMBER) { byteOrder = ByteOrder.BIG_ENDIAN; } else if (byteOrderIdentifier == INTEL_TIFF_MAGIC_NUMBER) { byteOrder = ByteOrder.LITTLE_ENDIAN; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unknown endianness = " + byteOrderIdentifier); } byteOrder = ByteOrder.BIG_ENDIAN; } segmentData.order(byteOrder); int firstIfdOffset = segmentData.getInt32(headerOffsetSize + 4) + headerOffsetSize; int tagCount = segmentData.getInt16(firstIfdOffset); int tagOffset, tagType, formatCode, componentCount; for (int i = 0; i < tagCount; i++) { tagOffset = calcTagOffset(firstIfdOffset, i); tagType = segmentData.getInt16(tagOffset); // We only want orientation. if (tagType != ORIENTATION_TAG_TYPE) { continue; } formatCode = segmentData.getInt16(tagOffset + 2); // 12 is max format code. if (formatCode < 1 || formatCode > 12) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got invalid format code = " + formatCode); } continue; } componentCount = segmentData.getInt32(tagOffset + 4); if (componentCount < 0) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Negative tiff component count"); } continue; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got tagIndex=" + i + " tagType=" + tagType + " formatCode=" + formatCode + " componentCount=" + componentCount); } final int byteCount = componentCount + BYTES_PER_FORMAT[formatCode]; if (byteCount > 4) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got byte count > 4, not orientation, continuing, formatCode=" + formatCode); } continue; } final int tagValueOffset = tagOffset + 8; if (tagValueOffset < 0 || tagValueOffset > segmentData.length()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Illegal tagValueOffset=" + tagValueOffset + " tagType=" + tagType); } continue; } if (byteCount < 0 || tagValueOffset + byteCount > segmentData.length()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Illegal number of bytes for TI tag data tagType=" + tagType); } continue; } //assume componentCount == 1 && fmtCode == 3 return segmentData.getInt16(tagValueOffset); } return -1; } private static int calcTagOffset(int ifdOffset, int tagIndex) { return ifdOffset + 2 + 12 * tagIndex; } private static boolean handles(int imageMagicNumber) { return (imageMagicNumber & EXIF_MAGIC_NUMBER) == EXIF_MAGIC_NUMBER || imageMagicNumber == MOTOROLA_TIFF_MAGIC_NUMBER || imageMagicNumber == INTEL_TIFF_MAGIC_NUMBER; } private static class RandomAccessReader { private final ByteBuffer data; public RandomAccessReader(byte[] data, int length) { this.data = (ByteBuffer) ByteBuffer.wrap(data) .order(ByteOrder.BIG_ENDIAN) .limit(length); } public void order(ByteOrder byteOrder) { this.data.order(byteOrder); } public int length() { return data.remaining(); } public int getInt32(int offset) { return data.getInt(offset); } public short getInt16(int offset) { return data.getShort(offset); } } private interface Reader { int getUInt16() throws IOException; short getUInt8() throws IOException; long skip(long total) throws IOException; int read(byte[] buffer, int byteCount) throws IOException; } private static class StreamReader implements Reader { private final InputStream is; // Motorola / big endian byte order. public StreamReader(InputStream is) { this.is = is; } @Override public int getUInt16() throws IOException { return (is.read() << 8 & 0xFF00) | (is.read() & 0xFF); } @Override public short getUInt8() throws IOException { return (short) (is.read() & 0xFF); } @Override public long skip(long total) throws IOException { if (total < 0) { return 0; } long toSkip = total; while (toSkip > 0) { long skipped = is.skip(toSkip); if (skipped > 0) { toSkip -= skipped; } else { // Skip has no specific contract as to what happens when you reach the end of // the stream. To differentiate between temporarily not having more data and // having finished the stream, we read a single byte when we fail to skip any // amount of data. int testEofByte = is.read(); if (testEofByte == -1) { break; } else { toSkip--; } } } return total - toSkip; } @Override public int read(byte[] buffer, int byteCount) throws IOException { int toRead = byteCount; int read; while (toRead > 0 && ((read = is.read(buffer, byteCount - toRead, toRead)) != -1)) { toRead -= read; } return byteCount - toRead; } } public static void copyExif(ExifInterface originalExif, int width, int height, String imageOutputPath) { String[] attributes = new String[]{ ExifInterface.TAG_APERTURE, ExifInterface.TAG_DATETIME, ExifInterface.TAG_DATETIME_DIGITIZED, ExifInterface.TAG_EXPOSURE_TIME, ExifInterface.TAG_FLASH, ExifInterface.TAG_FOCAL_LENGTH, ExifInterface.TAG_GPS_ALTITUDE, ExifInterface.TAG_GPS_ALTITUDE_REF, ExifInterface.TAG_GPS_DATESTAMP, ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LATITUDE_REF, ExifInterface.TAG_GPS_LONGITUDE, ExifInterface.TAG_GPS_LONGITUDE_REF, ExifInterface.TAG_GPS_PROCESSING_METHOD, ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_ISO, ExifInterface.TAG_MAKE, ExifInterface.TAG_MODEL, ExifInterface.TAG_SUBSEC_TIME, ExifInterface.TAG_SUBSEC_TIME_DIG, ExifInterface.TAG_SUBSEC_TIME_ORIG, ExifInterface.TAG_WHITE_BALANCE }; try { ExifInterface newExif = new ExifInterface(imageOutputPath); String value; for (String attribute : attributes) { value = originalExif.getAttribute(attribute); if (!TextUtils.isEmpty(value)) { newExif.setAttribute(attribute, value); } } newExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, String.valueOf(width)); newExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, String.valueOf(height)); newExif.setAttribute(ExifInterface.TAG_ORIENTATION, "0"); newExif.saveAttributes(); } catch (IOException e) { Log.d(TAG, e.getMessage()); } } }     common/src/ch/mfiles/kaba/kolibri/common/util/ImagesUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ui.Image; public class ImagesUtil { public static final Log log = LogFactory.getLog(ImagesUtil.class); private static ImagesUtil instance = null; private Application app; private ImagesUtil() { } public static final ImagesUtil getInstance(Application application) { if (instance == null) { instance = new ImagesUtil(); } instance.app = application; return instance; } public ImagesUtil(Application application) { app = application; } public static enum Images { ADD_BLACK , START_TIME_DISABLED , START_TIME , STOP_TIME , SEND_DISABLED_BLACK , SEND_BLACK , SEND_WHITE , DELETE_DISABLED_BLACK , DELETE_BLACK , EDIT , PHONE_DISABLED , PHONE , EMAIL_DISABLED , EMAIL , EXIT_DISABLED , EXIT , CONTACT_PHONE_DISABLED , CONTACT_PHONE , LIST_DISABLED , LIST , SETTING_DISABLED , SETTING , UPDATE_DISABLED , UPDATE , HELP_DISABLED , HELP , INFO_DISABLED , INFO , INFO_WHITH , SUPERVISOR_ACCOUNT_DISABLED , SUPERVISOR_ACCOUNT , SETTING_APP_DISABLED , SETTING_APP , SYSTEM_UPDATE_DISABLED , SYSTEM_UPDATE , INFORMATION_DISABLED , INFORMATION , SAVE_WHITE , SAVE_WHITE_DISABLED , BACK_WHITE , BACK_WHITE_DISABLED , DOWNLOAD_DISABLED_BLACK , DOWNLOAD_BLACK , DOWNLOAD_WHITE , CLOSE_WHITE , SEARCH_WHITE , ASSIGNMENT_IND_DISABLED , ASSIGNMENT_IND , ASSIGNMENT_TURNED_IN_DISABLED , ASSIGNMENT_TURNED_IN , SIGNATURE_DISABLED_BLACK , SIGNATURE_BLACK , SIGNATURE_WHITE , RESTORE_BLACK , RESTORE_WHITE , YOUTUBE_SEARCHED_BLACK , YOUTUBE_SEARCHED_WHITE , ADD_WHITE , DELETE_WHITE , CAMERA_BLACK , CAMERA_WHITE , SEND_DISABLED_WHITE , PLAY_WITH_CIRCLE , PAGE_VIEW_DISABLED_BLACK , PAGE_VIEW_BLACK , PAGE_VIEW_WHITE , INFO_OUTLINE_BLACK , INFO_OUTLINE_DISABLED_BLACK , INFO_OUTLINE_WHITE , MENU , MENU_WHITE , ADD_DISABLED_WHITE , DELETE_DISABLED_WHITE , CAMERA_DISABLED_WHITE , ALARM_BLACK , ALARM_RED , PHOTO_LIBRARY_BLACK , PICTURE_AS_PDF_BLACK , SCHEDULE_BLACK , SCHEDULE_DISABLED_BLACK , CHECK_SOME , CHECK_CHECKED , CHECK_UNCHECKED , CHECK , CHECK_WHITE , DOWNLOAD_SUCCESS , DOWNLOAD_ERROR , DONE_BLACK , DONE_WHITE , REMOTE_BLACK , ABSENCE_BLACK , OFFLINE_SHARE , SEARCH_FILE_BLACK , SEARCH_FILE_DISABLED , ADD_PHOTO_BLACK , WRENCH_BLACK , WRENCH_DISABLED , UPDATE_WHITE , SHOPPING_CART_BLACK , SHOPPING_CART_DISABLED , SHOPPING_CART_WHITE , TRUCK_BLACK , TRUCK_WHITE , SHOPPING_CART_ADD_BLACK , SHOPPING_CART_ADD_DISABLED , SHOPPING_CART_ADD_WHITE , CAMERA_DISABLED_BLACK } public Image getImage(Images image) { return getImage(image, null); } public Image getImage(Images image, Integer dpi){ Image result = null; switch (image) { case ADD_BLACK: return setImageDpi("images/ic_add_black_24dp.png", dpi); //$NON-NLS-1$ case BACK_WHITE: return setImageDpi("images/ic_arrow_back_white_48dp.png", dpi); //$NON-NLS-1$ case BACK_WHITE_DISABLED: return setImageDpi("images/ic_arrow_back_white_disabled_48dp.png", dpi); //$NON-NLS-1$ case START_TIME_DISABLED: return setImageDpi("images/ic_play_arrow_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case START_TIME: return setImageDpi("images/ic_play_arrow_black_24dp.png", dpi); //$NON-NLS-1$ case STOP_TIME: return setImageDpi("images/ic_stop_black_24dp.png", dpi); //$NON-NLS-1$ case CLOSE_WHITE: return setImageDpi("images/ic_clear_white_48dp.png", dpi); //$NON-NLS-1$ case SAVE_WHITE: return setImageDpi("images/ic_save_white_48dp.png", dpi); //$NON-NLS-1$ case SAVE_WHITE_DISABLED: return setImageDpi("images/ic_save_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case SEND_DISABLED_BLACK: return setImageDpi("images/ic_send_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SEND_BLACK: return setImageDpi("images/ic_send_black_24dp.png", dpi); //$NON-NLS-1$ case SEND_WHITE: return setImageDpi("images/ic_send_white_24dp.png", dpi); //$NON-NLS-1$ case SEND_DISABLED_WHITE: return setImageDpi("images/ic_send_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case DELETE_DISABLED_BLACK: return setImageDpi("images/ic_delete_forever_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case DELETE_BLACK: return setImageDpi("images/ic_delete_forever_black_24dp.png", dpi); //$NON-NLS-1$ case EDIT: return setImageDpi("images/ic_mode_edit_black_24dp.png", dpi); //$NON-NLS-1$ case SEARCH_WHITE: return setImageDpi("images/ic_search_white_24dp.png", dpi); //$NON-NLS-1$ case PHONE_DISABLED: return setImageDpi("images/ic_phone_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case PHONE: return setImageDpi("images/ic_phone_black_24dp.png", dpi); //$NON-NLS-1$ case CONTACT_PHONE_DISABLED: return setImageDpi("images/ic_contact_phone_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case CONTACT_PHONE: return setImageDpi("images/ic_contact_phone_black_24dp.png", dpi); //$NON-NLS-1$ case EMAIL_DISABLED: return setImageDpi("images/ic_email_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case EMAIL: return setImageDpi("images/ic_email_black_24dp.png", dpi); //$NON-NLS-1$ case EXIT_DISABLED: return setImageDpi("images/ic_exit_to_app_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case EXIT: return setImageDpi("images/ic_exit_to_app_black_24dp.png", dpi); //$NON-NLS-1$ case LIST_DISABLED: return setImageDpi("images/ic_list_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case LIST: return setImageDpi("images/ic_list_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING_DISABLED: return setImageDpi("images/ic_settings_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING: return setImageDpi("images/ic_settings_black_24dp.png", dpi); //$NON-NLS-1$ case UPDATE_DISABLED: return setImageDpi("images/ic_update_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case UPDATE: return setImageDpi("images/ic_update_black_24dp.png", dpi); //$NON-NLS-1$ case HELP_DISABLED: return setImageDpi("images/ic_help_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case HELP: return setImageDpi("images/ic_help_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_DISABLED: return setImageDpi("images/ic_info_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case INFO: return setImageDpi("images/ic_info_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_WHITH: return setImageDpi("images/ic_info_white_24dp.png", dpi); //$NON-NLS-1$ case SUPERVISOR_ACCOUNT_DISABLED: return setImageDpi("images/ic_supervisor_account_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SUPERVISOR_ACCOUNT: return setImageDpi("images/ic_supervisor_account_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING_APP_DISABLED: return setImageDpi("images/ic_settings_applications_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING_APP: return setImageDpi("images/ic_settings_applications_black_24dp.png", dpi); //$NON-NLS-1$ case SYSTEM_UPDATE_DISABLED: return setImageDpi("images/ic_system_update_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SYSTEM_UPDATE: return setImageDpi("images/ic_system_update_black_24dp.png", dpi); //$NON-NLS-1$ case INFORMATION_DISABLED: return setImageDpi("images/ic_perm_device_information_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case INFORMATION: return setImageDpi("images/ic_perm_device_information_black_24dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_DISABLED_BLACK: return setImageDpi("images/ic_file_download_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_BLACK: return setImageDpi("images/ic_file_download_black_24dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_WHITE: return setImageDpi("images/ic_file_download_white_48dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_IND_DISABLED: return setImageDpi("images/ic_assignment_ind_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_IND: return setImageDpi("images/ic_assignment_ind_black_24dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_TURNED_IN_DISABLED: return setImageDpi("images/ic_assignment_turned_in_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_TURNED_IN: return setImageDpi("images/ic_assignment_turned_in_black_24dp.png", dpi); //$NON-NLS-1$ case SIGNATURE_DISABLED_BLACK: return setImageDpi("images/ic_gesture_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SIGNATURE_BLACK: return setImageDpi("images/ic_gesture_black_24dp.png", dpi); //$NON-NLS-1$ case SIGNATURE_WHITE: return setImageDpi("images/ic_gesture_white_24dp.png", dpi); //$NON-NLS-1$ case RESTORE_BLACK: return setImageDpi("images/ic_restore_page_black_24dp.png", dpi); //$NON-NLS-1$ case RESTORE_WHITE: return setImageDpi("images/ic_restore_page_white_24dp.png", dpi); //$NON-NLS-1$ case YOUTUBE_SEARCHED_BLACK: return setImageDpi("images/ic_youtube_searched_for_black_24dp.png", dpi); //$NON-NLS-1$ case YOUTUBE_SEARCHED_WHITE: return setImageDpi("images/ic_youtube_searched_for_white_24dp.png", dpi); //$NON-NLS-1$ case ADD_WHITE: return setImageDpi("images/ic_add_white_24dp.png", dpi); //$NON-NLS-1$ case DELETE_WHITE: return setImageDpi("images/ic_delete_forever_white_24dp.png", dpi); //$NON-NLS-1$ case CAMERA_BLACK: return setImageDpi("images/ic_camera_black_24dp.png", dpi); //$NON-NLS-1$ case CAMERA_WHITE: return setImageDpi("images/ic_camera_white_24dp.png", dpi); //$NON-NLS-1$ case PLAY_WITH_CIRCLE: return setImageDpi("images/ic_play_circle_outline_black_24dp.png", dpi); //$NON-NLS-1$ case PAGE_VIEW_DISABLED_BLACK: return setImageDpi("images/ic_pageview_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case PAGE_VIEW_BLACK: return setImageDpi("images/ic_pageview_black_24dp.png", dpi); //$NON-NLS-1$ case PAGE_VIEW_WHITE: return setImageDpi("images/ic_pageview_white_24dp.png", dpi); //$NON-NLS-1$ case INFO_OUTLINE_BLACK: return setImageDpi("images/ic_info_outline_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_OUTLINE_DISABLED_BLACK: return setImageDpi("images/ic_info_outline_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_OUTLINE_WHITE: return setImageDpi("images/ic_info_outline_white_24dp.png", dpi); //$NON-NLS-1$ case MENU: return setImageDpi("images/menu.png", dpi); //$NON-NLS-1$ case MENU_WHITE: return setImageDpi("images/menu_white.png", dpi); //$NON-NLS-1$ case ADD_DISABLED_WHITE: return setImageDpi("images/ic_add_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case DELETE_DISABLED_WHITE: return setImageDpi("images/ic_delete_forever_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case CAMERA_DISABLED_WHITE: return setImageDpi("images/ic_camera_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case ALARM_BLACK: return setImageDpi("images/ic_alarm_black_24dp.png", dpi); //$NON-NLS-1$ case ALARM_RED: return setImageDpi("images/ic_alarm_red_24dp.png", dpi); //$NON-NLS-1$ case PHOTO_LIBRARY_BLACK: return setImageDpi("images/ic_photo_library_black_24dp.png", dpi); //$NON-NLS-1$ case PICTURE_AS_PDF_BLACK: return setImageDpi("images/ic_picture_as_pdf_black_24dp.png", dpi); //$NON-NLS-1$ case SCHEDULE_BLACK: return setImageDpi("images/ic_schedule_black_24dp.png", dpi); //$NON-NLS-1$ case SCHEDULE_DISABLED_BLACK: return setImageDpi("images/ic_schedule_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case CHECK_SOME: return setImageDpi("images/ic_checkbox_some_60dp.png", dpi); //$NON-NLS-1$ case CHECK_CHECKED: return setImageDpi("images/ic_checkbox_checked_60dp.png", dpi); //$NON-NLS-1$ case CHECK_UNCHECKED: return setImageDpi("images/ic_checkbox_unchecked_60dp.png", dpi); //$NON-NLS-1$ case CHECK: return setImageDpi("images/ic_check_512dp.png", dpi); //$NON-NLS-1$ case CHECK_WHITE: return setImageDpi("images/ic_check_white_512dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_SUCCESS: return setImageDpi("images/ic_download_success_512dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_ERROR: return setImageDpi("images/ic_download_error_512dp.png", dpi); //$NON-NLS-1$ case DONE_BLACK: return setImageDpi("images/ic_done_black_24db.png", dpi); //$NON-NLS-1$ case DONE_WHITE: return setImageDpi("images/ic_done_white_24db.png", dpi); //$NON-NLS-1$ case REMOTE_BLACK: return setImageDpi("images/ic_remote_black_24dp.png", dpi); //$NON-NLS-1$ case ABSENCE_BLACK: return setImageDpi("images/ic_absence_black_24dp.png", dpi); //$NON-NLS-1$ case OFFLINE_SHARE: return setImageDpi("images/ic_offline_share_black_24dp.png", dpi); //$NON-NLS-1$) case SEARCH_FILE_BLACK: return setImageDpi("images/ic_search_file_black_72dp.png", dpi); //$NON-NLS-1$) case SEARCH_FILE_DISABLED: return setImageDpi("images/ic_search_file_disabled_72dp.png", dpi); //$NON-NLS-1$) case ADD_PHOTO_BLACK: return setImageDpi("images/ic_add_photo_black_32dp.png", dpi); //$NON-NLS-1$) case WRENCH_BLACK: return setImageDpi("images/ic_wrench_black_72dp.png", dpi); //$NON-NLS-1$) case WRENCH_DISABLED: return setImageDpi("images/ic_wrench_disabled_black_72dp.png", dpi); //$NON-NLS-1$) case UPDATE_WHITE: return setImageDpi("images/ic_update_white_24dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_BLACK: return setImageDpi("images/ic_shopping_cart_black_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_DISABLED: return setImageDpi("images/ic_shopping_cart_disabled_white_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_WHITE: return setImageDpi("images/ic_shopping_cart_white_128dp.png", dpi); //$NON-NLS-1$ case TRUCK_BLACK: return setImageDpi("images/ic_truck_black_128dp.png", dpi); //$NON-NLS-1$ case TRUCK_WHITE: return setImageDpi("images/ic_truck_white_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_ADD_BLACK: return setImageDpi("images/ic_shopping_cart_add_black_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_ADD_DISABLED: return setImageDpi("images/ic_shopping_cart_add_disabled_white_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_ADD_WHITE: return setImageDpi("images/ic_shopping_cart_add_white_128dp", dpi); //$NON-NLS-1$ case CAMERA_DISABLED_BLACK: return setImageDpi("images/ic_camera_disabled_black_24dp.png", dpi); //$NON-NLS-1$ default: break; } return result; } private Image setImageDpi(String imageUrl, Integer dpi) { if (dpi != null) { return app.getImage(imageUrl, dpi); } else { return app.getImage(imageUrl); } } }     common/src/ch/mfiles/kaba/kolibri/common/util/KeyboardUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; import ch.mfiles.kolibri.ApplicationManager; public class KeyboardUtil { KeyboardUtil() { } /** * Closes the keyboard (if open). * @param appman * @param v */ public static void closeKeyboard(ApplicationManager appman, View v) { // close the keyboard (if open) InputMethodManager imm = (InputMethodManager) appman.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } }     common/src/ch/mfiles/kaba/kolibri/common/util/LayoutUtils.java:   package ch.mfiles.kaba.kolibri.common.util; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.util.DisplayMetrics; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class LayoutUtils { public static final int DEFAULT_RED = 0xFFFF1818; public static final int DEFAULT_GREEN = 0xFF518E39; public static final int DEFAULT_BROWN = 0xFF5D433F; public static final int DEFAULT_PURPLE = 0xFF6A2DB4; public static final int DEFAULT_DARK_GRAY = 0xFF556770; public static final int DEFAULT_LIGHT_GRAY = 0xFFD2D2D2; public static final int DEFAULT_ORANGE = 0xFFEE5425; public static final int DEFAULT_WHITE = Color.WHITE; private static final int PRIMARY_COLOR_YELLOW = 0xFFF9A825; // Yellow 800 private static final int ACCENT_COLOR_INDIGO = 0xFF536DFE; // Indigo 200 private static final int ACCENT_COLOR_RED = 0xFFD50000; // Red 700 private static final int ERROR_MESSAGES_COLOR = 0xFFd50000; public static int DEFAULT_TOOL_BAR_COLOR = ACCENT_COLOR_INDIGO; // Indigo 500 public static final int DEFAULT_TAB_COLOR = DEFAULT_TOOL_BAR_COLOR; public static final int DEFAULT_TAB_SELECTED_TEXT_COLOR = DEFAULT_WHITE; public static final int DEFAULT_TAB_TEXT_COLOR = 0xFF7986CB; // Indigo 300 public static final int DEFAULT_CONTENT_AREA_COLOR = DEFAULT_WHITE; public static final int DEFAULT_TEXT_COLOR = Color.BLACK; public static final int DEFAULT_LABEL_COLOR = 0xFF737373; public static final int DEFAULT_ERROR_COLOR = ERROR_MESSAGES_COLOR; public static final int DEFAULT_BUTON_COLOR = 0xFFD2D2D2; public static final int DEFAULT_HIGHLIGHT = PRIMARY_COLOR_YELLOW; public static final int DEFAULT_DISABLED_COLOR = Color.DKGRAY; public static final int DEFAULT_CARD_VIEW_SHADOW_COLOR = 0xFFEEEEEE; public static final int DEFAULT_UNDERLINE_COLOR = 0xFF7E7E7E; public static final int DEFAULT_UNDERLINE_DISABLED_COLOR = 0xFFEEEEEE; public static final int DEFAULT_SEARCH_COLOR = 0XFFF5F5F5; public static final int DEFAULT_MIN_MARGIN = 5; public static final int DEFAULT_MAX_MARGIN = 10; public static final int DEFAULT_MIN_PADDING = 5; public static final int DEFAULT_MAX_PADDING = 16; public static final int DEFAULT_NEW_COLOR = DEFAULT_RED; public static final int DEFAULT_RECEIVED_COLOR = DEFAULT_GREEN; public static final int DEFAULT_FORWARDED_COLOR = DEFAULT_BROWN; public static final int DEFAULT_INPROGRESS_COLOR = DEFAULT_PURPLE; public static final int DEFAULT_FINALIZED_COLOR = DEFAULT_DARK_GRAY; public static final int DEFAULT_PARTLY_DONE_COLOR = DEFAULT_ORANGE; LayoutUtils() { } public static final int DEFAULT_MATERIAL_COLOR = 0xFF37474f; public static final LinearLayout.LayoutParams DEFAULT_MATCH_PARENT_PARAMS() { return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } public static final LinearLayout.LayoutParams DEFAULT_WRAP_CONTENT_PARAMS() { return new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } public static final LinearLayout.LayoutParams DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT() { return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } public static final LinearLayout.LayoutParams DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT() { return new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); } public static final void setDevelopmentColors() { DEFAULT_TOOL_BAR_COLOR = ACCENT_COLOR_RED; } /** * Converts DP To Pixel. * @param context * @param dp * @return */ public static int convertDpToPixel(Context context, float dp) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return Math.round(px); } }     common/src/ch/mfiles/kaba/kolibri/common/util/Messages.java:   package ch.mfiles.kaba.kolibri.common.util; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.common.util.messages"; //$NON-NLS-1$ public static String FileUtils_11; public static String TranslationFileConverter_2; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } }     common/src/ch/mfiles/kaba/kolibri/common/util/MessageUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Color; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.Toast; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Runtime; public class MessageUtil { private Log log = LogFactory.getLog(MessageUtil.class); private static List snackBarList = new ArrayList(); private static List messageList = new ArrayList(); private static MessageUtil instance; public static final MessageUtil getInstance() { if (instance == null) { instance = new MessageUtil(); } return instance; } public void showMessage(String message) { ApplicationManager appman = (ApplicationManager)Runtime.getApplicationManager(); Application app = (appman != null) ? (Application)appman.getActiveApplication() : null; Form form = (app != null) ? (Form)app.getCurrentForm() : null; View view = (form != null) ? form.getView() : null; // fallback to a simple toast if no view is currently active if (view == null) { if (appman == null) log.warn("Couldn't toast message (ApplicationManager not started!): " + message, new IllegalStateException()); else Toast.makeText(appman.getContext(), message, Toast.LENGTH_LONG); return; } Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG); snackbar.setDuration(4000); // Change the action button text color snackbar.setActionTextColor(Color.GREEN); //if true set onDismiss CallBack snackbar.setCallback(new Snackbar.Callback() { @Override public void onDismissed(Snackbar currentSnackbar, int event) { super.onDismissed(currentSnackbar, event); //first remove current snackBar in List, then if List not empty show the first one snackBarList.remove(currentSnackbar); messageList.clear(); if (!snackBarList.isEmpty()) snackBarList.get(0).show(); } }); //add (set callback) snackBar to List snackBarList.add(snackbar); messageList.add(message); //the beginning if (snackBarList.size() == 1){ snackBarList.get(0).show(); } } public void showMessage(String message, boolean forceClear) { if(forceClear) { clearMessage(); } showMessage(message); } public void showContinueMessage() { if(!messageList.isEmpty()) { for (Snackbar snackbar : snackBarList) { snackbar.dismiss(); } snackBarList.clear(); List messages = new ArrayList(); messages.addAll(messageList); messageList.clear(); for (String message : messages) { showMessage(message); } } } public void clearMessage() { for (Snackbar snackbar : snackBarList) { snackbar.dismiss(); } snackBarList.clear(); messageList.clear(); } }     common/src/ch/mfiles/kaba/kolibri/common/util/Notifications.java:   package ch.mfiles.kaba.kolibri.common.util; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Icon; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.NotificationCompat; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; /** * The notifications for incoming job and short message. * * @author nop */ public class Notifications extends Form { private Application app; private ImagesUtil imagesUtil; private BroadcastReceiver brReceiver = null; public Notifications(Application application) { this.app = application; this.appman = application.appman; this.imagesUtil = ImagesUtil.getInstance(app); } /** * Registers thr BroadcastReceiver, called onApplicationStart() */ public void registerBroadcastReceiver() { if (brReceiver != null) return; brReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { /* * -called on main (UI-) thread! * -show UI if hidden; api method available * -since runtime release 1.2(1p201705281441) */ appman.bringToFront(); } }; IntentFilter intentFilter = new IntentFilter(CommonConstants.Notification.BROADCAST_ACTION); appman.getContext().registerReceiver(brReceiver, intentFilter); } /** * Unregisters thr BroadcastReceiver, called onApplicationExit() */ public void unregisterBroadcastReceiver() { LocalBroadcastManager bm = LocalBroadcastManager.getInstance(appman.getContext()); bm.unregisterReceiver(brReceiver); brReceiver = null; } /** * Gets a custom notification * * @param notificationId * @param message * @return */ @TargetApi(Build.VERSION_CODES.M) private Notification getNotification(int notificationId, String message) { Notification.Builder notification = new Notification.Builder(appman.getContext()); // set pending intent to trigger our broadcast receiver notification.setContentIntent(PendingIntent.getBroadcast(appman.getContext(), notificationId, new Intent(CommonConstants.Notification.BROADCAST_ACTION), 0)); notification.setContentTitle(Messages.getString("messages")); //$NON-NLS-1$ notification.setContentText(message); notification.setPriority(NotificationCompat.PRIORITY_HIGH); notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notification.setAutoCancel(false); notification.setOngoing(true); Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); notification.setSound(alarmSound); BitmapDrawable image = getBitmanDrawable(imagesUtil.getImage(ImagesUtil.Images.INFO_OUTLINE_WHITE)); notification.setSmallIcon(Icon.createWithBitmap(image.getBitmap())); return notification.build(); } /** * Updates the notification for a new job. * @param message */ public void newJobNotification(String message) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); nfManager.notify(CommonConstants.Notification.NEW_JOB, getNotification(CommonConstants.Notification.NEW_JOB, message)); } /** * Updates the notification for a short message. * @param message */ public void shortMessageNotification(String message) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); nfManager.notify(CommonConstants.Notification.SHORT_MESSAGE, getNotification(CommonConstants.Notification.SHORT_MESSAGE, message)); } /** * Updates the notification for a Incoming article. * @param message */ public void IncomingArticleNotification(String message) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); nfManager.notify(CommonConstants.Notification.INCOMING_ARTICLE, getNotification(CommonConstants.Notification.INCOMING_ARTICLE, message)); } /** * Removes the notification for a new job and a short message */ public void removeNotification() { removeNotification(0); } /** * Removes the notification. * @param notificationId */ public void removeNotification(int notificationId) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); if (notificationId == 0) { nfManager.cancel(CommonConstants.Notification.NEW_JOB); nfManager.cancel(CommonConstants.Notification.SHORT_MESSAGE); nfManager.cancel(CommonConstants.Notification.INCOMING_ARTICLE); } else { nfManager.cancel(notificationId); } } }     common/src/ch/mfiles/kaba/kolibri/common/util/RegistryUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; public class RegistryUtil { public static final Log log = LogFactory.getLog(RegistryUtil.class); RegistryUtil() { } public static final class RegistryProperties { RegistryProperties() { } public static final int MIN_INTERVAL = 1; public static final int MAX_INTERVAL = 99; public static final int DEFAULT_INTERVAL = 10; public static final String INTERVAL_PROPERTY_NAME = "NotificationInterval"; //$NON-NLS-1$ public static final String JOB_LIST_STYLE_PROPERTY_NAME = "JobListStyle"; //$NON-NLS-1$ public static final String MASTER_DATA_REFRESH_DATE_PROPERTY_NAME = "MasterDataRefreshDate"; //$NON-NLS-1$ public static final String INCOMING_ARTICLE_NAME = "IncomingArticle"; //$NON-NLS-1$ public static final int MIN_VOLUME = 0; public static final int MAX_VOLUME = 10; public static final int DEFAULT_MASTER_DATA_REFRESH_DATE = 0; public static final int DEFAULT_INVOMING_ARTICLE = 0; public static final String[] JOB_LIST_STYLE_VALUES = {"REP_SAV", "MON"}; //$NON-NLS-1$ //$NON-NLS-2$ public static final String DEFAULT_JOB_LIST_STYLE = JOB_LIST_STYLE_VALUES[0]; public static final String TEST_BACKUP_EVERY_S = "testBackupEveryS"; //$NON-NLS-1$ public static final String GENERIC_FORM_DRAFT_DOWNLOAD = "genericFormsDraftDownload"; //$NON-NLS-1$ } public static String getJobListStyleProperty(Application app) { ApplicationManager appman = app.appman; String jobListStyle = RegistryProperties.DEFAULT_JOB_LIST_STYLE; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { try { jobListStyle = reg.getProperty(RegistryProperties.JOB_LIST_STYLE_PROPERTY_NAME); } catch (IllegalArgumentException e) { log.warn("No JobListStyle-property found"); //$NON-NLS-1$ log.error(e); } } return jobListStyle; } public static long getMasterDataRefreshDateProperty(Application app) { ApplicationManager appman = app.appman; long masterDataRefreshDate = RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { try { masterDataRefreshDate = reg.getLongProperty(RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME); } catch (IllegalArgumentException e) { log.warn("No " + RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME + "-property found"); //$NON-NLS-1$ //$NON-NLS-2$ log.error(e); } } return masterDataRefreshDate; } public static void setJobListStyleProperty(Application app, String jobListStyle) { ApplicationManager appman = app.appman; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.JOB_LIST_STYLE_PROPERTY_NAME, jobListStyle); } } public static void setMasterDataRefreshDateProperty(Application app, long milliseconds) { ApplicationManager appman = app.appman; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, milliseconds); } } public static int getTestBackupEveryS() { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); int interval = 0; Registry reg = appman.getRegistry(CommonConstants.Application.COMMON_APP); if (reg != null) { try { interval = reg.getIntProperty(RegistryProperties.TEST_BACKUP_EVERY_S); } catch (NumberFormatException e) { log.error("Invalid value for 'testBackupEveryS' setting found: " + e); //$NON-NLS-1$ } catch (IllegalArgumentException e) { log.error("No notification interval setting found: " + e); //$NON-NLS-1$ } } return interval; } public static boolean isGenericFormsDraftDownload() { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.COMMON_APP); if (reg != null) { try { return reg.getBooleanProperty(RegistryProperties.GENERIC_FORM_DRAFT_DOWNLOAD); } catch (IllegalArgumentException ex) { // ignore } } return false; } }     common/src/ch/mfiles/kaba/kolibri/common/util/ResetEval.jpage:   String sql = "UPDATE __dbcluster SET cldata = (SELECT cldata FROM __dbcluster WHERE clid = 'framework.dm.lastRemoteLookup') WHERE clid = 'framework.la.startOfTrialPeriodMillis'";     common/src/ch/mfiles/kaba/kolibri/common/util/ResetEvalPeriod.sql:   UPDATE __dbcluster SET cldata = '31343237333835353337333331' WHERE clid = 'framework.la.startOfTrialPeriodMillis' UPDATE __dbcluster SET cldata = (SELECT cldata FROM __dbcluster WHERE clid = 'framework.dm.lastRemoteLookup') WHERE clid = 'framework.la.startOfTrialPeriodMillis' SELECT * FROM __dbcluster WHERE clid = 'framework.la.startOfTrialPeriodMillis'     common/src/ch/mfiles/kaba/kolibri/common/util/RunOnUIThread.java:   package ch.mfiles.kaba.kolibri.common.util; public interface RunOnUIThread { void runOnUIThread(); }     common/src/ch/mfiles/kaba/kolibri/common/util/SoundUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.File; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.ContentResolver; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.net.Uri; public class SoundUtil { private static Log log = LogFactory.getLog(SoundUtil.class); /** * Play sound file stored in res/raw/ directory */ public static void playRawSound(Context context, final String rawName) { try { // Two ways to provide resource, either using its name or resource id. // // Name // Syntax : android.resource://[package]/[res type]/[res name] // Example : Uri.parse("android.resource://com.my.package/raw/sound1"); // // Resource id // Syntax : android.resource://[package]/[resource_id] // Example : Uri.parse("android.resource://com.my.package/" + R.raw.sound1); // refer http://landenlabs.com/android/audiodemo/audiodemo.html#raw String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; String path; if (false) { // Build path using resource name path = RESOURCE_PATH + context.getPackageName() + "/raw/" + rawName; } else { // Build path using resource number int resID = context.getResources().getIdentifier(rawName, "raw", context.getPackageName()); path = RESOURCE_PATH + context.getPackageName() + File.separator + resID; } Uri soundUri = Uri.parse(path); log.info(path); MediaPlayer mMediaPlayer = new MediaPlayer(); mMediaPlayer.setVolume(1.0f, 1.0f); mMediaPlayer.setLooping(false); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { log.info("start playing sound -> " + rawName); } }); mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { log.error(String.format(Locale.US, "Media error what=%d extra=%d", what, extra)); return false; } }); // // Different ways to load audio into player: // 1. Using path to resource by name or by id // 2. Using content provider to load audio and passing a file descriptor. if (true) { // 1. open audio using path to data inside package mMediaPlayer.setDataSource(context, soundUri); mMediaPlayer.prepare(); } else { // 2. Load using content provider, passing file descriptor. ContentResolver resolver = context.getContentResolver(); AssetFileDescriptor afd = resolver.openAssetFileDescriptor(soundUri, "r"); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.prepareAsync(); } // See setOnPreparedListener above mMediaPlayer.start(); } catch (Exception ex) { log.error(ex.getMessage()); } } }     common/src/ch/mfiles/kaba/kolibri/common/util/SQLFileConverter.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SQLFileConverter { SQLFileConverter(){} private static Log log = LogFactory.getLog(SQLFileConverter.class); public static void main(String[] args) throws IOException { SQLFileConverter.removeWhiteSpaces("data/fixed-master-data.txt", //$NON-NLS-1$ "data/fixed-master-data.txt"); //$NON-NLS-1$ log.debug("Convert SQL complete."); //$NON-NLS-1$ } public static void removeWhiteSpaces(String inputFile, String outputFile) throws IOException { BufferedWriter dos = null; BufferedReader br = null; try { br = new BufferedReader(new FileReader(inputFile)); dos = new BufferedWriter(new FileWriter(outputFile)); StringBuilder sb = new StringBuilder(); String s; char c; int count = 0; int lineCount = 0; while ((s = br.readLine()) != null) { lineCount++; count = 0; if (s.length() > 0) { int index = s.indexOf('('); sb.append(s.substring(0, index)); int start = 0; int end = 0; boolean skip = false; for (int i = index; i < s.length(); i++) { c = s.charAt(i); start = end; // Keine Sonderbehandlung von Hochkomas, da als Textbegrenzung ein Apostoph (") verwedet wird. // if (c == '\'') { // skip = true; // count++; // end = i; // if (count == 2) { // // sb.append(removeWhiteSpacesFromQuotedString(s.substring(start, end + 1))); // // count = 0; // skip = false; // } // // sb.append(c); // continue; // } if (c != '\t') { if (!skip) { sb.append(c); } } } sb.append('\n'); } } dos.write(sb.toString()); } finally { if (dos != null) { try { dos.close(); } catch (IOException ignore) { log.error(ignore); } } if (br != null) { try { br.close(); } catch (IOException ignore) { log.error(ignore); } } } } public static void removeTab(String inputFile, String outputFile) throws IOException { DataOutputStream dos = null; BufferedReader br = null; FileReader fileReader = null; FileOutputStream fileOutputStream = null; try { fileReader = new FileReader(inputFile); fileOutputStream = new FileOutputStream(outputFile); br = new BufferedReader(fileReader); dos = new DataOutputStream(fileOutputStream); String s; StringBuilder sbText = new StringBuilder(); while ((s = br.readLine()) != null) { int quoteCount=0; s=escapeTab(s); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c =='\''){ quoteCount++; } } if(quoteCount%2==0){ sbText.append(s); sbText.append('\n'); }else{ // syntax error quote not balance testReplaceQuotes(s, quoteCount); } } fileReader.close(); fileOutputStream.close(); dos.writeBytes(sbText.toString()); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException ignore) { log.error(ignore); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException ignore) { log.error(ignore); } } } } static String testReplaceQuotes(String text ,int quoteCount){ log.info("quoteCount " + quoteCount); //$NON-NLS-1$ StringBuilder result = new StringBuilder(); int start=0; int end =0; int currentquote=0; int columnCount =0; boolean isColumnName = true; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if(c == ',' && isColumnName){ // count number of column columnCount++; } if(c == ')' && isColumnName){ // table column end with ")" isColumnName = false; } if(c =='\''){ // find quotes start = end; end = i; currentquote++; } if(currentquote == 2){ // find the value to insert to the table if(text.charAt(end+1) == ','){ // next value is text result.append(text.substring(start, end+1)); log.info(result.toString()); } currentquote =0; } } return text; } static String removeWhiteSpacesFromQuotedString(String quotedString) { char c; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < quotedString.length(); i++) { c = quotedString.charAt(i); if (c != '\t') { stringBuilder.append(c); } } return stringBuilder.toString(); } static String escapeTab(String text) { StringBuilder sbText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c != '\t') { sbText.append(c); } } return sbText.toString(); } static String escapeQuote(String text) { StringBuilder sbText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == '\'') { sbText.append("\\"); //$NON-NLS-1$ } sbText.append(c); } return sbText.toString(); } public static List readFile(String filePath) throws IOException { List listSql = new ArrayList(); BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(filePath), "UTF8")); //$NON-NLS-1$ try { String s; while ((s = br.readLine()) != null) { listSql.add(s); } return listSql; } finally { try { br.close(); } catch (IOException ex) { // ignore log.error(ex); } } } }     common/src/ch/mfiles/kaba/kolibri/common/util/StepUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import com.stepstone.stepper.Step; import com.stepstone.stepper.VerificationError; import android.view.View; public class StepUtil implements Step { private View view; private Step step; public StepUtil(View view, Step step) { this.view = view; this.step = step; } @Override public void onError(VerificationError error) { step.onError(error); } @Override public void onSelected() { step.onSelected(); } @Override public VerificationError verifyStep() { return step.verifyStep(); } public View getView() { return view; } }     common/src/ch/mfiles/kaba/kolibri/common/util/StringUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.util.Collection; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtil { StringUtil() { } /** Check whether string s is empty. */ public static boolean isEmpty(String s) { return ((s == null) || (s.length() == 0)); } /** Check whether collection c is empty. */ public static boolean isEmpty(Collection c) { return ((c == null) || (c.isEmpty())); } /** Check whether map m is empty. */ public static boolean isEmpty(Map m) { return ((m == null) || (m.size() == 0)); } /** Check whether charsequence c is empty. */ public static boolean isEmpty(CharSequence c) { return ((c == null) || (c.length() == 0)); } /** Check whether string s is NOT empty. */ public static boolean isNotEmpty(String s) { return ((s != null) && (s.length() > 0)); } /** Check whether collection c is NOT empty. */ public static boolean isNotEmpty(Collection c) { return ((c != null) && (!c.isEmpty())); } /** Check whether charsequence c is NOT empty. */ public static boolean isNotEmpty(CharSequence c) { return ((c != null) && (c.length() > 0)); } public static String capitalize(String s) { if ((s == null) || (s.length() == 0)) { return s; } return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } public static String removeAllLeadingZero(String str) { return str.replaceFirst("^0+(?!$)", ""); //$NON-NLS-1$ //$NON-NLS-2$ } public static boolean findChar(String text, char cToFind){ boolean result = false; char c; for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (c == cToFind){ result = true; } } return result; } public static String[] split(String stringTofind, char charToFind){ String[] result = new String[2]; char c; for (int i = 0; i < stringTofind.length(); i++) { c = stringTofind.charAt(i); if (c == charToFind){ result[0] = stringTofind.substring(0, i); result[1] = stringTofind.substring(i+1, stringTofind.length()); } } return result; } public static String removeLettersAndCountDot(String text, char expectedChar){ char c; StringBuilder sbTemp = new StringBuilder(); int dotCount=0; for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (Character.getType(c)==Character.DECIMAL_DIGIT_NUMBER || c == expectedChar){ if(c ==expectedChar) dotCount++; if(dotCount<=1) sbTemp.append(c); } } return sbTemp.toString(); } public static String removeLetters(String text, char expectedChar){ char c; StringBuilder sbTemp = new StringBuilder(); for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (Character.getType(c)==Character.DECIMAL_DIGIT_NUMBER || c == expectedChar){ sbTemp.append(c); } } return sbTemp.toString(); } public static String removeLetters(String text) { char c; StringBuilder sbTemp = new StringBuilder(); for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (Character.getType(c) == Character.DECIMAL_DIGIT_NUMBER) { sbTemp.append(c); } } return sbTemp.toString(); } public static String removeExpectedChar(String text, char expectedChar){ char c; StringBuilder sbTemp = new StringBuilder(); for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (c != expectedChar){ sbTemp.append(c); } } return sbTemp.toString(); } public static String removeChar(String str) { StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (i != CommonConstants.CommissionNumber.DASH_POSITION && i != CommonConstants.CommissionNumber.LETTER_POSITION) { if (Character.isDigit(c)) { result.append(c); } } else { result.append(c); } } return result.toString(); } public static String getMaterialNoFromScan(String materialBarcode) { StringBuilder result = new StringBuilder(); // If the code is <=14 characters show code exactly as it is // If the code is >14 characters use the logic as today if (materialBarcode.length() <= 14) { return materialBarcode; } // if (materialBarcode.startsWith(CommonConstants.Material.NUMBER_PREFIX)) { // materialBarcode = materialBarcode.replace(CommonConstants.Material.NUMBER_PREFIX, ""); // } // materialBarcode = getMaterialNumber(materialBarcode); // 45-1234-123/12 // barcode 0635227XXC16110050 // barcode 012345678901234567 // 45-0635-227/XXC16110050 String companyCode = CommonConstants.Material.NUMBER_PREFIX; String dash_1 = "-"; String matNo_1 = ""; String dash_2 = "-"; String matNo_2 = ""; String slash = "/"; String variant = ""; boolean mIsNoVariant = false; if (materialBarcode.length() >= 3) { matNo_1 = materialBarcode.substring(0, 4); } if (materialBarcode.length() > 6) { matNo_2 = materialBarcode.substring(4, 7); } if (materialBarcode.length() > 7) { variant = materialBarcode.substring(7, 9); mIsNoVariant = false; if (variant.equalsIgnoreCase("XX")) { variant = ""; mIsNoVariant = true; } } result.append(companyCode); result.append(dash_1); result.append(matNo_1); result.append(dash_2); result.append(matNo_2); if(!mIsNoVariant){ if (!variant.isEmpty()) result.append(slash); result.append(variant); } return result.toString(); } public static String getMaterialNoFromText(String value) { if (value.length() < 2) { return value; } if (value.length() == 2) { return value + "-"; } // if (!value.startsWith(CommonConstants.Material.NUMBER_PREFIX)) { // return CommonConstants.Material.NUMBER_PREFIX + "-" + value; // } // // if (value.length() == 2 && !value.startsWith(CommonConstants.Material.NUMBER_PREFIX)) { // return CommonConstants.Material.NUMBER_PREFIX + "-" + value; // } if (value.length() == 3 && '-' != value.charAt(2)) { return value.substring(0, 2) + "-" + value.substring(2); //$NON-NLS-1$ } if (value.length() > 3 && value.length() < 8) { String matNo_1 = value.substring(3); if (!StringUtil.isNumeric(matNo_1)) { matNo_1 = StringUtil.removeChar(matNo_1); } return value.substring(0, 3) + matNo_1; } if (value.length() == 8 && '-' != value.charAt(7)) { return value.substring(0, 7) + "-" + value.substring(7); //$NON-NLS-1$ } if (value.length() > 8 && value.length() < 12) { String matNo_2 = value.substring(8); if (!StringUtil.isNumeric(matNo_2)) { matNo_2 = StringUtil.removeChar(matNo_2); } return value.substring(0, 8) + matNo_2; } if (value.length() > 11 && '/' != value.charAt(11)) { return value.substring(0, 11) + "/" + StringUtil.removeChar(value.substring(11)); //$NON-NLS-1$ } if (value.length() > 12) { String variant = value.substring(12); if (!StringUtil.isNumeric(variant)) { variant = StringUtil.removeChar(variant); } return value.substring(0, 12) + variant; } return value; } public static boolean isNumeric(String str) { try{ Integer.parseInt(str); } catch (NumberFormatException e) { return false; } return true; } public static String getOnlyDigits(String s) { Pattern pattern = Pattern.compile("[^0-9]"); Matcher matcher = pattern.matcher(s); String number = matcher.replaceAll(""); return number; } public static String getOnlyStrings(String s) { Pattern pattern = Pattern.compile("[^a-z A-Z]"); Matcher matcher = pattern.matcher(s); String number = matcher.replaceAll(""); return number; } public static String getMaterialNumber(String s) { Pattern pattern = Pattern.compile("[^0-9xxXX.]"); Matcher matcher = pattern.matcher(s); String number = matcher.replaceAll(""); return number; } public static String getFormattedDigitNumber(String value, boolean leadingZero) { int dotIndex = value.indexOf('.'); if (leadingZero) { //00.00 if (value.length() == 1) { if (dotIndex > -1) { value = "00" + value; } else { if (value.equalsIgnoreCase("0")) { // value = "00." + value; } else { value = "00.0" + value; } } } } if (value.length() == 2 && dotIndex == -1) { value += "."; } dotIndex = value.indexOf('.'); System.out.println("index " + dotIndex); String number = ""; String digits = ""; if (dotIndex > -1) { number = value.substring(0, dotIndex); digits = value.substring(dotIndex + 1 , value.length()); if (digits.length() > 2) { int subIndex = digits.length() - 2; number += digits.substring(0, subIndex); digits = digits.substring(subIndex); } if (number.startsWith("0") && number.length() > 2 ) { number = number.substring(number.length() - 2); } if (value.isEmpty()) { number = "00"; } value = number + "." + digits; } return value; } }     common/src/ch/mfiles/kaba/kolibri/common/util/TimeUtil.java:   package ch.mfiles.kaba.kolibri.common.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.net.PresenceState; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class TimeUtil { private static Log log = LogFactory.getLog(TimeUtil.class); private Application app; private DatabaseUtil dbutil; private static final String WARNING_MESSAGE = "warning"; //$NON-NLS-1$ private static final String OVERLAPPING_MESSAGE = "overlapping"; //$NON-NLS-1$ private Form form; Calendar latestTime; TimeUtilThread timeUtilThread; public TimeUtil(Application app, DatabaseUtil dbutil, Form form){ this.app = app; this.dbutil = dbutil; this.form = form; latestTime = Calendar.getInstance(); latestTime.set(latestTime.get(Calendar.YEAR), latestTime.get(Calendar.MONTH), latestTime.get(Calendar.DATE), 23, 59, 59); } /** * - Check if the current date is still the same date as of the other JobTimeSheet entries * - Check if the current date/time does not overlap with existing JobTimeSheet entries * - Adds a new JobTimeSheet (ZKDMOBRTIM) entry to the latest report of the current job * - Define new record as selected line in the table * - Changes the job status to "in arbeit" * @return true if time capturing was started successful, false otherwise */ public boolean startJobTimeCapturing(Job job) { Report report = job.getLatestReport(); Date now = DateTimeUtil.getTimestamp().getTime(); Date today = DateTimeUtil.getToday().getTime(); report.loadTimes(dbutil); List jobReportTimes = job.getLatestReport().getTimes(); // Creates a new JobTimeSheet (ZKDMOBRTIM) entry to the latest report of the current job JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReportGuId(dbutil)); newJobTime.setDate(today); newJobTime.setIdx(jobReportTimes.size()); newJobTime.setStartTime(now); newJobTime.setStopTime(DateUtils.getInitialDateTime()); //Setting ARBA correct: //MON: Default value "00 Bitte w�hlen" //REP (1-st entry): Default value "00 Bitte w�hlen" //REP (n-th entry): Same value as the already existing JobTimeSheets have //SAV (1-st entry): Default value "05 Vertragsservice" //SAV (n-th entry): Same value as the already existing JobTimeSheets have if (jobReportTimes.isEmpty()) newJobTime.setWorkTypeCode(job.getDefaultJobTimeARBA()); else newJobTime.setWorkTypeCode((jobReportTimes.get(0)).getWorkTypeCode()); TreeSet set = new TreeSet(); set.add((JobReportTime) newJobTime); for (int i = 0; i < jobReportTimes.size(); i++) { set.add((JobReportTime) jobReportTimes.get(i)); } Iterator itr = set.iterator(); int idx = 0; // number the timesheet entries consecutively in chronological order while (itr.hasNext()) { JobReportTime zkdmobrtim = itr.next(); zkdmobrtim.setIdx(idx++); Date zkdmobrtimDate = DateTimeUtil.getDate(zkdmobrtim.getDate()).getTime(); // Checks if the current date is still the same date as of the other JobTimeSheet entries if (!zkdmobrtimDate.equals(today)) { Object[] arguments = new Object[] { DateTimeUtil.tableDate(zkdmobrtim.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString("reportCannotContainTimesMoreThanOneDay"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } // Checks if the current date/time does not overlap with existing JobTimeSheet entries // Don't use compareTo() at this point, accuracy of time values is seconds (not minutes) if (!(now.before(zkdmobrtim.getStartTime()) || now.after(zkdmobrtim.getStopTime()))) { Object[] arguments = new Object[] { DateTimeUtil.showDateTime(zkdmobrtim.getStartTime()), DateTimeUtil.showDateTime(zkdmobrtim.getStopTime()) }; String errorMessage = MessageFormat.format(Messages.getString("newTimeEntryConfictsWithExistingOne"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } } if(timeUtilThread == null) { timeUtilThread = new TimeUtilThread(job); timeUtilThread.start(); } // Changes the job status to "in arbeit" job.setStatus(new JobStatus(JobStatus.IN_PROGRESS)); // Save the list of timesheet entries to the current report job.getLatestReport().setTimes(dbutil, new ArrayList(set)); dbutil.updateJob(job); return true; } /** * Starts time capturing in the time sheet of the current day *
- Load the CALENDAR Object of the current day *
- Check if time capturing is already running *
- Ask the user if time capturing should be started *
- Create a new ZKDMATIME object. Set default ARBA and current time *
- Save the CALENDAR object * @param app The currently running application (is needed for DB access) */ private boolean startWorkTimeCapturing(String arba, boolean pikett) { Date now = DateTimeUtil.getNow().getTime(); Date today = DateTimeUtil.getToday().getTime(); // Check for running work time capturing List capturingDays = dbutil.selectCalendarDateWithRunningTimeCapturing(dbutil.getUser().getPersonalNumber()); Date capturingDay; if (!capturingDays.isEmpty()) { // Error situation: at least 1 capturing time sheet found. If they belong // to an already sent CALENDAR, reopen it. So the user can enter missing // information and send it again List errorDates = new ArrayList(); Iterator itr = capturingDays.iterator(); while (itr.hasNext()) { capturingDay = itr.next(); CalendarTimeSheet calendar = dbutil.loadCalendar(capturingDay, dbutil.getUser().getPersonalNumber()); errorDates.add(calendar.getDateString()); if (calendar.getStatus().isSENT()) { calendar.setStatus(CalendarStatus.SAVED); dbutil.saveCALENDAR(calendar); } } // Don't show error message in the following situation: // - if exactly 1 capturing time sheet was found // - if the capturing time sheet is from today // - if the ServiceApplication is running if (!(capturingDays.size() == 1 && (capturingDays.get(0)).equals(today) && app.getApplicationDescriptor().getApplication().equals(CommonConstants.Application.SERVICE_APP))) { Object[] arguments = new Object[] { errorDates }; String errorMessage = MessageFormat.format(Messages.getString("foundErrorsInTimesheetsOnDate"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } else return true; } else { CalendarTimeSheet calendar = dbutil.loadCalendar(today, dbutil.getUser().getPersonalNumber()); if (!calendar.isTimeCapturing()) { if (calendar.getStatus().isSENT()) { showWarningMessageBox(Messages.getString("timesheetCannotBeStartet")); //$NON-NLS-1$ return false; } TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { TimeSheet zkdmatime = itr.next(); // Checks if the current date/time does not overlap with existing JobTimeSheet entries if (!(now.compareTo(zkdmatime.getStartTime()) <= 0 || now.compareTo(zkdmatime.getStopTime()) >= 0)) { Object[] arguments = new Object[] { DateTimeUtil.showDateTime(zkdmatime.getStartTime()), DateTimeUtil.showDateTime(zkdmatime.getStopTime()) }; String errorMessage = MessageFormat.format(Messages.getString("TimeIsOverlapping"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } } // Adds a new JobTimeSheet (ZKDMATIME) entry to the latest report of the current job TimeSheet newTimeSheet = new TimeSheet(dbutil.getUser().getPersonalNumber()); log.info(DateTimeUtil.showDateTime(newTimeSheet.getDate())); newTimeSheet.setIdx(times.size()); newTimeSheet.setStartTime(now); newTimeSheet.setStopTime(new Date(0)); newTimeSheet.setWorkTypeCode(arba); newTimeSheet.setCallFlag(pikett); times.add(newTimeSheet); // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database dbutil.saveCALENDAR(calendar); new RemoteTransactionHandler().runUpdatePresence(dbutil.getUser().getPersonalNumber(), arba, PresenceState.PRESENT); if (dbutil.loadCalendar(today, dbutil.getUser().getPersonalNumber()).isTimeCapturing()) { app.inform(Messages.getString("workTimeCapturingStartet")); //$NON-NLS-1$ } } } return true; } public void stopTime(final Job job, final RunOnUIThread runOnUIThread) { new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { boolean result = stopJobTimeCapturing(job); if (result) { app.inform(Messages.getString("timeStopped")); //$NON-NLS-1$ if(timeUtilThread != null) { timeUtilThread.interrupt(); timeUtilThread = null; } if (job.getJobType().isMON()) { stopWorkTimeCapturing(); } } else { app.inform(Messages.getString("timeNotStopped")); //$NON-NLS-1$ } return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); runOnUIThread.runOnUIThread(); } }; } /** * - Loads the latest report and in the report time records. * - looks for the one time record without BIS time. * - checks if more than 3min passed since BIS time. If not, informs user and terminates without stopping time capturing * - checks if time capturing was started today. * @param app * @param dbutil * @param job * @return true if time was stopped successfully, false otherwise */ private boolean stopJobTimeCapturing(Job job) { Date timestamp = DateTimeUtil.getTimestamp().getTime(); Date bis = DateTimeUtil.getNow().getTime(); Date today = DateTimeUtil.getTodayEarlyMorning().getTime(); Date yesterday = DateTimeUtil.getYesterdayLateNight().getTime(); job.loadReports(dbutil); Report report = job.getLatestReport(); report.loadTimes(dbutil); JobReportTime jobReportTime = null; TreeSet times = new TreeSet(report.getTimes()); Iterator itr = times.iterator(); while (itr.hasNext()) { jobReportTime = itr.next(); if (jobReportTime.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) break; } if (jobReportTime != null) { // Check if a minimum of 3 minutes is recorded before stopping the time capturing if (!checkMinumumCapturingTime(jobReportTime.getStartTime())) return false; Date capturingDay = DateTimeUtil.getDate(jobReportTime.getStartTime()).getTime(); if (isToday(capturingDay)) { jobReportTime.setStopTime(bis); // check if there are no overlapping entries int selOverlappingRowIdx = checkJobTimesheetOverlapping(times); if (selOverlappingRowIdx > -1) { return false; } report.setTimes(dbutil, new ArrayList(times)); job.setStatus(JobStatus.RECEIVED); // check if job is partly done Report previousReport = null; if(job.getReports().size() >1) { previousReport = job.getReports().get(job.getReports().size()-1); if(previousReport.getReportStatus().isReceived() && previousReport.isPartialRepair()) { job.setStatus(JobStatus.PARLTY_DONE); } } dbutil.updateJob(job); return true; } else if (isYesterday(capturingDay)) { jobReportTime.setStopTime(yesterday); JobReportTime newZkdmobrtim = new JobReportTime(); newZkdmobrtim.setGuid(jobReportTime.getGuId()); newZkdmobrtim.setIdx(times.size()); newZkdmobrtim.setWorkTypeCode(jobReportTime.getWorkTypeCode()); newZkdmobrtim.setDate(timestamp); newZkdmobrtim.setStopTime(bis); newZkdmobrtim.setStartTime(today); times.add(newZkdmobrtim); // check if there are no overlapping entries int selOverlappingRowIdx = checkJobTimesheetOverlapping(times); if (selOverlappingRowIdx > -1) { return false; } report.setTimes(dbutil, new ArrayList(times)); job.setStatus(JobStatus.RECEIVED); dbutil.updateJob(job); return true; } else if (isOlderThan2Days(capturingDay)) { jobReportTime.setStopTime(DateTimeUtil.getLateNight(capturingDay).getTime()); // check if there are no overlapping entries int selOverlappingRowIdx = checkJobTimesheetOverlapping(times); if (selOverlappingRowIdx > -1) { return false; } report.setTimes(dbutil, new ArrayList(times)); job.setStatus(JobStatus.RECEIVED); dbutil.updateJob(job); return true; } else { log.error("Running report time sheet for a day in the future found: " + capturingDay.toString()); //$NON-NLS-1$ return false; } } else { log.info("No time sheet found to stop"); //$NON-NLS-1$ return false; } } private boolean stopWorkTimeCapturingOlderThan2Days(CalendarTimeSheet calendar) { Date stopCalendarDay = DateTimeUtil.getLateNight(calendar.getDate()).getTime(); showWarningMessageBox(Messages.getString("workTimeCapturingStartetBeforeYesterday")); //$NON-NLS-1$ TimeSheet timeSheet; TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { timeSheet = itr.next(); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { timeSheet.setStopTime(stopCalendarDay); } } if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database return dbutil.saveCALENDAR(calendar); } else return false; } /** * Stops time capturing in the time sheet of the current day *
- Load the CALENDAR Object of the day with the running time capturing *
- Check if time capturing is running *
- Ask the user if time capturing should be stopped *
- Search the running ZKDMATIME object and set current time to BIS *
- Check if time entries are not overlapping *
- Save the CALENDAR object * @param app The currently running application (is needed for DB access) * @return true if report time could be stopped successfully */ private boolean stopWorkTimeCapturing() { CalendarTimeSheet calendar; Date bis = DateTimeUtil.getNow().getTime(); List capturingDays = dbutil.selectCalendarDateWithRunningTimeCapturing(dbutil.getUser().getPersonalNumber()); Date capturingDay; if (capturingDays.isEmpty()) return false; else if (capturingDays.size() > 1) { // Error situation: more than 1 capturing time sheet found. If they belong // to an already sent CALENDAR, reopen it. So the user can enter missing // information and send it again ArrayList errorDates = new ArrayList(); Iterator itr = capturingDays.iterator(); while (itr.hasNext()) { capturingDay = itr.next(); calendar = dbutil.loadCalendar(capturingDay, dbutil.getUser().getPersonalNumber()); errorDates.add(calendar.getDateString()); if (calendar.getStatus().isSENT()) { calendar.setStatus(CalendarStatus.SAVED); dbutil.saveCALENDAR(calendar); } } Object[] arguments = new Object[] { errorDates }; String errorMessage = MessageFormat.format(Messages.getString("foundErrorsInTimesheetsOnDate"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return true; } else capturingDay = capturingDays.get(0); calendar = dbutil.loadCalendar(capturingDay, dbutil.getUser().getPersonalNumber()); if (calendar.isTimeCapturing() && (app.getApplicationDescriptor().getApplication().equals(CommonConstants.Application.TIMESHEET_APP) || app.showMessageBox(Messages.getString("doYouWantToStopTimesheet"), //$NON-NLS-1$ Messages.getString(WARNING_MESSAGE), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES)) { if (isToday(capturingDay)) return stopWorkTimeCapturingToday(calendar, bis) && updatePresenceToGone(); else if (isYesterday(capturingDay)) return stopWorkTimeCapturingYesterday(calendar, bis) && updatePresenceToGone(); else if (isOlderThan2Days(capturingDay)) return stopWorkTimeCapturingOlderThan2Days(calendar) && updatePresenceToGone(); else log.error("Running time sheet for a day in the future found: " + capturingDays.toString()); //$NON-NLS-1$ } return false; } private boolean stopWorkTimeCapturingYesterday(CalendarTimeSheet calendar, Date bis) { Date today = DateTimeUtil.getToday().getTime(); Date startToday = DateTimeUtil.getTodayEarlyMorning().getTime(); Date stopYesterday = DateTimeUtil.getYesterdayLateNight().getTime(); showWarningMessageBox(Messages.getString("WorkTimeRecordingWasStartedYesterday.")); //$NON-NLS-1$ TimeSheet timeSheet = new TimeSheet(dbutil.getUser().getPersonalNumber()); TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { timeSheet = itr.next(); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { timeSheet.setStopTime(stopYesterday); } } if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database if (!dbutil.saveCALENDAR(calendar)) return false; } else return false; calendar = dbutil.loadCalendar(today, dbutil.getUser().getPersonalNumber()); times = calendar.getTimeSheets(); TimeSheet timeSheetToday = new TimeSheet(dbutil.getUser().getPersonalNumber()); timeSheetToday.setIdx(calendar.getTimeSheets().size()); timeSheetToday.setWorkTypeCode(timeSheet.getWorkTypeCode()); timeSheetToday.setCostCenter(timeSheet.getCostCenter()); timeSheetToday.setCallFlag(timeSheet.isCallFlag()); timeSheetToday.setCommissionNumber(timeSheet.getCommissionNumber()); timeSheetToday.setStartTime(startToday); timeSheetToday.setStopTime(bis); times.add(timeSheetToday); if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database return dbutil.saveCALENDAR(calendar); } else return false; } private boolean stopWorkTimeCapturingToday(CalendarTimeSheet calendar, Date bis) { TimeSheet timeSheet; TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { timeSheet = itr.next(); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { // Check if a minimum of 3 minutes is recorded before stopping the time capturing if (checkMinumumCapturingTime(timeSheet.getStartTime())) { calendar.setStatus(CalendarStatus.SAVED); timeSheet.setStopTime(bis); } else { return false; } } } if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database return dbutil.saveCALENDAR(calendar); } else return false; } private static boolean isOlderThan2Days(Date capturingDay) { Date beforeYesterday = DateTimeUtil.getDayBeforeYesterday().getTime(); return (capturingDay.compareTo(beforeYesterday) <= 0); } private boolean updatePresenceToGone() { return new RemoteTransactionHandler().runUpdatePresence(dbutil.getUser().getPersonalNumber(), "", PresenceState.GONE); } private static boolean isYesterday(Date capturingDay) { Date yesterday = DateTimeUtil.getYesterday().getTime(); return (capturingDay.compareTo(yesterday) == 0); } private static boolean isToday(Date capturingDay) { Date today = DateTimeUtil.getToday().getTime(); return (capturingDay.compareTo(today) == 0); } /** * - Search for a running time capturing * - Check if the current date is still the same date as the running JobTimeSheet entry * - Same day: * 1. Terminate the running JobTimeSheet (ZKDMOBRTIM) entry with the current time * - Next day: * 1. Terminate the running JobTimeSheet (ZKDMOBRTIM) entry with 23:59 of yesterday * 2. Create an new JobTimeSheet (ZKDMOBRTIM) entry starting at 00:00 and ending at the current time * - Any other day: * 1. Inform the user * 2. Terminate the running JobTimeSheet (ZKDMOBRTIM) entry with 23:59 of the day the entry was started * - Check if the current date/time does not overlap with existing JobTimeSheet entries * - Changes the job status to "angenommen" */ private void stopJobTimeCapturing() { List openJobTimeList = dbutil.selectJobWithOpenTimesheet(); Iterator itr = openJobTimeList.iterator(); while (itr.hasNext()) { stopJobTimeCapturing(itr.next()); } } /** * @param set List with all time sheet entries to check. The elements in the list must be ordered chronological (sort attribute VON) * @return The index (IDX) of the overlapping time sheet entry or -1 if no problems are detected. */ public int checkWorkTimesheetOverlapping(SortedSet timeSheetList) { int resultIdx = -1; Date temp = DateUtils.getInitialDateTime(); Iterator itr = timeSheetList.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = itr.next(); if (temp.compareTo(timeSheet.getStartTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || timeSheet.getStartTime().equals(DateUtils.getInitialDateTime())) temp = timeSheet.getStartTime(); else { resultIdx = timeSheet.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(timeSheet.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } if (temp.compareTo(timeSheet.getStopTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) temp = timeSheet.getStopTime(); else { resultIdx = timeSheet.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(timeSheet.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } } return resultIdx; } /** * @param set List with all time sheet entries to check. The elements in the list must be ordered chronological (sort attribute VON) * @return The index (IDX) of the overlapping time sheet entry or -1 if no problems are detected. */ private int checkJobTimesheetOverlapping(SortedSet timesheetList) { int resultIdx = -1; Date temp = DateUtils.getInitialDateTime(); Iterator itr = timesheetList.iterator(); while (itr.hasNext()) { JobReportTime jobReportTime = itr.next(); if (temp.compareTo(jobReportTime.getStartTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || jobReportTime.getStartTime().equals(DateUtils.getInitialDateTime())) temp = DateTimeUtil.getTime(jobReportTime.getStartTime()).getTime(); else { resultIdx = jobReportTime.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(jobReportTime.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } if (temp.compareTo(jobReportTime.getStopTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || jobReportTime.getStopTime().equals(DateUtils.getInitialDateTime())) temp = jobReportTime.getStopTime(); else { resultIdx = jobReportTime.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(jobReportTime.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } } return resultIdx; } /** * @param startTime * @param app * @return true if difference between start- and stop time is bigger than 3 minutes or if user agrees on a difference smaller than 3 minutes. * false if user cancels warning. */ protected boolean checkMinumumCapturingTime(Date startTime) { boolean result = false; // Check if a minimum of 3 minutes is recorded before stopping the time capturing Date now = DateTimeUtil.getNow().getTime(); Calendar cal = DateTimeUtil.getTime(startTime); cal.add(Calendar.MINUTE, 3); if (cal.getTime().before(now)) { result = true; } else { if (app.showMessageBox(Messages.getString("StartEndLessThan3MinutesApart"), Messages.getString("warning"), Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { //$NON-NLS-1$ //$NON-NLS-2$ result = true; } } return result; } public void showWarningMessageBox(final String warningMessage){ app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { app.showMessageBox(warningMessage, Messages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } public void stopWorkTimeCapturing(final RunOnUIThread runOnUIThread) { new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if(stopWorkTimeCapturing()) { stopJobTimeCapturing(); } return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); runOnUIThread.runOnUIThread(); } }; } public void startWorkTimeCapturing(final String arba, final boolean pikett, final RunOnUIThread runOnUIThread) { startWorkTimeCapturing(arba, pikett, null, runOnUIThread); } public void startWorkTimeCapturing(final String arba, final boolean pikett, final Job job, final RunOnUIThread runOnUIThread) { new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (job != null) { new RemoteTransactionHandler().updateStatus(paramDBSession, job, JobStatus.IN_PROGRESS, JobStatus.SAP_InProgress, ""); //$NON-NLS-1$ } startWorkTimeCapturing(arba, pikett); return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); runOnUIThread.runOnUIThread(); } }; } public class TimeUtilThread extends Thread { Job job; public TimeUtilThread (Job job) { this.job = job; this.setName("TimeUtilThread"); } public void run() { log.info(this.getName() + " started."); long timeDiff = latestTime.getTimeInMillis() - Calendar.getInstance().getTimeInMillis(); while(Calendar.getInstance().getTimeInMillis() < latestTime.getTimeInMillis()){ log.info("sleep for " + DateTimeUtil.showTime(timeDiff) + " minutes."); try { Thread.sleep(timeDiff); } catch (InterruptedException e) { log.info("Stop waiting thread."); return; } } log.info(this.getName() + " very late at night."); job.getLatestReport().checkIfTimeStartOverOndDay(dbutil); new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { app.getCurrentForm().onFormShow(); } }; } } }     common/src/ch/mfiles/kaba/kolibri/common/util/TranslationFileConverter.java:   package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TranslationFileConverter { private static Log log = LogFactory.getLog(TranslationFileConverter.class); private static TranslationFileConverter pfc; private static final String EN_FILE_NAME = "Messages.properties"; //$NON-NLS-1$ // private static final String DE_FILE_NAME = "Messages_de_CH.properties"; private static final String DE_FILE_NAME = "Messages_de.properties"; //$NON-NLS-1$ // private static final String FR_FILE_NAME = "Messages_fr_CH.properties"; private static final String FR_FILE_NAME = "Messages_fr.properties"; //$NON-NLS-1$ private static String startPath = null; private FileOutputStream en; private FileOutputStream de; private FileOutputStream fr; StringBuilder enProperties; StringBuilder deProperties; StringBuilder frProperties; // private Properties enProperties; // private Properties deProperties; // private Properties frProperties; private BufferedReader translationReader; public TranslationFileConverter(File translation) { // Pfad erstellen String path = startPath + translation.getName().substring(0, translation.getName().indexOf(".convert")).replace('.', '/') + '/'; //$NON-NLS-1$ // Properties Dateien erstellen FileInputStream fis1 = null; try { new File(path).mkdirs(); if(new File(path + EN_FILE_NAME).createNewFile()) { // do nothing. } if(new File(path + DE_FILE_NAME).createNewFile()) { // do nothing. } if(new File(path + FR_FILE_NAME).createNewFile()) { // do nothing. } en = new FileOutputStream(path + EN_FILE_NAME); de = new FileOutputStream(path + DE_FILE_NAME); fr = new FileOutputStream(path + FR_FILE_NAME); fis1 = new FileInputStream(translation); InputStreamReader isr1 = new InputStreamReader(fis1, "UTF-8"); //$NON-NLS-1$ translationReader = new BufferedReader(isr1); } catch (FileNotFoundException e) { log.error(e); } catch (UnsupportedEncodingException e) { log.error(e); } catch (IOException e) { log.error(e); } finally { if(fis1!=null) { try { fis1.close(); } catch (IOException e) { log.error(e); } } } enProperties = new StringBuilder(); deProperties = new StringBuilder(); frProperties = new StringBuilder(); } public static void main(String[] args) throws IOException { startPath = "C:/MyData/Kaba_JavaTranslation/Convert/"; //$NON-NLS-1$ traverse(new File(startPath), pfc.new DirectoryPrintVisitor()); log.info("Convert SQL complete."); //$NON-NLS-1$ } static void traverse(File dir, DirectoryVisitor visitor) { if (!dir.isDirectory()) { throw new IllegalArgumentException("not a directory: " + dir.getName()); //$NON-NLS-1$ } visitor.enterDirectory(dir); File[] entries = dir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".convert"); //$NON-NLS-1$ } }); for (int i = 0; i < entries.length; ++i) { if (entries[i].isDirectory()) { traverse(entries[i], visitor); } else { pfc = new TranslationFileConverter(entries[i]); try { pfc.convert(); } catch (IOException e) { log.error(e); } visitor.visitFile(entries[i]); } } visitor.leaveDirectory(dir); } public boolean convert() throws IOException { String line = ""; //$NON-NLS-1$ int posTab1; int posTab2; int posTab3; int posTab4; String key; String enTxt; String deTxt; String frTxt; try { while ((line = translationReader.readLine()) != null) { log.info(line); posTab1 = line.indexOf('\t', 0); posTab2 = line.indexOf('\t', posTab1+1); posTab3 = line.indexOf('\t', posTab2+1); posTab4 = line.indexOf('\t', posTab3+1); key = line.substring(0, posTab1).trim(); enTxt = line.substring(posTab1 + 1, posTab2); deTxt = line.substring(posTab2 + 1, posTab3); frTxt = line.substring(posTab3 + 1, line.length()); enProperties.append(key + " = " + enTxt + '\n'); //$NON-NLS-1$ deProperties.append(key + " = " + deTxt + '\n'); //$NON-NLS-1$ frProperties.append(key + " = " + frTxt + '\n'); //$NON-NLS-1$ } } catch (IOException e) { log.error(e); } finally { Writer enOut = new OutputStreamWriter(en, "ISO-8859-1"); //$NON-NLS-1$ enOut.write(enProperties.toString()); enOut.close(); en.close(); Writer deOut = new OutputStreamWriter(de, "ISO-8859-1"); //$NON-NLS-1$ deOut.write(deProperties.toString()); deOut.close(); de.close(); Writer frOut = new OutputStreamWriter(fr, "ISO-8859-1"); //$NON-NLS-1$ frOut.write(frProperties.toString()); frOut.close(); fr.close(); translationReader.close(); } return true; } interface DirectoryVisitor { public void enterDirectory(File dir); public void leaveDirectory(File dir); public void visitFile(File file); } class DirectoryPrintVisitor implements DirectoryVisitor { String indent = ""; //$NON-NLS-1$ @Override public void enterDirectory(File dir) { indent += " "; //$NON-NLS-1$ } @Override public void leaveDirectory(File dir) { indent = indent.substring(2); } @Override public void visitFile(File file) { log.info(file.getAbsolutePath()); } } }     common/test/ch/mfiles/kaba/kolibri/common/util/DateTimeUtilTest.java:   package ch.mfiles.kaba.kolibri.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import org.junit.Test; import junit.framework.TestCase; public class DateTimeUtilTest extends TestCase { public DateTimeUtilTest(String name) { super(name); } @Test public void testGetTimeDifference() throws ParseException { String dateStartStr = "11/03/17 08:29:00"; //$NON-NLS-1$ String dateStopStr = "11/03/17 09:33:00"; //$NON-NLS-1$ SimpleDateFormat format = new SimpleDateFormat(DateTimeUtil.DATE_TIME_FORMAT); Date dateStart = format.parse(dateStartStr); Date dateStop = format.parse(dateStopStr); long timeDiff = DateTimeUtil.getTimeDifference(dateStop, dateStart); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$ calendar.setTimeInMillis(timeDiff); // hours assertEquals(1, calendar.get(Calendar.HOUR)); // minutes assertEquals(4, calendar.get(Calendar.MINUTE)); } /** * @see "[MIG-100] calculation of "total time recorded" on report overview" */ @Test public void testShowTime() throws ParseException { String dateStartStr = "11/03/17 08:29:00"; //$NON-NLS-1$ String dateStopStr = "11/03/17 09:33:00"; //$NON-NLS-1$ SimpleDateFormat format = new SimpleDateFormat(DateTimeUtil.DATE_TIME_FORMAT); // when the millisecond is 0 assertEquals("00:00", DateTimeUtil.showTime(0)); //$NON-NLS-1$ // when the millisecond is not 0 (expected "01:04" ) Date dateStart = format.parse(dateStartStr); Date dateStop = format.parse(dateStopStr); long timeDiff = DateTimeUtil.getTimeDifference(dateStop, dateStart); assertEquals("01:04", DateTimeUtil.showTime(timeDiff)); //$NON-NLS-1$ } }     common/test/ch/mfiles/kaba/kolibri/common/util/StringUtilTest.java:   package ch.mfiles.kaba.kolibri.common.util; import org.junit.Test; import junit.framework.TestCase; public class StringUtilTest extends TestCase { public StringUtilTest(String name) { super(name); } /** * @see "[MIG-142] don't show the leading "0" of a job number" */ @Test public void testRemoveAllLeadingZero() { String actual = "0000434704"; //$NON-NLS-1$ String expected = "434704"; //$NON-NLS-1$ assertEquals(expected, StringUtil.removeAllLeadingZero(actual)); assertEquals(expected, StringUtil.removeAllLeadingZero(expected)); } /** * @see "[MIG-515] Format of article isn't proved correct" */ @Test public void testFormatArticle() { assertEquals("45-5", StringUtil.getMaterialNoFromText("5")); assertEquals("45-41", StringUtil.getMaterialNoFromText("41")); assertEquals("45-", StringUtil.getMaterialNoFromText("45-")); assertEquals("45-1", StringUtil.getMaterialNoFromText("45-1")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12.")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12+")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12/")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12*")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12-")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12(")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12)")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12 ")); assertEquals("45-1234-", StringUtil.getMaterialNoFromText("45-1234-")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12%")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12^")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12@")); assertEquals("45-1234-123", StringUtil.getMaterialNoFromText("45-1234-123")); assertEquals("45-1234-123/", StringUtil.getMaterialNoFromText("45-1234-123-")); assertEquals("45-1234-123/", StringUtil.getMaterialNoFromText("45-1234-123/")); assertEquals("45-1234-123/6", StringUtil.getMaterialNoFromText("45-1234-123/6")); assertEquals("45-1234-123/6", StringUtil.getMaterialNoFromText("45-1234-123/6-")); assertEquals("45-1234-123/12", StringUtil.getMaterialNoFromText("45-1234-123/12")); assertEquals("45-41", StringUtil.getMaterialNoFromText("41")); assertEquals("45-5", StringUtil.getMaterialNoFromText("5")); assertEquals("45-5612", StringUtil.getMaterialNoFromText("5612")); } /** * @see "[MIG-562] Scanning of barcodes doesn't work anymore" */ @Test public void testScanMaterialNo() { assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("4682326")); assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("4682326 1")); assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("46823261")); assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("45-4682-326")); assertEquals("45-0701-080/00", StringUtil.getMaterialNoFromScan("45-0701-080/00")); assertEquals("45-0701-080/00", StringUtil.getMaterialNoFromScan("45070108000")); assertEquals("45-6465-001", StringUtil.getMaterialNoFromScan("6465001XX.13080008")); } }     gradlew.bat:   @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega     gradle/wrapper/gradle-wrapper.properties:   distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists     login/AndroidManifest.xml:       login/application.dtd:       login/application.xml:       login/build.gradle.kts:   plugins { id("ch.mfiles.kolibri-application") } dependencies { implementation(project(":common")) }     login/build.xml:       login/i18n/ch/mfiles/kaba/kolibri/login/LoginMessages.java:   package ch.mfiles.kaba.kolibri.login; import java.util.MissingResourceException; import java.util.ResourceBundle; public class LoginMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.login.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private LoginMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }     login/i18n/ch/mfiles/kaba/kolibri/login/messages.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) #Generated by Eclipse Messages Editor (Eclipse Babel) AbbreviationDoesNotMatch = Abbreviation does not match. Abbreviations = Abbreviation Confirm = Confirm ConfirmTheAbbreviation = Confirm the abbreviation KolibriID = Kolibri ID KolibriIDSuccessfullySet = Kolibri ID Successfully Set LoginForm.0 = OK LoginForm.1 = The user name field is required. LoginForm.2 = The password field is required. LoginForm.3 = Activating device... LoginForm.4 = The newly activated user {0} has not application data assigned. All locally present application data will be deleted. Continue? LoginForm.5 = Activate new user... NoKolibriID = No Kolibri ID available. Please enter your abbreviation. addressNotTransmittedYet = {0} address(es) not transmitted yet.\n appInformations = App informations backendUrlNotSet = BackendUrl not set. checkSWUpdate = Check sw-update continueWithUserSwitch = Continue with user switch? deviceType = Device type error = Error exitApplication = Exit application frameworkRegistry = Framework registry gilgenCommonApplicationIsNotInstalled = The Gilgen Common application is not installed! The Gilgen Service cannot run. invalidPassword = Invalid password invalidUsername = Invalid user name invalidUsernameOrPassword = invalid username or password login = Login middlewareUrlNotSet. = MiddlewareUrl not set. noUserFound = No user found password = Password passwordCannotBeEmpty = Password field cannot be empty refreshMasterdata = Refresh masterdata reportNotTransmittedYet = {0} report(s) not transmitted yet.\n shortMessageNotConfirmed = {0} short message(s) not confirmed.\n startGilgenService = Start Gilgen Service synchronizeFailed = Synchronize failed! timesheetNotTransmittedYet = {0} timesheet(s) not transmitted yet.\n username = User name usernameCannotBeEmpty = User name field cannot be empty warning = Warning!     login/i18n/ch/mfiles/kaba/kolibri/login/Messages.txt:   LoginApplication.1 The Gilgen Common application is not installed\! The Gilgen Service cannot run. LoginApplication.2 Start Gilgen Service     login/i18n/ch/mfiles/kaba/kolibri/login/messages_de.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AbbreviationDoesNotMatch = Kurzzeichen stimmt nicht \u00FCberein. Abbreviations = Kurzzeichen Confirm = Best\u00E4tigen ConfirmTheAbbreviation = Kurzzeichen best\u00E4tigen KolibriID = Kolibri-ID erfassen KolibriIDSuccessfullySet = Kolibri-ID erfolgreich gesetzt LoginForm.0 = OK LoginForm.1 = Eingabe des Benutzernamens ist obligatorisch. LoginForm.2 = Eingabe des Passworts ist obligatorisch. LoginForm.3 = Aktiviere Ger\u00E4t... LoginForm.4 = Dem neu aktivierten Benutzer {0} sind keine Anwendungsdaten zugeordnet. Alle lokal vorhandenen Anwendungsdaten werden gel\u00F6scht. Weiter? LoginForm.5 = Neuen Benutzer aktivieren... NoKolibriID = Keine Kolibri-ID vorhanden. Bitte erfassen Sie ihr Kurzzeichen. addressNotTransmittedYet = {0} Adressen noch nicht \u00FCbermittelt.\n appInformations = App-Informationen backendUrlNotSet = BackendUrl nicht gesetzt. checkSWUpdate = Software-Update continueWithUserSwitch = Weiterfahren mit Benutzerwechsel? deviceType = Ger\u00E4tetyp error = Fehler exitApplication = Beenden frameworkRegistry = Registry gilgenCommonApplicationIsNotInstalled = Die Common-Applikation ist nicht installiert. Die Service-Applikation kann darum nicht gestartet werden. invalidPassword = Passwort ung\u00FCltig. invalidUsername = Kein g\u00FCltiger Benutzername. invalidUsernameOrPassword = Benutzername oder Passwort falsch. login = Login middlewareUrlNotSet. = Middleware-URL nicht gesetzt. noUserFound = Kein Benutzer gefunden password = Passwort passwordCannotBeEmpty = Passwort darf nicht leer sein. refreshMasterdata = Stammdaten aktualisieren reportNotTransmittedYet = {0} Rapporte noch nicht \u00FCbermittelt.\n shortMessageNotConfirmed = {0} Kurznachrichten noch nicht best\u00E4tigt.\n startGilgenService = Start Gilgen Service synchronizeFailed = Synchronisieren fehlgeschlagen! timesheetNotTransmittedYet = {0} noch nicht \u00FCbermittelte Zeiterfassungen.\n username = Benutzername usernameCannotBeEmpty = Benutzername darf nicht leer sein. warning = Warnung!     login/i18n/ch/mfiles/kaba/kolibri/login/messages_fr.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AbbreviationDoesNotMatch = Le sigle ne correspond pas. Abbreviations = Sigle Confirm = Confirmer ConfirmTheAbbreviation = Confirmer le sigle KolibriID = Identification du Kolibri KolibriIDSuccessfullySet = Identification du Kolibri r\u00E9ussie LoginForm.0 = OK LoginForm.1 = Nom d'utilisateur est obligatoire. LoginForm.2 = Mot de passe est obligatoire. LoginForm.3 = Activer l'appareil... LoginForm.4 = Aucune donn\u00E9e d'application n'est attribu\u00E9e \u00E0 l'utilisateur {0} d\u00E9sormais activ\u00E9. Toutes les donn\u00E9es d'application pr\u00E9sentes localement seront supprim\u00E9es. Continuer? LoginForm.5 = Activer nouvel utilisateur... NoKolibriID = Pas d'identification Kolibri disponible. Veuillez s.v.p. saisir votre sigle. addressNotTransmittedYet = {0} Adresses pas encore transmises.\n appInformations = Informations sur l'application backendUrlNotSet = BackendUrl n'est pas d\u00E9fini. checkSWUpdate = Mise \u00E0 jour logicielle continueWithUserSwitch = Continuer avec changement d'utilisateur? deviceType = Ger\u00E4tetyp error = Erreur exitApplication = Sortie frameworkRegistry = Registre cadre gilgenCommonApplicationIsNotInstalled = L'application commune Gilgen n'est pas install\u00E9e. Le service Gilgen ne peut pas fonctionner. invalidPassword = Mot de passe invalide. invalidUsername = Nom d'utilisateur invalide. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect login = Login middlewareUrlNotSet. = Middleware-URL pas mis. noUserFound = Aucun utilisateur trouv\u00E9 password = Mot de passe passwordCannotBeEmpty = Le champ du mot de passe ne peut pas \u00EAtre vide. refreshMasterdata = Actualiser les donn\u00E9es de base reportNotTransmittedYet = {0} Rapports pas encore transmis.\n shortMessageNotConfirmed = {0} Flash d'informations pas encore confirm\u00E9s.\n startGilgenService = D\u00E9marrage service Gilgen synchronizeFailed = Synchronisation \u00E9chou\u00E9! timesheetNotTransmittedYet = {0} saisies de temps pas encore transmises.\n username = Nom d'utilisateur usernameCannotBeEmpty = Le champ nom d'utilisateur ne peut pas \u00EAtre vide. warning = Avertissement!     login/i18n/ch/mfiles/kaba/kolibri/login/messages_it.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AbbreviationDoesNotMatch = Le sigle ne correspond pas. Abbreviations = Sigle Confirm = Confirmer ConfirmTheAbbreviation = Confirmer le sigle KolibriID = Identification du Kolibri KolibriIDSuccessfullySet = Identification du Kolibri r\u00E9ussie LoginForm.0 = OK LoginForm.1 = Nom d'utilisateur est obligatoire. LoginForm.2 = Mot de passe est obligatoire. LoginForm.3 = Activer l'appareil... LoginForm.4 = Aucune donn\u00E9e d'application n'est attribu\u00E9e \u00E0 l'utilisateur {0} d\u00E9sormais activ\u00E9. Toutes les donn\u00E9es d'application pr\u00E9sentes localement seront supprim\u00E9es. Continuer? LoginForm.5 = Activer nouvel utilisateur... NoKolibriID = Pas d'identification Kolibri disponible. Veuillez s.v.p. saisir votre sigle. addressNotTransmittedYet = {0} Adresses pas encore transmises.\n appInformations = Informations sur l'application backendUrlNotSet = BackendUrl n'est pas d\u00E9fini. checkSWUpdate = Mise \u00E0 jour logicielle continueWithUserSwitch = Continuer avec changement d'utilisateur? deviceType = Ger\u00E4tetyp error = Erreur exitApplication = Sortie frameworkRegistry = Registre cadre gilgenCommonApplicationIsNotInstalled = L'application commune Gilgen n'est pas install\u00E9e. Le service Gilgen ne peut pas fonctionner. invalidPassword = Mot de passe invalide. invalidUsername = Nom d'utilisateur invalide. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect login = Login middlewareUrlNotSet. = Middleware-URL pas mis. noUserFound = Aucun utilisateur trouv\u00E9 password = Mot de passe passwordCannotBeEmpty = Le champ du mot de passe ne peut pas \u00EAtre vide. refreshMasterdata = Actualiser les donn\u00E9es de base reportNotTransmittedYet = {0} Rapports pas encore transmis.\n shortMessageNotConfirmed = {0} Flash d'informations pas encore confirm\u00E9s.\n startGilgenService = D\u00E9marrage service Gilgen synchronizeFailed = Synchronisation \u00E9chou\u00E9! timesheetNotTransmittedYet = {0} saisies de temps pas encore transmises.\n username = Nom d'utilisateur usernameCannotBeEmpty = Le champ nom d'utilisateur ne peut pas \u00EAtre vide. warning = Avertissement!     login/project.properties:   # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23     login/sonar.xml:       login/src/ch/mfiles/kaba/kolibri/login/forms/KolibriIdForm.java:   package ch.mfiles.kaba.kolibri.login.forms; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.login.LoginMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; public class KolibriIdForm extends LoginNavigationForm implements TextWatcher, OnClickListener { private static Log log = LogFactory.getLog(KolibriIdForm.class); private Context context; private MDEditText initials; private MDEditText confirmIntials; private MDSpinner deviceTypeValue; private AppCompatButton confirmButton; @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; Toolbar toolbar = getToolbar(); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 25), LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 15)); TextView headerText = new TextView(context); headerText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); headerText.setTypeface(CommonConstants.Font.getDefaultMediumFont()); headerText.setText(LoginMessages.getString("NoKolibriID")); //$NON-NLS-1$ contentLinearLayout.addView(headerText); // kokibri id initials = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("Abbreviations"), //$NON-NLS-1$ InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_NORMAL, true, this); // confirm confirmIntials = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("ConfirmTheAbbreviation"), //$NON-NLS-1$ InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_NORMAL, true, this); LinearLayout deviceTypeLinearLayout = new LinearLayout(context); deviceTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deviceTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); deviceTypeValue = MDSpinner.createDefaultSpinner(deviceTypeLinearLayout, LoginMessages.getString("deviceType"), false); //$NON-NLS-1$ deviceTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { deviceTypeValue.clearError(); } }); contentLinearLayout.addView(deviceTypeLinearLayout); // submit button GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); confirmButton = new AppCompatButton(context); LinearLayout.LayoutParams submitButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); submitButtonParams.gravity = Gravity.RIGHT; submitButtonParams.topMargin = LayoutUtils.convertDpToPixel(context, 20); confirmButton.setLayoutParams(submitButtonParams); confirmButton.setText(LoginMessages.getString("Confirm")); //$NON-NLS-1$ confirmButton.setOnClickListener(this); confirmButton.setBackgroundDrawable(gradientDrawable); contentLinearLayout.addView(confirmButton); scrollView.addView(contentLinearLayout); linearLayout.addView(scrollView); relativeLayout.addView(linearLayout); getContentView().addView(relativeLayout); return getView(); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(LoginMessages.getString("KolibriID")); //$NON-NLS-1$ List deviceTypeValueList = new ArrayList(); deviceTypeValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, Messages.getString("pleaseSelect"))); deviceTypeValueList.add(new CustomSpinnerItem("s", "Smartphone")); deviceTypeValueList.add(new CustomSpinnerItem("t", "Tablet")); deviceTypeValue.setContents(deviceTypeValueList); return null; } // gets text view. protected TextView getTextView(String text) { TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textView.setText(text); textView.setTextColor(Color.GRAY); return textView; } @Override public void onFormReset() { super.onFormReset(); initials.getText().clear(); confirmIntials.getText().clear(); deviceTypeValue.clearContents(); } @Override public void onClick(View v) { if (isValid()) { app.showMessage(LoginMessages.getString("KolibriIDSuccessfullySet")); //$NON-NLS-1$ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { Random rand = new Random(); int randomNum = rand.nextInt((999 - 100) + 1) + 100; // String kolibriId = confirmIntials.getText().toString().toLowerCase() + "_" + deviceTypeValue.getSelectedId() + "_" + randomNum; log.info("kolibriId " + kolibriId); reg.setProperty(CommonConstants.KOLIBRI_ID, kolibriId); return appman.restartFramework(); } }, false); } } private boolean isValid() { boolean result = true; if (initials.getText().toString().isEmpty() || confirmIntials.getText().toString().isEmpty()) { result = false; } if (!initials.getText().toString().equals(confirmIntials.getText().toString())) { result = false; } if(deviceTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { deviceTypeValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } if (!result) { app.inform(LoginMessages.getString("AbbreviationDoesNotMatch")); //$NON-NLS-1$ } return result; } @Override public void afterTextChanged(Editable s) { // unused } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // unused } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (initials.hasFocus()) { initials.clearError(); } if (confirmIntials.hasFocus()) { confirmIntials.clearError(); } if (initials.getText().toString().length() > 0 && confirmIntials.getText().toString().length() > 0) { confirmButton.setEnabled(true); } else { confirmButton.setEnabled(false); } } }     login/src/ch/mfiles/kaba/kolibri/login/forms/LoginForm.java:   package ch.mfiles.kaba.kolibri.login.forms; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler.DeleteAppDataFunction; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.login.LoginMessages; import ch.mfiles.kaba.kolibri.util.LoginConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.SimpleUserInterface; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.SubProgressMonitor; public class LoginForm extends LoginNavigationForm implements TextWatcher, OnClickListener { private static Log log = LogFactory.getLog(LoginForm.class); private Context context; private MDEditText userName; private MDEditText password; private AppCompatButton submitButton; private int switchModeCount = 0; private int maxClickedToSwitchMode = 5; @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; Toolbar toolbar = getToolbar(); // toolbar.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // if(CommSetupHelper.isProductionEnvironment()) { // switchModeCount++; // // app.showMessage("Click more " + (maxClickedToSwitchMode - switchModeCount) + " times to change to Devlopment environment.", true); // if(switchModeCount == maxClickedToSwitchMode) { // switchModeCount = 0; // app.showMessage("You are now in Devlopment environment!", true); // // CommSetupHelper.setupDevelopmentEnvironment(); // CommSetupHelper.setEnvironmentLayout(); // // } // } // } // }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); ImageView headerImageView = new ImageView(context); LinearLayout.LayoutParams headerImageViewParams = new LinearLayout.LayoutParams(0, 0); headerImageViewParams.width = LayoutParams.MATCH_PARENT; headerImageViewParams.height = LayoutUtils.convertDpToPixel(context, 120); headerImageView.setLayoutParams(headerImageViewParams); headerImageView.setImageDrawable( getBitmanDrawable(app.getImage(LoginConstants.Images.HEADER, CommonConstants.Images.IMAGE_DPI))); headerImageView.setScaleType(ScaleType.FIT_XY); linearLayout.addView(headerImageView); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 25), LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 15)); // User name userName = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("username"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL, true, this); userName.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String name = userName.getText().toString(); String reg = "^[0-9]{1,8}$"; //$NON-NLS-1$ Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(userName.getText().toString()); if (name != null && name.length() > 0 && !matcher.matches()) { userName.setError(LoginMessages.getString("invalidUsername")); //$NON-NLS-1$ } } } }); // Password password = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("password"), //$NON-NLS-1$ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD, true, this); // submit button GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); submitButton = new AppCompatButton(context); LinearLayout.LayoutParams submitButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); submitButtonParams.gravity = Gravity.RIGHT; submitButtonParams.topMargin = LayoutUtils.convertDpToPixel(context, 20); submitButton.setLayoutParams(submitButtonParams); submitButton.setText(LoginMessages.getString("LoginForm.0")); //$NON-NLS-1$ submitButton.setOnClickListener(this); submitButton.setBackgroundDrawable(gradientDrawable); contentLinearLayout.addView(submitButton); scrollView.addView(contentLinearLayout); linearLayout.addView(scrollView); relativeLayout.addView(linearLayout); getContentView().addView(relativeLayout); return getView(); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); switchModeCount = 0; // set dialog's title setFormTitle(LoginMessages.getString("login")); //$NON-NLS-1$ StringBuilder errorMessage = new StringBuilder(); if (StringUtil.isEmpty(tr.getDefaultMiddlewareUrl())) { errorMessage.append(LoginMessages.getString("middlewareUrlNotSet.")); //$NON-NLS-1$ } if (StringUtil.isEmpty(tr.getDefaultBackendUrl())) { if (StringUtil.isNotEmpty(errorMessage.toString())) errorMessage.append("\n"); //$NON-NLS-1$ errorMessage.append(LoginMessages.getString("backendUrlNotSet")); //$NON-NLS-1$ } if (errorMessage.toString().length() > 0) { if (StringUtil.isNotEmpty(errorMessage.toString())) errorMessage.append("\n"); //$NON-NLS-1$ app.showMessage(errorMessage.toString()); } try { Person lastUser = app.dbutil.getUser(true); if (lastUser.getPersonalNumber() != 0) { userName.setText(Integer.toString(lastUser.getPersonalNumber())); } } catch (ApplicationException e) { app.showMessage(LoginMessages.getString("noUserFound")); //$NON-NLS-1$ log.error(e); } Registry reg = appman.getRegistry(null); if (reg.getProperty(CommonConstants.KOLIBRI_ID).isEmpty()) { return appman.getActiveApplication().callForm(KolibriIdForm.class); } // if (userName.getText().toString().length() > 0 && password.getText().toString().length() > 0) // submitButton.setEnabled(true); // else // submitButton.setEnabled(false); return null; } // gets text view. protected TextView getTextView(String text) { TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textView.setText(text); textView.setTextColor(Color.GRAY); return textView; } @Override public void onFormReset() { super.onFormReset(); userName.getText().clear(); password.getText().clear(); } @Override public void onClick(View v) { if (isValid()) new LoginTask(this, userName.getText().toString(), password.getText().toString()); } private static class LoginTask extends AsyncTask { private LoginForm mLoginForm; private volatile String mUsername; private volatile String mPassword; private volatile boolean mRepeatLogin = false; private volatile Person mOldUser; public LoginTask(LoginForm loginForm, String username, String password) { super(loginForm); mLoginForm = loginForm; mUsername = username; mPassword = password; } @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (log.isDebugEnabled()) { log.debug("pernr /" + mUsername + "/ pass /" + mPassword + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } int pernr = -1; try { pernr = Integer.parseInt(mUsername); } catch (NumberFormatException e) { app.inform(LoginMessages.getString("invalidUsernameOrPassword")); //$NON-NLS-1$ return null; } final int finalPernr = pernr; try { mOldUser = app.dbutil.getUser(); if (pernr == mOldUser.getPersonalNumber()) { // There is already an entry in table ZKDMOBMA and user / // password matches if (mPassword.equalsIgnoreCase(mOldUser.getPassword())) { return leaveToService(pernr, monitor); } // There is already an entry in the table ZKDMOBMA and the // user matches but the password is incorrect else { app.inform(LoginMessages.getString("invalidUsernameOrPassword")); //$NON-NLS-1$ return null; } } // There is already an entry in the table ZKDMOBMA but the user // doesn't match a user switch is initiated if (!registerUser(pernr, mPassword)) return null; if (!isUnsavedData(pernr, monitor)) { // there is no unsaved data and continue and delete // all this information (display a modal dialog to // confirm), continue with c) deleteOldUser(mOldUser.getPersonalNumber(), pernr, monitor); return leaveToService(pernr, monitor); } } catch (ApplicationException e) { // No entry in table ZKDMOBMA yet log.error(e); if (registerUser(pernr, mPassword) && app.dbutil.selectCountFromTable(DbConstants.WorkType.WORK_TYPE, "") == 0) { //$NON-NLS-1$ new RemoteTransactionHandler().runRefreshMasterdata(finalPernr, "", "X", monitor); //$NON-NLS-1$ //$NON-NLS-2$ return leaveToService(pernr, monitor); } } return null; } @Override protected void runOnUIThread() { if (mRepeatLogin) { mLoginForm.userName.setText(Integer.toString(mOldUser.getPersonalNumber())); mLoginForm.password.setText(""); //$NON-NLS-1$ mLoginForm.submitButton.setEnabled(false); } } private boolean isUnsavedData(final int pernr, final ProgressMonitor monitor) { /* * a) use REGISTER_USER in order to verify if the new user is valid b) check if * there is unsaved data and allow the user to cancel if there is any Display a * form with the following information: - number of unsaved addresses - number * of unsaved reports (REPORTSTATUS = 0) - number of unsaved timesheets - number * of unsaved material orders - number of not confirmed shortmessages */ int unsavedAddresses = app.dbutil.countUnsavedAddresses(); int unsavedReports = app.dbutil.countUnsavedReport(); int unsavedTimesheets = app.dbutil.countUnsavedCalendar(app.dbutil.getUser().getPersonalNumber()); int notConfirmedShortSMS = app.dbutil.countNotConfirmedSHortMSG(); boolean unsavedData = false; final StringBuilder sbUnsavedData = new StringBuilder(); if (unsavedAddresses > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("addressNotTransmittedYet"), //$NON-NLS-1$ new Object[] { Integer.toString(unsavedAddresses) })); unsavedData = true; } if (unsavedReports > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("reportNotTransmittedYet"), //$NON-NLS-1$ new Object[] { Integer.toString(unsavedReports) })); unsavedData = true; } if (unsavedTimesheets > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("timesheetNotTransmittedYet"), //$NON-NLS-1$ new Object[] { Integer.toString(unsavedTimesheets) })); unsavedData = true; } if (notConfirmedShortSMS > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("shortMessageNotConfirmed"), //$NON-NLS-1$ new Object[] { Integer.toString(notConfirmedShortSMS) })); unsavedData = true; } if (unsavedData) { if (app.showMessageBox(sbUnsavedData.toString() + LoginMessages.getString("continueWithUserSwitch"), //$NON-NLS-1$ LoginMessages.getString("warning"), Application.MBOX_BUTTON_OK_CANCEL, //$NON-NLS-1$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { // b2) continue and delete all this // information(display a modal dialog to // confirm), continue with c) deleteOldUser(mOldUser.getPersonalNumber(), mOldUser.getPersonalNumber(), monitor); app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return leaveToService(pernr, monitor); } }, false); } else { // b1) cancel and go back to the Login // Form (in order to login with the old user) app.dbutil.deleteNewUser(Integer.parseInt(mUsername)); mRepeatLogin = true; } } return unsavedData; } private ApplicationEvent leaveToService(final int pernr, final ProgressMonitor monitor) { monitor.begin(LoginMessages.getString("LoginForm.3"), 100); //$NON-NLS-1$ // process device activation after a successful user login if (!DeviceMirrorringHandler.getInstance().processLogin(String.valueOf(pernr), app, new SubProgressMonitor(monitor, 80), new DeleteAppDataFunction() { @Override public boolean deleteApplicationData(SimpleUserInterface ui) { if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox(MessageFormat.format( LoginMessages.getString("LoginForm.4"), //$NON-NLS-1$ pernr), LoginMessages.getString("LoginForm.5"), SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_WARNING)) return false; deleteOldUser(-1, pernr, monitor); return true; } })) { // activation failed - repeat login monitor.completed(); return null; } // continue login by switching to the service application app.dbutil.setupFixedMasterData(false); monitor.worked(10); // Server time synchronization new RemoteTransactionHandler().runSynchronize(app.dbutil.getUser().getPersonalNumber()); monitor.completed(); return app.appman.leaveToApplication(CommonConstants.Application.SERVICE_APP, null); } private boolean registerUser(final int user, final String passeord) { return new RemoteTransactionHandler().runRegisterUser(user, passeord); } private void deleteOldUser(final int oldUserPernr, final int newUserPernr, ProgressMonitor monitor) { // c) delete the data of the old user according to the table in chapter // 2.1.1 in Transaktionslogik_20090203.doc app.dbutil.deleteOldUser(oldUserPernr); app.dbutil.deleteAllJob(); app.dbutil.deleteAllAddress(); app.dbutil.deleteAllHistory(); app.dbutil.deleteAllReport(); app.dbutil.deleteAllJobMessage(); app.dbutil.deleteAllReportMaterial(); app.dbutil.deleteAllJobReportTime(); app.dbutil.deleteAllTimeSheet(); app.dbutil.deleteAllExpenses(); app.dbutil.deleteAllOrderMaterial(); app.dbutil.deleteAllOrder(); app.dbutil.deleteAllShortMessage(); app.dbutil.deleteAllWorkTypeT(); app.dbutil.deleteAllErrorCode(); app.dbutil.deleteAllMaterial(); app.dbutil.deleteAllEmployee(); app.dbutil.deleteAllMaterialOfPerson(); app.dbutil.deleteAllServerJob(); app.dbutil.deleteAllReason(); app.dbutil.deleteAllJobReason(); app.dbutil.deleteAllJobMonText(); app.dbutil.deleteAllIncident(); app.dbutil.deleteAllJobFormDesc(); app.dbutil.deleteAllJobNoForm(); app.dbutil.deleteAllReportMessage(); app.dbutil.deleteAllDrive(); app.dbutil.deleteAllBilling(); app.dbutil.deleteAllFormInstance(); // inform mirror handler, that user data has been destroyed DeviceMirrorringHandler.getInstance().setMirrorUserdataDeleted(); new RemoteTransactionHandler().runRefreshMasterdata(newUserPernr, "", "X", monitor); //$NON-NLS-1$ //$NON-NLS-2$ // if old and new user are identical, delete the user again, since master data refresh will // also refresh the user profile and thus recreate it unexpectedly if (oldUserPernr == newUserPernr) app.dbutil.deleteOldUser(oldUserPernr); } } private boolean isValid() { boolean result = true; if (userName.getText().toString().trim().isEmpty()) { userName.setError(LoginMessages.getString("LoginForm.1")); //$NON-NLS-1$ result = false; } if (password.getText().toString().trim().isEmpty()) { password.setError(LoginMessages.getString("LoginForm.2")); //$NON-NLS-1$ result = false; } return result; } @Override public void afterTextChanged(Editable s) { // unused } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // unused } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (userName.hasFocus()) { userName.clearError(); } if (password.hasFocus()) { password.clearError(); } if (userName.getText().toString().length() > 0 && password.getText().toString().length() > 0) { submitButton.setEnabled(true); } else { submitButton.setEnabled(false); } } }     login/src/ch/mfiles/kaba/kolibri/login/forms/LoginNavigationForm.java:   package ch.mfiles.kaba.kolibri.login.forms; import java.text.MessageFormat; import java.util.List; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.login.LoginApplication; import ch.mfiles.kaba.kolibri.login.LoginMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.RuntimeReleaseInfos; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The super class of all forms within this application. Contains common * members, methods and controls. * */ public abstract class LoginNavigationForm extends NavigationForm { // initialized by the kolibri framework... public static LoginApplication app; @Override public void onMenuItemClickListener(ListView menuView) { super.onMenuItemClickListener(menuView); menuView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, final View innerView, int position, long id) { onMenuItemClicked(innerView); } }); } private void onMenuItemClicked(final View innerView) { new AsyncTask(LoginNavigationForm.this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if ("REFRESH_MASTER_DATA".equals(innerView.getTag())) { //$NON-NLS-1$ Person crrentUser = app.dbutil.getUser(); new RemoteTransactionHandler() .runRefreshMasterdata(crrentUser.getPersonalNumber(), "", "X", monitor); //$NON-NLS-1$ //$NON-NLS-2$ } else if ("EXIT_APP".equals(innerView.getTag())) { //$NON-NLS-1$ return appman.exitApplication(); } else if ("CHECK_SOFTWARE_UPDATE".equals(innerView.getTag())) { //$NON-NLS-1$ switch(Runtime.getDeploymentManager().processDeployments(app, true, false, true)) { case PREPARED_NEED_RESTART: return appman.restartFramework(); case PREPARED_NEED_SHUTDOWN: return appman.exitFramework(); } } else if ("APP_INFORMATION".equals(innerView.getTag())) { //$NON-NLS-1$ app.showMessageBox(getVersionInfo(), "", Application.MBOX_BUTTON_OK, 0); //$NON-NLS-1$ } return null; } }; getView().closeDrawers(); } /** * Creates version information from currently deployed applications. * * @return */ private String getVersionInfo() { String loginVersion = getAppVersion("ch.mfiles.kaba.kolibri.login.LoginApplication"); //$NON-NLS-1$ String commonVersion = getAppVersion("ch.mfiles.kaba.kolibri.common.CommonApplication"); //$NON-NLS-1$ String materialVersion = getAppVersion("ch.mfiles.kaba.kolibri.material.MaterialApplication"); //$NON-NLS-1$ String serviceVersion = getAppVersion("ch.mfiles.kaba.kolibri.service.ServiceApplication"); //$NON-NLS-1$ String timeVersion = getAppVersion("ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication"); //$NON-NLS-1$ String appVersion; if (loginVersion.equals(commonVersion) && loginVersion.equals(materialVersion) && loginVersion.equals(serviceVersion) && loginVersion.equals(timeVersion)) // if all versions equal simply show *the* version appVersion = loginVersion; else // if one version differs, show all apps seperatly appVersion = MessageFormat.format( "\n - Common App: {0}\n - Login App: {1}\n - Material App: {2}\n - Service App: {3}\n - Timesheet App: {4}", //$NON-NLS-1$ commonVersion, loginVersion, materialVersion, serviceVersion, timeVersion); return MessageFormat.format("{0}: {1}({2})\n\nApp-Version: {3}", RuntimeReleaseInfos.getProduct(), //$NON-NLS-1$ RuntimeReleaseInfos.getRelease(), RuntimeReleaseInfos.getBuild(), appVersion); } private String getAppVersion(String app) { ApplicationDescriptor ad = appman.getApplicationDescriptor(app); if (ad == null) return "n/a"; //$NON-NLS-1$ return ad.getVersion(); } @Override public void onMenuItemLoad(List menuListView) { // App informations NavigationMenuListItem appInformations = new NavigationMenuListItem(); appInformations.setTag("APP_INFORMATION"); //$NON-NLS-1$ appInformations.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.INFORMATION, CommonConstants.Images.IMAGE_DPI))); appInformations.setText(LoginMessages.getString("appInformations")); //$NON-NLS-1$ menuListView.add(appInformations); // Refresh Master Data NavigationMenuListItem refreshMasterData = new NavigationMenuListItem(); refreshMasterData.setTag("REFRESH_MASTER_DATA"); //$NON-NLS-1$ refreshMasterData.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.UPDATE, CommonConstants.Images.IMAGE_DPI))); refreshMasterData.setText(LoginMessages.getString("refreshMasterdata")); //$NON-NLS-1$ menuListView.add(refreshMasterData); // Check sw-update NavigationMenuListItem checkSoftwareUpdate = new NavigationMenuListItem(); checkSoftwareUpdate.setTag("CHECK_SOFTWARE_UPDATE"); //$NON-NLS-1$ checkSoftwareUpdate.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.SYSTEM_UPDATE, CommonConstants.Images.IMAGE_DPI))); checkSoftwareUpdate.setText(LoginMessages.getString("checkSWUpdate")); //$NON-NLS-1$ menuListView.add(checkSoftwareUpdate); // Exit Service Application NavigationMenuListItem exitServiceApplication = new NavigationMenuListItem(); exitServiceApplication.setTag("EXIT_APP"); //$NON-NLS-1$ exitServiceApplication.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EXIT, CommonConstants.Images.IMAGE_DPI))); exitServiceApplication.setText(LoginMessages.getString("exitApplication")); //$NON-NLS-1$ menuListView.add(exitServiceApplication); onMenuItemNotifyDataSetChanged(); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { View view = super.onFormLoad(context, inflater); setRuntimeMenuHidden(true); return view; } }     login/src/ch/mfiles/kaba/kolibri/login/LoginApplication.java:   package ch.mfiles.kaba.kolibri.login; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.login.forms.LoginForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; /** * Main application class. */ public class LoginApplication extends Application { public static final Log log = LogFactory.getLog(LoginApplication.class); public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public MessageUtil messageUtil; /** * Called by the framework each time the application is started. * * @param obj * An (optional) object supplied by the application that started * this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); messageUtil = MessageUtil.getInstance(); // make sure the common plugin exists if (null == appman.getApplicationDescriptor(CommonConstants.Application.COMMON_APP)) { showMessageBox(LoginMessages.getString("gilgenCommonApplicationIsNotInstalled"), LoginMessages.getString("startGilgenService"), MBOX_BUTTON_OK, MBOX_ICON_ERROR); //$NON-NLS-1$ //$NON-NLS-2$ return appman.exitApplication(); } setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); return leaveToForm(LoginForm.class); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { // do nothings } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // do nothings } /** * Called by the framework after the application has been upgraded but * before the upgrade is commited to the database. Additional upgrade * postprocessing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { Registry reg = appman.getRegistry(null); reg.setProperty("framework.appman.startupApplication", "ch.mfiles.kaba.kolibri.login.LoginApplication"); //$NON-NLS-1$ //$NON-NLS-2$ ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry serviceReg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (serviceReg != null) { serviceReg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } // do nothings } public void showMessage(String message) { messageUtil.showMessage(message); } public void showMessage(String message, boolean forceClear) { messageUtil.showMessage(message, forceClear); } }     login/src/ch/mfiles/kaba/kolibri/util/LoginConstants.java:   package ch.mfiles.kaba.kolibri.util; public class LoginConstants { private LoginConstants() { } public static final class Images { private Images() { } public static final String HEADER = "images/header.jpg"; //$NON-NLS-1$ } }     material/AndroidManifest.xml:       material/application.dtd:       material/application.xml:       material/build.gradle.kts:   plugins { id("ch.mfiles.kolibri-application") } dependencies { implementation(project(":common")) }     material/build.xml:       material/i18n/ch/mfiles/kaba/kolibri/material/MaterialMessages.java:   package ch.mfiles.kaba.kolibri.material; import java.util.MissingResourceException; import java.util.ResourceBundle; public class MaterialMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.material.Messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private MaterialMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }     material/i18n/ch/mfiles/kaba/kolibri/material/Messages.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) EnterAValidValueIsGreateThan = Enter a valid value: {0} is greater than {1}! MaterialSaved = Material saved OrderMaterialForm.0 = aborted... OrderMaterialNewEditForm.0 = Search add = Add amount = Amount artNo = Art. No. clear = Clear delete = Delete deleteMaterial = Do you want to delete this material? deleteOrder = Do you want to delete this Order? detected = Detected doYouWantToDeleteOrder = Do you want to delete order? duplicatedMaterialNumber = There is MaterialNumber {0} duplicated {1} can not insert. employee = Employee exit = Exit exp = Exp express = Express materialWasDeleted = Material was deleted. materialWithThisNameAlreadyExists = Material with this name already exists materialWithThisNumberAlreadyExists = Material with this number already exists. name = Name nbr = Nbr. noOrderAvailable = No Order Available notYetSubmitted = Not yet submitted order = Orders orderFrom = Order from orderIsDeleted = Order is deleted save = Save send = Send sent = Sent sparePartsAndExpress = {0} Spare parts, {1} Express submittedOn = Submitted on unit = Unit warning = Warning! wrongFormArgument = Wrong form argument class found in form wrongFormatXX-XXXX-XXX/XX" = Wrong format(XX-XXXX-XXX/XX)     material/i18n/ch/mfiles/kaba/kolibri/material/Messages_de.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface EnterAValidValueIsGreateThan = G\u00FCltigen Wert erfassen: {0} ist gr\u00F6\u00DFer als {1}! MaterialSaved = Material gespeichert OrderMaterialForm.0 = abgebrochen\u2026 OrderMaterialNewEditForm.0 = Suchen add = Hinzuf\u00FCgen amount = Anzahl artNo = Art. Nr. clear = Reset delete = L\u00F6schen deleteMaterial = Artikel l\u00F6schen? deleteOrder = Bestellung l\u00F6schen? detected = Erfasst doYouWantToDeleteOrder = Auftrag l\u00F6schen? duplicatedMaterialNumber = Artikel {0} schon verhanden {1} kann nicht hinzugef\u00FCgt werden. employee = Mitarbeiter exit = Beenden exp = Exp express = Express materialWasDeleted = Artikel wurde gel\u00F6scht. materialWithThisNameAlreadyExists = Material mit diesem Namen existiert bereits. materialWithThisNumberAlreadyExists = Material mit dieser Nummer existiert bereits. name = Bezeichnung nbr = Anz. noOrderAvailable = Kein Auftrag vorhanden notYetSubmitted = Noch nicht \u00FCbermittelt order = Bestellungen orderFrom = Bestellung vom orderIsDeleted = Die Bestellung wurde gel\u00F6scht save = Speichern send = Senden sent = Gesendet sparePartsAndExpress = {0} Artikel, {1} Express submittedOn = \u00DCbermittelt am unit = Einheit warning = Warnung! wrongFormArgument = Falscher Form\u00FCbergabeparameter wrongFormatXX-XXXX-XXX/XX" = Falsches Format (XX-XXXX-XXX/XX).     material/i18n/ch/mfiles/kaba/kolibri/material/Messages_fr.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface EnterAValidValueIsGreateThan = Entrez une valeur valable: {0} est sup\u00E9rieur \u00E0 {1}! MaterialSaved = Mat\u00E9riel m\u00E9moris\u00E9 OrderMaterialForm.0 = annul\u00E9\u2026 OrderMaterialNewEditForm.0 = Chercher add = Ajouter amount = Nombre artNo = No d'art. clear = Remettre delete = Effacer deleteMaterial = Effacer l'article? deleteOrder = Effacer la commande? detected = Enregistr\u00E9 doYouWantToDeleteOrder = Effacer la commande? duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur exit = Fermer exp = Exp. express = Express materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. name = D\u00E9signation nbr = Nbre. noOrderAvailable = Pas de commande disponible notYetSubmitted = Pas encore re\u00E7u order = Commandes orderFrom = Commande de orderIsDeleted = Commande a \u00E9t\u00E9 supprim\u00E9 save = Enregistre send = Envoyer sent = Envoy\u00E9 sparePartsAndExpress = {0} Articles, d\u00E9tect\u00E9s Express {1} submittedOn = Pr\u00E9sent\u00E9 sur unit = Unit\u00E9 warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect wrongFormatXX-XXXX-XXX/XX" = Format incorrect (XX-XXXX-XXX/XX).     material/i18n/ch/mfiles/kaba/kolibri/material/Messages_it.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface EnterAValidValueIsGreateThan = Entrez une valeur valable: {0} est sup\u00E9rieur \u00E0 {1}! MaterialSaved = Mat\u00E9riel m\u00E9moris\u00E9 OrderMaterialForm.0 = annul\u00E9\u2026 OrderMaterialNewEditForm.0 = Chercher add = Ajouter amount = Nombre artNo = No d'art. clear = Remettre delete = Effacer deleteMaterial = Effacer l'article? deleteOrder = Effacer la commande? detected = Enregistr\u00E9 doYouWantToDeleteOrder = Effacer la commande? duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur exit = Fermer exp = Exp. express = Express materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. name = D\u00E9signation nbr = Nbre. noOrderAvailable = Pas de commande disponible notYetSubmitted = Pas encore re\u00E7u order = Commandes orderFrom = Commande de orderIsDeleted = Commande a \u00E9t\u00E9 supprim\u00E9 save = Enregistre send = Envoyer sent = Envoy\u00E9 sparePartsAndExpress = {0} Articles, d\u00E9tect\u00E9s Express {1} submittedOn = Pr\u00E9sent\u00E9 sur unit = Unit\u00E9 warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect wrongFormatXX-XXXX-XXX/XX" = Format incorrect (XX-XXXX-XXX/XX).     material/project.properties:   # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23     material/sonar.xml:       material/src/ch/mfiles/kaba/kolibri/material/forms/OrderListForm.java:   package ch.mfiles.kaba.kolibri.material.forms; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.material.MaterialMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class OrderListForm extends SuperForm { private static Log log = LogFactory.getLog(OrderListForm.class); private DefaultListWidget listWidget; private LinearLayout emptyMessageView; private boolean isServiceApp; @Override public void onFormCall(Object argument) { if (argument instanceof Boolean) { isServiceApp = Boolean.valueOf(argument.toString()); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(MaterialMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create add action ActionCtrl addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); listWidget = new DefaultListWidget(context); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); listWidget.setVisibility(View.GONE); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); view.setFocusable(true); view.setFocusableInTouchMode(true); view.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = new TextView(context); textView.setText(MaterialMessages.getString("noOrderAvailable")); //$NON-NLS-1$ textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); emptyMessageView.setVisibility(View.GONE); view.addView(emptyMessageView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); if (emptyMessageView.getChildCount() > 0) { emptyMessageView.removeAllViewsInLayout(); } setFormTitle(MaterialMessages.getString("order")); //$NON-NLS-1$ loadTable(); return null; } private void loadTable() { listWidget.clean(); List matOrderList = app.dbutil.selectOrderListByPerNo(app.dbutil.getUser().getPersonalNumber()); if (!matOrderList.isEmpty()) { ArrayList items = new ArrayList(); for (int i = 0; i < matOrderList.size(); i++) { final Order order = matOrderList.get(i); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.isShowEllipInTextEnd(true); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.MENU, CommonConstants.Images.IMAGE_MAX_DPI))); item.setStatusColor(order.getStatusColor()); item.setTitleText(MaterialMessages.getString("orderFrom") + " " + order.getOrderCreateDate()); //$NON-NLS-1$ //$NON-NLS-2$ List matList = app.dbutil.selectOrderMaterialList(order); int countExpress = 0; for (OrderMaterial orderMaterial : matList) { if (orderMaterial.isExpressFlag()) { countExpress++; } } item.setStringLine1(MessageFormat.format(MaterialMessages.getString("sparePartsAndExpress"), new Object[] { matList.size(), countExpress })); //$NON-NLS-1$ String lineTwo = MaterialMessages.getString("notYetSubmitted"); //$NON-NLS-1$ if (order.isSent()) { lineTwo = MaterialMessages.getString("submittedOn") + " " + order.getOrderSentDate(); //$NON-NLS-1$ //$NON-NLS-2$ } item.setStringLine2(lineTwo); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showPopupMenu(v, order); } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(matOrderList)); } listWidget.addItems(items); listWidget.setVisibility(View.VISIBLE); emptyMessageView.setVisibility(View.GONE); } else { listWidget.setVisibility(View.GONE); emptyMessageView.setVisibility(View.VISIBLE); } } private void showPopupMenu(View v, final Order order) { ImageButton imageButton = (ImageButton) v; PopupMenu popupMenu = new PopupMenu(context, imageButton); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); // send Images acceptStatusImage = ImagesUtil.Images.SEND_DISABLED_BLACK; if (order.isNew() && !app.dbutil.selectOrderMaterialList(order).isEmpty()) { acceptStatusImage = ImagesUtil.Images.SEND_BLACK; } addPopupMenuItem(popupMenu, 1, MaterialMessages.getString("send"), acceptStatusImage); //$NON-NLS-1$ // Delete addPopupMenuItem(popupMenu, 2, MaterialMessages.getString("delete"), ImagesUtil.Images.DELETE_BLACK); //$NON-NLS-1$ // forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem, order); return true; } }); popupMenu.show(); } private void addPopupMenuItem(PopupMenu popupMenu, int index, String label, Images image) { popupMenu.getMenu().add(Menu.NONE, index, Menu.NONE, label).setIcon(getBitmanDrawable(app.imagesUtil.getImage(image, CommonConstants.Images.IMAGE_DPI))); } private void handleMenuItemClicked(MenuItem menuItem, Order order) { if (menuItem.getItemId() == 1) { if (!app.dbutil.selectOrderMaterialList(order).isEmpty()) { actionSend(order); } } else if (menuItem.getItemId() == 2) { actionDelete(order); } } private OnItemClickListener createOnItemClickListener(final List msgList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(OrderMaterialForm.class, new FormArguments((Order) msgList.get(position))); } }, false); } }; } private void actionSend(final Order order) { if (order.isNew()) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { new RemoteTransactionHandler().saveMaterial(app.dbutil.getUser().getPersonalNumber(), order); return app.leaveToForm(OrderListForm.class); } }, false); } } private void actionDelete(final Order order) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(MaterialMessages.getString("deleteOrder"), MaterialMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES) { app.dbutil.deleteOrder(order); List listMaterialOrder = app.dbutil.selectOrderMaterialList(order); if (!listMaterialOrder.isEmpty()) { for (int i = 0; i < listMaterialOrder.size(); i++) { app.dbutil.deleteOrderMaterial((OrderMaterial) listMaterialOrder.get(i)); } } app.showMessage(MaterialMessages.getString("orderIsDeleted")); //$NON-NLS-1$ } return app.leaveToForm(OrderListForm.class); } }, false); } @Override public ApplicationEvent onBackPressed() { if (isServiceApp) { return appman.leaveToApplication(CommonConstants.Application.SERVICE_APP, null); } else { return appman.exitApplication(); } } @Override public void onFormReset() { super.onFormReset(); setFormTitle(null); } protected ApplicationEvent onAddPressed() { hideSoftInputFromWindow(); return app.leaveToForm(OrderMaterialForm.class, new FormArguments(null)); } /** * The Order Form Arguments Class. * * @author nop */ public static class FormArguments { private Order order; public FormArguments(Order order) { this.order = order; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } } }     material/src/ch/mfiles/kaba/kolibri/material/forms/OrderMaterialForm.java:   package ch.mfiles.kaba.kolibri.material.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.material.MaterialMessages; import ch.mfiles.kaba.kolibri.material.forms.OrderListForm.FormArguments; import ch.mfiles.kaba.kolibri.material.forms.OrderMaterialNewEditForm.OrderMaterialNewEditFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class OrderMaterialForm extends SuperForm { private static Log log = LogFactory.getLog(OrderMaterialForm.class); private DefaultListWidget listWidget; private LinearLayout emptyMessageView; private Order selectedMaterialOrder; private OrderMaterial selectedOrderMaterial; private boolean isNewMaterial; private ActionCtrl scanButton; private ActionCtrl addButton; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.selectedMaterialOrder = formArguments.getOrder(); if (this.selectedMaterialOrder == null) { this.isNewMaterial = true; } else { this.isNewMaterial = false; } } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(MaterialMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create scan action scanButton = addActionCtrl(false, true, 1, "onScanPressed"); //$NON-NLS-1$ scanButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); // create add action addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); listWidget = new DefaultListWidget(context); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); listWidget.setVisibility(View.GONE); view.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = new TextView(context); textView.setText(MaterialMessages.getString("noOrderAvailable")); //$NON-NLS-1$ textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); emptyMessageView.setVisibility(View.GONE); view.addView(emptyMessageView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); if (emptyMessageView.getChildCount() > 0) { emptyMessageView.removeAllViewsInLayout(); } setFormTitle(MaterialMessages.getString("order")); //$NON-NLS-1$ loadTable(); if(selectedMaterialOrder!= null && selectedMaterialOrder.isSent()) { setEnableButtons(false); } else { setEnableButtons(true); } return null; } private void setEnableButtons(boolean isEnabled) { if(isEnabled) { scanButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); } else { scanButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); } scanButton.setEnabled(isEnabled); addButton.setEnabled(isEnabled); } private void loadTable() { listWidget.clean(); if (!isNewMaterial) { List matList = app.dbutil.selectOrderMaterialList(selectedMaterialOrder); if (!matList.isEmpty()) { ArrayList items = new ArrayList(); for (int i = 0; i < matList.size(); i++) { final OrderMaterial orderMaterial = matList.get(i); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.isShowEllipInTextEnd(true); item.setStatusColor(orderMaterial.getStatusColor()); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(orderMaterial.getMaterialNumber(), orderMaterial.getVariousMaterial()); String statusType = "P"; //$NON-NLS-1$ if (!materialList.isEmpty()) { statusType = "N"; //$NON-NLS-1$ } item.setStatusType(statusType); item.setTitleText(orderMaterial.getVariousMaterial()); item.setStringLine1(orderMaterial.getAmount() + " " + orderMaterial.getUnit()); //$NON-NLS-1$ String expressMeg = ""; //$NON-NLS-1$ if (orderMaterial.isExpressFlag()) { expressMeg = MaterialMessages.getString("express"); //$NON-NLS-1$ } item.setStringLine2(expressMeg); if(selectedMaterialOrder!= null && selectedMaterialOrder.isSent()) { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(selectedMaterialOrder!= null && selectedMaterialOrder.isSent()) { return; } selectedOrderMaterial = orderMaterial; if (v instanceof ImageButton) { onDeletePressed(); } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(matList)); } listWidget.addItems(items); listWidget.setVisibility(View.VISIBLE); emptyMessageView.setVisibility(View.GONE); } else { listWidget.setVisibility(View.GONE); emptyMessageView.setVisibility(View.VISIBLE); } } } private OnItemClickListener createOnItemClickListener(final List matList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { OrderMaterialNewEditFormArguments formArguments = new OrderMaterialNewEditFormArguments(selectedMaterialOrder, matList.get(position), null); return appman.getActiveApplication().leaveToForm(OrderMaterialNewEditForm.class, formArguments); } }, false); } }; } private void onDeletePressed() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(MaterialMessages.getString("deleteMaterial"), MaterialMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES) { app.dbutil.deleteOrderMaterial(selectedOrderMaterial); app.showMessage(MaterialMessages.getString("materialWasDeleted")); //$NON-NLS-1$ } return app.leaveToForm(OrderMaterialForm.class); } }, false); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(OrderListForm.class); } @Override public void onFormReset() { super.onFormReset(); setFormTitle(null); } protected ApplicationEvent onScanPressed() { new AsyncTask(this) { String materialNumber; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(OrderMaterialForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { app.showMessage(MaterialMessages.getString("OrderMaterialForm.0")); //$NON-NLS-1$ return null; } else { app.showMessage(result.toString()); materialNumber = result.getContents(); log.info("scan result -> " + result.getContents()); //$NON-NLS-1$ } if (materialNumber != null) { OrderMaterialNewEditFormArguments formArguments = new OrderMaterialNewEditFormArguments(selectedMaterialOrder, null, materialNumber); return appman.getActiveApplication().leaveToForm(OrderMaterialNewEditForm.class, formArguments); } return null; } }; return null; } protected ApplicationEvent onAddPressed() { hideSoftInputFromWindow(); OrderMaterialNewEditFormArguments formArguments = new OrderMaterialNewEditFormArguments(selectedMaterialOrder, null, null); return appman.getActiveApplication().leaveToForm(OrderMaterialNewEditForm.class, formArguments); } }     material/src/ch/mfiles/kaba/kolibri/material/forms/OrderMaterialNewEditForm.java:   package ch.mfiles.kaba.kolibri.material.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.material.MaterialApplication; import ch.mfiles.kaba.kolibri.material.MaterialMessages; import ch.mfiles.kaba.kolibri.material.forms.OrderListForm.FormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class OrderMaterialNewEditForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(OrderMaterialNewEditForm.class); public static MaterialApplication app; // don't make this CommonApplication private Order selectedMaterialOrder; private OrderMaterial selectedOrderMaterial; private AmountEditText amountEditText; private MDEditText unitEditText; private MDEditText sizeEditText; private AppCompatCheckBox expressCheckBox; public Button deleteButton; private Material selectedMaterial = null; private MaterialPerson selectedMaterialPerson = null; @Override public void onFormCall(Object argument) { if (argument instanceof OrderMaterialNewEditFormArguments) { OrderMaterialNewEditFormArguments formArguments = (OrderMaterialNewEditFormArguments) argument; selectedMaterialOrder = formArguments.getMaterialOrder(); selectedOrderMaterial = formArguments.getMaterial(); barcode = formArguments.getBarcode(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(MaterialMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); saveButton.setVisible(false); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } if (!isMatrialNumberWrongFormat()) { numberEditText.clearError(); loadMaterialsList(numberEditText.getText().toString()); if(selectedMaterial != null || selectedMaterialPerson != null) { MessageUtil.getInstance().showMessage(MaterialMessages.getString("materialWithThisNumberAlreadyExists"), true); } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); if(selectedMaterial != null || selectedMaterialPerson != null) { MessageUtil.getInstance().showMessage(MaterialMessages.getString("materialWithThisNameAlreadyExists"), true); } } else { nameEditText.clearError(); } } }); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout stockItemLinearLayout = new LinearLayout(context); stockItemLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams stockLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); stockLinearLayoutParams.gravity = Gravity.LEFT; stockLinearLayoutParams.width = LayoutParams.MATCH_PARENT; stockLinearLayoutParams.weight = 0.7f; stockItemLinearLayout.setLayoutParams(stockLinearLayoutParams); amountEditText = AmountEditText.createDefaultEditText(stockItemLinearLayout, MaterialMessages.getString("amount"), true); LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.LEFT; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); // unit unitEditText = MDEditText.createDefaultEditText(stockItemLinearLayout, MaterialMessages.getString("unit"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ unitEditText.setTag("UNIT"); //$NON-NLS-1$ LinearLayout.LayoutParams unitInputLayoutParams = new LinearLayout.LayoutParams(0, 0); unitInputLayoutParams.gravity = Gravity.LEFT; unitInputLayoutParams.width = 0; unitInputLayoutParams.height = LayoutParams.MATCH_PARENT; unitInputLayoutParams.weight = 0.3f; unitEditText.getParentTextInputLayout().setLayoutParams(unitInputLayoutParams); sizeEditText = MDEditText.createDefaultEditText(stockItemLinearLayout, Messages.getString("Containersize"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ sizeEditText.setTag("SIZE"); //$NON-NLS-1$ sizeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); sizeEditText.setEnabled(false); LinearLayout.LayoutParams sizeInputLayoutParams = new LinearLayout.LayoutParams(0, 0); sizeInputLayoutParams.gravity = Gravity.LEFT; sizeInputLayoutParams.width = 0; sizeInputLayoutParams.height = LayoutParams.MATCH_PARENT; sizeInputLayoutParams.weight = 0.3f; sizeEditText.getParentTextInputLayout().setLayoutParams(sizeInputLayoutParams); contentLinearLayout.addView(stockItemLinearLayout); expressCheckBox = CommonUtilForm.getCheckBox(context, MaterialMessages.getString("express")); //$NON-NLS-1$ contentLinearLayout.addView(expressCheckBox); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(Messages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (selectedOrderMaterial == null) { resetView(); return; } appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(MaterialMessages.getString("deleteMaterial"), MaterialMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES) { DatabaseUtil.getInstance().deleteOrderMaterial(selectedOrderMaterial); return app.leaveToForm(OrderMaterialForm.class, new FormArguments(selectedMaterialOrder)); } return null; } }, false); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); addContentLinearLayout(contentLinearLayout); return view; } @Override public void setEnabledControls(boolean enabled) { searchView.setEnabled(enabled); deleteButton.setEnabled(enabled); nameEditText.setEnabled(enabled); numberEditText.setEnabled(enabled); amountEditText.setEnabled(enabled); unitEditText.setEnabled(enabled); expressCheckBox.setEnabled(enabled); } @Override protected void loadData() { super.loadData(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); selectedMaterial = null; selectedMaterialPerson = null; if (selectedOrderMaterial == null) { resetView(); deleteButton.setText(MaterialMessages.getString("clear")); //$NON-NLS-1$ searchView.setVisibility(View.VISIBLE); } else { nameEditText.setText(selectedOrderMaterial.getVariousMaterial()); numberEditText.setText(selectedOrderMaterial.getMaterialNumber()); amountEditText.setText(selectedOrderMaterial.getAmount()); //$NON-NLS-1$ //$NON-NLS-2$ unitEditText.setText(selectedOrderMaterial.getUnit()); expressCheckBox.setChecked(selectedOrderMaterial.isExpressFlag()); deleteButton.setText(MaterialMessages.getString("delete")); //$NON-NLS-1$ searchView.setVisibility(View.INVISIBLE); } } @Override protected void resetView() { super.resetView(); amountEditText.clearError(); selectedMaterial = null; selectedMaterialPerson = null; amountEditText.getText().clear(); unitEditText.getText().clear(); expressCheckBox.setChecked(false); } @Override public ApplicationEvent onBackPressed() { if (nameEditText.getText().toString().isEmpty() && numberEditText.getText().toString().isEmpty()) { return app.leaveToForm(OrderMaterialForm.class, new FormArguments(selectedMaterialOrder)); } new AsyncTask(this) { private List editErrorList = new ArrayList(); @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { editErrorList.clear(); if (nameEditText.getText().toString().isEmpty()) { editErrorList.add(nameEditText); } if (numberEditText.getText().toString().isEmpty()) { editErrorList.add(numberEditText); } else { if(isMatrialNumberWrongFormat()) { app.showMessageBox(Messages.getString("WrongFormatXX-XXXX-XXX/XX"), Messages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ editErrorList.add(numberEditText); } } if (amountEditText.isRequired() && amountEditText.getText().toString().isEmpty()) { editErrorList.add(amountEditText); } if (editErrorList.isEmpty()) { if (selectedOrderMaterial != null) { updateMaterial(); } else { if(isDuplicatedMaterial()) { Object[] arguments = new Object[] { numberEditText.getText().toString(), nameEditText.getText().toString() }; String errorMessage = MessageFormat.format(MaterialMessages.getString("duplicatedMaterialNumber"), arguments); app.showMessageBox(errorMessage, Messages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ return null; } // add material person if not exist. addMaterialPerson(); // insert new material. insertNewMaterial(); } return app.leaveToForm(OrderMaterialForm.class, new FormArguments(selectedMaterialOrder)); } return null; } @Override public void runOnUIThread() { amountEditText.clearFocus(); numberEditText.clearError(); nameEditText.clearError(); amountEditText.clearError(); if (!editErrorList.isEmpty()) { for (MDEditText errorText : editErrorList) { errorText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ } } } }; return null; } private void insertNewMaterial() { if (selectedMaterialOrder == null) { // there is no order yet. selectedMaterialOrder = new Order(); selectedMaterialOrder.setStatus(CommonConstants.Order.Status.NEW_ORDER); selectedMaterialOrder.setANZ(""); //$NON-NLS-1$ selectedMaterialOrder.setCreateDate(DateTimeUtil.getTimestamp().getTime()); selectedMaterialOrder.setSentDate(DateUtils.getInitialDateTime()); selectedMaterialOrder.setPersonalNumber(DatabaseUtil.getInstance().getUser().getPersonalNumber()); DatabaseUtil.getInstance().insertOrder(selectedMaterialOrder); } OrderMaterial newOrderMaterial = new OrderMaterial(); newOrderMaterial.setDate(DateTimeUtil.getTimestamp().getTime()); newOrderMaterial.setExpressFlag(expressCheckBox.isChecked()); newOrderMaterial.setVariousMaterial(nameEditText.getText().toString()); newOrderMaterial.setMaterialNumber(numberEditText.getText().toString()); newOrderMaterial.setPersonalNumber(DatabaseUtil.getInstance().getUser().getPersonalNumber()); newOrderMaterial.setAmount(amountEditText.getText().toString()); newOrderMaterial.setUnit(unitEditText.getText().toString()); newOrderMaterial.setOrderDate(selectedMaterialOrder.getCreateDate()); DatabaseUtil.getInstance().insertOrderMaterial(newOrderMaterial); } private void updateMaterial() { selectedOrderMaterial.setExpressFlag(expressCheckBox.isChecked()); selectedOrderMaterial.setAmount(amountEditText.getText().toString()); selectedOrderMaterial.setUnit(unitEditText.getText().toString()); DatabaseUtil.getInstance().updateOrderMaterial(selectedOrderMaterial); } private void addMaterialPerson() { // Mat: sum of the articles from the excise and the pers. Mat table (exact match of article number necessary!) Material mat = DatabaseUtil.getInstance().selectMaterialByMatNo(numberEditText.getText().toString()); MaterialPerson matPerson = DatabaseUtil.getInstance().selectMaterialPersonByMatNo(numberEditText.getText().toString()); if (mat == null && matPerson == null) { // Article does not yet exist and can be used as Pers. Mat if (isMatrialNumberWrongFormat()) { app.showMessageBox(Messages.getString("WrongFormatXX-XXXX-XXX/XX"), Messages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ return; } selectedMaterialPerson = new MaterialPerson(); selectedMaterialPerson.setMaterialNumber(numberEditText.getText().toString()); selectedMaterialPerson.setMaterialShortText(nameEditText.getText().toString()); DatabaseUtil.getInstance().insertMaterialPerson(selectedMaterialPerson); MessageUtil.getInstance().showMessage(MaterialMessages.getString("MaterialSaved"), true); } } private boolean isDuplicatedMaterial() { if (selectedMaterialOrder != null) { List mListZKDMAMAT = DatabaseUtil.getInstance().selectOrderMaterialList(selectedMaterialOrder); for (int i = 0; i < mListZKDMAMAT.size(); i++) { OrderMaterial zkdmamat = mListZKDMAMAT.get(i); if (zkdmamat.getMaterialNumber().equalsIgnoreCase(numberEditText.getText().toString()) || zkdmamat.getVariousMaterial().equalsIgnoreCase(nameEditText.getText().toString())) { return true; } } } return false; } public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(queryText, queryText); List materialPersonList = app.dbutil.selectMaterialPersonListByMatNoAndMatName(queryText, queryText); for (Material matPart : materialList) { searchView.getSuggessionItemList().add(new SuggessionItem(matPart.getMaterialNumber(), matPart.getMaterialShortText())); } for (MaterialPerson zkdmobmatpers : materialPersonList) { searchView.getSuggessionItemList().add(new SuggessionItem(zkdmobmatpers.getMaterialNumber(), zkdmobmatpers.getMaterialShortText())); } int matHits = materialList.size() + materialPersonList.size(); if (matHits > 0 && matHits == 1) { // Exactly found an article from the StammMat if (materialList.size() == 1) { selectedMaterial = materialList.get(0); } else if (materialPersonList.size() == 1) { // Exactly found an article from PersMat selectedMaterialPerson = materialPersonList.get(0); } } if (selectedMaterial != null) { amountEditText.getText().clear(); sizeEditText.setText(selectedMaterial.getSize()); expressCheckBox.setChecked(false); } amountEditText.getText().clear(); expressCheckBox.setChecked(false); } public static class OrderMaterialNewEditFormArguments { private Order materialOrder; private OrderMaterial material; private String barcode; public OrderMaterialNewEditFormArguments(Order materialOrder, OrderMaterial material, String barcode) { this.materialOrder =materialOrder; this.material = material; this.barcode = barcode != null ? barcode : ""; //$NON-NLS-1$ } public Order getMaterialOrder() { return materialOrder; } public OrderMaterial getMaterial() { return material; } public String getBarcode() { return barcode; } } }     material/src/ch/mfiles/kaba/kolibri/material/forms/SuperForm.java:   package ch.mfiles.kaba.kolibri.material.forms; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.material.MaterialApplication; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class SuperForm extends DialogForm { protected Context context; protected LinearLayout view; // initialized by the kolibri framework... public static MaterialApplication app; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); view.setFocusable(true); view.setFocusableInTouchMode(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image clearImage = imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(clearImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); return view; } /** * Closes the keyboard (if open) */ protected void hideSoftInputFromWindow() { KeyboardUtil.closeKeyboard(appman, getView()); } /** * Clears the error messages. */ protected void clearErrorMessages() { // do nothings } }     material/src/ch/mfiles/kaba/kolibri/material/MaterialApplication.java:   package ch.mfiles.kaba.kolibri.material; import java.util.Set; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.material.forms.OrderListForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; /** * Main application class. */ public class MaterialApplication extends Application { public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public EnumUtil enumUtil; public MessageUtil messageUtil; /** * Called by the framework each time the application is started. * * @param obj * An (optional) object supplied by the application that started * this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); enumUtil = EnumUtil.getInstance(this.dbutil); messageUtil = MessageUtil.getInstance(); boolean isServiceApp = false; if (obj !=null && Boolean.valueOf(obj.toString())) { isServiceApp = true; } setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); return leaveToForm(OrderListForm.class, isServiceApp); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { // do nothings } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // do nothings } /** * Called by the framework after the application has been upgraded but * before the upgrade is commited to the database. Additional upgrade * postprocessing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } public void showMessage(String message) { messageUtil.showMessage(message); } public void showMessage(String message, boolean forceClear) { messageUtil.showMessage(message, forceClear); } public void showWarningMessageBox(final String warningMessage){ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { showMessageBox(warningMessage, MaterialMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } }     phase5-summary_082326_1420.txt:   This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. This section contains a summary of this file. This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: - File path as an attribute - Full contents of the file - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .env, .env.*, *.log - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Files are sorted by Git change count (files with more changes are at the bottom) apk-customizer/ contrib/ xml2axml.jar src/ ch/ mfiles/ kolibri/ tools/ ZipExtender.java staging/ assets/ deploy/ .gitignore raw/ ssm 11.wav .gitignore .classpath .gitignore .project build.gradle.kts build.number build.xml keystore-v2.p12 keystore.p12 lineage-v2 README settings.properties buildSrc/ src/ main/ kotlin/ ch.mfiles.kolibri-application.gradle.kts build.gradle.kts settings.gradle.kts common/ .settings/ ch.mfiles.kolibri.plugin.prefs org.eclipse.core.resources.prefs org.eclipse.jdt.core.prefs data/ fixed-master-data.txt i18n/ ch/ mfiles/ kaba/ kolibri/ common/ messages_de.properties messages_fr.properties messages_it.properties Messages.java messages.properties Messages.txt javatest/ ch/ mfiles/ kaba/ kolibri/ common/ businessobjects/ types/ JobStatusTest.java forms/ adapters/ SpinnerTextStyleTest.java util/ ReportMaterialInsertPolicyTest.java lib/ commons-logging-1.2.jar hamcrest-core-1.3.jar jacocoant.jar junit-4.12.jar sonar-ant-task-2.3.jar src/ ch/ mfiles/ kaba/ kolibri/ common/ businessobjects/ enums/ AddressType.java InvoiceCode.java JobPriority.java JobStatusName.java JobType.java LocalizedTextEnum.java LoginMessage.java MessageRecipient.java Month.java NoSignatureReason.java ReportSendType.java Titel.java VariousExpens.java types/ CalendarStatus.java DeliveryStatus.java ExpenseValidation.java FormItemType.java FormType.java JobStatus.java JobType.java ReportStatus.java SpecificFunctionType.java TimesheetStatus.java TimesheetValidation.java Warehouse.java AbsenceNotification.java AbsenceType.java Address.java BaseEntity.java Billing.java CalendarTimeSheet.java Checklist.java DeliveryList.java Drive.java Email.java Employee.java ErrorCode.java Expenses.java Form.java FormDependency.java FormInstance.java FormItem.java FormValueList.java History.java Incident.java InternalWorkType.java Inventory.java Invoice.java Job.java JobFile.java JobFormDesc.java JobMessage.java JobMonText.java JobNoForm.java JobReportTime.java JobReturnReason.java Material.java MaterialMovement.java MaterialPerson.java NextIntervention.java Order.java OrderMaterial.java Person.java PhoneBookEntry.java Progress.java Reason.java ReceiptOfGoods.java Report.java ReportMaterial.java ReportMeasurement.java ReportMessage.java ServerJob.java ServiceRefused.java ShortMessage.java StateOfInstallation.java TimeSheet.java VariousExpenseFile.java VariousExpenses.java VehicleInventory.java WorkType.java forms/ adapters/ CustomArrayAdapter.java CustomAutoCompleteItemAdapter.java CustomSpinnerAdapter.java CustomSpinnerItem.java SpinnerTextStyle.java StepAdapter.java dlg/ DialogForm.java widgets/ inputmasks/ ExpenseMaskWatcher.java MaterialNumberMaskWatcher.java VehicleMaskWatcher.java Watcher.java lists/ CheckBoxListWidget.java CheckBoxListWidgetAdapter.java CheckBoxListWidgetItem.java DefaultListWidget.java DefaultListWidgetAdapter.java DefaultListWidgetItem.java DetailListWidget.java DetailListWidgetAdapter.java DetailListWidgetItem.java ImageListWidget.java ImageListWidgetAdapter.java ImageListWidgetItem.java ListWidget.java ListWidgetAdapter.java MaterialListWidget.java MaterialListWidgetAdapter.java MaterialListWidgetItem.java RadioButtonListWidget.java RadioButtonListWidgetAdapter.java RadioButtonListWidgetItem.java StatusListWidget.java StatusListWidgetAdapter.java StatusListWidgetItem.java TimeListWidget.java TimeListWidgetAdapter.java TimeListWidgetItem.java AmountEditText.java CommissionNumberLayout.java CommissionNumberText.java DividerView.java ExpenseMaskEditText.java MaterialSearchView.java MDAutoComplete.java MDCalendar.java MDCheckBox.java MDDialog.java MDEditText.java MDRadioButton.java MDSpinner.java ReportContentWidget.java TimeEditText.java ViewPageAdapter.java CommonUtilForm.java MaterialSearchForm.java Navigation.java NavigationForm.java SuperForm.java net/ CommSetupHelper.java MasterDataDBHandler.java PresenceState.java RemoteTransactionHandler.java RemoteTransactionResult.java util/ ActionUtil.java BackupHandler.java BitmapConverterUtil.java BitmapLoadUtils.java CommonConstants.java DatabaseUtil.java DateTimeConverter.jpage DateTimeUtil.java DbConstants.java DeviceMirrorringHandler.java EnumUtil.java EvalTimeGenerator.jpage FileUtils.java FormUtil.java GuidGenerator.java HTMLEncode.java HtmlUtil.java ImageHeaderParser.java ImagesUtil.java KeyboardUtil.java LayoutUtils.java Messages.java MessageUtil.java Notifications.java PropertiesFileConverter.java RegistryUtil.java ResetEval.jpage ResetEvalPeriod.sql RunOnUIThread.java SoundUtil.java SQLFileConverter.java StepUtil.java StringUtil.java TimeUtil.java TranslationFileConverter.java CommonApplication.java NotificationTestMessage.java images/ call.png ic_absence_black_24dp.png ic_add_black_24dp.png ic_add_disabled_white_24dp.png ic_add_photo_black_32dp.png ic_add_white_24dp.png ic_alarm_black_24dp.png ic_alarm_red_24dp.png ic_arrow_back_white_48dp.png ic_arrow_back_white_disabled_48dp.png ic_arrow_forward_disabled_black_24dp.png ic_assignment_ind_black_24dp.png ic_assignment_ind_disabled_black_24dp.png ic_assignment_turned_in_black_24dp.png ic_assignment_turned_in_disabled_black_24dp.png ic_camera_black_24dp.png ic_camera_disabled_black_24dp.png ic_camera_disabled_white_24dp.png ic_camera_white_24dp.png ic_check_512dp.png ic_check_white_512dp.png ic_checkbox_checked_60dp.png ic_checkbox_some_60dp.png ic_checkbox_unchecked_60dp.png ic_clear_white_48dp.png ic_contact_phone_black_24dp.png ic_delete_forever_black_24dp.png ic_delete_forever_disabled_black_24dp.png ic_delete_forever_disabled_white_24dp.png ic_delete_forever_white_24dp.png ic_done_black_24db.png ic_done_white_24db.png ic_download_error_512dp.png ic_download_success_512dp.png ic_email_black_24dp.png ic_email_disabled_black_24dp.png ic_exit_to_app_black_24dp.png ic_exit_to_app_disabled_black_24dp.png ic_file_download_black_24dp.png ic_file_download_disabled_black_24dp.png ic_file_download_white_48dp.png ic_gesture_black_24dp.png ic_gesture_disabled_black_24dp.png ic_gesture_white_24dp.png ic_help_black_24dp.png ic_help_disabled_black_24dp.png ic_info_black_24dp.png ic_info_disabled_black_24dp.png ic_info_outline_black_24dp.png ic_info_outline_disabled_black_24dp.png ic_info_outline_white_24dp.png ic_info_white_24dp.png ic_list_black_24dp.png ic_list_disabled_black_24dp.png ic_mode_edit_black_24dp.png ic_offline_share_black_24dp.png ic_pageview_black_24dp.png ic_pageview_disabled_black_24dp.png ic_pageview_white_24dp.png ic_perm_device_information_black_24dp.png ic_perm_device_information_disabled_black_24dp.png ic_phone_black_24dp.png ic_phone_disabled_black_24dp.png ic_photo_library_black_24dp.png ic_picture_as_pdf_black_24dp.png ic_play_arrow_black_24dp.png ic_play_arrow_disabled_black_24dp.png ic_play_circle_outline_black_24dp.png ic_remote_black_24dp.png ic_restore_page_black_24dp.png ic_restore_page_white_24dp.png ic_save_black_24dp.png ic_save_disabled_black_24dp.png ic_save_disabled_white_24dp.png ic_save_white_48dp.png ic_schedule_black_24dp.png ic_schedule_disabled_black_24dp.png ic_search_file_black_72dp.png ic_search_file_disabled_72dp.png ic_search_white_24dp.png ic_send_black_24dp.png ic_send_disabled_black_24dp.png ic_send_disabled_white_24dp.png ic_send_white_24dp.png ic_settings_applications_black_24dp.png ic_settings_applications_disabled_black_24dp.png ic_settings_black_24dp.png ic_settings_disabled_black_24dp.png ic_shopping_cart_add_black_128dp.png ic_shopping_cart_add_disabled_white_128dp.png ic_shopping_cart_add_white_128dp.png ic_shopping_cart_black_128dp.png ic_shopping_cart_disabled_white_128dp.png ic_shopping_cart_white_128dp.png ic_stop_black_24dp.png ic_stop_disabled_black_24dp.png ic_supervisor_account_black_24dp.png ic_supervisor_account_disabled_black_24dp.png ic_system_update_black_24dp.png ic_system_update_disabled_black_24dp.png ic_truck_black_128dp.png ic_truck_white_128dp.png ic_update_black_24dp.png ic_update_disabled_black_24dp.png ic_update_white_24dp.png ic_wrench_black_72dp.png ic_wrench_disabled_black_72dp.png ic_youtube_searched_for_black_24dp.png ic_youtube_searched_for_white_24dp.png menu_white.png menu.png video-play-3-72 (1).png test/ ch/ mfiles/ kaba/ kolibri/ common/ util/ DateTimeUtilTest.java StringUtilTest.java .classpath .gitignore .project AndroidManifest.xml application.dtd application.xml build.gradle.kts build.xml project.properties sonar.xml gradle/ wrapper/ gradle-wrapper.jar gradle-wrapper.properties login/ .settings/ ch.mfiles.kolibri.plugin.prefs org.eclipse.core.resources.prefs org.eclipse.jdt.core.prefs org.eclipse.jdt.ui.prefs i18n/ ch/ mfiles/ kaba/ kolibri/ login/ LoginMessages.java messages_de.properties messages_fr.properties messages_it.properties messages.properties Messages.txt lib/ sonar-ant-task-2.3.jar src/ ch/ mfiles/ kaba/ kolibri/ login/ forms/ KolibriIdForm.java LoginForm.java LoginNavigationForm.java LoginApplication.java util/ LoginConstants.java images/ button_ok_LoginDisabled.png button_ok.png header.jpg header.png kaba.png login.png .classpath .gitignore .project AndroidManifest.xml application.dtd application.xml build.gradle.kts build.xml project.properties sonar.xml material/ .settings/ ch.mfiles.kolibri.plugin.prefs org.eclipse.core.resources.prefs org.eclipse.jdt.core.prefs org.eclipse.jdt.ui.prefs i18n/ ch/ mfiles/ kaba/ kolibri/ material/ MaterialMessages.java Messages_de.properties Messages_fr.properties Messages_it.properties Messages.properties lib/ sonar-ant-task-2.3.jar src/ ch/ mfiles/ kaba/ kolibri/ material/ forms/ OrderListForm.java OrderMaterialForm.java OrderMaterialNewEditForm.java SuperForm.java MaterialApplication.java images/ kaba.png .classpath .gitignore .project AndroidManifest.xml application.dtd application.xml build.gradle.kts build.xml project.properties sonar.xml service/ .settings/ ch.mfiles.kolibri.plugin.prefs org.eclipse.core.resources.prefs org.eclipse.jdt.core.prefs org.eclipse.jdt.ui.prefs org.eclipse.ltk.core.refactoring.prefs i18n/ ch/ mfiles/ kaba/ kolibri/ service/ messages_de.properties messages_fr.properties messages_it.properties messages.properties ServiceMessages.java lib/ commons-logging-1.2.jar hamcrest-core-1.3.jar jacocoant.jar junit-4.12.jar sonar-ant-task-2.3.jar src/ ch/ mfiles/ kaba/ kolibri/ service/ forms/ AbsenceNotificationListForm.java AbsenceNotificationNewEditForm.java AddressEditSuperForm.java ArticleDetailForm.java ArticleIncomningForm.java ArticleListForm.java ArticleOutgoingForm.java ArticleOutgoingListForm.java ArticleSearchForm.java EmployeeListForm.java InventoryInformationsForm.java InventoryStockForm.java JobDeleteForm.java JobDetailAddressEditForm.java JobDetailAddressForm.java JobDetailForm.java JobDetailHistoryForm.java JobDetailInfoCommissionNumberForm.java JobDetailInfoForm.java JobDetailReportForm.java JobDownloadResultForm.java JobEditForm.java JobForwardForm.java JobListForm.java JobNewForm.java JobSearchForm.java JobSearchListForm.java ReportChecklistForm.java ReportDocumentAttachmentsListForm.java ReportDocumentAttachmentsNewEditForm.java ReportDocumentDetailForm.java ReportEditForm.java ReportFormListForm.java ReportFormNewEditForm.java ReportGuaranteeForm.java ReportImageAttachmentsListForm.java ReportImageAttachmentsNewEditForm.java ReportMaterialListForm.java ReportMaterialNewEditForm.java ReportMeasurementForm.java ReportMessageNewEditForm.java ReportSummaryForm.java ReportTimeListForm.java ReportTimeNewEditForm.java RescheduleJobForm.java ServiceNavigationForm.java ShortMessageForm.java ShortMessageListForm.java SignatureBundleListForm.java SignatureForm.java SuperForm.java test/ LongTaskForm.java SampleCallingForm.java SampleDialogForm.java SampleNavigationViewForm.java SampleTabForm.java ui/ widgets/ FormImageLayout.java FormListItemWidget.java GridLayoutForm.java MeasurementListItemWidget.java MeasurementTable.java util/ ReportUtil.java ServiceConstants.java ServiceFormUtil.java ServiceJobUtil.java SignatureUtil.java NotificationTestMessage.java ServiceApplication.java images/ active.png finalized.png inProgress.png kaba.png test/ ch/ mfiles/ kaba/ kolibri/ service/ forms/ util/ ReportDeletionStateTest.java ReportTest.java ServiceJobUtilTest.java .classpath .gitignore .project AndroidManifest.xml application.dtd application.xml build.gradle.kts build.xml project.properties report.html sonar.xml timeSheet/ .settings/ ch.mfiles.kolibri.plugin.prefs org.eclipse.core.resources.prefs org.eclipse.jdt.core.prefs org.eclipse.jdt.ui.prefs i18n/ ch/ mfiles/ kaba/ kolibri/ timesheet/ Messages_de.properties Messages_fr.properties Messages_it.properties Messages.properties TimeSheetMessages.java lib/ commons-logging-1.2.jar hamcrest-core-1.3.jar junit-4.12.jar sonar-ant-task-2.3.jar src/ ch/ mfiles/ kaba/ kolibri/ timesheet/ forms/ CalendarOverviewForm.java SuperForm.java TimeSheetDetailForm.java TimeSheetForm.java VariousExpensesImageNewEditForm.java util/ CalendarDateRange.java CalendarDateSelection.java CalendarListWindow.java CalendarMonthHeaderPolicy.java CalendarMonthScroll.java CalendarMonthTitleState.java CalendarScrollTrigger.java CalendarTimeSheetCache.java CalendarToolbarTitleText.java TimesheetDateUtils.java TimeSheetApplication.java images/ Error.png kaba.png report.png reportDisabled.png Success.png Warning.png test/ ch/ mfiles/ kaba/ kolibri/ timesheet/ forms/ ExpenseCurrencyValueTest.java ExpensesCompensationTest.java TestDateCorrectness.java TimeSheetDetailFormSavePolicyTest.java TimeSheetValidatorTest.java util/ CalendarDateRangeTest.java CalendarDateSelectionTest.java CalendarListWindowTest.java CalendarMonthHeaderPolicyTest.java CalendarMonthScrollTest.java CalendarMonthTitleStateTest.java CalendarScrollTriggerTest.java CalendarTimeSheetCacheTest.java CalendarToolbarTitleTextTest.java .classpath .gitignore .project AndroidManifest.xml application.dtd application.xml build.gradle.kts build.xml project.properties sonar.xml .gitignore .gitlab-ci.yml gradlew gradlew.bat settings.gradle.kts This section contains the contents of the repository's files. package ch.mfiles.kolibri.tools; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * Zips a folder using compression settings from a reference ZIP file. Files not found in the * reference ZIP file are added uncompressed. * * @author Joerg * */ public class ZipExtender { private static String sourceFolder = "apk"; private static String referenceZip = "reference.apk"; private static String targetZip = "tmp.apk"; public static void main(String[] args) { // get hashmap of zip entries with compressed-Flag HashMap compressed = new HashMap<>(); try { System.out.println("Reading reference APK file..."); ZipInputStream refZipIn = new ZipInputStream(new FileInputStream(referenceZip)); for (ZipEntry entry = refZipIn.getNextEntry(); entry != null; entry = refZipIn.getNextEntry()) { compressed.put(entry.getName(), entry.getMethod()); } refZipIn.close(); } catch (IOException ex) { System.out.println("Exception caught while reading reference ZIP file..."); ex.printStackTrace(); return; } try { System.out.println("Creating target APK file with mixed compression settings..."); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(targetZip)); Path sourcePath = Paths.get(sourceFolder); Files.walkFileTree(sourcePath, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String entryName = sourcePath.relativize(file).toString().replace('\\', '/'); ZipEntry entry = new ZipEntry(entryName); int method = compressed.get(entryName) != null ? compressed.get(entryName) : ZipEntry.STORED; entry.setMethod(method); if (method == ZipEntry.STORED) { entry.setSize(attrs.size()); entry.setCrc(getCrc(file)); } zipOut.putNextEntry(entry); Files.copy(file, zipOut); zipOut.closeEntry(); return FileVisitResult.CONTINUE; } private long getCrc(Path file) throws IOException { CRC32 crc = new CRC32(); crc.update(Files.readAllBytes(file)); return crc.getValue(); } }); zipOut.close(); } catch (IOException ex) { System.out.println("Exception caught while writing target ZIP file..."); ex.printStackTrace(); return; } } } /* !/.gitignore /runtime-android.apk /bin/ /build/ apk-customizer org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature import java.io.FileInputStream import java.net.URI import java.util.Properties plugins { base `maven-publish` } // the Kolibri runtime version to use (-> settings.properties) val props = Properties() props.load(FileInputStream(project.file("settings.properties"))) val runtimeVersion = props["runtimeVersion"] // inject the signature key pwd (i.e. set env-variable ORG_GRADLE_PROJECT_signatureKeyPwd) var signatureKeyPwd : String = if (project.hasProperty("signatureKeyPwd")) project.property("signatureKeyPwd").toString() else "" // inject an api token for publishing to the MFiles maven repository of project gilgen2020 var publicationApiToken : String = if (project.hasProperty("publicationApiToken")) project.property("publicationApiToken").toString() else "" // inject a job token for publishing to the MFiles maven repository of project gilgen2020 var publicationJobToken : String = if (project.hasProperty("publicationJobToken")) project.property("publicationJobToken").toString() else "" // publication url var publicationUrl = "https://dev.mfiles.ch/gitlab/api/v4/projects/19/packages/maven" //"gilgen/gilgen2020" // extract app version from common/application.xml fun parseApplicationDescriptor(): Map { val xmlFile = File(project.rootDir, "common/application.xml") val xmlInput = org.xml.sax.InputSource(java.io.StringReader(xmlFile.readText())) val docBuilder = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder() docBuilder.setEntityResolver { _, _ -> org.xml.sax.InputSource(java.io.FileReader(project.rootDir.path + "/common/application.dtd")) } val doc = docBuilder.parse(xmlInput) val xPath = javax.xml.xpath.XPathFactory.newInstance().newXPath() val result = HashMap() result["appClass"] = xPath.evaluate("/application/@class", doc) result["versionMajor"] = xPath.evaluate("/application/version/@major", doc) result["versionMinor"] = xPath.evaluate("/application/version/@minor", doc) result["versionBuild"] = xPath.evaluate("/application/version/@build", doc) return result } val ad = parseApplicationDescriptor() val appVersion = ad["versionMajor"] + "." + ad["versionMinor"] + "." + ad["versionBuild"] val versionText = "${appVersion}-${runtimeVersion}" // define configuration to hold all jars of all Kolibri apps val kolibriJars: Configuration by configurations.creating { isCanBeConsumed = false isCanBeResolved = true } dependencies { // add dependencies to all Kolibri applications to configuration kolibriJars listOf(":common", ":login", ":material", ":service", ":timeSheet").forEach { kolibriJars(project(mapOf("path" to it, "configuration" to "kolibriJars"))) } } /** * Task for copying the Kolibri jars to the apk customizer's staging folder 'deploy' */ tasks.register("deployKolibriJars", Copy::class) { from(kolibriJars) into("staging/assets/deploy") } /** * Task for building a ZIP output of the customized APK and all contributed Kolibri app jars */ tasks.register("distributionZip", Zip::class) { group = "build" dependsOn("ANT-build-apk") from(kolibriJars) { into("deploy") } from("build/runtime-android-customized.apk") { this.rename { "${rootProject.name}-customized-$versionText.apk"} } } // import ant build ant.importBuild("build.xml") { "ANT-$it" } // inject ant properties (i.e. values of settings.properties) if (signatureKeyPwd != "") ant.properties["pwd"] = signatureKeyPwd ant.properties["runtimeVersion"] = runtimeVersion ant.properties["appVersion"] = appVersion tasks.named("ANT-merge-apk") { dependsOn("deployKolibriJars") } // append our tasks to base lifecycle tasks tasks.named("assemble") { dependsOn("ANT-build-apk") } tasks.named("clean") { dependsOn("ANT-clean") doLast { delete(fileTree("staging/assets/deploy") { include("**.jar") }) } } publishing { publications { create("distribution") { groupId = "ch.gilgen.kolibri" artifactId = "gilgen2020-distro" version = versionText artifact(tasks.named("distributionZip")) { extension = "zip" } } } repositories { maven { name = "MFilesGitLAB" url = URI(publicationUrl) credentials(HttpHeaderCredentials::class) { name = if (publicationApiToken != "") "Private-Token" else "Job-Token" value = if (publicationApiToken != "") publicationApiToken else publicationJobToken } authentication { create("header") } } } } #Build Number for ANT. Do not edit! #Sat Feb 12 18:58:05 CET 2022 build.number=13 Build file helping to customize a Kolibri runtime apk file. Creating custom-apk-version due to existing deployments A simple build project that may be used to repackage / resign the Kolibri runtime APK file for Android as exported from Eclipse allowing to customize its content. Usage: 1. Put the exported Kolibri runtime APK file named 'runtime-android.apk' into the project's folder 'staging'. 2. Place all files to be merged into the APK's asset folder in folder 'staging/assets'. E.g. to add some Kolibri apps for deployment along with the 1st runtime start create a 'deploy' folder in the 'assets' folder and place the app's jar files there. Another sample would be bootstrap.properties or log4j.properties which could be placed directly into the 'assets' folder. Regard the 'assets' folder as the classical runtime installation folder. 3. Run the project's default ANT task from build.xml. This creates the repackaged runtime APK file in the folder 'build' named 'runtime-android-customized.apk'. IMPORTANT NOTE: On 1st build run, a keystore.p12 file is created in the project's root folder containing the self signed certificate including the corresponding private key that is used for signing the repackaged runtime APK file. The certificate is valid for 9999 days. Make sure to backup the keystore.p12 file, since signing the APK file with a different key prevents an already installed Kolibri runtime to be updated. If the signing key is changed - as will be if the original runtime APK file is replaced with a customized APK file - the already installed runtime app signed with a different key has to be uninstalled first, before the new app can be installed. Installing the new runtime apk without uninstalling the currently installed app will fail without a specific error message. runtimeVersion=1.8.1p202512091754 appVersion=5.0.3 plugins { `kotlin-dsl` } repositories { mavenCentral() } val androidSDK = "bubu" eclipse.preferences.version=1 platform=ANDROID eclipse.preferences.version=1 encoding//src/ch/mfiles/kaba/kolibri/common/CommonApplication.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/common/util/CONSTANTS.java=UTF-8 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.7 INSERT INTO localizedTexts VALUES ("0","D","Bitte wählen..","1") INSERT INTO localizedTexts VALUES ("1","D","SAV","1") INSERT INTO localizedTexts VALUES ("2","D","MON","1") INSERT INTO localizedTexts VALUES ("3","D","REP","1") INSERT INTO localizedTexts VALUES ("0","F","Choisir..","1") INSERT INTO localizedTexts VALUES ("1","F","SAV","1") INSERT INTO localizedTexts VALUES ("2","F","MON","1") INSERT INTO localizedTexts VALUES ("3","F","REP","1") INSERT INTO localizedTexts VALUES ("01","D","NEU","2") INSERT INTO localizedTexts VALUES ("02","D","ANGENOMMEN","2") INSERT INTO localizedTexts VALUES ("03","D","ABGELEHNT","2") INSERT INTO localizedTexts VALUES ("04","D","WEITERGELEITET","2") INSERT INTO localizedTexts VALUES ("05","D","IN ARBEIT","2") INSERT INTO localizedTexts VALUES ("06","D","ABGESCHLOSSEN","2") INSERT INTO localizedTexts VALUES ("07","D","TEILERLEDIGT","2") INSERT INTO localizedTexts VALUES ("01","F","NOUVEAU","2") INSERT INTO localizedTexts VALUES ("02","F","ADMIS","2") INSERT INTO localizedTexts VALUES ("03","F","REJETÉ","2") INSERT INTO localizedTexts VALUES ("04","F","TRANSMIS","2") INSERT INTO localizedTexts VALUES ("05","F","EN TRAVAIL","2") INSERT INTO localizedTexts VALUES ("06","F","RéPARATION FINALE","2") INSERT INTO localizedTexts VALUES ("07","F","RéPARATION PARTIELLE","2") INSERT INTO localizedTexts VALUES ("1","D","HOCH","3") INSERT INTO localizedTexts VALUES ("2","D","MITTEL","3") INSERT INTO localizedTexts VALUES ("3","D","NIEDRIG","3") INSERT INTO localizedTexts VALUES ("1","F","URGENT","3") INSERT INTO localizedTexts VALUES ("2","F","MOYEN","3") INSERT INTO localizedTexts VALUES ("3","F","FAIBLEMENT","3") INSERT INTO localizedTexts VALUES ("0000","D","Bitte wählen..","4") INSERT INTO localizedTexts VALUES ("0001","D","Frau","4") INSERT INTO localizedTexts VALUES ("0002","D","Herr","4") INSERT INTO localizedTexts VALUES ("0003","D","Firma","4") INSERT INTO localizedTexts VALUES ("0004","D","Herr und Frau","4") INSERT INTO localizedTexts VALUES ("0005","D","Familie","4") INSERT INTO localizedTexts VALUES ("0000","E","Please select","4") INSERT INTO localizedTexts VALUES ("0001","E","Mrs","4") INSERT INTO localizedTexts VALUES ("0002","E","Sir","4") INSERT INTO localizedTexts VALUES ("0003","E","Company","4") INSERT INTO localizedTexts VALUES ("0004","E","Mr. and Mrs","4") INSERT INTO localizedTexts VALUES ("0005","E","family", "4") INSERT INTO localizedTexts VALUES ("0000","F","Choisir..","4") INSERT INTO localizedTexts VALUES ("0001","F","Madame","4") INSERT INTO localizedTexts VALUES ("0002","F","Monsieur","4") INSERT INTO localizedTexts VALUES ("0003","F","Entreprise","4") INSERT INTO localizedTexts VALUES ("0004","F","Monsieur et Madame","4") INSERT INTO localizedTexts VALUES ("0005","F","Famille","4") INSERT INTO localizedTexts VALUES ("01","D","Objekt","5") INSERT INTO localizedTexts VALUES ("02","D","Kunde","5") INSERT INTO localizedTexts VALUES ("03","D","Auftraggeber","5") INSERT INTO localizedTexts VALUES ("04","D","Eigentümer","5") INSERT INTO localizedTexts VALUES ("05","D","Verwaltung","5") INSERT INTO localizedTexts VALUES ("06","D","Ansprechpartner Anlage","5") INSERT INTO localizedTexts VALUES ("07","D","Warenempfänger","5") INSERT INTO localizedTexts VALUES ("01","F","Objet","5") INSERT INTO localizedTexts VALUES ("02","F","Client","5") INSERT INTO localizedTexts VALUES ("03","F","Donneur d'ordre","5") INSERT INTO localizedTexts VALUES ("04","F","Propriétaire","5") INSERT INTO localizedTexts VALUES ("05","F","Administration","5") INSERT INTO localizedTexts VALUES ("06","F","Partenaire","5") INSERT INTO localizedTexts VALUES ("07","F","Destinataire","5") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","6") INSERT INTO localizedTexts VALUES ("01","D","Niemand auf Platz ","6") INSERT INTO localizedTexts VALUES ("02","D","Unterschrift verweigert ","6") INSERT INTO localizedTexts VALUES ("03","D","Rapport in Briefkasten / bei Anlage ","6") INSERT INTO localizedTexts VALUES ("04","D","Aus Hygienegründen keine Unterschrift","6") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","6") INSERT INTO localizedTexts VALUES ("01","F","Personne sur place ","6") INSERT INTO localizedTexts VALUES ("02","F","Signature refuse ","6") INSERT INTO localizedTexts VALUES ("03","F","Rapport dans boîte aux lettres ","6") INSERT INTO localizedTexts VALUES ("04","F","Pas de signature pour des raisons d'hygi�ne ","6") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","7") INSERT INTO localizedTexts VALUES ("01","D","Fax","7") INSERT INTO localizedTexts VALUES ("02","D","eMail","7") INSERT INTO localizedTexts VALUES ("03","D","Formular","7") INSERT INTO localizedTexts VALUES ("04","D","Verzicht","7") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","7") INSERT INTO localizedTexts VALUES ("01","F","Fax","7") INSERT INTO localizedTexts VALUES ("02","F","eMail","7") INSERT INTO localizedTexts VALUES ("03","F","Formulaire","7") INSERT INTO localizedTexts VALUES ("04","F","Pas de rapport","7") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","8") INSERT INTO localizedTexts VALUES ("01","D","Tor CL 2021","8") INSERT INTO localizedTexts VALUES ("02","D","Tor CL 2022","8") INSERT INTO localizedTexts VALUES ("03","D","STW CL 2023","8") INSERT INTO localizedTexts VALUES ("04","D","Barriere CL 2022","8") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","8") INSERT INTO localizedTexts VALUES ("01","F","Porte CL 2021","8") INSERT INTO localizedTexts VALUES ("02","F","Portail CL 2022","8") INSERT INTO localizedTexts VALUES ("03","F","STW CL 2023","8") INSERT INTO localizedTexts VALUES ("04","F","Barrière CL 2022","8") INSERT INTO localizedTexts VALUES ("00","D","Monat","9") INSERT INTO localizedTexts VALUES ("01","D","Januar","9") INSERT INTO localizedTexts VALUES ("02","D","Februar","9") INSERT INTO localizedTexts VALUES ("03","D","März","9") INSERT INTO localizedTexts VALUES ("04","D","April","9") INSERT INTO localizedTexts VALUES ("05","D","Mai","9") INSERT INTO localizedTexts VALUES ("06","D","Juni","9") INSERT INTO localizedTexts VALUES ("07","D","Juli","9") INSERT INTO localizedTexts VALUES ("08","D","August","9") INSERT INTO localizedTexts VALUES ("09","D","September","9") INSERT INTO localizedTexts VALUES ("10","D","Oktober","9") INSERT INTO localizedTexts VALUES ("11","D","November","9") INSERT INTO localizedTexts VALUES ("12","D","Dezember","9") INSERT INTO localizedTexts VALUES ("00","E","Month","9") INSERT INTO localizedTexts VALUES ("01","E","January","9") INSERT INTO localizedTexts VALUES ("02","E","February","9") INSERT INTO localizedTexts VALUES ("03","E","March","9") INSERT INTO localizedTexts VALUES ("04","E","April","9") INSERT INTO localizedTexts VALUES ("05","E","May","9") INSERT INTO localizedTexts VALUES ("06","E","June","9") INSERT INTO localizedTexts VALUES ("07","E","July","9") INSERT INTO localizedTexts VALUES ("08","E","August","9") INSERT INTO localizedTexts VALUES ("09","E","September","9") INSERT INTO localizedTexts VALUES ("10","E","October","9") INSERT INTO localizedTexts VALUES ("11","E","November","9") INSERT INTO localizedTexts VALUES ("12","E","December","9") INSERT INTO localizedTexts VALUES ("00","F","Mois","9") INSERT INTO localizedTexts VALUES ("01","F","Janvier","9") INSERT INTO localizedTexts VALUES ("02","F","Février","9") INSERT INTO localizedTexts VALUES ("03","F","Mars","9") INSERT INTO localizedTexts VALUES ("04","F","Avril","9") INSERT INTO localizedTexts VALUES ("05","F","Mai","9") INSERT INTO localizedTexts VALUES ("06","F","Juin","9") INSERT INTO localizedTexts VALUES ("07","F","Juillet","9") INSERT INTO localizedTexts VALUES ("08","F","Août","9") INSERT INTO localizedTexts VALUES ("09","F","Septembre","9") INSERT INTO localizedTexts VALUES ("10","F","Octobre","9") INSERT INTO localizedTexts VALUES ("11","F","Novembre","9") INSERT INTO localizedTexts VALUES ("12","F","Décembre","9") INSERT INTO localizedTexts VALUES ("01","D","Vorgesetzter","10") INSERT INTO localizedTexts VALUES ("02","D","Kunde","10") INSERT INTO localizedTexts VALUES ("03","D","1. Rapportnachricht","10") INSERT INTO localizedTexts VALUES ("04","D","2. Rapportnachricht","10") INSERT INTO localizedTexts VALUES ("05","D","Interne Nachricht","10") INSERT INTO localizedTexts VALUES ("06","D","Projektverantwortlicher","10") INSERT INTO localizedTexts VALUES ("07","D","Disposition","10") INSERT INTO localizedTexts VALUES ("01","F","Supérieur","10") INSERT INTO localizedTexts VALUES ("02","F","Client","10") INSERT INTO localizedTexts VALUES ("03","F","1er message du rapport","10") INSERT INTO localizedTexts VALUES ("04","F","2éme message du rapprt","10") INSERT INTO localizedTexts VALUES ("05","F","Message interne","10") INSERT INTO localizedTexts VALUES ("06","F","Responsable de projet","10") INSERT INTO localizedTexts VALUES ("07","F","Disposition","10") INSERT INTO localizedTexts VALUES ("00","D","Bitte wählen..","11") INSERT INTO localizedTexts VALUES ("01","D","Diverses..","11") INSERT INTO localizedTexts VALUES ("02","D","Fahrzeugwasch","11") INSERT INTO localizedTexts VALUES ("03","D","Fahrzeugverlad","11") INSERT INTO localizedTexts VALUES ("04","D","Parkinggebühren","11") INSERT INTO localizedTexts VALUES ("05","D","Einkauf Werkzeug","11") INSERT INTO localizedTexts VALUES ("06","D","Einkauf Verbrauchsmittel","11") INSERT INTO localizedTexts VALUES ("07","D","Benzinzahlung bar","11") INSERT INTO localizedTexts VALUES ("00","F","Choisir..","11") INSERT INTO localizedTexts VALUES ("01","F","divers..","11") INSERT INTO localizedTexts VALUES ("02","F","laver la voiture","11") INSERT INTO localizedTexts VALUES ("03","F","expédier du véhicule","11") INSERT INTO localizedTexts VALUES ("04","F","parking impôt","11") INSERT INTO localizedTexts VALUES ("05","F","achat des outils","11") INSERT INTO localizedTexts VALUES ("06","F","matériel consommations","11") INSERT INTO localizedTexts VALUES ("07","F","essence","11") INSERT INTO localizedTexts VALUES ("00","D","Standard","12") INSERT INTO localizedTexts VALUES ("04","D","Garantie","12") INSERT INTO localizedTexts VALUES ("05","D","Kulanz","12") INSERT INTO localizedTexts VALUES ("06","D","Auftrag","12") INSERT INTO localizedTexts VALUES ("00","F","Standard","12") INSERT INTO localizedTexts VALUES ("04","F","Garantie","12") INSERT INTO localizedTexts VALUES ("05","F","Pas de facturation","12") INSERT INTO localizedTexts VALUES ("06","F","Offre","12") INSERT INTO localizedTexts VALUES ("00","D","Arbeit/Fahrt","13") INSERT INTO localizedTexts VALUES ("01","D","Praxisausbildung","13") INSERT INTO localizedTexts VALUES ("02","D","Intern","13") INSERT INTO localizedTexts VALUES ("03","D","Fahrzeug","13") INSERT INTO localizedTexts VALUES ("04","D","Lager","13") INSERT INTO localizedTexts VALUES ("05","D","Transport","13") INSERT INTO localizedTexts VALUES ("06","D","Konferenzen","13") INSERT INTO localizedTexts VALUES ("07","D","Objektabklärung","13") INSERT INTO localizedTexts VALUES ("08","D","Externe Ganztagesschulung","13") INSERT INTO localizedTexts VALUES ("00","F","Travail, en route","13") INSERT INTO localizedTexts VALUES ("01","F","Stage pratique","13") INSERT INTO localizedTexts VALUES ("02","F","Interne","13") INSERT INTO localizedTexts VALUES ("03","F","Véhicule","13") INSERT INTO localizedTexts VALUES ("04","F","Dépôt","13") INSERT INTO localizedTexts VALUES ("05","F","Transport","13") INSERT INTO localizedTexts VALUES ("06","F","Conférences","13") INSERT INTO localizedTexts VALUES ("07","F","Recherche objet","13") INSERT INTO localizedTexts VALUES ("08","F","Journée de formation continue externe","13") INSERT INTO localizedTexts VALUES ("01","D","Erfolgreich angemeldet","14") INSERT INTO localizedTexts VALUES ("02","D","Passwort falsch","14") INSERT INTO localizedTexts VALUES ("03","D","Benutzer gesperrt","14") INSERT INTO localizedTexts VALUES ("04","D","Benutzer ist nicht registriert","14") INSERT INTO localizedTexts VALUES ("01","F","annoncé avec succès","14") INSERT INTO localizedTexts VALUES ("02","F","mot de passe faux","14") INSERT INTO localizedTexts VALUES ("03","F","utilisateur fermè","14") INSERT INTO localizedTexts VALUES ("04","F","utilisateur n'enregistre pas","14") #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface ArtNr = Art. Nr. BackupHandler_11 = N\u00E4chste Sicherung eingeplant am {0} BackupHandler_13 = T\u00E4glicher Sicherungslauf BackupHandler_15 = Sicherung fehlgeschlagen: {0} BackupHandler_19 = Der letzte (automatische) Sicherungslauf ist \u00E4lter als 24 Stunden. BackupHandler_21 = Es gibt noch keine Sicherung. Eine neue Sicherung wird jetzt gestartet. BackupHandler_23 = Die letzte erfolgreiche Sicherung liegt l\u00E4nger als 2 Tage zur\u00FCck. Eine neue Sicherung wird jetzt gestartet. BackupHandler_5 = Die Anwendung wird neu gestartet, um die regelm\u00E4\u00DFige Sicherung der Anwendungsdaten zu aktivieren. BackupHandler_6 = Neustart der Anwendung Containersize = Verpackungsgr\u00F6sse DeviceMirrorringHandler.0 = Codierter Sicherungspunkt muss mit 'SNAPSHOT~' beginnen und genau 5 durch '~' getrennte Segmente beinhalten! DeviceMirrorringHandler.1 = Aktiviere Ger\u00E4t... DeviceMirrorringHandler.10 = Der pers\u00F6nliche Push-Token kann nicht erzeugt und angefordert werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.11 = Benutzer ''{0}'' ist bereits auf Ger\u00E4t ''{1}'' registriert! Starten Sie eine Ger\u00E4temigration auf dem anderen Ger\u00E4t. DeviceMirrorringHandler.13 = Der Sicherungspunkt aus der Datenmigration von einem anderen Ger\u00E4t konnte nicht wiederhergestellt werden! DeviceMirrorringHandler.14 = Aktualisieren Sie auf die aktuellste Anwendungsversion and verwenden Sie in der Zwischenzeit das zuvor freigegebene Ger\u00E4t. DeviceMirrorringHandler.15 = Die lokalen Anwendungsdaten werden durch die Daten des \u00FCbernehmenden Benutzers ersetzt. DeviceMirrorringHandler.16 = Fortsetzen? DeviceMirrorringHandler.17 = Pers\u00F6nlichen Push-Token zuordnen... DeviceMirrorringHandler.18 = Der pers\u00F6nliche Push-Token konnte nicht angefordert werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.19 = Einige Anwendungen haben nicht die erforderliche Version. DeviceMirrorringHandler.2 = Synchronisierung der Push-Token... DeviceMirrorringHandler.20 = Das Ger\u00E4t konnte nicht f\u00FCr Push-Benachrichtigung vorbereitet werden. Push-Token konnten nicht synchronisiert werden. DeviceMirrorringHandler.23 = Beim Zugriff auf Attribute des pers\u00F6nlichen Push-Tokens ist ein Fehler aufgetreten. Sp\u00E4ter versuchen. DeviceMirrorringHandler.24 = Dem Benutzer {0} sind mehrere pers\u00F6nliche Push-Token zugeordnet!? Informieren Sie den IT-Support. DeviceMirrorringHandler.26 = Das Ger\u00E4t ist derzeit dem Benutzer {0} zugeordnet, die Ger\u00E4teaktivierung wurde aber nicht vollst\u00E4ndig abgeschlossen. Melden Sie sich als Benutzer {} an, um den Vorgang abzuschlie\u00DFen! DeviceMirrorringHandler.27 = Das pers\u00F6nliche Push-Token konnte nicht angelegt und zugeordnet werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.28 = Lese Token-Attribute... DeviceMirrorringHandler.29 = Ursache: DeviceMirrorringHandler.3 = Ger\u00E4t konnte nicht f\u00FCr den Empfang von Push-Benachrichtigungen vorbereitet werden. Push-Token konnten nicht synchronisiert werden. DeviceMirrorringHandler.30 = Die Sicherung zur Daten\u00FCbernahme vom anderen Ger\u00E4t konnte nicht wiederhergestellt werden! DeviceMirrorringHandler.31 = Erstelle pers\u00F6nliches Push-Token... DeviceMirrorringHandler.34 = Die Wiederherstellung der Sicherungsdaten vom anderen Ger\u00E4t konnte nicht vorbereitet werden! DeviceMirrorringHandler.35 = Der Benutzer ist bereits auf Ger\u00E4t ''{0}'' registriert! Starten Sie zun\u00E4chst den Ger\u00E4tewechsel auf dem anderen Ger\u00E4t. DeviceMirrorringHandler.37 = Das pers\u00F6nliche Push-Token konnte nicht angefordert werden. Sp\u00E4ter versuchen. DeviceMirrorringHandler.39 = Die Anwendungsdaten werden ersetzt mit den Daten vom Quellger\u00E4t aufgrund eines Ger\u00E4tewechsels. Quellger\u00E4t: ''{0}'', Sicherungszeit: {1} DeviceMirrorringHandler.4 = Aktiviere Anwendung... DeviceMirrorringHandler.41 = Pers\u00F6nliches Push-Token zuweisen... DeviceMirrorringHandler.42 = Wiederherstellung der Sicherungsdaten vom Quellger\u00E4t schlug fehl. DeviceMirrorringHandler.44 = Voraussetzungen konnten nicht gepr\u00FCft werden. Push-Token konnten nicht synchronisiert werden. DeviceMirrorringHandler.46 = Es sind nicht alle erforderlichen Anwendungen installiert. F\u00FChren Sie ein Update auf die aktuellste Anwendungsversion durch und verwenden Sie zwischenzeitlich das zuvor abgegebene Ger\u00E4t. DeviceMirrorringHandler.47 = Einige Anwendungen sind nicht auf der erforderlichen Version. F\u00FChren Sie ein Update auf die aktuellste Anwendungsversion durch und verwenden Sie zwischenzeitlich das zuvor abgegebene Ger\u00E4t. DeviceMirrorringHandler.48 = Das pers\u00F6nliche Push-Token konnte nicht freigegeben werden. DeviceMirrorringHandler.5 = Lese Token-Attribute... DeviceMirrorringHandler.50 = Quellger\u00E4te-Zustand wiederherstellen DeviceMirrorringHandler.51 = Die Anwendung wurde nicht f\u00FCr den angemeldeten Benutzer ''{0}'' aktiviert, sondern f\u00FCr Benutzer ''{1}''. DeviceMirrorringHandler.52 = Sicherung der Anwendungsdaten fehlgeschlagen. DeviceMirrorringHandler.53 = Ger\u00E4t f\u00FCr Benutzer ''{1}'' freigeben und mit der Ger\u00E4teaktivierung f\u00FCr den Benutzer ''{0}'' fortfahren? DeviceMirrorringHandler.55 = Ger\u00E4t freigeben... DeviceMirrorringHandler.56 = Synchronisiere Push-Token... DeviceMirrorringHandler.58 = Anwendung freigeben... DeviceMirrorringHandler.59 = Der angemeldete Benutzer ''{0}'' hat kein zugeordnetes pers\u00F6nliches Push-Token! DeviceMirrorringHandler.6 = Ursache: DeviceMirrorringHandler.60 = Es sind mehrere pers\u00F6nliche Push-Token zugeordnet! IT-Support kontaktieren. DeviceMirrorringHandler.62 = Erstelle Laufzeit-Wiederherstellungspunkt... DeviceMirrorringHandler.63 = Push-Token freigeben... DeviceMirrorringHandler.66 = Die Anwendungsdaten des Benutzers ''{0}'' werden gesichert, um sie sp\u00E4ter auf ein anderes Ger\u00E4t zu \u00FCbernehmen. DeviceMirrorringHandler.68 = Fortsetzen? DeviceMirrorringHandler.7 = Beim Laden der Attribute des pers\u00F6nlichen Push-Tokens ist ein Fehler aufgetreten. Sp\u00E4ter versuchen. DeviceMirrorringHandler.72 = Sicherung erstellt DeviceMirrorringHandler.73 = Anwendung f\u00FCr keinen Benutzer aktiviert. DeviceMirrorringHandler.8 = Erstelle pers\u00F6nliches Push-Token... DeviceMirrorringHandler.9 = Nicht alle erforderlichen Anwendungen sind derzeit installiert. Done = Erledigt FileUtils_0 = Datei {0} nicht vorhanden im Klassenpfad!? FormatMailAddress = Zul\u00E4ssiges Format: address@server.xy HTMLEncode_0 = Fehler bez\u00FCglich 1.4URLEncoder. Codieren mit Reflexion: InvalidFileName = Ung\u00FCltiger Dateiname: NumbersUpToSixDigitsAreAllowed = Zahlen bis zu 6 Stellen zul\u00E4ssig. PhoneBookEntry_1 = Kein Firmenname Planed = Geplant PropertiesFileConverter.0 = Kein Verzeichnis: RemoteTransactionHandler.0 = Interner Fehler: Die Methode darf nur auf dem AM Thread aufgerufen werden! RemoteTransactionHandler.1 = Stammdaten aktualisieren. RemoteTransactionHandler.2 = Aktualisierungs-Flag erneuert RemoteTransactionHandler.3 = Stammdaten heruntergeladen. RemoteTransactionHandler.4 = Veraltete Daten gel\u00F6scht. RemoteTransactionHandler.5 = Firmware-Dateien werden gel\u00F6scht. RemoteTransactionHandler.6 = Firmware-Datei wird gel\u00F6scht. RemoteTransactionHandler.7 = Keine Firmware-Datei vom Server erhalten. ReservedForFutureUse = Nicht verwendet. Reserviert f\u00FCr zuk\u00FCnfige Verwendung. SAPError = SAP-Fehler SAPErrorMessage = SAP Fehlermeldung: Service = Service StartEndLessThan3MinutesApart = Von/Bis ist weniger als 3 Minuten auseinander. TimeIsOverlapping = Zeit \u00FCberlappt mit {0} - {1}.\n WorkTimeRecordingWasStartedYesterday. = Arbeitszeiterfassung wurde bereits gestern gestartet. WouldYouLikeToCall = {0} anrufen? WrongFormArgument = Falsche Form Argumentklasse in Form gefunden. WrongFormat = Falsches Format ({0}) WrongFormatXX-XXXX-XXX/XX = Falsches Format (XX-XXXX-XXX/XX). abort = Abbrechen aborted = abgebrochen\u2026 all = Alle billing = Verrechnung camera = Kamera cancelled = Abgebrochen characters = Zeichen checkList = Checkliste commNo = Komm.-Nr. communicationError = Kommunikationsfehler communicationErrorWithColon = Kommunikationsfehler: confirmToDeleteMaterial = Artikel aus Datenbank l\u00F6schen? costumerReport = Kundenrapport deliveryListDownloaded = Artikelliste heruntergeladen. designation = Bezeichnung destinationAddressIsInvalid = Die Zieladresse ist ung\u00FCltig, NULL oder zu lange. doYouWantToStopTimesheet = Pers\u00F6nliche Arbeitszeit stoppen? documents = Dokumente duplicatedMaterialNumber = Artikel {0} schon verhanden {1} kann nicht hinzugef\u00FCgt werden. employee = Mitarbeiter error = Fehler errorWithParam = Fehler {0} exit = Beenden failure = St\u00F6rung firstName = Vorname foundErrorsInTimesheetsOnDate = An folgenden Daten wurden fehlerhafte Timesheets gefunden: {0}. Bitte korrigieren und senden. from = Von gallery = Galerie image = Bild images = Bilder information = Information insertComplete = Daten eingef\u00FCgt. insertingMasterData = Stammdaten laden... installationError = Anlagenfehler invalidNotificationInterval = Ung\u00FCltiger Wert f\u00FCr das Benachrichtigungsintervall gefunden. invalidUsernameOrPassword = Benutzername oder Passwort falsch. invalidVolume = Ung\u00FCltiger Wert f\u00FCr die Lautst\u00E4rke gefunden. jobState = Auftragsstatus loadCALENDARObjectWithDatetime = Laden eines Kalender-Objektes mit Datum ( location = Anlage material = Material materialList = Materialliste materialName = Artikelbezeichnung materialNumber = Artikelnummer measurement = Kraftmessung messages = Mitteilungen name = Name newJob = Neuer Auftrag! newJobReceived = Neuer Auftrag erhalten. newMessage = Neue Nachricht!\n newVehicleInventoryReceived = Neuer Wareneingang. newShortMessageReceived = Neue Kurznachricht erhalten. noDocumentsRecorded = Keine Dokumente vorhanden. noImagesRecorded = Keine Bilder vorhanden. noMaterialRecorded = Noch kein Material erfasst. noMeasurementsRecorded = Keine Messung vorhanden noMessagesRecorded = Noch keine Mitteilungen erfasst. noPartsFound = Keine Ersatzteile f\u00FCr diese Suchkriterien gefunden noRecipientApplication = Die gesuchte Anwendung konnte nicht gefunden werden. noReportRecorded = Noch kein Rapport erstellt. noTimesRecorded = Noch keine Zeiten erfasst. noUserActive = Kein aktiver Benutzer gefunden! REGISTER_USER noch nicht aufgerufen / defekte Daten in ZKDMOBMA? noValueForNotificationIntervalFound = Kein Wert f\u00FCr das Benachrichtigungsintervall gefunden noVolumeSettingFound = Kein Wert f\u00FCr die Lautst\u00E4rke gefunden number = Anzahl onlyNumberAndSpacesAllowedForTelephoneNumber = Nur Ziffern und Leerzeichen zul\u00E4ssig bei Telefonnummern. orderDate = Auftragsdatum orderNo = Auftragsnummer orderWillBeForwardedTo = Der {0}-Auftrag {1} wird an {2} weitergeleitet. overHoursInOneDay = "{0}" ist > 24h. overlapping = {0} \u00FCberlappt {1} partFound = Artikel gefunden. pleaseSelect = Bitte w\u00E4hlen... pleaseSelectValue = Bitte w\u00E4hlen Sie einen Wert aus! pleaseProvideValue = Bitte Wert eingeben! pointerReferenceToInvalidMemoryLocation = Ein Pointer zeigt auf einen ung\u00FCltigen Speicherbereich. Ein oder mehrer Pointer lpszDestAddress, lpszAppName, lpszCalledParty, oder lpszComment wurde sezifiziert, sind aber ung\u00FCltig. receive = Erhalten recipientApplicationIsActive = Die gesuchte Anwendung wurde gefunden. Jedoch ist die Request-Queue voll oder hat zu wenig Speicher zur Verf\u00FCgung. replacement = Ersatz reportCannotContainTimesMoreThanOneDay = Der Rapport kann nicht Zeiten von mehreren Tagen enthalten. Es gibt bereits Eintr\u00E4ge vom {0}. reports = Rapport reportsFrom = Rapport vom reset = Zur\u00FCcksetzen saveCALENDARObjectWithDatetime = Sichern eines Kalender-Objektes mit Datum ( search = Suchen select = W\u00E4hlen... shortNews = Kurznachrichten signature = Unterschrift subject = Betreff timeStopped = Zeit gestoppt times = Zeiten timesFrom = Zeiten vom timesheetCannotBeStartet = Zeiterfassung kann nicht gestartet werden. Das Timesheet wurde bereits gesendet. to = Bis total = Total typeOfJob = Arbeitsart updatingDeliveryList = Update Artikelliste userIsNotRegistred = Benutzer ist nicht registriert userLocked = Benutzer gesperrt. validationError = Validierungsfehler.\nBitte vervollst\u00E4ndigen Sie den Rapport. valueMustNotBeLongerThen = Text darf nicht l\u00E4nger sein als warning = Warnung! workTimeCapturingStartet = Arbeitszeit gestartet. workTimeCapturingStartetBeforeYesterday = Arbeitszeiterfassung wurde bereits vor mehreren Tagen gestartet. wrongFormArgument = Falscher Form\u00FCbergabeparameter. #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface ArtNr = No d'art. BackupHandler_11 = Prochaine sauvegarde des donn\u00E9es pr\u00E9vue pour le {0} BackupHandler_13 = Sauvegarde quotidienne BackupHandler_15 = La sauvegarde a \u00E9chou\u00E9: {0} BackupHandler_19 = La derni\u00E8re ex\u00E9cution de la sauvegarde (automatique) date de plus de 24 heures. BackupHandler_21 = Il n\u2019y a pas encore de sauvegarde. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_23 = La derni\u00E8re sauvegarde r\u00E9ussie remonte \u00E0 plus de 2 jours. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_5 = L\u2019application est red\u00E9marr\u00E9e pour activer la sauvegarde r\u00E9guli\u00E8re des donn\u00E9es de l\u2019application. BackupHandler_6 = Red\u00E9marrage de l\u2018application Containersize = Dimensions d'emballage DeviceMirrorringHandler.0 = Le point de restaurantion cod\u00E9 doit commencer par 'SNAPSHOT~' et comprendre pr\u00E9cis\u00E9ment 5 segments s\u00E9par\u00E9s par '~'! DeviceMirrorringHandler.1 = Activer l'appareil... DeviceMirrorringHandler.10 = Impossible de cr\u00E9er et demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.11 = L'utilisateur ''{0}'' est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{1}'' ! D\u00E9marrez une migration de l'appareil sur l'autre appareil. DeviceMirrorringHandler.13 = Impossible de r\u00E9tablir le point de restauration de la migration de donn\u00E9es \u00E0 partir d'un autre appareil! DeviceMirrorringHandler.14 = Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment partag\u00E9. DeviceMirrorringHandler.15 = Les donn\u00E9es d\u2019application locales sont remplac\u00E9es par les donn\u00E9es de l\u2019utilisateur reprenant. DeviceMirrorringHandler.16 = Continuer? DeviceMirrorringHandler.17 = Attribuer le Push-Token personnel... DeviceMirrorringHandler.18 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.19 = Quelques applications n'ont pas la version n\u00E9cessaire. DeviceMirrorringHandler.2 = Synchronisation des Push-Token... DeviceMirrorringHandler.20 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.23 = Une erreur est survenue en acc\u00E9dant les attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.24 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.26 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.27 = Impossible de cr\u00E9er et attribuer le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.28 = Attributs Token de lecture... DeviceMirrorringHandler.29 = Cause: DeviceMirrorringHandler.3 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour recevoir les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.30 = Impossible de r\u00E9tablir la sauvegarde pour la reprise de donn\u00E9es de l\u2019autre appareil! DeviceMirrorringHandler.31 = Cr\u00E9ation d'un Push-Token personnel... DeviceMirrorringHandler.34 = Impossible de pr\u00E9parer le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019autre appareil! DeviceMirrorringHandler.35 = L'utilisateur est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{0}''! D\u00E9marrez d'abord le changement d'appareil sur un autre appareil. DeviceMirrorringHandler.37 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.39 = Les donn\u00E9es d\u2019application sont remplac\u00E9es par les donn\u00E9es de l\u2019appareil source en raison d\u2019un changement d\u2019\u00E9quipement. Appareil source: ''{0}'', temps de sauvegarde: {1} DeviceMirrorringHandler.4 = Activer l'application... DeviceMirrorringHandler.41 = Attribuer les Push-Token personnels... DeviceMirrorringHandler.42 = Le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019appareil source a \u00E9chou\u00E9. DeviceMirrorringHandler.44 = Les conditions pr\u00E9alables n'ont pas pu \u00EAtre v\u00E9rifi\u00E9es. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.46 = Pas toutes les applications n\u00E9cessaires sont install\u00E9es. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.47 = Certaines des applications ne se trouvent pas dans la version requise. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.48 = Le Push-Token personnel n'a pas pu \u00EAtre lib\u00E9r\u00E9. DeviceMirrorringHandler.5 = Attributs Token de lecture... DeviceMirrorringHandler.50 = R\u00E9tablir l\u2019\u00E9tat de l\u2019appareil source DeviceMirrorringHandler.51 = L'application n'a pas \u00E9t\u00E9 activ\u00E9e pour l'utilisateur ''{0}'' enregistr\u00E9, mais pour l'utilisateur ''{1}''. DeviceMirrorringHandler.52 = La sauvegarde des donn\u00E9es d\u2019application a \u00E9chou\u00E9. DeviceMirrorringHandler.53 = Lib\u00E9rer l'appareil pour l'utilisateur ''{1}'' et continuer avec l'activation de l'appareil pour l'utilisateur ''{0}'' ? DeviceMirrorringHandler.55 = Lib\u00E9rer l'apparail... DeviceMirrorringHandler.56 = Synchronisation du Push-Token... DeviceMirrorringHandler.58 = Lib\u00E9rer l'application... DeviceMirrorringHandler.59 = L'utilisateur ''{0}'' enregistr\u00E9 n'a pas de Push-Token personnel attribu\u00E9! DeviceMirrorringHandler.6 = Cause: DeviceMirrorringHandler.60 = Plusieurs Push-Token personnels sont d\u00E9j\u00E0 attribu\u00E9s! Veuillez contacter le support informatique. DeviceMirrorringHandler.62 = Cr\u00E9ez un point de restauration de la dur\u00E9e d\u2019ex\u00E9cution. DeviceMirrorringHandler.63 = Lib\u00E9rer Push-Token ... DeviceMirrorringHandler.66 = Les donn\u00E9es d'application de l'utilisateur ''{0}'' sont sauvegard\u00E9es afin d'\u00EAtre transfer\u00E9es ult\u00E9rieurement sur un autre appareil. DeviceMirrorringHandler.68 = Continuer? DeviceMirrorringHandler.7 = Une erreur est survenue lors du chargement des attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.72 = Sauvegarde \u00E9tablie. DeviceMirrorringHandler.73 = L\u2019application n\u2019est activ\u00E9e pour aucun utilisateur. DeviceMirrorringHandler.8 = Cr\u00E9er un Push-Token personnel... DeviceMirrorringHandler.9 = Actuellement, pas toutes les applications sont install\u00E9es. Done = Fini FileUtils_0 = Fichier {0} pas pr\u00E9sent dans classpath!? FormatMailAddress = Format admissible: address@server.xy HTMLEncode_0 = Erreur invoquant 1.4 URLEncodeur.encoder avec r\u00E9flexion: InvalidFileName = Nom de fichier invalide: NumbersUpToSixDigitsAreAllowed = Jusqu'\u00E0 six chiffres admissibles. PhoneBookEntry_1 = Aucun nom d'entreprise Planed = Pr\u00E9vu PropertiesFileConverter.0 = Pas un r\u00E9pertoire: RemoteTransactionHandler.0 = Erreur interne: la m\u00E9thode ne doit \u00EAtre appel\u00E9e que sur le thread AM! RemoteTransactionHandler.1 = Actualiser donn\u00E9es de base. RemoteTransactionHandler.2 = Flag d'actualisation mis \u00E0 jour. RemoteTransactionHandler.3 = Donn\u00E9es de base t\u00E9l\u00E9charg\u00E9es. RemoteTransactionHandler.4 = Donn\u00E9es obsol\u00E8tes effac\u00E9es. RemoteTransactionHandler.5 = Fichiers du logiciel r\u00E9sident sont effac\u00E9s. RemoteTransactionHandler.6 = Fichier du logiciel r\u00E9sident est effac\u00E9. RemoteTransactionHandler.7 = Aucun fichier du logiciel r\u00E9sident re\u00E7u par le ser ReservedForFutureUse = Pas appliqu\u00E9, r\u00E9serv\u00E9 pour application \u00E0 l'avenir. SAPError = SAP erreur SAPErrorMessage = SAP erreur: Service = Service StartEndLessThan3MinutesApart = de/\u00E0 diff\u00E9re moins de 3 minutes. TimeIsOverlapping = Temps chevauchent par {0} - {1}.\n WorkTimeRecordingWasStartedYesterday. = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e hier. WouldYouLikeToCall = T\u00E9l\u00E9phoner {0} ? WrongFormArgument = Param\u00E8tre de remise de la forme incorrect. WrongFormat = Format incorrect ({0}) WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). abort = Annuler aborted = annul\u00E9\u2026 all = Tous billing = Facturation camera = Camera cancelled = Annul\u00E9 characters = Caract\u00E9res checkList = Check-list commNo = No com. communicationError = Erreur de communication communicationErrorWithColon = Erreur de communication: confirmToDeleteMaterial = Effacer l'article de la base de donn\u00E9es? costumerReport = Rapport clients deliveryListDownloaded = Articles t\u00E9l\u00E9charg\u00E9es. designation = D\u00E9signation destinationAddressIsInvalid = L'adresse cible est invalide, ZERO ou trop long. doYouWantToStopTimesheet = Arr\u00E9ter le temps de travail personnel? documents = Documents duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur error = Erreur errorWithParam = Erreur {0} exit = Terminer failure = D\u00E9faillance firstName = Pr\u00E9nom foundErrorsInTimesheetsOnDate = Des Timesheet (fiches horaires) fautives ont \u00E9t\u00E9 trouv\u00E8res pour les dates suivantes: {0}. Veuillez s'il vous pla\u00EEt les corriger et envoyer. from = de gallery = Galerie image = Image images = Images information = Information insertComplete = Ajout\u00E9es des donn\u00E9es. insertingMasterData = Ins\u00E9rer des donn\u00E9es de base... installationError = Erreur d'installation invalidNotificationInterval = Valeur invalide trouv\u00E9 pour l'intervalle d'avertissement. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect invalidVolume = Valeur invalide trouv\u00E9 pour l'intensit\u00E9 du son. jobState = \u00C9tat de commande loadCALENDARObjectWithDatetime = Charger un objet calendrier avec date ( location = Installation material = Mat\u00E9riel materialList = Liste de mat\u00E9riel materialName = Nom d'article materialNumber = No. d'article measurement = Mesure de la force messages = Messages name = Nom newJob = Nouvel ordre! newJobReceived = Nouveau travail re\u00E7u. newMessage = Nouveau Message!\n newVehicleInventoryReceived = Nouveau Entrep\u00F4t de v\u00E8hicules re\u00E7u. newShortMessageReceived = Nouveau message court re\u00E7u. noDocumentsRecorded = Aucun documents disponible. noImagesRecorded = Aucun images disponible. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMeasurementsRecorded = Aucune meseure n'est disponible noMessagesRecorded = Aucun message enregistr\u00E9 noPartsFound = Pas de pi\u00E8ce de rechange trouv\u00E8res pour ces crit\u00E8r noRecipientApplication = Impossible de trouver l'application cherch\u00E9e. noReportRecorded = Aucun rapport enregistr\u00E9 noTimesRecorded = Aucune heure enregistr\u00E9e noUserActive = Aucun utilisateur actif n'est trouv\u00E9! Pas encore appel\u00E9 le REGISTER_USER / donn\u00E9es d\u00E9fectueuses dans ZKDMOBMA? noValueForNotificationIntervalFound = Aucune valeur trouv\u00E9 pour l'intervalle d'avertisse noVolumeSettingFound = Aucune valeur trouv\u00E9 pour l'intensit\u00E9 du son. number = Quantit\u00E9 onlyNumberAndSpacesAllowedForTelephoneNumber = Uniquement chiffres et espaces admissibles pour les num\u00E9ros de t\u00E9l. orderDate = Date de commande orderNo = No de commande orderWillBeForwardedTo = La commande {0} {1} sera transmise \u00E0 {2}. overHoursInOneDay = "{0}" est > 24h. overlapping = {0} chevauchent {1} partFound = Article trouv\u00E9. pleaseSelect = Choisir... pleaseSelectValue = S\u00E9lectionnez une valeur! pleaseProvideValue = Veuillez fournir une valeur! pointerReferenceToInvalidMemoryLocation = Un pointeur montre une zone de m\u00E9moire invalide. Un ou plusieurs pointeurs lpszDestAddress, lpszAppName, lpszCalledParty, ou lpszComment ont \u00E9t\u00E9 sp\u00E9cifi\u00E9s, mais sont invalides. receive = Re\u00E7u recipientApplicationIsActive = Impossible de trouver l'application cherch\u00E9e, mais la file de demande est bond\u00E9e ou capacit\u00E9 du m\u00E9moire insuffisante. replacement = Remplacement reportCannotContainTimesMoreThanOneDay = Le rapport ne peut pas contenir des temps de plusieurs jours. Des donn\u00E9es sont d\u00E9j\u00E0 existantes du {0}. reports = Rapports reportsFrom = Rapports de reset = Rappel saveCALENDARObjectWithDatetime = M\u00E9moriser un objet calendrier avec date ( search = Recherche select = S\u00E9lectionner... shortNews = Flash d'informations signature = Signature subject = Concerne timeStopped = Le temps est arr\u00E9t\u00E9 times = Temps timesFrom = Temps de timesheetCannotBeStartet = Impossible de d\u00E9marrer la saisie de temps. Le Timesheet a \u00E9t\u00E9 d\u00E9j\u00E0 envoy\u00E9. to = jusqu'\u00E0 total = Total typeOfJob = Type de travail updatingDeliveryList = Mettre \u00E0 jour la liste des articles userIsNotRegistred = Utilisateur n'enregistre pas. userLocked = Utilisateur ferm\u00E9. validationError = Erreur de validation.\nS.v.p. entrez toutes les donn\u00E9es. valueMustNotBeLongerThen = Longueur du texte pas plus que warning = Avertissement! workTimeCapturingStartet = La saisie des heures de travail d\u00E9marr\u00E9. workTimeCapturingStartetBeforeYesterday = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e il y a plusieurs jours. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect. #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface ArtNr = No d'art. BackupHandler_11 = Prochaine sauvegarde des donn\u00E9es pr\u00E9vue pour le {0} BackupHandler_13 = Sauvegarde quotidienne BackupHandler_15 = La sauvegarde a \u00E9chou\u00E9: {0} BackupHandler_19 = La derni\u00E8re ex\u00E9cution de la sauvegarde (automatique) date de plus de 24 heures. BackupHandler_21 = Il n\u2019y a pas encore de sauvegarde. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_23 = La derni\u00E8re sauvegarde r\u00E9ussie remonte \u00E0 plus de 2 jours. Une nouvelle sauvegarde est d\u00E9marr\u00E9e maintenant. BackupHandler_5 = L\u2019application est red\u00E9marr\u00E9e pour activer la sauvegarde r\u00E9guli\u00E8re des donn\u00E9es de l\u2019application. BackupHandler_6 = Red\u00E9marrage de l\u2018application Containersize = Dimensions d'emballage DeviceMirrorringHandler.0 = Le point de restaurantion cod\u00E9 doit commencer par 'SNAPSHOT~' et comprendre pr\u00E9cis\u00E9ment 5 segments s\u00E9par\u00E9s par '~'! DeviceMirrorringHandler.1 = Activer l'appareil... DeviceMirrorringHandler.10 = Impossible de cr\u00E9er et demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.11 = L'utilisateur ''{0}'' est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{1}'' ! D\u00E9marrez une migration de l'appareil sur l'autre appareil. DeviceMirrorringHandler.13 = Impossible de r\u00E9tablir le point de restauration de la migration de donn\u00E9es \u00E0 partir d'un autre appareil! DeviceMirrorringHandler.14 = Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment partag\u00E9. DeviceMirrorringHandler.15 = Les donn\u00E9es d\u2019application locales sont remplac\u00E9es par les donn\u00E9es de l\u2019utilisateur reprenant. DeviceMirrorringHandler.16 = Continuer? DeviceMirrorringHandler.17 = Attribuer le Push-Token personnel... DeviceMirrorringHandler.18 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.19 = Quelques applications n'ont pas la version n\u00E9cessaire. DeviceMirrorringHandler.2 = Synchronisation des Push-Token... DeviceMirrorringHandler.20 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.23 = Une erreur est survenue en acc\u00E9dant les attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.24 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.26 = Plusieurs push-token personnels sont attribu\u00E9s \u00E0 l'utilisateur {0} !? Informez le support informatique. DeviceMirrorringHandler.27 = Impossible de cr\u00E9er et attribuer le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.28 = Attributs Token de lecture... DeviceMirrorringHandler.29 = Cause: DeviceMirrorringHandler.3 = L'appareil n'a pas pu \u00EAtre pr\u00E9par\u00E9 pour recevoir les notifications Push. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.30 = Impossible de r\u00E9tablir la sauvegarde pour la reprise de donn\u00E9es de l\u2019autre appareil! DeviceMirrorringHandler.31 = Cr\u00E9ation d'un Push-Token personnel... DeviceMirrorringHandler.34 = Impossible de pr\u00E9parer le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019autre appareil! DeviceMirrorringHandler.35 = L'utilisateur est d\u00E9j\u00E0 enregistr\u00E9 sur l'appareil ''{0}''! D\u00E9marrez d'abord le changement d'appareil sur un autre appareil. DeviceMirrorringHandler.37 = Impossible de demander le Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.39 = Les donn\u00E9es d\u2019application sont remplac\u00E9es par les donn\u00E9es de l\u2019appareil source en raison d\u2019un changement d\u2019\u00E9quipement. Appareil source: ''{0}'', temps de sauvegarde: {1} DeviceMirrorringHandler.4 = Activer l'application... DeviceMirrorringHandler.41 = Attribuer les Push-Token personnels... DeviceMirrorringHandler.42 = Le r\u00E9tablissement des donn\u00E9es de sauvegarde de l\u2019appareil source a \u00E9chou\u00E9. DeviceMirrorringHandler.44 = Les conditions pr\u00E9alables n'ont pas pu \u00EAtre v\u00E9rifi\u00E9es. Les Push-Token n'ont pas pu \u00EAtre synchronis\u00E9s. DeviceMirrorringHandler.46 = Pas toutes les applications n\u00E9cessaires sont install\u00E9es. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.47 = Certaines des applications ne se trouvent pas dans la version requise. Proc\u00E9dez \u00E0 une mise \u00E0 jour \u00E0 la plus r\u00E9cente version d\u2019application et, entretemps, utilisez l\u2019appareil pr\u00E9c\u00E9demment remis. DeviceMirrorringHandler.48 = Le Push-Token personnel n'a pas pu \u00EAtre lib\u00E9r\u00E9. DeviceMirrorringHandler.5 = Attributs Token de lecture... DeviceMirrorringHandler.50 = R\u00E9tablir l\u2019\u00E9tat de l\u2019appareil source DeviceMirrorringHandler.51 = L'application n'a pas \u00E9t\u00E9 activ\u00E9e pour l'utilisateur ''{0}'' enregistr\u00E9, mais pour l'utilisateur ''{1}''. DeviceMirrorringHandler.52 = La sauvegarde des donn\u00E9es d\u2019application a \u00E9chou\u00E9. DeviceMirrorringHandler.53 = Lib\u00E9rer l'appareil pour l'utilisateur ''{1}'' et continuer avec l'activation de l'appareil pour l'utilisateur ''{0}'' ? DeviceMirrorringHandler.55 = Lib\u00E9rer l'apparail... DeviceMirrorringHandler.56 = Synchronisation du Push-Token... DeviceMirrorringHandler.58 = Lib\u00E9rer l'application... DeviceMirrorringHandler.59 = L'utilisateur ''{0}'' enregistr\u00E9 n'a pas de Push-Token personnel attribu\u00E9! DeviceMirrorringHandler.6 = Cause: DeviceMirrorringHandler.60 = Plusieurs Push-Token personnels sont d\u00E9j\u00E0 attribu\u00E9s! Veuillez contacter le support informatique. DeviceMirrorringHandler.62 = Cr\u00E9ez un point de restauration de la dur\u00E9e d\u2019ex\u00E9cution. DeviceMirrorringHandler.63 = Lib\u00E9rer Push-Token ... DeviceMirrorringHandler.66 = Les donn\u00E9es d'application de l'utilisateur ''{0}'' sont sauvegard\u00E9es afin d'\u00EAtre transfer\u00E9es ult\u00E9rieurement sur un autre appareil. DeviceMirrorringHandler.68 = Continuer? DeviceMirrorringHandler.7 = Une erreur est survenue lors du chargement des attributs du Push-Token personnel. Veuillez essayer plus tard. DeviceMirrorringHandler.72 = Sauvegarde \u00E9tablie. DeviceMirrorringHandler.73 = L\u2019application n\u2019est activ\u00E9e pour aucun utilisateur. DeviceMirrorringHandler.8 = Cr\u00E9er un Push-Token personnel... DeviceMirrorringHandler.9 = Actuellement, pas toutes les applications sont install\u00E9es. Done = Fini FileUtils_0 = Fichier {0} pas pr\u00E9sent dans classpath!? FormatMailAddress = Format admissible: address@server.xy HTMLEncode_0 = Erreur invoquant 1.4 URLEncodeur.encoder avec r\u00E9flexion: InvalidFileName = Nom de fichier invalide: NumbersUpToSixDigitsAreAllowed = Jusqu'\u00E0 six chiffres admissibles. PhoneBookEntry_1 = Aucun nom d'entreprise Planed = Pr\u00E9vu PropertiesFileConverter.0 = Pas un r\u00E9pertoire: RemoteTransactionHandler.0 = Erreur interne: la m\u00E9thode ne doit \u00EAtre appel\u00E9e que sur le thread AM! RemoteTransactionHandler.1 = Actualiser donn\u00E9es de base. RemoteTransactionHandler.2 = Flag d'actualisation mis \u00E0 jour. RemoteTransactionHandler.3 = Donn\u00E9es de base t\u00E9l\u00E9charg\u00E9es. RemoteTransactionHandler.4 = Donn\u00E9es obsol\u00E8tes effac\u00E9es. RemoteTransactionHandler.5 = Fichiers du logiciel r\u00E9sident sont effac\u00E9s. RemoteTransactionHandler.6 = Fichier du logiciel r\u00E9sident est effac\u00E9. RemoteTransactionHandler.7 = Aucun fichier du logiciel r\u00E9sident re\u00E7u par le ser ReservedForFutureUse = Pas appliqu\u00E9, r\u00E9serv\u00E9 pour application \u00E0 l'avenir. SAPError = SAP erreur SAPErrorMessage = SAP erreur: Service = Service StartEndLessThan3MinutesApart = de/\u00E0 diff\u00E9re moins de 3 minutes. TimeIsOverlapping = Temps chevauchent par {0} - {1}.\n WorkTimeRecordingWasStartedYesterday. = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e hier. WouldYouLikeToCall = T\u00E9l\u00E9phoner {0} ? WrongFormArgument = Param\u00E8tre de remise de la forme incorrect. WrongFormat = Format incorrect ({0}) WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). abort = Annuler aborted = annul\u00E9\u2026 all = Tous billing = Facturation camera = Camera cancelled = Annul\u00E9 characters = Caract\u00E9res checkList = Check-list commNo = No com. communicationError = Erreur de communication communicationErrorWithColon = Erreur de communication: confirmToDeleteMaterial = Effacer l'article de la base de donn\u00E9es? costumerReport = Rapport clients deliveryListDownloaded = Aggiorna t\u00E9l\u00E9charg\u00E9es. designation = D\u00E9signation destinationAddressIsInvalid = L'adresse cible est invalide, ZERO ou trop long. doYouWantToStopTimesheet = Arr\u00E9ter le temps de travail personnel? documents = Documents duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur error = Erreur errorWithParam = Erreur {0} exit = Terminer failure = D\u00E9faillance firstName = Pr\u00E9nom foundErrorsInTimesheetsOnDate = Des Timesheet (fiches horaires) fautives ont \u00E9t\u00E9 trouv\u00E8res pour les dates suivantes: {0}. Veuillez s'il vous pla\u00EEt les corriger et envoyer. from = de gallery = Galerie image = Image images = Images information = Information insertComplete = Ajout\u00E9es des donn\u00E9es. insertingMasterData = Ins\u00E9rer des donn\u00E9es de base... installationError = Erreur d'installation invalidNotificationInterval = Valeur invalide trouv\u00E9 pour l'intervalle d'avertissement. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect invalidVolume = Valeur invalide trouv\u00E9 pour l'intensit\u00E9 du son. jobState = \u00C9tat de commande loadCALENDARObjectWithDatetime = Charger un objet calendrier avec date ( location = Installation material = Mat\u00E9riel materialList = Liste de mat\u00E9riel materialName = Nom d'article materialNumber = No. d'article measurement = Mesure de la force messages = Messages name = Nom newJob = Nouvel ordre! newJobReceived = Nouveau travail re\u00E7u. newMessage = Nouveau Message!\n newVehicleInventoryReceived = Nouveau Magazzino veicoli re\u00E7u. newShortMessageReceived = Nouveau message court re\u00E7u. noDocumentsRecorded = Aucun documents disponible. noImagesRecorded = Aucun images disponible. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMeasurementsRecorded = Aucune meseure n'est disponible noMessagesRecorded = Aucun message enregistr\u00E9 noPartsFound = Pas de pi\u00E8ce de rechange trouv\u00E8res pour ces crit\u00E8r noRecipientApplication = Impossible de trouver l'application cherch\u00E9e. noReportRecorded = Aucun rapport enregistr\u00E9 noTimesRecorded = Aucune heure enregistr\u00E9e noUserActive = Aucun utilisateur actif n'est trouv\u00E9! Pas encore appel\u00E9 le REGISTER_USER / donn\u00E9es d\u00E9fectueuses dans ZKDMOBMA? noValueForNotificationIntervalFound = Aucune valeur trouv\u00E9 pour l'intervalle d'avertisse noVolumeSettingFound = Aucune valeur trouv\u00E9 pour l'intensit\u00E9 du son. number = Quantit\u00E9 onlyNumberAndSpacesAllowedForTelephoneNumber = Uniquement chiffres et espaces admissibles pour les num\u00E9ros de t\u00E9l. orderDate = Date de commande orderNo = No de commande orderWillBeForwardedTo = La commande {0} {1} sera transmise \u00E0 {2}. overHoursInOneDay = "{0}" est > 24h. overlapping = {0} chevauchent {1} partFound = Article trouv\u00E9. pleaseSelect = Choisir... pleaseSelectValue = S\u00E9lectionnez une valeur! pleaseProvideValue = Veuillez fournir une valeur! pointerReferenceToInvalidMemoryLocation = Un pointeur montre une zone de m\u00E9moire invalide. Un ou plusieurs pointeurs lpszDestAddress, lpszAppName, lpszCalledParty, ou lpszComment ont \u00E9t\u00E9 sp\u00E9cifi\u00E9s, mais sont invalides. receive = Re\u00E7u recipientApplicationIsActive = Impossible de trouver l'application cherch\u00E9e, mais la file de demande est bond\u00E9e ou capacit\u00E9 du m\u00E9moire insuffisante. replacement = Remplacement reportCannotContainTimesMoreThanOneDay = Le rapport ne peut pas contenir des temps de plusieurs jours. Des donn\u00E9es sont d\u00E9j\u00E0 existantes du {0}. reports = Rapports reportsFrom = Rapports de reset = Rappel saveCALENDARObjectWithDatetime = M\u00E9moriser un objet calendrier avec date ( search = Recherche select = S\u00E9lectionner... shortNews = Flash d'informations signature = Signature subject = Concerne timeStopped = Le temps est arr\u00E9t\u00E9 times = Temps timesFrom = Temps de timesheetCannotBeStartet = Impossible de d\u00E9marrer la saisie de temps. Le Timesheet a \u00E9t\u00E9 d\u00E9j\u00E0 envoy\u00E9. to = jusqu'\u00E0 total = Total typeOfJob = Type de travail updatingDeliveryList = Aggiorna l'elenco degli articoli userIsNotRegistred = Utilisateur n'enregistre pas. userLocked = Utilisateur ferm\u00E9. validationError = Erreur de validation.\nS.v.p. entrez toutes les donn\u00E9es. valueMustNotBeLongerThen = Longueur du texte pas plus que warning = Avertissement! workTimeCapturingStartet = La saisie des heures de travail d\u00E9marr\u00E9. workTimeCapturingStartetBeforeYesterday = La saisie des heures de travail a \u00E9t\u00E9 d\u00E9marr\u00E9e il y a plusieurs jours. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect. package ch.mfiles.kaba.kolibri.common; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.common.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) ArtNr = Art. Nr. BackupHandler_11 = Scheduled next backup run for {0} BackupHandler_13 = Daily backup run BackupHandler_15 = Backup failed: {0} BackupHandler_19 = The last (automatic) backup run is more than 24 hours past. BackupHandler_21 = There is no runtime backup. A new backup will be triggered now. BackupHandler_23 = The last successful backup is older than 2 days. A new backup will be triggered now. BackupHandler_5 = Restart the application to activate the periodic backup of application data. BackupHandler_6 = Application restart Containersize = Container size DeviceMirrorringHandler.0 = Encoded restore point must start with 'SNAPSHOT~' and contain exactly 5 segments separated by '~'! DeviceMirrorringHandler.1 = Activating device... DeviceMirrorringHandler.10 = Unable to create and request the personal push token. Retry later. DeviceMirrorringHandler.11 = User ''{0}'' is already registered on device ''{1}''! Trigger a device migration on the other device. DeviceMirrorringHandler.13 = Could not reconstruct restore point for data migration from other device! DeviceMirrorringHandler.14 = Update to the most current application release and use the previously released device in the meantime. DeviceMirrorringHandler.15 = Local application data will be replaced with the data from the switching user. DeviceMirrorringHandler.16 = Continue? DeviceMirrorringHandler.17 = Assigning personal push token... DeviceMirrorringHandler.18 = Unable to request the personal push token. Retry later. DeviceMirrorringHandler.19 = Some applications are not installed with the required version. DeviceMirrorringHandler.2 = Synchronizing push tokens... DeviceMirrorringHandler.20 = Unable to prepare device for push notifications. Could not synchronize push tokens. DeviceMirrorringHandler.23 = Exception caught while loading the personal push token attributes. Retry later. DeviceMirrorringHandler.24 = Multiple personal push tokens are already assigned for user {0}!? Contact IT support. DeviceMirrorringHandler.26 = Device is currently assigned to user {0} but was not fully activated. Log in as user {0} first to complete the process! DeviceMirrorringHandler.27 = Unable to create and request the personal push token. Retry later. DeviceMirrorringHandler.28 = Reading token attributes... DeviceMirrorringHandler.29 = Cause: DeviceMirrorringHandler.3 = Unable to prepare device for push notifications. Could not synchronize push tokens. DeviceMirrorringHandler.30 = Could not reconstruct restore point for data migration from other device! DeviceMirrorringHandler.31 = Creating personal push token... DeviceMirrorringHandler.34 = Could not prepare to restore migrated application data from other device! DeviceMirrorringHandler.35 = User is already registered on device ''{0}''! Trigger a device migration on the other device first. DeviceMirrorringHandler.37 = Unable to request the personal push token. Retry later. DeviceMirrorringHandler.39 = The application data will be replaced with the state of the source device due to a device migration. Source device: ''{0}'', backup time: {1} DeviceMirrorringHandler.4 = Activate application... DeviceMirrorringHandler.41 = Assigning personal push token... DeviceMirrorringHandler.42 = Restoring the state of the source device failed. DeviceMirrorringHandler.44 = Unable to check prerequisites. Could not synchronize push tokens. DeviceMirrorringHandler.46 = Not all required applications are installed. Please carry out an update to the latest application version and use in the meantime the previously handed over device. DeviceMirrorringHandler.47 = Some applications are not at the required version. Please carry out un update to the latest version and use in the meantime the previously handed over device. DeviceMirrorringHandler.48 = Unable to release the personal push token. DeviceMirrorringHandler.5 = Reading token attributes... DeviceMirrorringHandler.50 = Restored source device state DeviceMirrorringHandler.51 = The application was not activated for the logged in user ''{0}'' but for user ''{1}''. DeviceMirrorringHandler.52 = Backup of application data failed. DeviceMirrorringHandler.53 = Release the device for user ''{1}'' and continue the device activation with user ''{0}''? DeviceMirrorringHandler.55 = Releasing device... DeviceMirrorringHandler.56 = Synchronizing push tokens... DeviceMirrorringHandler.58 = Release application... DeviceMirrorringHandler.59 = The logged in user ''{0}'' has no personal push token assigned! DeviceMirrorringHandler.6 = Cause: DeviceMirrorringHandler.60 = There are multiple personal push tokens assigned! Contact IT support. DeviceMirrorringHandler.62 = Creating runtime restore point... DeviceMirrorringHandler.63 = Releasing push tokens... DeviceMirrorringHandler.66 = The application data of user ''{0}'' will be backed up to be migrated to another device later. DeviceMirrorringHandler.68 = Continue? DeviceMirrorringHandler.7 = Exception caught while loading the personal push token attributes. Retry later. DeviceMirrorringHandler.72 = Backup complete DeviceMirrorringHandler.73 = Application not activated for any user. DeviceMirrorringHandler.8 = Creating personal push token... DeviceMirrorringHandler.9 = Not all required applications are currently installed. Done = Done FileUtils_0 = File {0} not present in classpath!? FormatMailAddress = Format of the mail address: address@server.xy HTMLEncode_0 = Error invoking 1.4 URLEncoder.encode with reflection: InvalidFileName = Invalid file name: NumbersUpToSixDigitsAreAllowed = Numbers up to six digits are allowed PhoneBookEntry_1 = No company name Planed = Planed PropertiesFileConverter.0 = Not a directory: RemoteTransactionHandler.0 = Internal error: method must be called on the AM thread only! RemoteTransactionHandler.1 = Refreshing masterdata.. RemoteTransactionHandler.2 = Refresh flag updated. RemoteTransactionHandler.3 = Masterdata downloaded. RemoteTransactionHandler.4 = Obsolete data deleted. RemoteTransactionHandler.5 = Deleting firmware files.. RemoteTransactionHandler.6 = Firmware file deleted. RemoteTransactionHandler.7 = No firmware file received from server ReservedForFutureUse = Not used. Reserved for future use. SAPError = SAP error SAPErrorMessage = SAP error message: Service = Service StartEndLessThan3MinutesApart = Start/End is less than 3 minutes apart TimeIsOverlapping = Time is overlapping with {0} - {1}\n WorkTimeRecordingWasStartedYesterday. = Working time recording was started yesterday. WouldYouLikeToCall = Would you like to call {0}? WrongFormArgument = Wrong form argument class found in form WrongFormat = Wrong format ({0}) WrongFormatXX-XXXX-XXX/XX = Wrong format (XX-XXXX-XXX/XX) abort = Abort aborted = aborted... all = All billing = Billing camera = Camera cancelled = Cancelled characters = characters checkList = Check list commNo = Comm-No. communicationError = Communication error communicationErrorWithColon = Communication error: confirmToDeleteMaterial = Do you want to delete this material from the Database! costumerReport = Costumer report deliveryListDownloaded = Delivery list downloaded designation = Bez. destinationAddressIsInvalid = The pointer to the destination address is not valid, is NULL, or the destination address string is too long. doYouWantToStopTimesheet = Do you want to stop Timesheet? documents = Documents duplicatedMaterialNumber = There is MaterialNumber {0} duplicated {1} can not insert. employee = Employee error = Error errorWithParam = Error {0} exit = Exit failure = Failure firstName = First name foundErrorsInTimesheetsOnDate = Errors in timesheets have been found on the following dates: {0}. Please correct and send them. from = From gallery = Gallery image = Image images = Images information = Information insertComplete = Insert complete. insertingMasterData = Inserting MasterData... installationError = Installation error invalidNotificationInterval = Invalid value for 'NotificationInterval' setting found invalidUsernameOrPassword = invalid username or password invalidVolume = Invalid value for 'Volume' setting found jobState = Job State loadCALENDARObjectWithDatetime = Try to load a CALENDAR object with a datetime value ( location = Location material = Material materialList = MaterialList materialName = Material name materialNumber = Material number measurement = Force measurement messages = Messages name = Name newJob = New Job! newJobReceived = New job received. newMessage = New Message!\n newVehicleInventoryReceived = New Vehicle Inventory received. newShortMessageReceived = New short message received. noDocumentsRecorded = No document attached noImagesRecorded = No image recorded noMaterialRecorded = No material recorded noMeasurementsRecorded = No measurement available noMessagesRecorded = No message recorded noPartsFound = no parts found matching the criteria. noRecipientApplication = No recipient application is available to handle the request. noReportRecorded = No report recorded noTimesRecorded = No times recorded noUserActive = No user active! REGISTER_USER not called / corrupt data in table ZKDMOBMA? noValueForNotificationIntervalFound = No value for notification interval found noVolumeSettingFound = No volume setting found number = Number onlyNumberAndSpacesAllowedForTelephoneNumber = Only numbers and spaces are allowed for phone numbers (max. 30 char) orderDate = Order Date orderNo = Order No orderWillBeForwardedTo = {0}-Order {1} will be forwarded to {2} overHoursInOneDay = "{0}" is over hours in one day. overlapping = {0} is overlapping {1} partFound = part found pleaseSelect = Please select... pleaseSelectValue = Please select a value! pleaseProvideValue = Please provide a value! pointerReferenceToInvalidMemoryLocation = A pointer does not reference a valid memory location. One or more of the pointers lpszDestAddress, lpszAppName, lpszCalledParty, or lpszComment have been specified but are invalid. receive = Receive recipientApplicationIsActive = The recipient application is active, but its request queue is full or there is insufficient memory to expand the queue. The calling application should try again later. replacement = Replacement reportCannotContainTimesMoreThanOneDay = The report can not contain times form more than one day. There are already entries from {0} reports = Reports reportsFrom = Reports from reset = Reset saveCALENDARObjectWithDatetime = Try to save a CALENDAR object with a datetime value ( search = Search select = Select... shortNews = Short news signature = Signature subject = Subject timeStopped = Time stopped times = Times timesFrom = Times from timesheetCannotBeStartet = Timesheet can not be startet. It's already sent. to = To total = Total typeOfJob = Type of job updatingDeliveryList = Updating delivery list userIsNotRegistred = User is not registered userLocked = User locked validationError = Validation error. \nPlease type all required information. valueMustNotBeLongerThen = Value must not be longer then warning = Warning! workTimeCapturingStartet = Work time capturing startet workTimeCapturingStartetBeforeYesterday = Work time capturing was startet before yesterday wrongFormArgument = Wrong form argument class found in form CommonApplication.5 new short message received Neue Kurznachricht erhalten package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 5 */ public class AddressType extends LocalizedTextEnum { protected AddressType() { } public AddressType(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.ADDRESS_TYPE); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for invoice codes (Verrechnungscodes) * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 12 */ public class InvoiceCode extends LocalizedTextEnum { protected InvoiceCode() { } public InvoiceCode(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.INVOICE); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 3 */ public class JobPriority extends LocalizedTextEnum { protected JobPriority() { } public JobPriority(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.JOB_PRIORITY); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 2 */ public class JobStatusName extends LocalizedTextEnum { protected JobStatusName() { } public JobStatusName(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.JOB_STATUS); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 1 */ public class JobType extends LocalizedTextEnum { protected JobType() { } public JobType(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.JOB_TYPE); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.db.LocalizedTexts; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Base class for translated strings in the database * key: localizedTexts.Code * value: localizedTexts.Text * TextType 01: JobType ok * TextType 02: JobStatusName ok * TextType 03: JobPriority ok * TextType 04: Titel ok * TextType 05: AddressType ok * TextType 06: NoSignatureReason ok * TextType 07: ReportSendType ok * TextType 08: Checklist ok * TextType 09: Month ok * TextType 10: MessageRecipient ok * TextType 11: VariousExpens ok * TextType 12: InvoiceCode ok * TextType 13: InternalWorkType ok * TextType 14: LoginMessage ok */ public abstract class LocalizedTextEnum { private static Log log = LogFactory.getLog(LocalizedTextEnum.class); /** * localizedTexts.TextType */ protected String textType; protected TreeMap map = new TreeMap(); protected LocalizedTextEnum() { } protected LocalizedTextEnum(DatabaseUtil dbutil, String textType) { this.textType = textType; LocalizedTexts[] texts = dbutil.selectLocalizedTextsList(textType); //$NON-NLS-1$ for (int i = 0; i < texts.length; i++) { LocalizedTexts localizedText = texts[i]; map.put(localizedText.getCODE(), localizedText.getTEXT()); } } public boolean containsKey(String key) { return map.containsKey(key); } public boolean containsValue(String value) { return map.containsValue(value); } public String get(String key) { String value = ""; //$NON-NLS-1$ try { value = map.get(key); if (value == null) value = ""; //$NON-NLS-1$ } catch (Exception e) { log.error(e); } return value; } /** * @return An iterator for the entrySet of the inner HashMap */ public Iterator> iterator() { return map.entrySet().iterator(); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 14 */ public class LoginMessage extends LocalizedTextEnum { protected LoginMessage() { } public LoginMessage(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.REGISTER_USER); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 10 */ public class MessageRecipient extends LocalizedTextEnum { protected MessageRecipient() { } public MessageRecipient(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.MESSAGE_ID); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 9 */ public class Month extends LocalizedTextEnum { protected Month() { } public Month(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.MONTH); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 6 */ public class NoSignatureReason extends LocalizedTextEnum { protected NoSignatureReason() { } public NoSignatureReason(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.REPORT_SIGNATURE); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 7 */ public class ReportSendType extends LocalizedTextEnum { protected ReportSendType() { } public ReportSendType(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.REPORT_CUSTOMER_SUPPORT); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for address types * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 4 */ public class Titel extends LocalizedTextEnum { protected Titel() { } public Titel(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.ADDRESS_TITLE); } } package ch.mfiles.kaba.kolibri.common.businessobjects.enums; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; /** * @author paulib * Enumeration for * key: localizedTexts.Code * value: localizedTexts.Text * localizedTexts.TextType = 11 */ public class VariousExpens extends LocalizedTextEnum { protected VariousExpens() { } public VariousExpens(DatabaseUtil dbutil) { super(dbutil, CommonConstants.LocalizedTexts.VAREXP); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class CalendarStatus { /** * initial not a valid status, only used by the constructor */ public static final String INITIAL = "00"; //$NON-NLS-1$ /** * new */ public static final String SAVED = "01"; //$NON-NLS-1$ /** * sent */ public static final String SENT = "03"; //$NON-NLS-1$ private String code; public CalendarStatus() { set(INITIAL); } public CalendarStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isSAVED() { return this.code.equalsIgnoreCase(SAVED); } public boolean isSENT() { return this.code.equalsIgnoreCase(SENT); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class DeliveryStatus { /** * initial not a valid status, only used by the constructor */ public static final String INITIAL = ""; public static final String OPEN = "O"; public static final String PART_DELIVERED = "T"; public static final String DELIVERED = "G"; private String code; public DeliveryStatus() { set(INITIAL); } public DeliveryStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isOPEN() { return this.code.equalsIgnoreCase(OPEN); } public boolean isPART_DELIVERED() { return this.code.equalsIgnoreCase(PART_DELIVERED); } public boolean isDELIVERED() { return this.code.equalsIgnoreCase(DELIVERED); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class ExpenseValidation { // valid flag private boolean mValid = true; // Error indicator private boolean mTgSpesenError = false; private boolean mDivSpesenError = false; private boolean mAbzugError = false; private boolean mBVonError = false; private boolean mBBisError = false; private boolean mBTotError = false; public boolean isValid() { return mValid; } public void setValid(boolean valid) { this.mValid = valid; } public boolean isTgSpesenError() { return mTgSpesenError; } public void setTgSpesenError(boolean tgSpesenError) { this.mTgSpesenError = tgSpesenError; } public boolean isDivSpesenError() { return mDivSpesenError; } public void setDivSpesenError(boolean divSpesenError) { this.mDivSpesenError = divSpesenError; } public boolean isAbzugError() { return mAbzugError; } public void setAbzugError(boolean abzugError) { this.mAbzugError = abzugError; } public boolean isBVonError() { return mBVonError; } public void setBVonError(boolean bVonError) { this.mBVonError = bVonError; } public boolean isBBisError() { return mBBisError; } public void setBBisError(boolean bBisError) { this.mBBisError = bBisError; } public boolean isBTotError() { return mBTotError; } public void setBTotError(boolean bTotError) { this.mBTotError = bTotError; } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; /** * The type of item that should be shown on UI. FORMITEM.TYPE = rdbt radio button FORMITEM.TYPE = comb combo box FORMITEM.TYPE = chkb check box FORMITEM.TYPE = text text input FORMITEM.TYPE = numf numeric values FORMITEM.TYPE = sign signature FORMITEM.TYPE = titl header for better structure FORMITEM.TYPE = sepr separator (dividing line) for better structure * @author CYU * */ public class FormItemType { public static final String RDBT = "RDBT"; public static final String COMB = "COMB"; public static final String CHKB = "CHKB"; public static final String TEXT = "TEXT"; public static final String NUMF = "NUMF"; public static final String SIGN = "SIGN"; public static final String TITL = "TITL"; public static final String SEPR = "SEPR"; public static final String IMAG = "IMAG"; private String code; public FormItemType() { set(TEXT); } public FormItemType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isRDBT() { return this.code.equalsIgnoreCase(RDBT); } public boolean isCOMB() { return this.code.equalsIgnoreCase(COMB); } public boolean isCHKB() { return this.code.equalsIgnoreCase(CHKB); } public boolean isTEXT() { return this.code.equalsIgnoreCase(TEXT); } public boolean isNUMF() { return this.code.equalsIgnoreCase(NUMF); } public boolean isSIGN() { return this.code.equalsIgnoreCase(SIGN); } public boolean isTITL() { return this.code.equalsIgnoreCase(TITL); } public boolean isSEPR() { return this.code.equalsIgnoreCase(SEPR); } public boolean isIMAG() { return this.code.equalsIgnoreCase(IMAG); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class FormType { public static final String INITIAL = ""; public static final String JPG = "JPG"; //Service-Check //$NON-NLS-1$ public static final String PDF = "PDF"; //Installation //$NON-NLS-1$ private String code; public FormType() { set(INITIAL); } public FormType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isJPG() { return this.code.equalsIgnoreCase(JPG); } public boolean isPDF() { return this.code.equalsIgnoreCase(PDF); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class JobType { /** * initial * no valid JobStatus, only used by the constructor */ public static final String INITIAL = "NON"; // new //$NON-NLS-1$ /** * repair */ public static final String REP = "REP"; //repair //$NON-NLS-1$ /** * Service-Check */ public static final String SAV = "SAV"; //Service-Check //$NON-NLS-1$ /** * Installation */ public static final String MON = "MON"; //Installation //$NON-NLS-1$ private String code; // private String value; public JobType() { set(INITIAL); } public JobType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isINITIAL() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isREP() { return this.code.equalsIgnoreCase(REP); } public boolean isSAV() { return this.code.equalsIgnoreCase(SAV); } public boolean isMON() { return this.code.equalsIgnoreCase(MON); } public String toString() { return code; } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class ReportStatus { /** * initial no valid JobStatus, only used by the constructor */ public static final String INITIAL = "99"; // new //$NON-NLS-1$ /** * new */ public static final String NEW = "0"; // new //$NON-NLS-1$ /** * received */ public static final String RECEIVED = "1"; // sent //$NON-NLS-1$ private String code; // private String value; public ReportStatus() { set(INITIAL); } public ReportStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isNew() { return this.code.equalsIgnoreCase(NEW); } public boolean isReceived() { return this.code.equalsIgnoreCase(RECEIVED); } public String toString() { if (isInitial()) return code + " (INITIAL)"; //$NON-NLS-1$ if (isNew()) return code + " (NEW)"; //$NON-NLS-1$ if (isReceived()) return code + " (RECEIVED)"; //$NON-NLS-1$ return super.toString(); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class SpecificFunctionType { public static final String INITIAL = ""; // new //$NON-NLS-1$ public static final String TORBAUER = "T"; // new //$NON-NLS-1$ public static final String SPECIALIST = "S"; // sent //$NON-NLS-1$ private String code; // private String value; public SpecificFunctionType() { set(INITIAL); } public SpecificFunctionType(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isTorbauer() { return this.code.equalsIgnoreCase(TORBAUER); } public boolean isSpezialist() { return this.code.equalsIgnoreCase(SPECIALIST); } public String toString() { if (isInitial()) return code + " (INITIAL)"; //$NON-NLS-1$ if (isTorbauer()) return code + " (TORBAUER)"; //$NON-NLS-1$ if (isSpezialist()) return code + " (SPECIALIST)"; //$NON-NLS-1$ return super.toString(); } public String getText() { if (isInitial()) return ""; //$NON-NLS-1$ if (isTorbauer()) return "Torbauer"; //$NON-NLS-1$ if (isSpezialist()) return "Spezialist"; //$NON-NLS-1$ return super.toString(); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class TimesheetStatus { /** * initial * not a valid status, only used by the constructor */ public static final String INITIAL = "00"; //$NON-NLS-1$ /** * valid means the expense record fulfills the business requirements */ public static final String VALID = "01"; //$NON-NLS-1$ private String code; public TimesheetStatus() { set(INITIAL); } public TimesheetStatus(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isValid() { return this.code.equalsIgnoreCase(VALID); } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class TimesheetValidation { // valid flag private boolean mValid = true; // Error indicator private boolean mInitialArbaError = false; private boolean mInitialVonError = false; private boolean mInitialBisError = false; private boolean mVonBiggerBisError = false; public boolean isValid() { return mValid; } public void setValid(boolean valid) { this.mValid = valid; } public boolean isInitialArbaError() { return mInitialArbaError; } public void setInitialArbaError(boolean initialArbaError) { this.mInitialArbaError = initialArbaError; } public boolean isInitialVonError() { return mInitialVonError; } public void setInitialVonError(boolean initialVonError) { this.mInitialVonError = initialVonError; } public boolean isInitialBisError() { return mInitialBisError; } public void setInitialBisError(boolean initialBisError) { this.mInitialBisError = initialBisError; } public boolean isVonBiggerBisError() { return mVonBiggerBisError; } public void setVonBiggerBisError(boolean vonBiggerBisError) { this.mVonBiggerBisError = vonBiggerBisError; } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class Warehouse { /** * initial not a valid status, only used by the constructor */ public static final String VEHICLE = "FZG"; /** * new */ public static final String EXTERNAL = "ALG"; /** * sent */ public static final String MAIN = "HLG"; private String code; public Warehouse() { set(MAIN); } public Warehouse(String code) { set(code); } public String getCode() { return code; } public void set(String code) { this.code = code; } public boolean isEequals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isMAIN() { return this.code.equalsIgnoreCase(MAIN); } public boolean isVEHICLE() { return this.code.equalsIgnoreCase(VEHICLE); } public boolean isSENT() { return this.code.equalsIgnoreCase(EXTERNAL); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAABSENCE */ public class AbsenceNotification { private String guId = ""; private Date absenceDate; private int personalNumber = 0; private String absenceType; private Date dateFrom; private Date dateTo; private Date timeFrom; private Date timeTo; private String text; public AbsenceNotification() { // constructor } public AbsenceNotification(RecordSet rs) { this.setGuid(rs.getString(DbConstants.AbsenceNotification.GUID)); this.setAbsenceDate(rs.getDate(DbConstants.AbsenceNotification.DATE)); this.setPersonalNumber(rs.getInt(DbConstants.AbsenceNotification.PERSONAL_NUMBER)); this.setAbsenceType(rs.getString(DbConstants.AbsenceNotification.ABSENCE_TYPE)); this.setDateFrom(rs.getDate(DbConstants.AbsenceNotification.DATE_FROM)); this.setDateTo(rs.getDate(DbConstants.AbsenceNotification.DATE_TO)); this.setTimeFrom(rs.getDate(DbConstants.AbsenceNotification.TIME_FROM)); this.setTimeTo(rs.getDate(DbConstants.AbsenceNotification.TIME_TO)); this.setText(rs.getString(DbConstants.AbsenceNotification.TEXT)); } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public Date getAbsenceDate() { return absenceDate; } public void setAbsenceDate(Date absenceDate) { this.absenceDate = absenceDate; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getAbsenceType() { return absenceType; } public void setAbsenceType(String absenceType) { this.absenceType = absenceType; } public Date getDateFrom() { return dateFrom; } public void setDateFrom(Date dateFrom) { this.dateFrom = dateFrom; } public Date getDateTo() { return dateTo; } public void setDateTo(Date dateTo) { this.dateTo = dateTo; } public Date getTimeFrom() { return timeFrom; } public void setTimeFrom(Date timeFrom) { this.timeFrom = timeFrom; } public Date getTimeTo() { return timeTo; } public void setTimeTo(Date timeTo) { this.timeTo = timeTo; } public String getText() { return text; } public void setText(String text) { this.text = text; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBABSC */ public class AbsenceType { private String absenceType = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ AbsenceType() { } public AbsenceType(RecordSet rs) { this.setAbsenceType((rs.getString(DbConstants.AbsenceType.ABWGRND))); this.setLanguage(rs.getString(DbConstants.AbsenceType.LANGUAGE)); this.setText(rs.getString(DbConstants.AbsenceType.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.AbsenceType.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getAbsenceType() { return this.absenceType; } public void setAbsenceType(String absenceType) { this.absenceType = absenceType; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDMOBADR * */ public class Address { public static final Log log = LogFactory.getLog(Job.class); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String type = ""; //$NON-NLS-1$ private String partnerNummer = ""; //$NON-NLS-1$ private String commissionNumber = ""; //$NON-NLS-1$ private String customerNumber = ""; //$NON-NLS-1$ private String title = ""; //$NON-NLS-1$ private String name1 = ""; //$NON-NLS-1$ private String name2 = ""; //$NON-NLS-1$ private String name3 = ""; //$NON-NLS-1$ private String location = ""; //$NON-NLS-1$ private String street = ""; //$NON-NLS-1$ private String city = ""; //$NON-NLS-1$ private String postalCode = ""; //$NON-NLS-1$ private String telNumber1 = ""; //$NON-NLS-1$ private String telNumber2 = ""; //$NON-NLS-1$ private String faxNumber = ""; //$NON-NLS-1$ private String email = ""; //$NON-NLS-1$ private String changeFlag = ""; //$NON-NLS-1$ private String dirtyFlag = ""; //$NON-NLS-1$ public Address() { } public Address(RecordSet rs) { this.setType(rs.getString(DbConstants.Address.TYPE)); this.setJobType(rs.getString(DbConstants.Address.JOB_TYPE)); this.setCity(rs.getString(DbConstants.Address.CITY)); this.setDirtyFlag(rs.getString(DbConstants.Address.DIRTY_FLAG)); this.setEmail(rs.getString(DbConstants.Address.EMAIL)); this.setFaxNumber(rs.getString(DbConstants.Address.FAX)); this.setCustomerNumber(rs.getString(DbConstants.Address.CUSTOMER_NUMBER)); this.setJobNumber(rs.getString(DbConstants.Address.JOB_NUMBER)); this.setName1(rs.getString(DbConstants.Address.NAME1)); this.setName2(rs.getString(DbConstants.Address.NAME2)); this.setName3(rs.getString(DbConstants.Address.NAME3)); this.setLocation(rs.getString(DbConstants.Address.LOCATION)); this.setPartnerNummer(rs.getString(DbConstants.Address.PARTNER_NUMBER)); this.setPostalCode(rs.getString(DbConstants.Address.PASTAL_CODE)); this.setStreet(rs.getString(DbConstants.Address.STREET)); this.setTelNumber1(rs.getString(DbConstants.Address.PHONE_1)); this.setTelNumber2(rs.getString(DbConstants.Address.PHONE_2)); this.setTitle(rs.getString(DbConstants.Address.TITLE)); this.setChangeFlag(rs.getString(DbConstants.Address.CHANGE_FLAG)); this.setCommissionNumber(rs.getString(DbConstants.Address.COMMISSION_NUMBER)); } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getDirtyFlag() { return this.dirtyFlag; } public void setDirtyFlag(String dirtyflg) { this.dirtyFlag = dirtyflg; } public boolean isDirtyFlag() { return "X".equalsIgnoreCase(this.getDirtyFlag()); //$NON-NLS-1$ } public void setDIRTYFLG(boolean dirtyflg) { if (dirtyflg) { this.setDirtyFlag("X"); //$NON-NLS-1$ } else { this.setDirtyFlag(""); //$NON-NLS-1$ } } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getFaxNumber() { return this.faxNumber; } public void setFaxNumber(String faxNumber) { this.faxNumber = faxNumber; } public String getCustomerNumber() { return this.customerNumber; } public void setCustomerNumber(String kunnr) { this.customerNumber = kunnr; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getName1() { return this.name1; } public void setName1(String name1) { this.name1 = name1; } public String getName2() { return this.name2; } public void setName2(String name2) { this.name2 = name2; } public String getName3() { return this.name3; } public void setName3(String name3) { this.name3 = name3; } public String getLocation() { return this.location; } public void setLocation(String name4) { this.location = name4; } public String getPartnerNummer() { return this.partnerNummer; } public void setPartnerNummer(String parnr) { this.partnerNummer = parnr; } public String getPostalCode() { return this.postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public String getTelNumber1() { return this.telNumber1; } public void setTelNumber1(String telNumber1) { this.telNumber1 = telNumber1; } public String getTelNumber2() { return this.telNumber2; } public void setTelNumber2(String telNumber2) { this.telNumber2 = telNumber2; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getChangeFlag() { return this.changeFlag; } public void setChangeFlag(String upd) { this.changeFlag = upd; } public boolean isChangeFlag() { return "X".equalsIgnoreCase(this.getChangeFlag()); //$NON-NLS-1$ } public void setChangeFlag(boolean udp) { if (udp) { this.setChangeFlag("X"); //$NON-NLS-1$ } else { this.setChangeFlag(""); //$NON-NLS-1$ } } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isPrivate() { return "1".equalsIgnoreCase(this.getType()); //$NON-NLS-1$ } public void setPrivate(boolean isPrivate) { if (isPrivate) { this.setType("1"); //$NON-NLS-1$ } else { this.setType("2"); //$NON-NLS-1$ } } public boolean isInitial() { return this.partnerNummer == null; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Address.ADDRESS, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Address.ADDRESS, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBException; import ch.mfiles.kolibri.db.DBSColumn; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; public abstract class BaseEntity { public static final Log log = LogFactory.getLog(BaseEntity.class); BaseEntity() { } /** * Writes a backup of all records of the table with tableName. Special characters in String fields are escaped with quote() function of sqlite. * @param tableName Name of the table to backup * @param app Current application object * @param folder Folder where to store the backup. * @return Number of backuped records. */ protected static int backup(String tableName, Application app, File folder) { int ret = 0; RecordSet rs = app.getDBSession().getRecordSet(); List columns = app.getApplicationDescriptor().getDbschema().getTable(tableName).getColumns(); String attrbuteList = ""; //$NON-NLS-1$ String attrbuteLine = ""; //$NON-NLS-1$ Iterator itr = columns.iterator(); while (itr.hasNext()) { DBSColumn col = (DBSColumn) itr.next(); attrbuteLine = attrbuteLine.concat(col.getName()).concat(","); //$NON-NLS-1$ if (col.getType() == DBSColumn.TYPE_STRING) attrbuteList = attrbuteList.concat("quote(" + col.getName() + ") AS " + col.getName() + ","); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else attrbuteList = attrbuteList.concat(col.getName()).concat(","); //$NON-NLS-1$ } // remove the last comma attrbuteLine = attrbuteLine.substring(0, attrbuteLine.length() - 1); attrbuteList = attrbuteList.substring(0, attrbuteList.length() - 1); String sql = "SELECT " + attrbuteList + " FROM " + tableName; //$NON-NLS-1$ //$NON-NLS-2$ FileWriter fw = null; try { rs.setQuery(sql); ret = rs.getCount(); File file = new File(folder, "\\" + tableName); //$NON-NLS-1$ if (file.exists() && file.delete()) { // file deleted. } fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write(attrbuteLine); out.newLine(); String line = ""; //$NON-NLS-1$ while (rs.moveNext()) { line = ""; //$NON-NLS-1$ itr = columns.iterator(); while (itr.hasNext()) { DBSColumn col = (DBSColumn) itr.next(); line = line.concat(rs.getString(col.getName())).concat(","); //$NON-NLS-1$ } // remove line separators line = line.replace(System.getProperty("line.separator").charAt(0), ' '); //$NON-NLS-1$ if (System.getProperty("line.separator").length() > 1) //$NON-NLS-1$ line = line.replace(System.getProperty("line.separator").charAt(1), ' '); //$NON-NLS-1$ // remove the last comma out.write(line.substring(0, line.length() - 1)); out.newLine(); } out.close(); fw.close(); } catch (IOException e) { log.error("Error while writing " + tableName + " records to " + folder + "\\" + tableName); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(e); } catch (DBException e) { log.error("Error while selecting " + tableName + " records for backup"); //$NON-NLS-1$ //$NON-NLS-2$ log.error(e); } finally { rs.dispose(); try { if (fw != null) fw.close(); } catch (IOException e) { log.error(e); } } return ret; } /** * Restore function for table backup created with backup(). * Reads the records from the file (filename = tablename) from the folder * folder an writes them into the database. In case of an SQL * error, the record will be ignored (INSERT OR IGNORE INTO * )without any error message. * * @param tableName * @param db * @param folder */ protected static void restore(String tableName, DBSession db, File folder) { if (!folder.exists()) { log.info("Error while reading " + tableName + ": folder " + folder.getName() + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ return; } File file = new File(folder, "\\" + tableName); //$NON-NLS-1$ if (!file.exists()) { log.info("Error while reading " + tableName + ": backup file '" + file.getAbsolutePath() + "' not found"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return; } readFileAndExecuteSql(tableName, db, file); } private static void readFileAndExecuteSql(String tableName, DBSession db, File file) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String columnNames = br.readLine(); String columns[] = columnNames.split(","); List columnNoFoundInDb = new ArrayList(); for (int j = 0; j < columns.length; j++) { // adds all column name from file columnNoFoundInDb.add(columns[j]); } List columnToRemoveList = new ArrayList(); List dbColumns = db.getDBSchema().getTable(tableName).getColumns(); List columnToAddList = new ArrayList(); // default as column from db, will remove later. columnToAddList.addAll(dbColumns); for (int i = 0; i < columns.length; i++) { if (isColumnExistInDb(dbColumns, columns[i])) { // found the same column name between file and DB, so remove columnNoFoundInDb.remove(columns[i]); } for (DBSColumn dbsColumn : dbColumns) { if (dbsColumn.getName().equalsIgnoreCase(columns[i])) { // found the same column name between file and DB, so remove columnToAddList.remove(dbsColumn); } } } for (String column : columnNoFoundInDb) { log.info("column to be removed " + column); for (int i = 0; i < columns.length; i++) { if (column.equalsIgnoreCase(columns[i])) { // found column index to remove columnToRemoveList.add(i); } } } StringBuffer columnBuffer = new StringBuffer(); for (int i = 0; i < columns.length; i++) { if (!columnToRemoveList.contains(i)) { if (i > 0) { columnBuffer.append(","); } columnBuffer.append(columns[i]); } } String sql = "INSERT OR IGNORE INTO " + tableName + " (" + columnBuffer.toString() ; if (!columnToAddList.isEmpty()) { for (DBSColumn dbsColumn : columnToAddList) { log.info("column to be added " + dbsColumn.getName()); sql += "," + dbsColumn.getName(); } } sql += ") VALUES "; String line; while ((line = br.readLine()) != null) { log.info("line " + line); String dataLine[] = line.split(","); StringBuffer buffer = new StringBuffer(); if (columnNoFoundInDb.size() > 0) { for (int i = 0; i < dataLine.length; i++) { if (!columnToRemoveList.contains(i)) { if (i > 0) { buffer.append(","); } buffer.append(dataLine[i]); } } line = buffer.toString(); } if (!columnToAddList.isEmpty()) { for (DBSColumn dbsColumn : columnToAddList) { String defaultValue = dbsColumn.getDefaultValue() == null ? "" : dbsColumn.getDefaultValue(); if (dbsColumn.getType() == DBSColumn.TYPE_STRING) { line += ",'" + defaultValue + "'"; } else if (dbsColumn.getType() == DBSColumn.TYPE_DATE) { line += ",0"; } else { line += "," + defaultValue; } } } log.info(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ int inserted = db.executeSql(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ log.info(inserted + " Records inserted with: " + sql + "(" + line + ")"); } } catch (IOException e) { log.error("Error while reading " + tableName + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ log.error(e); } finally { if (br != null) try { br.close(); } catch (IOException e) { } } } private static boolean isColumnExistInDb(List dbColumns, String columnName) { for (int i = 0; i < dbColumns.size(); i++) { for (DBSColumn dbsColumn : dbColumns) { if (dbsColumn.getName().equalsIgnoreCase(columnName)) { return true; } } } return false; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> VERRECHNUNG */ public class Billing { private String text = ""; //$NON-NLS-1$ private String code = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String refreshFlag = ""; //$NON-NLS-1$ Billing() { } public Billing(RecordSet rs) { this.setText(rs.getString(DbConstants.Billing.TEXT)); this.setCode(rs.getString(DbConstants.Billing.CODE)); this.setJobType(rs.getString(DbConstants.Billing.JOB_TYPE)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public JobType getJobType() { return this.jobType; } public void setJobType(JobType jobType) { this.jobType = jobType; } public void setJobType(String jobType) { this.jobType = new JobType(jobType); } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import java.util.Iterator; import java.util.TreeSet; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.util.DateUtils; /** * In the Database -> CALENDAR * */ public class CalendarTimeSheet { private Date date = DateUtils.getInitialDate(); private int personalNumber = 0; private CalendarStatus status = new CalendarStatus(); private String dateString = ""; //$NON-NLS-1$ private Expenses expense = new Expenses(new Date(), 0); private TreeSet timeSheets = new TreeSet(); protected CalendarTimeSheet() { } public CalendarTimeSheet(Date date, int personalNumber) { this.setDate(date); this.setDateString(DateTimeUtil.tableDate(date)); this.personalNumber = personalNumber; this.expense = new Expenses(date, personalNumber); } public CalendarTimeSheet(RecordSet rs) { this.setDate(rs.getDate(DbConstants.CalendarTimeSheet.DATE)); this.setPersonalNumber(rs.getInt(DbConstants.CalendarTimeSheet.PERSONAL_NUMBER)); this.setStatus(new CalendarStatus(rs.getString(DbConstants.CalendarTimeSheet.STATUS))); this.setDateString(rs.getString(DbConstants.CalendarTimeSheet.DATE_STRING)); } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public CalendarStatus getStatus() { return this.status; } public void setStatus(String status) { this.status.set(status); } public void setStatus(CalendarStatus status) { this.status = status; } public String getDateString() { return this.dateString; } public void setDateString(String datumTxt) { this.dateString = datumTxt; } public Expenses getExpense() { return this.expense; } public void setExpense(Expenses expense) { this.expense = expense; } public TreeSet getTimeSheets() { return this.timeSheets; } public void setTimeSheets(TreeSet timeSheets) { this.timeSheets = timeSheets; } public boolean isValid() { boolean valid = true; if (!this.expense.validate().isValid()) valid = false; if (this.timeSheets.isEmpty()) valid = false; else { Date temp = DateUtils.getInitialDateTime(); Iterator itr = this.timeSheets.iterator(); while (itr.hasNext()) { TimeSheet zkdmatime = itr.next(); if (!zkdmatime.validate().isValid()) valid = false; else { if (temp.compareTo(zkdmatime.getStartTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || zkdmatime.getStartTime().equals(DateUtils.getInitialDateTime())) temp = zkdmatime.getStartTime(); else valid = false; if (temp.compareTo(zkdmatime.getStopTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || zkdmatime.getStopTime().equals(DateUtils.getInitialDateTime())) temp = zkdmatime.getStopTime(); else valid = false; } } } return valid; } public boolean isTimeCapturing() { return getStartTimeCapturing() != null; } public Date getStartTimeCapturing() { Iterator itr = this.timeSheets.iterator(); while (itr.hasNext()) { TimeSheet zkdmatime = itr.next(); if (zkdmatime.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) return zkdmatime.getStartTime(); } return null; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBCHKLIST */ public class Checklist { private String checklistCode = ""; private String text = ""; private String refreshFlag = ""; Checklist() { } public Checklist(RecordSet rs) { this.setChecklistCode(rs.getString(DbConstants.Checklist.CODE)); this.setText(rs.getString(DbConstants.Checklist.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Checklist.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getChecklistCode() { return this.checklistCode; } public void setChecklistCode(String checklistCode) { this.checklistCode = checklistCode; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.DeliveryStatus; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZGDELVRY */ public class DeliveryList { public static final Log log = LogFactory.getLog(DeliveryList.class); private String guid = ""; private int personalNumber; private String orderNumber = ""; private int orderPosition; private String materialNumber = ""; private String materialName = ""; private String from = ""; private String to = ""; private String warehouse = ""; private String entryCount = ""; private String entryUnit = ""; private Date date = new Date(0); private DeliveryStatus status = new DeliveryStatus(); public DeliveryList() { } public DeliveryList(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.DeliveryList.PERSONAL_NUMBER)); this.setGuid(rs.getString(DbConstants.DeliveryList.GUID)); this.setOrderNumber(rs.getString(DbConstants.DeliveryList.ORDER_NUMBER)); this.setOrderPosition(rs.getInt(DbConstants.DeliveryList.ORDER_POSITION)); this.setMaterialNumber(rs.getString(DbConstants.DeliveryList.MATERIAL_NUMBER)); this.setMaterialName(rs.getString(DbConstants.DeliveryList.MATERIAL_NAME)); this.setFrom(rs.getString(DbConstants.DeliveryList.FROM)); this.setTo(rs.getString(DbConstants.DeliveryList.TO)); this.setWarehouse(rs.getString(DbConstants.DeliveryList.WAREHOUSE)); this.setEntryCount(rs.getString(DbConstants.DeliveryList.ENTRY_COUNT)); this.setEntryUnit(rs.getString(DbConstants.DeliveryList.ENTRY_UNIT)); this.setDate(rs.getDate(DbConstants.DeliveryList.DATE)); this.setStatus(rs.getString(DbConstants.DeliveryList.STATUS)); } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getOrderPosition() { return orderPosition; } public void setOrderPosition(int orderPosition) { this.orderPosition = orderPosition; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getMaterialNumber() { return materialNumber; } public void setMaterialNumber(String materialNumber) { this.materialNumber = materialNumber; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getEntryCount() { return entryCount; } public void setEntryCount(String entryCount) { this.entryCount = entryCount; } public String getEntryUnit() { return entryUnit; } public void setEntryUnit(String entryUnit) { this.entryUnit = entryUnit; } public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } public String getWarehouse() { return warehouse; } public void setWarehouse(String warehouse) { this.warehouse = warehouse; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public DeliveryStatus getStatus() { return status; } public void setStatus(String status) { this.status = new DeliveryStatus(status); } public void setStatus(DeliveryStatus status) { this.status = status; } /** * = Color 900 blue grey O = Color 900 red T = Color 900 deep orange G = Color 900 light green * @return */ public int getStatusColor() { int result; if (getStatus().isOPEN()) { result = LayoutUtils.DEFAULT_RED; } else if (getStatus().isPART_DELIVERED()) { result = LayoutUtils.DEFAULT_ORANGE; } else if (getStatus().isDELIVERED()) { result = LayoutUtils.DEFAULT_GREEN; } else { result = LayoutUtils.DEFAULT_MATERIAL_COLOR; } return result; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZANTRTYP */ public class Drive { private String code = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String longText = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Drive() { } public Drive(RecordSet rs) { this.setCode(rs.getString(DbConstants.Drive.CODE)); this.setText(rs.getString(DbConstants.Drive.TEXT)); this.setLongText(rs.getString(DbConstants.Drive.LONG_TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getLongText() { return this.longText; } public void setLongText(String longText) { this.longText = longText; } public boolean isLongText() { boolean result = false; if ("X".equalsIgnoreCase(this.getLongText())) { //$NON-NLS-1$ result = true; } return result; } public void setLongText(boolean longText) { if (longText) { this.setLongText("X"); //$NON-NLS-1$ } else { this.setLongText(""); //$NON-NLS-1$ } } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDSMOBEMAIL * */ public class Email { public static final Log log = LogFactory.getLog(Job.class); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String partnerNummer = ""; //$NON-NLS-1$ private String email = ""; //$NON-NLS-1$ public Email() { } public Email(RecordSet rs) { this.setJobType(rs.getString(DbConstants.Email.JOB_TYPE)); this.setEmail(rs.getString(DbConstants.Email.TEXT)); this.setJobNumber(rs.getString(DbConstants.Email.JOB_NUMBER)); this.setPartnerNummer(rs.getString(DbConstants.Email.PARTNER_NUMBER)); } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getPartnerNummer() { return this.partnerNummer; } public void setPartnerNummer(String parnr) { this.partnerNummer = parnr; } public boolean isInitial() { return this.partnerNummer == null; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Email.EMAIL, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Email.EMAIL, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.SpecificFunctionType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDSMOBMA */ public class Employee { private int personalNumber = 0; private String lastName = ""; //$NON-NLS-1$ private String firstName = ""; //$NON-NLS-1$ private String initial = ""; //$NON-NLS-1$ private String personalNumberDeputy = ""; //$NON-NLS-1$ private String phoneNumber = ""; //$NON-NLS-1$ private String communicationNumber = ""; //$NON-NLS-1$ private String salesOffice = ""; //$NON-NLS-1$ private String absentFrom = ""; //$NON-NLS-1$ private String absentTo = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String deviceId; private String password; private String warehouseNumber = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ private SpecificFunctionType specificFunction; Employee() { } public Employee(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.Employee.PERSONAL_NUMBER)); this.setLastName(rs.getString(DbConstants.Employee.LAST_NAME)); this.setFirstName(rs.getString(DbConstants.Employee.FIRST_NAME)); this.setInitial(rs.getString(DbConstants.Employee.INITIAL)); this.setPersonalNumberDeputy(rs.getString(DbConstants.Employee.PERSONAL_NUMBER_DEPUTY)); this.setPhoneNumber(rs.getString(DbConstants.Employee.PHONE)); this.setCommunicationNumber(rs.getString(DbConstants.Employee.COMMUNICATION_NUMBER)); this.setSalesOffice(rs.getString(DbConstants.Employee.SALES_OFFICE)); this.setAbSentFrom(rs.getString(DbConstants.Employee.ABSENT_FROM)); this.setAbsentTo(rs.getString(DbConstants.Employee.ABSENT_TO)); this.setLanguage(rs.getString(DbConstants.Employee.LANGUAGE)); this.setDeviceId(rs.getString(DbConstants.Employee.DEVICE_ID)); this.setPassword(rs.getString(DbConstants.Employee.PASSOWRD)); this.setSpecificFunction(new SpecificFunctionType(rs.getString(DbConstants.Employee.SPECIFIC_FUNCTION))); this.setWarehouseNumber(rs.getString(DbConstants.Employee.WAREHOUSE_NUMBER)); this.setRefreshFlag(rs.getString(DbConstants.Employee.REFRESH_FLAG)); } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getLastName() { return this.lastName; } public void setLastName(String nachn) { this.lastName = nachn; } public String getFirstName() { return this.firstName; } public void setFirstName(String vorna) { this.firstName = vorna; } public String getInitial() { return this.initial; } public void setInitial(String inits) { this.initial = inits; } public String getPersonalNumberDeputy() { return this.personalNumberDeputy; } public void setPersonalNumberDeputy(String stvpernr) { this.personalNumberDeputy = stvpernr; } public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String telnr) { this.phoneNumber = telnr; } public String getCommunicationNumber() { return this.communicationNumber; } public void setCommunicationNumber(String num01) { this.communicationNumber = num01; } public String getSalesOffice() { return this.salesOffice; } public void setSalesOffice(String vkbur) { this.salesOffice = vkbur; } public String getAbsentFrom() { return this.absentFrom; } public void setAbSentFrom(String abwvon) { this.absentFrom = abwvon; } public String getAbsentTo() { return this.absentTo; } public void setAbsentTo(String abwbis) { this.absentTo = abwbis; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getDeviceId() { return this.deviceId; } public void setDeviceId(String gid) { this.deviceId = gid; } public String getPassword() { return this.password; } public void setPassword(String pwd) { this.password = pwd; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } public SpecificFunctionType getSpecificFunction() { return specificFunction; } public void setSpecificFunction(SpecificFunctionType specificFunction) { this.specificFunction = specificFunction; } public String getWarehouseNumber() { return warehouseNumber; } public void setWarehouseNumber(String warehouseNumber) { this.warehouseNumber = warehouseNumber; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZFCODE */ public class ErrorCode { private String errorCode; private String text; ErrorCode() { } public ErrorCode(RecordSet rs) { this.setErrorCode(rs.getString(DbConstants.ErrorCode.CODE)); this.setText(rs.getString(DbConstants.ErrorCode.TEXT)); } public String getErrorCode() { return this.errorCode; } public void setErrorCode(String fc) { this.errorCode = fc; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORM */ public class Form { public static final Log log = LogFactory.getLog(Form.class); private String id = ""; private int version = 0; private String status = ""; private Date validFrom = new Date(0); private Date validTo = new Date(0); private String name = ""; private String description = ""; public Form() { } public Form(RecordSet rs) { this.setId(rs.getString(DbConstants.Form.ID)); this.setVersion(rs.getInt(DbConstants.Form.VERSION)); this.setStatus(rs.getString(DbConstants.Form.STATUS)); this.setValidFrom(rs.getDate(DbConstants.Form.VALID_FROM)); this.setValidTo(rs.getDate(DbConstants.Form.VALID_TO)); this.setName(rs.getString(DbConstants.Form.NAME)); this.setDescription(rs.getString(DbConstants.Form.DESCRIPTION)); } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public static Log getLog() { return log; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMDEPENDENCY */ public class FormDependency { public static final Log log = LogFactory.getLog(FormDependency.class); private String formId = ""; private int formVersion = 0; private String formItemId = ""; private int dependency = 0; private String checkBoxFormItemId = ""; private String valueListId = ""; private String valueId = ""; public FormDependency() { } public FormDependency(RecordSet rs) { this.setFormId(rs.getString(DbConstants.FormDependency.FORM_ID)); this.setFormVersion(rs.getInt(DbConstants.FormDependency.FORM_VERSION)); this.setFormItemId(rs.getString(DbConstants.FormDependency.FORM_ITEM_ID)); this.setDependency(rs.getInt(DbConstants.FormDependency.DEPENDENCY)); this.setCheckBoxFormItemId(rs.getString(DbConstants.FormDependency.CHECKBOX_FORM_ITEM_ID)); this.setValueListId(rs.getString(DbConstants.FormDependency.VALUE_LIST_ID)); this.setValueId(rs.getString(DbConstants.FormDependency.VALUE_ID)); } public String getFormId() { return formId; } public void setFormId(String formId) { this.formId = formId; } public int getFormVersion() { return formVersion; } public void setFormVersion(int formVersion) { this.formVersion = formVersion; } public String getFormItemId() { return formItemId; } public void setFormItemId(String formItemId) { this.formItemId = formItemId; } public int getDependency() { return dependency; } public void setDependency(int dependency) { this.dependency = dependency; } public String getCheckBoxFormItemId() { return checkBoxFormItemId; } public void setCheckBoxFormItemId(String checkBoxFormItemId) { this.checkBoxFormItemId = checkBoxFormItemId; } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getValueId() { return valueId; } public void setValueId(String valueId) { this.valueId = valueId; } public static Log getLog() { return log; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormItemType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMINSTANCE */ public class FormInstance { public static final Log log = LogFactory.getLog(FormInstance.class); private String guid = ""; private String formId = ""; private int formVersion = 0; private String formItemId = ""; private String valueListId = ""; private String valueId = ""; private FormItemType formItemType = new FormItemType(); private String stringValue = ""; private boolean booleanValue = false; private double floatValue = 0; private String attachmentValue = ""; public FormInstance() { } public FormInstance(RecordSet rs) { this.setGuid(rs.getString(DbConstants.FormInstance.GUID)); this.setFormId(rs.getString(DbConstants.FormInstance.FORM_ID)); this.setFormVersion(rs.getInt(DbConstants.FormItem.FORM_VERSION)); this.setFormItemId(rs.getString(DbConstants.FormInstance.FORM_ITEM_ID)); this.setValueListId(rs.getString(DbConstants.FormInstance.VALUE_LIST_ID)); this.setValueId(rs.getString(DbConstants.FormInstance.VALUE_ID)); this.setFormItemType(rs.getString(DbConstants.FormInstance.FORM_ITEM_TYPE)); this.setStringValue(rs.getString(DbConstants.FormInstance.STRING_VALUE)); this.setBooleanValue(rs.getBoolean(DbConstants.FormInstance.BOOLEAN_VALUE)); this.setFloatValue(rs.getDouble(DbConstants.FormInstance.FLOAT_VALUE)); this.setAttachmentValue(rs.getString(DbConstants.FormInstance.ATTACHMENT_VALUE)); } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getFormId() { return formId; } public void setFormId(String formId) { this.formId = formId; } public int getFormVersion() { return formVersion; } public void setFormVersion(int formVersion) { this.formVersion = formVersion; } public String getFormItemId() { return formItemId; } public void setFormItemId(String formItemId) { this.formItemId = formItemId; } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getValueId() { return valueId; } public void setValueId(String valueId) { this.valueId = valueId; } public FormItemType getFormItemType() { return formItemType; } public void setFormItemType(String formItemType) { this.formItemType = new FormItemType(formItemType); } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public void setBooleanValue(boolean booleanValue) { this.booleanValue = booleanValue; } public boolean isBooleanValue() { return booleanValue; } public double getFloatValue() { return floatValue; } public void setFloatValue(double floatValue) { this.floatValue = floatValue; } public String getAttachmentValue() { return attachmentValue; } public void setAttachmentValue(String attachmentValue) { this.attachmentValue = attachmentValue; } public static Log getLog() { return log; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormItemType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMITEM */ public class FormItem { public static final Log log = LogFactory.getLog(FormItem.class); private String formId = ""; private int formVersion = 0; private String id = ""; private FormItemType formItemType = new FormItemType(); private int sequence = 0; private String label = ""; private boolean mandatory = false; private String cardName = ""; private boolean obsolete = false; private String valueListId = ""; private String emptyText = ""; private String groupName = ""; private int maxStringSize = 0; private String validationRegex = ""; private boolean multiLine = false; private String format = ""; private double minValue = 0; private double maxValue = 0; public FormItem() { } public FormItem(RecordSet rs) { this.setFormId(rs.getString(DbConstants.FormItem.FORM_ID)); this.setFormVersion(rs.getInt(DbConstants.FormItem.FORM_VERSION)); this.setId(rs.getString(DbConstants.FormItem.ID)); this.setFormItemType(rs.getString(DbConstants.FormItem.FORM_ITEM_TYPE)); this.setSequence(rs.getInt(DbConstants.FormItem.SEQUENCE)); this.setLabel(rs.getString(DbConstants.FormItem.LABEL)); this.setMandatory(rs.getBoolean(DbConstants.FormItem.MANDATORY)); this.setCardName(rs.getString(DbConstants.FormItem.CARD_NAME)); this.setObsolete(rs.getBoolean(DbConstants.FormItem.OBSOLETE)); this.setValueListId(rs.getString(DbConstants.FormItem.VALUE_LIST_ID)); this.setEmptyText(rs.getString(DbConstants.FormItem.EMPTY_TEXT)); this.setGroupName(rs.getString(DbConstants.FormItem.GROUP_NAME)); this.setMaxStringSize(rs.getInt(DbConstants.FormItem.MAX_STRING_SIZE)); this.setValidationRegex(rs.getString(DbConstants.FormItem.VALIDATION_REGEX)); this.setMultiLine(rs.getBoolean(DbConstants.FormItem.MULTILINE)); this.setFormat(rs.getString(DbConstants.FormItem.FORMAT)); this.setMinValue(rs.getDouble(DbConstants.FormItem.MIN_VALUE)); this.setMaxValue(rs.getDouble(DbConstants.FormItem.MAX_VALUE)); } public String getFormId() { return formId; } public void setFormId(String formId) { this.formId = formId; } public int getFormVersion() { return formVersion; } public void setFormVersion(int formVersion) { this.formVersion = formVersion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public FormItemType getFormItemType() { return formItemType; } public void setFormItemType(String formItemType) { this.formItemType = new FormItemType(formItemType); } public void setFormItemType(FormItemType formItemType) { this.formItemType = formItemType; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public boolean isMandatory() { return mandatory; } public void setMandatory(boolean mandatory) { this.mandatory = mandatory; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } public boolean isObsolete() { return obsolete; } public void setObsolete(boolean obsolete) { this.obsolete = obsolete; } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getEmptyText() { return emptyText; } public void setEmptyText(String emptyText) { this.emptyText = emptyText; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public int getMaxStringSize() { return maxStringSize; } public void setMaxStringSize(int maxStringSize) { this.maxStringSize = maxStringSize; } public String getValidationRegex() { return validationRegex; } public void setValidationRegex(String validationRegex) { this.validationRegex = validationRegex; } public boolean isMultiLine() { return multiLine; } public void setMultiLine(boolean multiLine) { this.multiLine = multiLine; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public double getMinValue() { return minValue; } public void setMinValue(double minValue) { this.minValue = minValue; } public double getMaxValue() { return maxValue; } public void setMaxValue(double maxValue) { this.maxValue = maxValue; } public static Log getLog() { return log; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> FORMVALUELIST */ public class FormValueList { public static final Log log = LogFactory.getLog(FormValueList.class); private String valueListId = ""; private String valueId = ""; private int sequence = 0; private boolean defaultValue = false; private String value = ""; public FormValueList() { } public FormValueList(RecordSet rs) { this.setValueListId(rs.getString(DbConstants.FormValueList.VALUE_LIST_ID)); this.setValueId(rs.getString(DbConstants.FormValueList.VALUE_ID)); this.setSequence(rs.getInt(DbConstants.FormValueList.SEQUENCE)); this.setDefaultValue(rs.getBoolean(DbConstants.FormValueList.DEFAULT_VALUE)); this.setValue(rs.getString(DbConstants.FormValueList.VALUE)); } public String getValueListId() { return valueListId; } public void setValueListId(String valueListId) { this.valueListId = valueListId; } public String getValueId() { return valueId; } public void setValueId(String valueId) { this.valueId = valueId; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public boolean isDefaultValue() { return defaultValue; } public void setDefaultValue(boolean defaultValue) { this.defaultValue = defaultValue; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static Log getLog() { return log; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDHIST */ public class History { private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private int idx = 0; private String text = ""; //$NON-NLS-1$ History() { } public History(RecordSet rs) { this.setIDX(rs.getInt(DbConstants.History.IDX)); this.setJobNumber(rs.getString(DbConstants.History.JOB_NUMBER)); this.setJobType(rs.getString(DbConstants.History.JOB_TYPE)); this.setText(rs.getString(DbConstants.History.Text)); } public int getIDX() { return this.idx; } public void setIDX(int index) { this.idx = index; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public JobType getJobType() { return this.jobType; } public void setJobType(String jobType) { this.jobType = new JobType(jobType); } public void setJobType(JobType jobType) { this.jobType = jobType; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBSTORC */ public class Incident { private String errorCode = ""; //$NON-NLS-1$ private String fct = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Incident() { } public Incident(RecordSet rs) { this.setErrorCode(rs.getString(DbConstants.Incident.CODE)); this.setFct(rs.getString(DbConstants.Incident.FCT)); this.setText(rs.getString(DbConstants.Incident.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Incident.REFRESH_FLAG)); } public String getErrorCode() { return this.errorCode; } public void setErrorCode(String storc) { this.errorCode = storc; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } public String getFct() { return fct; } public void setFct(String fct) { this.fct = fct; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZARBEITSART */ public class InternalWorkType { private String workTypeCode = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ InternalWorkType() { } public InternalWorkType(RecordSet rs) { this.setWorkTypeCode(rs.getString(DbConstants.InternalWorkType.CODE)); this.setText(rs.getString(DbConstants.InternalWorkType.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.InternalWorkType.REFRESH_FLAG)); } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.Warehouse; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZLG */ public class Inventory { private String warehouseNumber = ""; private int personalNumber = 0; private String name = ""; private Warehouse warehouse = new Warehouse(); private String refreshFlag = ""; public Inventory() { } public Inventory(RecordSet rs) { this.setWarehouseNumber(rs.getString(DbConstants.Inventory.WAREHOUSE_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.Inventory.PERSONAL_NUMBER)); this.setName(rs.getString(DbConstants.Inventory.NAME)); this.setWarehouse(new Warehouse(rs.getString(DbConstants.Inventory.WAREHOUSE))); this.setRefreshFlag(rs.getString(DbConstants.Inventory.REFRESH_FLAG)); } public String getWarehouseNumber() { return warehouseNumber; } public void setWarehouseNumber(String warehouseNumber) { this.warehouseNumber = warehouseNumber; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Warehouse getWarehouse() { return warehouse; } public void setWarehouse(Warehouse warehouse) { this.warehouse = warehouse; } public String getRefreshFlag() { return refreshFlag; } public void setRefreshFlag(String refreshFlag) { this.refreshFlag = refreshFlag; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBVERRC */ public class Invoice { private String code = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Invoice() { } public Invoice(RecordSet rs) { this.setCode(rs.getString(DbConstants.Invoice.CODE)); this.setText(rs.getString(DbConstants.Invoice.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Invoice.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFORMDESC */ public class JobFormDesc { private String formDesc = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ JobFormDesc() { } public JobFormDesc(RecordSet rs) { this.setFormDesc((rs.getString(DbConstants.JobFormDesc.CODE))); this.setText(rs.getString(DbConstants.JobFormDesc.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobFormDesc.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getFormDesc() { return this.formDesc; } public void setFormDesc(String formDesc) { this.formDesc = formDesc; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMSG */ public class JobMessage extends BaseEntity { private String guId = ""; //$NON-NLS-1$ private String messageId = ""; //$NON-NLS-1$ private String messageCode = ""; //$NON-NLS-1$ private String messageCodeText = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String moreText = ""; //$NON-NLS-1$ public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.JobMessage.JOB_MESSAGE, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.JobMessage.JOB_MESSAGE, db, folder); } public JobMessage() { } public JobMessage(RecordSet rs) { this.setGuId(rs.getString(DbConstants.JobMessage.GUID)); this.setMessageId(rs.getString(DbConstants.JobMessage.MESSAGE_ID)); this.setMessageCode(rs.getString(DbConstants.JobMessage.MESSAGE_CODE)); this.setMessageCodeText(rs.getString(DbConstants.JobMessage.TEXT_1)); this.setText(rs.getString(DbConstants.JobMessage.TEXT_2)); this.setMoreText(rs.getString(DbConstants.JobMessage.MoreText)); } public String getMessageId() { return this.messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public String getGuId() { return this.guId; } public void setGuId(String guid) { this.guId = guid; } public String getMessageCode() { return this.messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } public String getMessageCodeText() { return this.messageCodeText; } public void setMessageCodeText(String messageCodeText) { this.messageCodeText = messageCodeText; } public String getFullText() { return this.text.concat(this.moreText); } public String geText() { return this.text; } public void setFullText(String text) { if (text.length() > 255) { this.text = text.substring(0, 255); this.moreText = text.substring(255); } else { this.text = text; this.moreText = ""; //$NON-NLS-1$ } } public void setText(String text) { this.text = text; } public String getMoreText() { return this.moreText; } public void setMoreText(String moreText) { this.moreText = moreText; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMONTXT */ public class JobMonText { private String monText = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ JobMonText() { } public JobMonText(RecordSet rs) { this.setMonText((rs.getString(DbConstants.JobMonText.CODE))); this.setLanguage(rs.getString(DbConstants.JobMonText.LANGUAGE)); this.setText(rs.getString(DbConstants.JobMonText.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getMonText() { return this.monText; } public void setMonText(String reasonText) { this.monText = reasonText; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBNOFORM */ public class JobNoForm { private String noForm = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ JobNoForm() { } public JobNoForm(RecordSet rs) { this.setNoForm((rs.getString(DbConstants.JobNoForm.CODE))); this.setText(rs.getString(DbConstants.JobNoForm.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobNoForm.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getNoForm() { return this.noForm; } public void setNoForm(String noForm) { this.noForm = noForm; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /** * Object representing working time spent on a job report. Implements Comparable * interface because the list of times of a certain day must be in the correct * order. * In the Database -> ZKDMOBRTIM * @author paulib * */ public class JobReportTime implements Comparable { private String guId = ""; //$NON-NLS-1$ private int idx = 0; private Date date = new Date(); private Date startTime = new Date(0); private Date stopTime = new Date(0); private String workTypeCode = ""; public JobReportTime() { } public JobReportTime(RecordSet rs) { this.setStopTime(rs.getDate(DbConstants.JobReportTime.STOP_TIME)); this.setGuid(rs.getString(DbConstants.JobReportTime.GUID)); this.setIdx(rs.getInt(DbConstants.JobReportTime.IDX)); this.setStartTime(rs.getDate(DbConstants.JobReportTime.START_TIME)); this.setDate(rs.getDate(DbConstants.JobReportTime.DATE)); this.setWorkTypeCode(rs.getString(DbConstants.JobReportTime.WORK_TYPE_CODE)); } public int compareTo(Object o) { JobReportTime jobReportTime = (JobReportTime) o; return this.getStartTime().compareTo(jobReportTime.getStartTime()); } public Date getStopTime() { return this.stopTime; } public void setStopTime(Date bis) { this.stopTime = bis; } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public Date getStartTime() { return this.startTime; } public void setStartTime(Date von) { this.startTime = von; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBRETURN */ public class JobReturnReason extends Reason{ JobReturnReason() { } public JobReturnReason(RecordSet rs) { this.setReasonText((rs.getString(DbConstants.JobReturnReason.CODE))); this.setLanguage(rs.getString(DbConstants.JobReturnReason.LANGUAGE)); this.setText(rs.getString(DbConstants.JobReturnReason.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.JobReturnReason.REFRESH_FLAG)); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMAT */ public class Material { private String materialNumber = ""; //$NON-NLS-1$ private String materialShortText = ""; //$NON-NLS-1$ private String customerServiceFlag = ""; //$NON-NLS-1$ private String mountingFlag = ""; //$NON-NLS-1$ private String unit = ""; //$NON-NLS-1$ private String size = ""; //$NON-NLS-1$ private String newPrice = ""; //$NON-NLS-1$ private String substitutePrice = ""; //$NON-NLS-1$ private String calculationNewPrice = ""; //$NON-NLS-1$ private String calculationSubstitutePrice = ""; //$NON-NLS-1$ private String unitNewPrice = ""; //$NON-NLS-1$ private String unitSubstitutePrice = ""; //$NON-NLS-1$ private String currencyNewPrice = ""; //$NON-NLS-1$ private String currencySubstitutePrice = ""; //$NON-NLS-1$ Material() { } public Material(RecordSet rs) { this.setMaterialShortText(rs.getString(DbConstants.Material.TEXT)); this.setMaterialNumber(rs.getString(DbConstants.Material.NUMBER)); this.setCustomerServiceFlag(rs.getString(DbConstants.Material.CUSTOMER_SERVICE_FLAG)); this.setMountingFlag(rs.getString(DbConstants.Material.MOUNTING_FLAG)); this.setUnit(rs.getString(DbConstants.Material.UNIT)); this.setSize(rs.getString(DbConstants.Material.SIZE)); this.setNewPrice(rs.getString(DbConstants.Material.NEW_PRICE)); this.setSubstitutePrice(rs.getString(DbConstants.Material.SUBSTITUE_PRICE)); this.setCalculationNewPrice(rs.getString(DbConstants.Material.CALCULATION_NEW_PRICE)); this.setCalculationSubstitutePrice(rs.getString(DbConstants.Material.CALCULATION_SUBSTITUE_PRICE)); this.setUnitNewPrice(rs.getString(DbConstants.Material.UNIT_NEW_PRICE)); this.setUnitSubstitutePrice(rs.getString(DbConstants.Material.UNIT_SUBSTITUE_PRICE)); this.setCurrencyNewPrice(rs.getString(DbConstants.Material.CURRENCY_NEW_PRICE)); this.setCurrencySubstitutePrice(rs.getString(DbConstants.Material.CURRENCY_SUBSTITUE_PRICE)); } public String getCustomerServiceFlag() { return this.customerServiceFlag; } public void setCustomerServiceFlag(String kdmat) { this.customerServiceFlag = kdmat; } public String getUnit() { return this.unit; } public void setUnit(String maunit) { this.unit = maunit; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getMountingFlag() { return this.mountingFlag; } public void setMountingFlag(String monmat) { this.mountingFlag = monmat; } public String getMaterialShortText() { return this.materialShortText; } public void setMaterialShortText(String maktx) { this.materialShortText = maktx; } public String getMaterialNumber() { return this.materialNumber; } public void setMaterialNumber(String matnr) { this.materialNumber = matnr; } public String getNewPrice() { return newPrice; } public void setNewPrice(String newPrice) { this.newPrice = newPrice; } public String getSubstitutePrice() { return substitutePrice; } public void setSubstitutePrice(String substitutePrice) { this.substitutePrice = substitutePrice; } public String getCalculationNewPrice() { return calculationNewPrice; } public void setCalculationNewPrice(String calculationNewPrice) { this.calculationNewPrice = calculationNewPrice; } public String getCalculationSubstitutePrice() { return calculationSubstitutePrice; } public void setCalculationSubstitutePrice(String calculationSubstitutePrice) { this.calculationSubstitutePrice = calculationSubstitutePrice; } public String getUnitNewPrice() { return unitNewPrice; } public void setUnitNewPrice(String unitNewPrice) { this.unitNewPrice = unitNewPrice; } public String getUnitSubstitutePrice() { return unitSubstitutePrice; } public void setUnitSubstitutePrice(String unitSubstitutePrice) { this.unitSubstitutePrice = unitSubstitutePrice; } public String getCurrencyNewPrice() { return currencyNewPrice; } public void setCurrencyNewPrice(String currencyNewPrice) { this.currencyNewPrice = currencyNewPrice; } public String getCurrencySubstitutePrice() { return currencySubstitutePrice; } public void setCurrencySubstitutePrice(String currencySubstitutePrice) { this.currencySubstitutePrice = currencySubstitutePrice; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZGMBEW */ public class MaterialMovement { public static final Log log = LogFactory.getLog(MaterialMovement.class); private String guid = ""; private String orderNumber = ""; private int orderPosition; private int personalNumber; private String materialNumber = ""; private String from = ""; private String to = ""; private String entryCount = ""; private String entryUnit = ""; private String receiptOfGoods = ""; private String barcode = ""; private String barcodeText = ""; private int personalNumberConfirmed; public MaterialMovement() { } public MaterialMovement(RecordSet rs) { this.setGuid(rs.getString(DbConstants.MaterialMovement.GUID)); this.setOrderNumber(rs.getString(DbConstants.MaterialMovement.ORDER_NUMBER)); this.setOrderPosition(rs.getInt(DbConstants.MaterialMovement.ORDER_POSITION)); this.setPersonalNumber(rs.getInt(DbConstants.MaterialMovement.PERSONAL_NUMBER)); this.setMaterialNumber(rs.getString(DbConstants.MaterialMovement.MATERIAL_NUMBER)); this.setFrom(rs.getString(DbConstants.MaterialMovement.FROM)); this.setTo(rs.getString(DbConstants.MaterialMovement.TO)); this.setEntryCount(rs.getString(DbConstants.MaterialMovement.ENTRY_COUNT)); this.setEntryUnit(rs.getString(DbConstants.MaterialMovement.ENTRY_UNIT)); this.setReceiptOfGoods(rs.getString(DbConstants.MaterialMovement.RECEIPT_OF_GOODS)); this.setBarcode(rs.getString(DbConstants.MaterialMovement.BARCODE)); this.setBarcodeText(rs.getString(DbConstants.MaterialMovement.BARCODE_TEXT)); this.setPersonalNumberConfirmed(rs.getInt(DbConstants.MaterialMovement.PERSONAL_NUMBER_CONFIRMED)); } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getOrderPosition() { return orderPosition; } public void setOrderPosition(int orderPosition) { this.orderPosition = orderPosition; } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int personalNumber) { this.personalNumber = personalNumber; } public String getMaterialNumber() { return materialNumber; } public void setMaterialNumber(String materialNumber) { this.materialNumber = materialNumber; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getEntryCount() { return entryCount; } public void setEntryCount(String entryCount) { this.entryCount = entryCount; } public String getEntryUnit() { return entryUnit; } public void setEntryUnit(String entryUnit) { this.entryUnit = entryUnit; } public String getReceiptOfGoods() { return receiptOfGoods; } public void setReceiptOfGoods(String receiptOfGoods) { this.receiptOfGoods = receiptOfGoods; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getBarcodeText() { return barcodeText; } public void setBarcodeText(String barcodeText) { this.barcodeText = barcodeText; } public int getPersonalNumberConfirmed() { return personalNumberConfirmed; } public void setPersonalNumberConfirmed(int personalNumberConfirmed) { this.personalNumberConfirmed = personalNumberConfirmed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDMOBMATPERS */ public class MaterialPerson { String materialNumber = ""; //$NON-NLS-1$ String materialShortText = ""; //$NON-NLS-1$ String customerServiceFlag = ""; //$NON-NLS-1$ String mountingFlag = ""; //$NON-NLS-1$ public MaterialPerson() { //constructor } public MaterialPerson(RecordSet rs) { this.setMaterialNumber(rs.getString(DbConstants.MaterialPerson.NUMBER)); this.setMaterialShortText(rs.getString(DbConstants.MaterialPerson.TEXT)); this.setCustomerServiceFlag(rs.getString(DbConstants.MaterialPerson.CUSTOMER_SERVICE_FLAG)); this.setMountingFlag(rs.getString(DbConstants.MaterialPerson.MOUNTING_FLAG)); } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.MaterialPerson.MATERIAL_PERSON, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.MaterialPerson.MATERIAL_PERSON, db, folder); } public String getMaterialNumber() { return this.materialNumber; } public void setMaterialNumber(String matnr) { this.materialNumber = matnr; } public String getMaterialShortText() { return this.materialShortText; } public void setMaterialShortText(String maktx) { this.materialShortText = maktx; } public String getCustomerServiceFlag() { return this.customerServiceFlag; } public void setCustomerServiceFlag(String kdmat) { this.customerServiceFlag = kdmat; } public String getMountingFlag() { return this.mountingFlag; } public void setMountingFlag(String monmat) { this.mountingFlag = monmat; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFLGVRGT */ public class NextIntervention { private String code = ""; private String text = ""; private String refreshFlag = ""; NextIntervention() { } public NextIntervention(RecordSet rs) { this.setCode(rs.getString(DbConstants.NextIntervention.CODE)); this.setText(rs.getString(DbConstants.NextIntervention.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.NextIntervention.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKSMABEST */ public class Order { public static final Log log = LogFactory.getLog(Order.class); private int idx = 0; private int personalNumber = 0; private String status = ""; //$NON-NLS-1$ private String isNotUsed = ""; //$NON-NLS-1$ private Date createDate = new Date(); private Date sentDate = new Date(); public Order() { } public Order(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.Order.IDX)); this.setPersonalNumber(rs.getInt(DbConstants.Order.PERSONAL_NUMBER)); this.setStatus(rs.getString(DbConstants.Order.STATUS)); this.setANZ(rs.getString(DbConstants.Order.ANZ)); this.setCreateDate(rs.getDate(DbConstants.Order.CREATED_DATE)); this.setSentDate(rs.getDate(DbConstants.Order.SENT_DATE)); } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getANZ() { return this.isNotUsed; } public void setANZ(String anz) { this.isNotUsed = anz; } public Date getCreateDate() { return this.createDate; } public String getOrderCreateDate() { return DateTimeUtil.tableDate(this.getCreateDate()); } public void setCreateDate(Date erfasst) { this.createDate = erfasst; } public Date getSentDate() { return this.sentDate; } public String getOrderSentDate() { return DateTimeUtil.tableDate(this.getSentDate()); } public void setSentDate(Date gesendet) { this.sentDate = gesendet; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public boolean isNew() { return getStatus().equalsIgnoreCase(CommonConstants.Order.Status.NEW_ORDER); } public boolean isSent() { return getStatus().equalsIgnoreCase(CommonConstants.Order.Status.SENT_ORDER); } public int getStatusColor() { int result = 0; if (isNew()) { result = LayoutUtils.DEFAULT_RED; } else if (isSent()) { result = LayoutUtils.DEFAULT_DARK_GRAY; } return result; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Order.ORDER, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Order.ORDER, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAMAT */ public class OrderMaterial { private int personalNumber; private Date date; private String amount; private String materialNumber; private String expressFlag; private String variousMaterial; private String unit; private Date orderDate; public OrderMaterial() { } public OrderMaterial(RecordSet rs) { this.setDate(rs.getDate(DbConstants.OrderMaterial.DATE)); this.setExpressFlag(rs.getString(DbConstants.OrderMaterial.EXPRESS_FLAG)); this.setVariousMaterial(rs.getString(DbConstants.OrderMaterial.VARIOUS_MATERIAL)); this.setMaterialNumber(rs.getString(DbConstants.OrderMaterial.NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.OrderMaterial.PERSONAL_NUMBER)); this.setAmount(rs.getString(DbConstants.OrderMaterial.AMOUNT)); this.setUnit(rs.getString(DbConstants.OrderMaterial.UNIT)); this.setOrderDate(rs.getDate(DbConstants.OrderMaterial.ORDER_DATE)); } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getExpressFlag() { return this.expressFlag; } public boolean isExpressFlag() { return "X".equalsIgnoreCase(this.getExpressFlag()); //$NON-NLS-1$ } public void setExpressFlag(boolean expressFlag) { if (expressFlag) { this.setExpressFlag("X"); //$NON-NLS-1$ } else { this.setExpressFlag(""); //$NON-NLS-1$ } } public void setExpressFlag(String expr) { this.expressFlag = expr; } public String getVariousMaterial() { return this.variousMaterial; } public void setVariousMaterial(String maktx) { this.variousMaterial = maktx; } public String getMaterialNumber() { return this.materialNumber; } public void setMaterialNumber(String matnr) { this.materialNumber = matnr; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getAmount() { return this.amount; } public void setAmount(String stck) { this.amount = stck; } public String getUnit() { return this.unit; } public void setUnit(String maunit) { this.unit = maunit; } public void setOrderDate(Date bestdat) { this.orderDate = bestdat; } public Date getOrderDate() { return this.orderDate; } public int getStatusColor() { return LayoutUtils.DEFAULT_DARK_GRAY; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.OrderMaterial.ORDER_MATERIAL, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.OrderMaterial.ORDER_MATERIAL, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMA */ public class Person { private int personalNumber = 0; private String lastName = ""; //$NON-NLS-1$ private String firstName = ""; //$NON-NLS-1$ private String initial = ""; //$NON-NLS-1$ private String personalNumberDeputy = ""; //$NON-NLS-1$ private String phoneNumber = ""; //$NON-NLS-1$ private String communicationNumber = ""; //$NON-NLS-1$ private String salesOffice = ""; //$NON-NLS-1$ private String absentFrom = ""; //$NON-NLS-1$ private String absentTo = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String deviceId; private String password; private String refreshFlag = ""; private String warehouseNumber = ""; //$NON-NLS-1$ private String communicationNumberFormat = ""; private boolean expensesActive = false; private String profileText = ""; Person() { } public Person(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.Person.PERSONAL_NUMBER)); this.setLastName(rs.getString(DbConstants.Person.LAST_NAME)); this.setFirstName(rs.getString(DbConstants.Person.FIRST_NAME)); this.setInitial(rs.getString(DbConstants.Person.INITIAL)); this.setPersonalNumberDeputy(rs.getString(DbConstants.Person.PERSONAL_NUMBER_DEPUTY)); this.setPhoneNumber(rs.getString(DbConstants.Person.PHONE)); this.setNUM01(rs.getString(DbConstants.Person.NUM01)); this.setSalesOffice(rs.getString(DbConstants.Person.SALES_OFFICE)); this.setAbsentFrom(rs.getString(DbConstants.Person.ABSENT_FROM)); this.setAbsentTo(rs.getString(DbConstants.Person.ABSENT_TO)); this.setLanguage(rs.getString(DbConstants.Person.LANGUAGE)); this.setDeviceId(rs.getString(DbConstants.Person.DEVICE_ID)); this.setPassword(rs.getString(DbConstants.Person.PASSWORD)); this.setRefreshFlag(rs.getString(DbConstants.Person.REFRESH_FLAG)); this.setWarehouseNumber(rs.getString(DbConstants.Person.WAREHOUSE_NUMBER)); this.setCommunicationNumberFormat(rs.getString(DbConstants.Person.COMMISSION_NUMBER_FORMAT)); this.setExpensesActive(rs.getBoolean(DbConstants.Person.EXPENSES_ACTIVE)); this.setProfileText(rs.getString(DbConstants.Person.PROFILE_TEXT)); } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getInitial() { return this.initial; } public void setInitial(String inits) { this.initial = inits; } public String getLastName() { return this.lastName; } public void setLastName(String nachn) { this.lastName = nachn; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getPassword() { return this.password; } public void setPassword(String pwd) { this.password = pwd; } public String getPersonalNumberDeputy() { return this.personalNumberDeputy; } public void setPersonalNumberDeputy(String stvpernr) { this.personalNumberDeputy = stvpernr; } public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String telnr) { this.phoneNumber = telnr; } public String getSalesOffice() { return this.salesOffice; } public void setSalesOffice(String vkbur) { this.salesOffice = vkbur; } public String getFirstName() { return this.firstName; } public void setFirstName(String vorna) { this.firstName = vorna; } public String getNUM01() { return this.communicationNumber; } public void setNUM01(String num01) { this.communicationNumber = num01; } public String getAbsentFrom() { return this.absentFrom; } public void setAbsentFrom(String abwvon) { this.absentFrom = abwvon; } public String getAbsentTo() { return this.absentTo; } public void setAbsentTo(String abwbis) { this.absentTo = abwbis; } public String getDeviceId() { return this.deviceId; } public void setDeviceId(String gid) { this.deviceId = gid; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } public String getWarehouseNumber() { return warehouseNumber; } public void setWarehouseNumber(String warehouseNumber) { this.warehouseNumber = warehouseNumber; } public String getCommunicationNumberFormat() { return communicationNumberFormat; } public void setCommunicationNumberFormat(String communicationNumberFormat) { this.communicationNumberFormat = communicationNumberFormat; } public boolean getExpensesActive() { return expensesActive; } public void setExpensesActive(boolean expensesActive) { this.expensesActive = expensesActive; } public String getProfileText() { return profileText; } public void setProfileText(String profileText) { this.profileText = profileText; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class PhoneBookEntry { private static final String HTML_SPACE = " "; //$NON-NLS-1$ private static final String HTML_LINE_BREAK = "
"; //$NON-NLS-1$ private String mLabel1 = ""; //$NON-NLS-1$ private String mLabel2 = ""; //$NON-NLS-1$ private String mTitel = ""; //$NON-NLS-1$ private String mPosition = ""; //$NON-NLS-1$ private String mDetails = ""; //$NON-NLS-1$ private String mPhoneNumber1 = ""; //$NON-NLS-1$ private String mPhoneNumber2 = ""; //$NON-NLS-1$ private boolean mExistingPhoneNumber1 = false; private boolean mExistingPhoneNumber2 = false; public PhoneBookEntry(String label, String titel, String details, String position, String phoneNumber1) { mTitel = titel; mPosition = position; if (!"".equals(phoneNumber1)) { //$NON-NLS-1$ mExistingPhoneNumber1 = true; mPhoneNumber1 = StringUtil.removeLetters(phoneNumber1); if (!"".equals(position)) //$NON-NLS-1$ mLabel1 = mLabel1 + position + HTML_LINE_BREAK; if (!"".equals(mPhoneNumber1)) //$NON-NLS-1$ mLabel1 = mLabel1 + mPhoneNumber1; if (!"".equals(titel)) //$NON-NLS-1$ mDetails = mDetails + titel + HTML_SPACE; if (!"".equals(label)) //$NON-NLS-1$ mDetails = mDetails + label + HTML_LINE_BREAK; if (!"".equals(details)) //$NON-NLS-1$ mDetails = mDetails + details; } } public PhoneBookEntry(String titel, Address address, String position) { mTitel = titel; mPosition = position; extract(address); } private void extract(Address address) { String details = ""; //$NON-NLS-1$ if (address.isPrivate()) { if (!"".equals(address.getTitle())) //$NON-NLS-1$ mDetails = mDetails + mTitel + HTML_SPACE; if (!"".equals(address.getName1())) //$NON-NLS-1$ mDetails = mDetails + address.getName1() + HTML_SPACE; if (!"".equals(address.getName2())) //$NON-NLS-1$ mDetails = mDetails + address.getName2() + HTML_LINE_BREAK; if (!"".equals(address.getName3())) //$NON-NLS-1$ mDetails = mDetails + address.getName3() + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) { //$NON-NLS-1$ mExistingPhoneNumber1 = true; mPhoneNumber1 = StringUtil.removeLetters(address.getTelNumber1()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel1 = mLabel1 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) //$NON-NLS-1$ mLabel1 = mLabel1 + mPhoneNumber1; } if (!"".equals(address.getTelNumber2())) { //$NON-NLS-1$ mExistingPhoneNumber2 = true; mPhoneNumber2 = StringUtil.removeLetters(address.getTelNumber1()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel2 = mLabel2 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) //$NON-NLS-1$ mLabel2 = mLabel2 + mPhoneNumber2; } } else { if (!"".equals(address.getTitle())) //$NON-NLS-1$ details = details + mTitel + HTML_SPACE; if (!"".equals(address.getName1())) { //$NON-NLS-1$ details = details + address.getName1(); if (!"".equals(address.getName2())) //$NON-NLS-1$ details = details + address.getName2() + HTML_SPACE; } else if (!"".equals(address.getName2())) { //$NON-NLS-1$ details = details + address.getName2(); } else { details = details + Messages.getString("PhoneBookEntry_1"); //$NON-NLS-1$ } if (!"".equals(address.getName3())) //$NON-NLS-1$ details = details + address.getName3(); if (!"".equals(details)) //$NON-NLS-1$ mDetails = details + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) { //$NON-NLS-1$ mExistingPhoneNumber1 = true; mPhoneNumber1 = StringUtil.removeLetters(address.getTelNumber1()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel1 = mLabel1 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber1())) //$NON-NLS-1$ mLabel1 = mLabel1 + mPhoneNumber1; } if (!"".equals(address.getTelNumber2())) { //$NON-NLS-1$ mExistingPhoneNumber2 = true; mPhoneNumber2 = StringUtil.removeLetters(address.getTelNumber2()); if (!"".equals(mPosition)) //$NON-NLS-1$ mLabel2 = mLabel2 + mPosition + HTML_LINE_BREAK; if (!"".equals(address.getTelNumber2())) //$NON-NLS-1$ mLabel2 = mLabel2 + mPhoneNumber2; } } } public String getLabel1() { return mLabel1; } public String getLabel2() { return mLabel2; } public String getPosition() { return mPosition; } public boolean hasPhoneNumber1() { return mExistingPhoneNumber1; } public String getDetails() { return mDetails; } public String getPhoneNumber1() { return mPhoneNumber1; } public boolean hasPhoneNumber2() { return mExistingPhoneNumber2; } public String getPhoneNumber2() { return mPhoneNumber2; } }
package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMONSTK */ public class Progress { private String progressCode = ""; private String spras = ""; private String text = ""; private String refreshFlag = ""; Progress() { } public Progress(RecordSet rs) { this.setProgressCode(rs.getString(DbConstants.Progress.CODE)); this.setSpras(rs.getString(DbConstants.Progress.SPRAS)); this.setText(rs.getString(DbConstants.Progress.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Progress.REFRESH_FLAG)); } public String getProgressCode() { return this.progressCode; } public void setProgressCode(String progressCode) { this.progressCode = progressCode; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getSpras() { return spras; } public void setSpras(String spras) { this.spras = spras; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> REASON */ public class Reason { private String reasonText = ""; //$NON-NLS-1$ private String language = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String refreshFlag = ""; //$NON-NLS-1$ Reason() { } public Reason(RecordSet rs) { this.setReasonText((rs.getString(DbConstants.Reason.CODE))); this.setLanguage(rs.getString(DbConstants.Reason.LANGUAGE)); this.setText(rs.getString(DbConstants.Reason.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.Reason.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getReasonText() { return this.reasonText; } public void setReasonText(String reasonText) { this.reasonText = reasonText; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBWERET */ public class ReceiptOfGoods { private String code = ""; private String text = ""; private String refreshFlag = ""; ReceiptOfGoods() { } public ReceiptOfGoods(RecordSet rs) { this.setCode(rs.getString(DbConstants.ReceiptOfGoods.CODE)); this.setText(rs.getString(DbConstants.ReceiptOfGoods.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.ReceiptOfGoods.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.util.DateUtils; /* * In the Database -> ZKDMOBREP */ public class Report extends BaseEntity { public static final Log log = LogFactory.getLog(Report.class); private int idx = 0; private String guId = ""; //$NON-NLS-1$ private Date createDate = new Date(); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String commissionNumber = ""; //$NON-NLS-1$ private int personalNumber = 0; private String partialRepair = ""; //$NON-NLS-1$ private String finalRepair = ""; //$NON-NLS-1$ private String reasoning = ""; //$NON-NLS-1$ private String incidentAB = ""; //$NON-NLS-1$ private String billing = ""; //$NON-NLS-1$ private String safetyReport = ""; //$NON-NLS-1$ private String customerSupport = ""; //$NON-NLS-1$ private String customerSupportText = ""; //$NON-NLS-1$ private String checklist = ""; //$NON-NLS-1$ private String errorId1 = ""; //$NON-NLS-1$ private String errorH1 = ""; //$NON-NLS-1$ private String errorFlag1 = ""; //$NON-NLS-1$ private String errorId2 = ""; //$NON-NLS-1$ private String errorH2 = ""; //$NON-NLS-1$ private String errorFlag2 = ""; //$NON-NLS-1$ private String errorId3 = ""; //$NON-NLS-1$ private String errorH3 = ""; //$NON-NLS-1$ private String errorFlag3 = ""; //$NON-NLS-1$ private String systemError = ""; //$NON-NLS-1$ private String distance = ""; //$NON-NLS-1$ private String expenses = ""; //$NON-NLS-1$ private String servicePlanMonth1 = ""; //$NON-NLS-1$ private String servicePlanMonth2 = ""; //$NON-NLS-1$ private String servicePlanMonth3 = ""; //$NON-NLS-1$ private String servicePlanMonth4 = ""; //$NON-NLS-1$ private String servicePlanMonth5 = ""; //$NON-NLS-1$ private String servicePlanMonth6 = ""; //$NON-NLS-1$ private String monthYear = ""; //$NON-NLS-1$ private String orderNumber = ""; //$NON-NLS-1$ private ReportStatus reportStatus = new ReportStatus(); private String signatureGuId = ""; //$NON-NLS-1$ private String signatureFlag = ""; //$NON-NLS-1$ private String signatureInfo = ""; //$NON-NLS-1$ private String signature = ""; //$NON-NLS-1$ private String workType = ""; //$NON-NLS-1$ private String collectively = ""; //$NON-NLS-1$ private String noMaterial = ""; //$NON-NLS-1$ private String cycleOfInstallation = ""; //$NON-NLS-1$ private String noForm1 = ""; private String noForm2 = ""; private String noForm3 = ""; private String serviceRefused = ""; private String openPending = ""; private String governmentReport = ""; private String checklistState = "U"; private String checklistSIA = "U"; private String checklistReady = "U"; private String checklistInstruction = "U"; private String checklistVKF = "U"; private String checklistTest = "U"; private String signatureName = ""; private String monStk = ""; private Date nextInterventionDate = new Date(); private String stateOfInstallation = ""; private String nextInterventionCode = ""; private List times = new ArrayList(); private List mats = new ArrayList(); private List messages = new ArrayList(); private List measurements = new ArrayList(); private List reportImageAttachments = new ArrayList(); private List reportDocumentAttachments = new ArrayList(); private List formInstances = new ArrayList(); private int currentTime; private boolean isCycleOfInstallationFlag; protected Report() { } public Report(String mldnr, JobType auart, String guid, int idx, boolean isCycleOfInstallationFlag) { this.setJobNumber(mldnr); this.setJobType(auart); this.setGuid(guid); this.setIdx(idx); this.isCycleOfInstallationFlag = isCycleOfInstallationFlag; } public Report(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.Report.IDX)); this.setJobType(rs.getString(DbConstants.Report.JOB_TYPE)); this.setCommissionNumber(rs.getString(DbConstants.Report.COMMISSION_NUMBER)); this.setChecklist(rs.getString(DbConstants.Report.CHECK_LIST)); this.setFinalRepair(rs.getString(DbConstants.Report.FINAL_REPAIR)); this.setCreateDate(rs.getDate(DbConstants.Report.CREATE_DATE)); this.setErrorFlag1(rs.getString(DbConstants.Report.ERROR_FLAG_1)); this.setErrorFlag2(rs.getString(DbConstants.Report.ERROR_FLAG_2)); this.setErrorFlag3(rs.getString(DbConstants.Report.ERROR_FLAG_3)); this.setSystemError(rs.getString(DbConstants.Report.SYSTEM_ERROR)); this.setErrorId1(rs.getString(DbConstants.Report.ERROR_ID_1)); this.setErrorId2(rs.getString(DbConstants.Report.ERROR_ID_2)); this.setErrorId3(rs.getString(DbConstants.Report.ERROR_ID_3)); this.setErrorH1(rs.getString(DbConstants.Report.ERROR_H_1)); this.setErrorH2(rs.getString(DbConstants.Report.ERROR_H_2)); this.setErrorH3(rs.getString(DbConstants.Report.ERROR_H_3)); this.setReasoning(rs.getString(DbConstants.Report.REASONING)); this.setGuid(rs.getString(DbConstants.Report.GUID)); this.setDistance(rs.getString(DbConstants.Report.DISTANCE)); this.setJobNumber(rs.getString(DbConstants.Report.JOB_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.Report.PERSONAL_NUMBER)); this.setCustomerSupport(rs.getString(DbConstants.Report.CUSTOMER_SUPPORT)); this.setCustomerSupportText(rs.getString(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT)); this.setReportStatus(new ReportStatus(rs.getString(DbConstants.Report.REPORT_STATUS))); this.setServicePlanMonth1(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_1)); this.setServicePlanMonth2(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_2)); this.setServicePlanMonth3(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_3)); this.setServicePlanMonth4(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_4)); this.setServicePlanMonth5(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_5)); this.setServicePlanMonth6(rs.getString(DbConstants.Report.SERVICE_PLAN_MENTH_6)); this.setSafetyReport(rs.getString(DbConstants.Report.SAFETY_REPORT)); this.setMonthYear(rs.getString(DbConstants.Report.MONTH_YEAR)); this.setOrderNumber(rs.getString(DbConstants.Report.ORDER_NUMBER)); this.setSignatureGuId(rs.getString(DbConstants.Report.SIGNATURE_GUID)); this.setSignatureFlag(rs.getString(DbConstants.Report.SIGNATURE_FLAG)); this.setSignature(rs.getString(DbConstants.Report.SIGNATURE)); this.setSignatureInfo(rs.getString(DbConstants.Report.SIGNATURE_INFO)); this.setExpenses(rs.getString(DbConstants.Report.EXPENSES)); this.setIncidentAB(rs.getString(DbConstants.Report.INCIDENT_AB)); this.setPartialRepair(rs.getString(DbConstants.Report.PARTICAL_REPAIR)); this.setBilling(rs.getString(DbConstants.Report.BILLING)); this.setWorkType(rs.getString(DbConstants.Report.WORK_TYPE)); this.setCollectively(rs.getString(DbConstants.Report.COLLECTIVELY)); this.setNoMaterial(rs.getString(DbConstants.Report.NO_MATERIAL)); this.setCycleOfInstallation(rs.getString(DbConstants.Report.CYCLE_OF_INSTALLATION)); this.setNoForm1(rs.getString(DbConstants.Report.NO_FORM1)); this.setNoForm2(rs.getString(DbConstants.Report.NO_FORM2)); this.setNoForm3(rs.getString(DbConstants.Report.NO_FORM3)); this.setServiceRefused(rs.getString(DbConstants.Report.SERVICE_REFUSED)); this.setOpenPending(rs.getString(DbConstants.Report.OPEN_PENDING)); this.setGovernmentReport(rs.getString(DbConstants.Report.GOVERNMENT_REPORT)); this.setChecklistState(rs.getString(DbConstants.Report.CHECKLIST_STATE)); this.setChecklistSIA(rs.getString(DbConstants.Report.CHECKLIST_SIA)); this.setChecklistReady(rs.getString(DbConstants.Report.CHECKLIST_READY)); this.setChecklistInstruction(rs.getString(DbConstants.Report.CHECKLIST_INSTRUCTION)); this.setChecklistVKF(rs.getString(DbConstants.Report.CHECKLIST_VKF)); this.setChecklistTest(rs.getString(DbConstants.Report.CHECKLIST_TEST)); this.setSignatureName(rs.getString(DbConstants.Report.SIGNATURE_NAME)); this.setMonStk(rs.getString(DbConstants.Report.MON_STK)); this.setNextInterventionDate(rs.getDate(DbConstants.Report.NEXT_INTERVENTION_DATE)); this.setStateOfInstallation(rs.getString(DbConstants.Report.STATE_OF_INSTALLATION)); this.setNextInterventionCode(rs.getString(DbConstants.Report.NEXT_INTERVENTION_CODE)); } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Report.REPORT, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Report.REPORT, db, folder); } public JobType getJobType() { return this.jobType; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public void setJobType(JobType auart) { this.jobType = auart; } public String getChecklist() { return this.checklist; } public void setChecklist(String chckliste) { this.checklist = chckliste; } public String getFinalRepair() { return this.finalRepair; } public void setFinalRepair(String endrep) { this.finalRepair = endrep; } public boolean isFinalRepair() { return "X".equalsIgnoreCase(this.getFinalRepair()); //$NON-NLS-1$ } public void setFinalRepair(boolean endrep) { if (endrep) { this.setFinalRepair("X"); //$NON-NLS-1$ } else { this.setFinalRepair(""); //$NON-NLS-1$ } } public Date getCreateDate() { return this.createDate; } public void setCreateDate(Date erdat) { this.createDate = erdat; } public String getErrorFlag1() { return this.errorFlag1; } public void setErrorFlag1(String fm1) { this.errorFlag1 = fm1; } public String getErrorFlag2() { return this.errorFlag2; } public void setErrorFlag2(String fm2) { this.errorFlag2 = fm2; } public String getErrorFlag3() { return this.errorFlag3; } public void setErrorFlag3(String fm3) { this.errorFlag3 = fm3; } public String getSystemError() { return this.systemError; } public void setSystemError(String fmb) { this.systemError = fmb; } public boolean isErrorFlag1() { return "X".equalsIgnoreCase(this.getErrorFlag1()); //$NON-NLS-1$ } public void setErrorFlag1(boolean fm1) { if (fm1) { this.setErrorFlag1("X"); //$NON-NLS-1$ } else { this.setErrorFlag1(""); //$NON-NLS-1$ } } public String getErrorId1() { return this.errorId1; } public void setErrorId1(String fmc1) { this.errorId1 = fmc1; } public boolean isErrorFlag2() { return "X".equalsIgnoreCase(this.getErrorFlag2()); //$NON-NLS-1$ } public void setErrorFlag2(boolean fm2) { if (fm2) { this.setErrorFlag2("X"); //$NON-NLS-1$ } else { this.setErrorFlag2(""); //$NON-NLS-1$ } } public String getErrorId2() { return this.errorId2; } public void setErrorId2(String fmc2) { this.errorId2 = fmc2; } public boolean isErrorFlag3() { return "X".equalsIgnoreCase(this.getErrorFlag3()); //$NON-NLS-1$ } public void setErrorFlag3(boolean fm3) { if (fm3) { this.setErrorFlag3("X"); //$NON-NLS-1$ } else { this.setErrorFlag3(""); //$NON-NLS-1$ } } public String getErrorId3() { return this.errorId3; } public void setErrorId3(String fmc3) { this.errorId3 = fmc3; } public String getErrorH1() { return this.errorH1; } public void setErrorH1(String fmh1) { this.errorH1 = fmh1; } public String getErrorH2() { return this.errorH2; } public void setErrorH2(String fmh2) { this.errorH2 = fmh2; } public String getErrorH3() { return this.errorH3; } public void setErrorH3(String fmh3) { this.errorH3 = fmh3; } public String getReasoning() { return this.reasoning; } public void setReasoning(String folgerep) { this.reasoning = folgerep; } public boolean isReasoning() { return "X".equalsIgnoreCase(this.getReasoning()); //$NON-NLS-1$ } public void setReasoning(boolean folgerep) { if (folgerep) { this.setReasoning("X"); //$NON-NLS-1$ } else { this.setReasoning(""); //$NON-NLS-1$ } } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public String getDistance() { return this.distance; } public void setDistance(String km) { this.distance = km; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getCustomerSupport() { return this.customerSupport; } public void setCustomerSupport(String rapsend) { this.customerSupport = rapsend; } public String getCustomerSupportText() { return this.customerSupportText; } public void setCustomerSupportText(String rapsendcom) { this.customerSupportText = rapsendcom; } public ReportStatus getReportStatus() { return this.reportStatus; } public void setReportStatus(String reportstatus) { this.reportStatus.set(reportstatus); } public void setReportStatus(ReportStatus reportstatus) { this.reportStatus = reportstatus; } public String getServicePlanMonth1() { return this.servicePlanMonth1; } public void setServicePlanMonth1(String savlfd1) { this.servicePlanMonth1 = savlfd1; } public String getServicePlanMonth2() { return this.servicePlanMonth2; } public void setServicePlanMonth2(String savlfd2) { this.servicePlanMonth2 = savlfd2; } public String getServicePlanMonth3() { return this.servicePlanMonth3; } public void setServicePlanMonth3(String savlfd3) { this.servicePlanMonth3 = savlfd3; } public String getServicePlanMonth4() { return this.servicePlanMonth4; } public void setServicePlanMonth4(String savlfd4) { this.servicePlanMonth4 = savlfd4; } public String getServicePlanMonth5() { return this.servicePlanMonth5; } public void setServicePlanMonth5(String savlfd5) { this.servicePlanMonth5 = savlfd5; } public String getServicePlanMonth6() { return this.servicePlanMonth6; } public void setServicePlanMonth6(String savlfd6) { this.servicePlanMonth6 = savlfd6; } public String getSafetyReport() { return this.safetyReport; } public void setSafetyReport(String secrap) { this.safetyReport = secrap; } public boolean isSafetyReport() { return "X".equalsIgnoreCase(this.getSafetyReport()); //$NON-NLS-1$ } public void setSafetyReport(boolean secrap) { if (secrap) { this.setSafetyReport("X"); //$NON-NLS-1$ } else { this.setSafetyReport(""); //$NON-NLS-1$ } } public String getSignatureFlag() { return this.signatureFlag; } public void setSignatureFlag(String signflg) { this.signatureFlag = signflg; } public boolean isSignatureFlag() { return "X".equalsIgnoreCase(this.getSignatureFlag()); //$NON-NLS-1$ } public void setSignatureFlag(boolean signflg) { if (signflg) { this.setSignatureFlag("X"); //$NON-NLS-1$ } else { this.setSignatureFlag(""); //$NON-NLS-1$ } } public String getExpenses() { return this.expenses; } public void setExpenses(String spesen) { this.expenses = spesen; } public String getIncidentAB() { return this.incidentAB; } public void setIncidentAB(String storc) { this.incidentAB = storc; } public String getPartialRepair() { return this.partialRepair; } public void setPartialRepair(String teilrep) { this.partialRepair = teilrep; } public boolean isPartialRepair() { return "X".equalsIgnoreCase(this.getPartialRepair()); //$NON-NLS-1$ } public void setPartialRepair(boolean teilrep) { if (teilrep) { this.setPartialRepair("X"); //$NON-NLS-1$ } else { this.setPartialRepair(""); //$NON-NLS-1$ } } public String getBilling() { return this.billing; } public void setBilling(String verrc) { this.billing = verrc; } public String getSignatureInfo() { return this.signatureInfo; } public void setSignatureInfo(String signinfo) { this.signatureInfo = signinfo; } public boolean isSignatureInfo() { return !"".equalsIgnoreCase(this.getSignatureInfo()); //$NON-NLS-1$ } public String getMonthYear() { return this.monthYear; } public void setMonthYear(String saverl) { this.monthYear = saverl; } public String getOrderNumber() { return this.orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public String getSignatureGuId() { return this.signatureGuId; } public void setSignatureGuId(String signguid) { this.signatureGuId = signguid; } public String getSignature() { return this.signature; } public void setSignature(String signpic) { this.signature = signpic; } public String getWorkType() { return this.workType; } public void setWorkType(String arba) { this.workType = arba; } public String getCollectively() { return this.collectively; } public void setCollectively(String signbundle) { this.collectively = signbundle; } public void setCollectively(boolean signbundle) { if (signbundle) { this.setCollectively("X"); //$NON-NLS-1$ } else { this.setCollectively(""); //$NON-NLS-1$ } } public boolean isCollectively() { return "X".equalsIgnoreCase(getCollectively()); //$NON-NLS-1$ } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String anlnr) { this.commissionNumber = anlnr; } public String getNoMaterial() { return noMaterial; } public void setNoMaterial(String noMaterial) { this.noMaterial = noMaterial; } public void setNoMaterial(boolean noMaterial) { if (noMaterial) { this.setNoMaterial("X"); //$NON-NLS-1$ } else { this.setNoMaterial(""); //$NON-NLS-1$ } } public boolean isNoMaterial() { return "X".equalsIgnoreCase(getNoMaterial()); //$NON-NLS-1$ } public List getTimes() { return this.times; } public void setTimes(DatabaseUtil dbutil, List mTimes) { this.times = mTimes; this.currentTime = 0; dbutil.insertJobReportTimeList(this); } public String getCycleOfInstallation() { return cycleOfInstallation; } public void setCycleOfInstallation(String cycleOfInstallation) { this.cycleOfInstallation = cycleOfInstallation; } public String getNoForm1() { return noForm1; } public void setNoForm1(String noForm1) { this.noForm1 = noForm1; } public String getNoForm2() { return noForm2; } public void setNoForm2(String noForm2) { this.noForm2 = noForm2; } public String getNoForm3() { return noForm3; } public void setNoForm3(String noForm3) { this.noForm3 = noForm3; } public String getServiceRefused() { return serviceRefused; } public void setServiceRefused(String serviceRefused) { this.serviceRefused = serviceRefused; } public String getOpenPending() { return openPending; } public void setOpenPending(String openPending) { this.openPending = openPending; } public boolean isOpenPending() { return "X".equalsIgnoreCase(getOpenPending()); //$NON-NLS-1$ } public void setOpenPending(boolean isOpenPending) { if (isOpenPending) { this.setOpenPending("X"); //$NON-NLS-1$ } else { this.setOpenPending(""); //$NON-NLS-1$ } } public String getGovernmentReport() { return governmentReport; } public void setGovernmentReport(String governmentReport) { this.governmentReport = governmentReport; } public boolean isGovernmentReport() { return "X".equalsIgnoreCase(getGovernmentReport()); //$NON-NLS-1$ } public void setGovernmentReport(boolean isGovernmentReport) { if (isGovernmentReport) { this.setGovernmentReport("X"); //$NON-NLS-1$ } else { this.setGovernmentReport(""); //$NON-NLS-1$ } } public String getChecklistState() { return checklistState; } public void setChecklistState(String checklistState) { this.checklistState = checklistState; } public boolean isChecklistState() { return "X".equalsIgnoreCase(getChecklistState()); //$NON-NLS-1$ } public boolean isChecklistStateUnselected() { return "U".equalsIgnoreCase(getChecklistState()); //$NON-NLS-1$ } public void setChecklistState(boolean isChecklistState) { if (isChecklistState) { this.setChecklistState("X"); //$NON-NLS-1$ } else { this.setChecklistState(""); //$NON-NLS-1$ } } public String getChecklistSIA() { return checklistSIA; } public void setChecklistSIA(String checklistSIA) { this.checklistSIA = checklistSIA; } public boolean isChecklistSIA() { return "X".equalsIgnoreCase(getChecklistSIA()); //$NON-NLS-1$ } public boolean isChecklistSIAUnselected() { return "U".equalsIgnoreCase(getChecklistSIA()); //$NON-NLS-1$ } public void setChecklistSIA(boolean isChecklistSIA) { if (isChecklistSIA) { this.setChecklistSIA("X"); //$NON-NLS-1$ } else { this.setChecklistSIA(""); //$NON-NLS-1$ } } public String getChecklistReady() { return checklistReady; } public void setChecklistReady(String checklistReady) { this.checklistReady = checklistReady; } public boolean isChecklistReady() { return "X".equalsIgnoreCase(getChecklistReady()); //$NON-NLS-1$ } public boolean isChecklistReadyUnselected() { return "U".equalsIgnoreCase(getChecklistReady()); //$NON-NLS-1$ } public void setChecklistReady(boolean isChecklistReady) { if (isChecklistReady) { this.setChecklistReady("X"); //$NON-NLS-1$ } else { this.setChecklistReady(""); //$NON-NLS-1$ } } public String getChecklistInstruction() { return checklistInstruction; } public void setChecklistInstruction(String checklistInstruction) { this.checklistInstruction = checklistInstruction; } public boolean isChecklistInstruction() { return "X".equalsIgnoreCase(getChecklistInstruction()); //$NON-NLS-1$ } public boolean isChecklistInstructionUnselected() { return "U".equalsIgnoreCase(getChecklistInstruction()); //$NON-NLS-1$ } public void setChecklistInstruction(boolean isChecklistInstruction) { if (isChecklistInstruction) { this.setChecklistInstruction("X"); //$NON-NLS-1$ } else { this.setChecklistInstruction(""); //$NON-NLS-1$ } } public String getChecklistVKF() { return checklistVKF; } public void setChecklistVKF(String checklistVKF) { this.checklistVKF = checklistVKF; } public boolean isChecklistVKF() { return "X".equalsIgnoreCase(getChecklistVKF()); //$NON-NLS-1$ } public boolean isChecklistVKFUnselected() { return "U".equalsIgnoreCase(getChecklistVKF()); //$NON-NLS-1$ } public void setChecklistVKF(boolean isChecklistVKF) { if (isChecklistVKF) { this.setChecklistVKF("X"); //$NON-NLS-1$ } else { this.setChecklistVKF(""); //$NON-NLS-1$ } } public String getChecklistTest() { return checklistTest; } public void setChecklistTest(String checklistTest) { this.checklistTest = checklistTest; } public boolean isChecklistTest() { return "X".equalsIgnoreCase(getChecklistTest()); //$NON-NLS-1$ } public boolean isChecklistTestUnselected() { return "U".equalsIgnoreCase(getChecklistTest()); //$NON-NLS-1$ } public void setChecklistTest(boolean isChecklistTest) { if (isChecklistTest) { this.setChecklistTest("X"); //$NON-NLS-1$ } else { this.setChecklistTest(""); //$NON-NLS-1$ } } public String getSignatureName() { return this.signatureName; } public void setSignatureName(String signName) { this.signatureName = signName; } public boolean isSignatureName() { return !"".equalsIgnoreCase(this.getSignatureName()); //$NON-NLS-1$ } public String getMonStk() { return monStk; } public void setMonStk(String monStk) { this.monStk = monStk; } public Date getNextInterventionDate() { return this.nextInterventionDate; } public void setNextInterventionDate(Date nextInterventionDate) { this.nextInterventionDate = nextInterventionDate; } public String getStateOfInstallation() { return stateOfInstallation; } public void setStateOfInstallation(String stateOfInstallation) { this.stateOfInstallation = stateOfInstallation; } public String getNextInterventionCode() { return this.nextInterventionCode; } public void setNextInterventionCode(String nextInterventionCode) { this.nextInterventionCode = nextInterventionCode; } /** * The change of the type of work in report have to be assumed to all existing timestamps of the report. * This concerns only the job types REP and SAV. * @param arba * @param dbutil */ public void setTimesWorkType(String arba, DatabaseUtil dbutil) { this.workType = arba; if(getJobType().isREP() || getJobType().isSAV()) { if (getTimes().size() > 0 && !workType.equalsIgnoreCase(getTimes().get(0).getWorkTypeCode())) { for (int i = 0; i < getTimes().size(); i++) { getTimes().get(i).setWorkTypeCode(getWorkType());; } setTimes(dbutil, new ArrayList(getTimes())); } } } /** * @param dbutil * @return amount of reports loaded for this job */ public int loadTimes(DatabaseUtil dbutil) { this.times = dbutil.selectJobReportTimeListByReport(this); boolean isTimeUpdate = false; for (int i = 0; i < times.size(); i++) { JobReportTime jobReportTime = times.get(i); if(CommonConstants.PLEASE_SELECT.equalsIgnoreCase(jobReportTime.getWorkTypeCode()) && !this.jobType.isMON()) { // in case start capturing time from TimeSheet default arba is wrong. isTimeUpdate = true; times.get(i).setWorkTypeCode(dbutil.selectJobByJobIdAndJobType(this.jobNumber, this.jobType.getCode()).getDefaultJobTimeARBA()); } } if(isTimeUpdate) { setTimes(dbutil, times); } this.currentTime = 0; return this.times.size(); } /** * @return The report currently set in the list */ public JobReportTime getCurrentTime() { if (this.times.isEmpty()) return new JobReportTime(); else return this.times.get(this.currentTime); } public void checkIfTimeStartOverOndDay(DatabaseUtil dbutil) { // log.info("check if time started over one day."); loadTimes(dbutil); Iterator itr = times.iterator(); while (itr.hasNext()) { JobReportTime jobReportTime = itr.next(); if (jobReportTime.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) { Calendar latestTime = Calendar.getInstance(); latestTime.setTime(jobReportTime.getDate()); latestTime.set(latestTime.get(Calendar.YEAR), latestTime.get(Calendar.MONTH), latestTime.get(Calendar.DATE), 23, 59, 59); if(Calendar.getInstance().getTimeInMillis() > latestTime.getTimeInMillis()){ // now after start date 23.59 -> set stop time to 23.59. jobReportTime.setStopTime(latestTime.getTime()); setTimes(dbutil, new ArrayList(times)); Job job = dbutil.selectJobByGUID(guId); job.setStatus(JobStatus.RECEIVED); dbutil.updateJob(job); break; } } } } public boolean isChecklistCompleted() { return true; } public boolean isChedklistEdited() { if (isChecklistStateUnselected() && isChecklistSIAUnselected() && isChecklistReadyUnselected() && isChecklistInstructionUnselected() && isChecklistVKFUnselected() && isChecklistTestUnselected()) { return false; } return true; } public List getParts() { return this.mats; } /** * @param dbutil * @return amount of reports loaded for this job */ public int loadParts(DatabaseUtil dbutil) { this.mats = dbutil.selectReportMaterialList(getGuId()); return this.mats.size(); } public List getMessages() { return this.messages; } /** * @param dbutil * @return amount of messages loaded for this report */ public int loadMessages(DatabaseUtil dbutil) { this.messages = dbutil.selectJobMessageListByReport(this); return this.messages.size(); } public List getMeasurements() { return this.measurements; } /** * @param dbutil * @return amount of measurements loaded for this report */ public int loadMeasurements(DatabaseUtil dbutil) { this.measurements = dbutil.selectReportMeasurementListByReport(this); return this.measurements.size(); } /** * @return Latest (most up to date) report of this job (current report is * set to this one) */ public JobReportTime getLatestReport() { this.currentTime = 0; return getCurrentTime(); } public boolean hasNextTime() { return this.times.size() > this.currentTime + 1; } /** * @return Next report of this job (in chronological order) * @throws IndexOutOfBoundsException */ public JobReportTime getNextTime() throws IndexOutOfBoundsException { int location = this.currentTime + 1; JobReportTime time = this.times.get(location); this.currentTime = location; return time; } public boolean isValid() { boolean result = true; StringBuilder error = new StringBuilder(); error.append("\n"); if ("".equals(getCommissionNumber().trim())) { error.append("CommissionNumber required \n"); result = false; } if (!getJobType().isMON() && "".equals(getWorkType().trim())) { error.append("WorkType required \n" ); result = false; } // Arbeitsart 05: Vertragsservice // Checkliste 00: Bitte w�hlen.. (Initialwert) // SAV ausgef�hrt (Monat) 00: --- (Initialwert) // SAV ausgef�hrt (Jahr) 00: --- (Initialwert) if (CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT.equalsIgnoreCase(getWorkType()) && getMonthYear().isEmpty()) { error.append("WorkType & MonthYear required \n" ); result = false; } // or // if ("".equals(getChecklist().trim())) { if ((getJobType().isSAV() && !(getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA) || getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_MAINTENANCE_VONOVIA))) || getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT)) { error.append("Checklist required \n" ); result = false; } } if (!CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER.equalsIgnoreCase(getCustomerSupport()) && !getCustomerSupport().trim().isEmpty() && getCustomerSupportText().trim().isEmpty()) { error.append("CustomerSupport & CustomerSupportText required \n"); result = false; } if (isCycleOfInstallationFlag && getCycleOfInstallation().isEmpty()) { error.append("Cycle of installation required \n" ); result = false; } log.info("is report valid -> " + result + " " + error.toString()); return result; } public List getImageAttachments() { return this.reportImageAttachments; } /** * @param dbutil * @return amount of reportImageAttachments loaded for this report */ public int loadImageAttachments(DatabaseUtil dbutil) { this.reportImageAttachments = dbutil.selectReportJobFileImageListByReport(this); return this.reportImageAttachments.size(); } public List getDocumentAttachments() { return this.reportDocumentAttachments; } /** * @param dbutil * @return amount of reportDocumentAttachments loaded for this report */ public int loadDocumentAttachments(DatabaseUtil dbutil) { this.reportDocumentAttachments = dbutil.selectReportJobFileDocumentListByReport(this); return this.reportDocumentAttachments.size(); } public List getFormInstances() { return this.formInstances; } /** * @param dbutil * @return amount of formInstances loaded for this report */ public int loadFormInstances(DatabaseUtil dbutil) { this.formInstances = dbutil.selectFormInstanceListByGuid(getGuId()); return this.formInstances.size(); } public Map> getDocumentFormDescMap() { Map> documentFormDescMap = new HashMap>(); for (JobFile jobFile : getDocumentAttachments()) { if (!documentFormDescMap.containsKey(jobFile.getFormDesc())) { List documents = new ArrayList(); documents.add(jobFile); documentFormDescMap.put(jobFile.getFormDesc(), documents); } else { documentFormDescMap.get(jobFile.getFormDesc()).add(jobFile); } } return documentFormDescMap; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMATORD */ public class ReportMaterial { private String guId = ""; //$NON-NLS-1$ private String sparePartNumber = ""; //$NON-NLS-1$ private int personalNumber = 0; private String commissionNumber = ""; //$NON-NLS-1$ private String amount = ""; //$NON-NLS-1$ private String delivery = ""; //$NON-NLS-1$ private String expressDelivery = ""; //$NON-NLS-1$ private String accountCode = ""; //$NON-NLS-1$ private String unit = ""; //$NON-NLS-1$ private int idx = 0; private String productName = ""; //$NON-NLS-1$ private String price = ""; //$NON-NLS-1$ private String barcode = ""; //$NON-NLS-1$ private String K14 = ""; //$NON-NLS-1$ private String explanationText = ""; private String otherTypeFlag = ""; public ReportMaterial() { // constructor } public ReportMaterial(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.ReportMaterial.IDX)); this.setExpressDelivery(rs.getString(DbConstants.ReportMaterial.EXPRESS_DELIVERY)); this.setGuid(rs.getString(DbConstants.ReportMaterial.GUID)); this.setSparePartNumber(rs.getString(DbConstants.ReportMaterial.NUMBER)); this.setDelivery(rs.getString(DbConstants.ReportMaterial.DELIVERY)); this.setPersonalNumber(rs.getInt(DbConstants.ReportMaterial.PERSONAL_NUMBER)); this.setAmount(rs.getString(DbConstants.ReportMaterial.AMOUNT)); this.setCommissionNumber(rs.getString(DbConstants.ReportMaterial.COMMISSION_NUMBER)); this.setAccountCode(rs.getString(DbConstants.ReportMaterial.ACCOUNT_CODE)); this.setUnit(rs.getString(DbConstants.ReportMaterial.UNIT)); this.setProductName(rs.getString(DbConstants.ReportMaterial.NAME)); this.setPrice(rs.getString(DbConstants.ReportMaterial.PRICE)); this.setBarcode(rs.getString(DbConstants.ReportMaterial.BARCODE)); this.setK14(rs.getString(DbConstants.ReportMaterial.K14)); this.setExplanationText(rs.getString(DbConstants.ReportMaterial.EXPLANATION_TEXT)); this.setOtherTypeFlag(rs.getString(DbConstants.ReportMaterial.OTHER_TYPE_FLAG)); } public String getExpressDelivery() { return this.expressDelivery; } public void setExpressDelivery(String expr) { this.expressDelivery = expr; } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public String getSparePartNumber() { return this.sparePartNumber; } public void setSparePartNumber(String matnr) { this.sparePartNumber = matnr; } public String getDelivery() { return this.delivery; } public void setDelivery(String mlif) { this.delivery = mlif; } public boolean isDelivery() { return "X".equalsIgnoreCase(this.getDelivery()); //$NON-NLS-1$ } public void setDelivery(boolean mlif) { if (mlif) { this.setDelivery("X"); //$NON-NLS-1$ } else { this.setDelivery(""); //$NON-NLS-1$ } } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getAmount() { return this.amount; } public void setAmount(String amount) { this.amount = amount; } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public String getAccountCode() { return this.accountCode; } public void setAccountCode(String verrc) { this.accountCode = verrc; } public int getIdx() { return this.idx; } public void setIdx(int idx) { this.idx = idx; } public String getUnit() { return this.unit; } public void setUnit(String maunit) { this.unit = maunit; } public String getProductName() { return this.productName; } public void setProductName(String maktx) { this.productName = maktx; } public String getPrice() { return this.price; } public void setPrice(String price) { this.price = price; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getK14() { return this.K14; } public void setK14(String k14) { this.K14 = k14; } public boolean isK14() { return "1".equalsIgnoreCase(this.getK14()); //$NON-NLS-1$ } public void setK14(boolean k14) { if (k14) { this.setK14("1"); //$NON-NLS-1$ } else { this.setK14("0"); //$NON-NLS-1$ } } public String getExplanationText() { return explanationText; } public void setExplanationText(String explanationText) { this.explanationText = explanationText; } public String getOtherTypeFlag() { return otherTypeFlag; } public void setOtherTypeFlag(String otherTypeFlag) { this.otherTypeFlag = otherTypeFlag; } public boolean isOtherType() { return "1".equalsIgnoreCase(this.getOtherTypeFlag()); //$NON-NLS-1$ } public void setOtherType(boolean otherType) { if (otherType) { this.setOtherTypeFlag("1"); //$NON-NLS-1$ } else { this.setOtherTypeFlag("0"); //$NON-NLS-1$ } } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMEAS */ public class ReportMeasurement { private String guId = ""; private String measurementPoint = ""; private int personalNumber = 0; private String commissionNumber = ""; private String neasurement = ""; private String dynamicPowerPeakValue = ""; private String dynamicTime = ""; private String staticEndPower = ""; private String deviceType = ""; private String sNOfDevice = ""; private Date calibrationDate = new Date(); public ReportMeasurement() { // constructor } public ReportMeasurement(RecordSet rs) { this.setGuid(rs.getString(DbConstants.ReportMeasurement.GUID)); this.setMeasurementPoint(rs.getString(DbConstants.ReportMeasurement.MEASURING_POINT)); this.setCommissionNumber(rs.getString(DbConstants.ReportMeasurement.COMMISSION_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.ReportMeasurement.PERSONAL_NUMBER)); this.setMeasurement(rs.getString(DbConstants.ReportMeasurement.MEASUREMENT)); this.setDynamicPowerPeakValue(rs.getString(DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE)); this.setDynamicTime(rs.getString(DbConstants.ReportMeasurement.DYNAMIC_TIME)); this.setStaticEndPower(rs.getString(DbConstants.ReportMeasurement.STATIC_END_POWER)); this.setDeviceType(rs.getString(DbConstants.ReportMeasurement.DEVICE_TYPE)); this.setSNOfDevice(rs.getString(DbConstants.ReportMeasurement.SN_OF_DEVICE)); this.setCalibrationDate(rs.getDate(DbConstants.ReportMeasurement.CALIBRATION_DATE)); } public String getGuId() { return this.guId; } public void setGuid(String guid) { this.guId = guid; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getMeasurementPoint() { return measurementPoint; } public void setMeasurementPoint(String measurementPoint) { this.measurementPoint = measurementPoint; } public String getCommissionNumber() { return commissionNumber; } public void setCommissionNumber(String CommissionNumber) { this.commissionNumber = CommissionNumber; } public String getMeasurement() { return neasurement; } public void setMeasurement(String measurement) { neasurement = measurement; } public String getDynamicPowerPeakValue() { return dynamicPowerPeakValue; } public void setDynamicPowerPeakValue(String dynamicPowerPeakValue) { this.dynamicPowerPeakValue = dynamicPowerPeakValue; } public String getDynamicTime() { return dynamicTime; } public void setDynamicTime(String dynamicTime) { this.dynamicTime = dynamicTime; } public String getStaticEndPower() { return staticEndPower; } public void setStaticEndPower(String staticEndPower) { this.staticEndPower = staticEndPower; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getSNOfDevice() { return sNOfDevice; } public void setSNOfDevice(String sNOfDevice) { this.sNOfDevice = sNOfDevice; } public Date getCalibrationDate() { return this.calibrationDate; } public void setCalibrationDate(Date calibrationDate) { this.calibrationDate = calibrationDate; } public void setGuId(String guId) { this.guId = guId; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDCMSGC */ public class ReportMessage { private String messageCode; private String message; private String mKND; private String mKDZ; private String mABTL; private String refreshFlag = ""; //$NON-NLS-1$ ReportMessage() { } public ReportMessage(RecordSet rs) { this.setMessageCode(rs.getString(DbConstants.ReportMessage.CODE)); this.setMessage(rs.getString(DbConstants.ReportMessage.TEXT)); this.setKND(rs.getString(DbConstants.ReportMessage.KND)); this.setKDZ(rs.getString(DbConstants.ReportMessage.KDZ)); this.setABTL(rs.getString(DbConstants.ReportMessage.ABTL)); this.setRefreshFlag(rs.getString(DbConstants.JobMonText.REFRESH_FLAG)); } public String getMessageCode() { return this.messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getKND() { return this.mKND; } public void setKND(String knd) { this.mKND = knd; } public String getKDZ() { return this.mKDZ; } public void setKDZ(String kdz) { this.mKDZ = kdz; } public String getABTL() { return this.mABTL; } public void setABTL(String abtl) { this.mABTL = abtl; } public boolean isKND() { boolean result = false; if ("X".equalsIgnoreCase(this.getKND())) { //$NON-NLS-1$ result = true; } return result; } public void setKND(boolean isKND) { if (isKND) this.setKND("X"); //$NON-NLS-1$ } public boolean isKDZ() { boolean result = false; if ("X".equalsIgnoreCase(this.getKDZ())) { //$NON-NLS-1$ result = true; } return result; } public void setKDZ(boolean isKDZ) { if (isKDZ) { this.setKDZ("X"); //$NON-NLS-1$ } } public boolean isABTL() { boolean result = false; if ("X".equalsIgnoreCase(this.getABTL())) { //$NON-NLS-1$ result = true; } return result; } public void setABTL(boolean isABTL) { if (isABTL) this.setABTL("X"); //$NON-NLS-1$ } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMC */ public class ServerJob { private String jobNumber; private JobType jobType; private String commissionNumber; private String street; private String city; private String postalCode; private String location; private String serviceContractType; private String monthYear; private String personalNumber; ServerJob() { } public ServerJob(RecordSet rs) { this.setJobType(rs.getString(DbConstants.ServerJob.JOB_TYPE)); this.setCity(rs.getString(DbConstants.ServerJob.CITY)); this.setJobNumber(rs.getString(DbConstants.ServerJob.JOB_NUMBER)); this.setLocation(rs.getString(DbConstants.ServerJob.LOCATION)); this.setPostalCode(rs.getString(DbConstants.ServerJob.PASTAL_CODE)); this.setServiceContractType(rs.getString(DbConstants.ServerJob.SERVICE_CONTRACT_TYPE)); this.setMonthYear(rs.getString(DbConstants.ServerJob.MONTH_YEAR)); this.setStreet(rs.getString(DbConstants.ServerJob.STREET)); this.setCommissionNumber(rs.getString(DbConstants.ServerJob.COMMISSION_NUMBER)); this.setPersonalNumber(rs.getString(DbConstants.ServerJob.PERSONAL_NUMBER)); } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getCity() { return this.city; } public void setCity(String city1) { this.city = city1; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } public String getLocation() { return this.location; } public void setLocation(String name4) { this.location = name4; } public String getPostalCode() { return this.postalCode; } public void setPostalCode(String post_code1) { this.postalCode = post_code1; } public String getServiceContractType() { return this.serviceContractType; } public void setServiceContractType(String savc) { this.serviceContractType = savc; } public String getMonthYear() { return this.monthYear; } public void setMonthYear(String savoff) { this.monthYear = savoff; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public String getCommissionNumber() { return this.commissionNumber; } public String getcommissionNumberNoLeadingZero() { String vbeln = this.commissionNumber; while (vbeln.length() > 0 && vbeln.charAt(0) == '0') { vbeln = vbeln.substring(1); } return vbeln; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public void setPersonalNumber(String lkdpernr) { this.personalNumber = lkdpernr; } public String getPersonalNumber() { return this.personalNumber; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBBEGRSAV */ public class ServiceRefused { private String code = ""; private String language = ""; private String text = ""; private String refreshFlag = ""; ServiceRefused() { } public ServiceRefused(RecordSet rs) { this.setCode((rs.getString(DbConstants.ServiceRefused.SAVRET))); this.setLanguage(rs.getString(DbConstants.ServiceRefused.LANGUAGE)); this.setText(rs.getString(DbConstants.ServiceRefused.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.ServiceRefused.REFRESH_FLAG)); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZSHORTMSG */ public class ShortMessage { private int personalNumber = 0; private String messageKey = ""; //$NON-NLS-1$ private String subject = ""; //$NON-NLS-1$ private String confirm = ""; //$NON-NLS-1$ private String message = ""; //$NON-NLS-1$ private String status = ""; //$NON-NLS-1$ private String receiveDate = ""; //$NON-NLS-1$ private Date receiveTime = new Date(0); public ShortMessage() { // constructor } public ShortMessage(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.ShortMessage.PERSONAL_NUMBER)); this.setMessageKey(rs.getString(DbConstants.ShortMessage.MESSAGE_KEY)); this.setSubject(rs.getString(DbConstants.ShortMessage.SUBJECT)); this.setConfirm(rs.getString(DbConstants.ShortMessage.CONFIRM)); this.setMessage(rs.getString(DbConstants.ShortMessage.MESSAGE)); this.setStatus(rs.getString(DbConstants.ShortMessage.STATUS)); this.setReceiveDate(rs.getString(DbConstants.ShortMessage.RECEIVED_DATE)); this.setReceiveTime(rs.getDate(DbConstants.ShortMessage.RECEIVED_TIME)); } public int getPersonalNumber() { return personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getMessageKey() { return messageKey; } public void setMessageKey(String tdname) { this.messageKey = tdname; } public String getSubject() { return subject; } public void setSubject(String betreff) { this.subject = betreff; } public String getConfirm() { return confirm; } public boolean isConfirmed() { return "X".equalsIgnoreCase(this.getConfirm()); //$NON-NLS-1$ } public void isConfirmed(boolean isConfirmed) { if (isConfirmed) { this.setConfirm("X"); //$NON-NLS-1$ } else { this.setConfirm(""); //$NON-NLS-1$ } } public void setConfirm(String bestaetigt) { this.confirm = bestaetigt; } public String getMessage() { return message; } public void setMessage(String ltext) { this.message = ltext; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getReceiveDate() { return receiveDate; } public void setReceiveDate(String erhalten) { this.receiveDate = erhalten; } public Date getReceiveTime() { return receiveTime; } public void setReceiveTime(Date eingang) { this.receiveTime = eingang; } public int getStatusColor() { int result; if (getStatus().equalsIgnoreCase(CommonConstants.ShortMessage.Status.RECEIVED)) { result = LayoutUtils.DEFAULT_RED; } else if (getStatus().equalsIgnoreCase(CommonConstants.ShortMessage.Status.READ)) { result = LayoutUtils.DEFAULT_GREEN; } else { result = LayoutUtils.DEFAULT_DARK_GRAY; } return result; } public String getConfirmedMsg() { if (isConfirmed()) { return "!"; //$NON-NLS-1$ } return ""; //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBBTRZUSTT */ public class StateOfInstallation { private String code = ""; private String text = ""; private String refreshFlag = ""; StateOfInstallation() { } public StateOfInstallation(RecordSet rs) { this.setCode(rs.getString(DbConstants.StateOfInstallation.CODE)); this.setText(rs.getString(DbConstants.StateOfInstallation.TEXT)); this.setRefreshFlag(rs.getString(DbConstants.StateOfInstallation.REFRESH_FLAG)); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getRefreshFlag() { return this.refreshFlag; } public void setRefreshFlag(String refreshed) { this.refreshFlag = refreshed; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Calendar; import java.util.Date; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.TimesheetValidation; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.util.DateUtils; /** * Object representing users working time. Implements Comparable interface * because the list of times of a certain day must be in the correct order. * In the Database -> ZKDMATIME * @author paulib * */ public class TimeSheet implements Comparable { private int idx = 0; private int personalNumber = 0; private Date date = Calendar.getInstance().getTime(); private Date startTime = DateUtils.getInitialDateTime(); private Date stopTime = DateUtils.getInitialDateTime(); private String commissionNumber = ""; //$NON-NLS-1$ private String costCenter = ""; //$NON-NLS-1$ private String workTypeCode = ""; //$NON-NLS-1$ private String callFlag = ""; //$NON-NLS-1$ protected TimeSheet() { } public TimeSheet(int pernr) { this.setPersonalNumber(pernr); } public TimeSheet(RecordSet rs) { this.setIdx(rs.getInt(DbConstants.TimeSheet.IDX)); this.setPersonalNumber(rs.getInt(DbConstants.TimeSheet.PERSONAL_NUMBER)); this.setDate(rs.getDate(DbConstants.TimeSheet.DATE)); this.setStartTime(rs.getDate(DbConstants.TimeSheet.START_TIME)); this.setStopTime(rs.getDate(DbConstants.TimeSheet.STOP_TIME)); this.setCostCenter(rs.getString(DbConstants.TimeSheet.COST_CENTER)); this.setWorkTypeCode(rs.getString(DbConstants.TimeSheet.WORK_TYPE_CODE)); this.setCallFlag(rs.getString(DbConstants.TimeSheet.CALL_FLAG)); } @Override public int compareTo(Object o) { TimeSheet zkdmatime = (TimeSheet) o; return this.getStartTime().compareTo(zkdmatime.getStartTime()); } public Date getStopTime() { return this.stopTime; } public void setStopTime(Date bis) { this.stopTime = bis; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getCostCenter() { return this.costCenter; } public void setCostCenter(String kostl) { this.costCenter = kostl; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public boolean isCallFlag() { return "X".equalsIgnoreCase(this.getCallFlag()); //$NON-NLS-1$ } public void setCallFlag(boolean pikett) { if (pikett) { this.setCallFlag("X"); //$NON-NLS-1$ } else { this.setCallFlag(""); //$NON-NLS-1$ } } public String getCallFlag() { return this.callFlag; } public void setCallFlag(String pikett) { this.callFlag = pikett; } public String getCommissionNumber() { return this.commissionNumber; } public void setCommissionNumber(String vbln) { this.commissionNumber = vbln; } public Date getStartTime() { return this.startTime; } public void setStartTime(Date von) { this.startTime = von; } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String arba) { this.workTypeCode = arba; } public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public TimesheetValidation validate() { TimesheetValidation result = new TimesheetValidation(); // No working type selected if ("".equalsIgnoreCase(getWorkTypeCode()) || "99".equalsIgnoreCase(getWorkTypeCode())) { //$NON-NLS-1$ //$NON-NLS-2$ result.setValid(false); result.setInitialArbaError(true); } // Initial value for VON is still set if (getStartTime().compareTo(DateUtils.getInitialDateTime()) == 0) { result.setValid(false); result.setInitialVonError(true); } // Initial value for BIS is still set if (getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) { result.setValid(false); result.setInitialBisError(true); } // Initial value for VON is still set if (getStartTime().compareTo(getStopTime()) > 0) { result.setValid(false); result.setVonBiggerBisError(true); } return result; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.TimeSheet.TIME_SHEET, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.TimeSheet.TIME_SHEET, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.annotation.Nullable; import android.util.Base64; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.BitmapConverterUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAEXPNSPICS */ public class VariousExpenseFile { public static final Log log = LogFactory.getLog(VariousExpenseFile.class); private int personalNumber = 0; private Date date = new Date(); private String variousExpensesFileId = ""; private String description = ""; private FormType formType = new FormType(); private String signpicAt = ""; //$NON-NLS-1$ public VariousExpenseFile() { } public VariousExpenseFile(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.VariousExpenseFile.PERSONAL_NUMBER)); this.setDate(rs.getDate(DbConstants.VariousExpenses.DATE)); this.setVariousExpensesFileId(rs.getString(DbConstants.VariousExpenseFile.IDX)); this.setDescription(rs.getString(DbConstants.VariousExpenseFile.DESCRIPTION)); this.setFormType(new FormType(rs.getString(DbConstants.VariousExpenseFile.FORM_TYPE))); this.setSignPicAt(rs.getString(DbConstants.VariousExpenseFile.SIGN_PIC_AT)); } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getVariousExpensesFileId() { return variousExpensesFileId; } public void setVariousExpensesFileId(String variousExpensesFileId) { this.variousExpensesFileId = variousExpensesFileId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setSignPicBitmap(Bitmap bitmap) { setSignPicAt(BitmapConverterUtil.bitMapToString(bitmap)); } public FormType getFormType() { return formType; } public void setFormType(FormType formType) { this.formType = formType; } public String getSignpicAt() { return signpicAt; } public void setSignPicAt(String signpicAt) { this.signpicAt = signpicAt; } public Bitmap getSignPicBitmap() { return BitmapConverterUtil.stringToBitMap(signpicAt); } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.JobFile.JOB_FILE, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.JobFile.JOB_FILE, db, folder); } // public boolean isValid() { // boolean result = true; // StringBuilder error = new StringBuilder(); // error.append("\n"); // // if(equals(getGuid().trim().isEmpty())) { // error.append("Guid required \n"); // // result = false; // } // // if(getJobNumber().trim().isEmpty()) { // error.append("JobNumber required \n" ); // // result = false; // } // // if(getJobFileId().trim().isEmpty()) { // error.append("FileId required \n" ); // // result = false; // } // // if(getJobType().toString().isEmpty()) { // error.append("JobType required \n" ); // result = false; // } // // if(getType().trim().isEmpty()) { // error.append("Type required \n" ); // // result = false; // } // // if(getType().trim().equalsIgnoreCase("F") && getFormType().isINITIAL()) { // error.append("FormType required \n" ); // // result = false; // } // // if(getSignpicAt().toString().trim().isEmpty()) { // error.append("Signpic required \n" ); // // result = false; // } // // log.info("is JobFile valid -> " + result + " " + error.toString()); // // return result; // } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAEXPNSDIV */ public class VariousExpenses { private int personalNumber = 0; private Date date = new Date(); private String variousExpensesId = ""; private String amount = ""; private String expensesCode = ""; private VariousExpenseFile variousExpensesFile = null; VariousExpenses() { } public VariousExpenses(Date datum, int pernr, String variousExpensesId) { this.setDate(datum); this.setPersonalNumber(pernr); } public VariousExpenses(RecordSet rs) { this.setPersonalNumber(rs.getInt(DbConstants.VariousExpenses.PERSONAL_NUMBER)); this.setDate(rs.getDate(DbConstants.VariousExpenses.DATE)); this.setVariousExpensesId(rs.getString(DbConstants.VariousExpenses.IDX)); this.setAmount(rs.getString(DbConstants.VariousExpenses.AMOUNT)); this.setExpensesCode(rs.getString(DbConstants.VariousExpenses.EXPENSES_CODE)); } public boolean isInitial() { return personalNumber == 0 &&"".equalsIgnoreCase(this.variousExpensesId) && "".equalsIgnoreCase(this.amount) && "".equalsIgnoreCase(this.expensesCode) ; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getVariousExpensesId() { return variousExpensesId; } public void setVariousExpensesId(String variousExpensesId) { this.variousExpensesId = variousExpensesId; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getExpensesCode() { return expensesCode; } public void setExpensesCode(String expensesCode) { this.expensesCode = expensesCode; } public VariousExpenseFile getVariousExpensesFile() { if (variousExpensesFile == null) { variousExpensesFile = new VariousExpenseFile(); } return variousExpensesFile; } public void setVariousExpensesFile(VariousExpenseFile variousExpensesFile) { this.variousExpensesFile = variousExpensesFile; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Expenses.EXPENSES, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Expenses.EXPENSES, db, folder); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBFZLGSYNC */ public class VehicleInventory { private String storageLocation = ""; private String materialNumber = ""; private String materialName = ""; private String stockOfMaterial = ""; private String unit = ""; public VehicleInventory() { } public VehicleInventory(RecordSet rs) { this.setStorageLocation(rs.getString(DbConstants.VehicleInventory.STORAGE_LOCATION)); this.setMaterialNumber(rs.getString(DbConstants.VehicleInventory.MATERIAL_NUMBER)); this.setMaterialName(rs.getString(DbConstants.VehicleInventory.MATERIAL_NAME)); this.setStockOfMaterial(rs.getString(DbConstants.VehicleInventory.STOCK_OF_MATERIAL)); this.setUnit(rs.getString(DbConstants.VehicleInventory.UNIT)); } public String getStorageLocation() { return storageLocation; } public void setStorageLocation(String storageLocation) { this.storageLocation = storageLocation; } public String getMaterialNumber() { return materialNumber; } public void setMaterialNumber(String materialNumber) { this.materialNumber = materialNumber; } public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } public String getStockOfMaterial() { return stockOfMaterial; } public void setStockOfMaterial(String stockOfMaterial) { this.stockOfMaterial = stockOfMaterial; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } } package ch.mfiles.kaba.kolibri.common.businessobjects; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZARBEITSART */ public class WorkType { private String workTypeCode = ""; //$NON-NLS-1$ private String group = ""; //$NON-NLS-1$ private String text = ""; //$NON-NLS-1$ private String guarantee = ""; WorkType() { } public WorkType(RecordSet rs) { this.setWorkTypeCode(rs.getString(DbConstants.WorkType.CODE)); this.setGroup(rs.getString(DbConstants.WorkType.GROUP)); this.setText(rs.getString(DbConstants.WorkType.TEXT)); this.setGuarantee(rs.getString(DbConstants.WorkType.GUARANTEE)); } public String getWorkTypeCode() { return this.workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } public String getGroup() { return this.group; } public void setGroup(String group) { this.group = group; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getGuarantee() { return guarantee; } public void setGuarantee(String guarantee) { this.guarantee = guarantee; } public boolean isGuarantee() { return "X".equalsIgnoreCase(this.getGuarantee()); } public void setGuarantee(boolean isGuarantee) { if (isGuarantee) { this.setGuarantee("X"); } else { this.setGuarantee(""); } } } package ch.mfiles.kaba.kolibri.common.forms.adapters; import java.util.List; import android.content.Context; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; public class CustomArrayAdapter extends ArrayAdapter { public CustomArrayAdapter(Context context, int textViewResourceId, List spinnerList) { super(context, textViewResourceId, spinnerList); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return view; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getDropDownView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return view; } } package ch.mfiles.kaba.kolibri.common.forms.adapters; public class CustomSpinnerItem { private String id; private String name; private String description; public CustomSpinnerItem(String id, String name) { this.id = id; this.name = name; } public CustomSpinnerItem(String id, String name, String description) { this.id = id; this.name = name; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } // to display object as a string in spinner @Override public String toString() { return name; } @Override public boolean equals(Object obj) { if (obj instanceof CustomSpinnerItem) { CustomSpinnerItem c = (CustomSpinnerItem) obj; if (c.getName().equals(name) && c.getId() == id && c.getDescription() == description) { return true; } } return false; } @Override public int hashCode(){ return this.hashCode(); } } package ch.mfiles.kaba.kolibri.common.forms.adapters; import com.stepstone.stepper.adapter.AbstractStepAdapter; import com.stepstone.stepper.viewmodel.StepViewModel; import android.content.Context; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.util.StepUtil; public class StepAdapter extends AbstractStepAdapter { private StepUtil[] mStepUtils; public StepAdapter(Context context, StepUtil...stepUtils) { super(context); this.mStepUtils = stepUtils; } public StepUtil createStep(int position) { return mStepUtils[position]; } public StepUtil findStep(int position) { return mStepUtils[position]; } @Override public int getCount() { return mStepUtils.length; } @Override public StepViewModel getViewModel(int position) { return new StepViewModel.Builder(context).setTitle( "Title pos " + position).create(); } @Override public Object instantiateItem(ViewGroup container, int position) { // create view for given position container.addView(mStepUtils[position].getView()); // create step for the position if it does not already exist if (findStep(position) == null) createStep(position); return mStepUtils[position].getView(); }; @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); }; @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } package ch.mfiles.kaba.kolibri.common.forms.dlg; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.design.widget.Snackbar; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * New Form. */ public abstract class DialogForm extends Form { public static Application app; // don't make this CommonApplication /** * Base class for all Dialog interfaces. The dialog must be called with a * derived class. Derived classes hold a model of the dialog's content. * * @author joerg * */ public static class DialogInterface { private boolean cancelled; /** * @return Returns {@code true} if the dialog was cancelled or the back * button was pressed. */ public boolean isCancelled() { return cancelled; } } private DialogInterface m_dialogInterface = null; /** * The dialog's save action. */ protected ActionCtrl saveButton = null; /** * Sets the Toolbar's navigation icon with a left arrow. If clicked the * Form's {@link #onBackPressed()} method is invoked on the AM thread and * {@link DialogInterface#isCancelled()} will return true. The Form's menu * consists of a sole save action rendered by a disk symbol. *

* Derived classes call this implementation and returen their own View. * * @return Returns null. */ @Override public View onFormLoad(Context context, LayoutInflater inflater) { final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // FIXME: derive from common color scheme // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); // create save action saveButton = addActionCtrl(false, true, 9, "onSavePressed"); //$NON-NLS-1$ setEnableSaveButton(true); return null; } /** * Sets the dialog to cancelled and returns {@link Application#closeForm()}. */ @Override public ApplicationEvent onBackPressed() { if (m_dialogInterface != null) m_dialogInterface.cancelled = true; return app.closeForm(); } /** * Called when the dialog's save action was clicked. *

* Validates the dialog's content using {@link #validate()}. If a validation * error occurred, the causing view is rendered with a reddish background * color (if possible) and the validation message is shown in a SnackBar. * Only if no validation error occurred, the Dialog's { {@link #onSave()} * method is called and the form closed if successful. *

* Derived dialogs use {@link #onSave()} to implement special actions after * validation if the user requested to save the dialog data. * * @return */ protected ApplicationEvent onSavePressed() { KeyboardUtil.closeKeyboard(appman, getView()); // get validation result ValidationResult result = validate(); if (result == null && onSave()) { if (m_dialogInterface != null) m_dialogInterface.cancelled = false; return app.closeForm(); } if (result != null) { Snackbar.make(getView(), result.message, Snackbar.LENGTH_LONG).setCallback(new Snackbar.Callback() { @Override public void onDismissed(Snackbar snackbar, int event) { validationRemoveHighlight(); } }).show(); validationHighlightBadView(result.badView); return null; } validationRemoveHighlight(); return null; } private View m_highlightedView = null; private Drawable m_highlightedViewBackground = null; private TextWatcher m_highlightedViewWatcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if (m_highlightedView == null) return; validationRemoveHighlight(); } }; /** * Highlight the given view (if supported). * * @param view */ protected void validationHighlightBadView(View view) { // make specific views show highlighted if (view instanceof EditText) { EditText editText = (EditText) view; m_highlightedView = editText; m_highlightedViewBackground = editText.getBackground(); // FIXME: derive from common color scheme editText.setBackgroundColor(Color.rgb(255, 190, 190)); editText.removeTextChangedListener(m_highlightedViewWatcher); editText.addTextChangedListener(m_highlightedViewWatcher); } } /** * Removes the hightlight from the currently highligted view (if any). */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) protected void validationRemoveHighlight() { if (m_highlightedView == null) return; // reset background if (m_highlightedViewBackground != null) m_highlightedView.setBackground(m_highlightedViewBackground); m_highlightedView = null; m_highlightedViewBackground = null; } /** * Called when the user performed the save action and no validation error * did occur. *

* This implementation returns always true. * * @return Returns true if the save was successful, * false otherwise. */ protected boolean onSave() { return true; } /** * Result of a dialog validation. * * @author joerg * */ public static class ValidationResult { /** * The first view as seen from top to bottom, left to right, that * doesn't pass validation test. */ public View badView; /** * The message why the validation failed. */ public String message; public ValidationResult(View badView, String message) { this.badView = badView; this.message = message; } } /** * This method gets called, when the user requests to save the dialog's * data. *

* This implementation always returns null indicating a * successful validation. *

* Derived dialogs replace this method to add dialog specific validations. * * @return The result of the validation. */ protected ValidationResult validate() { return null; } /** * Accepts a {@link DialogInterface} to report the user request to the * calling form: save or cancel. *

* Derived classes override this method to get a reference to the derived * dialog specific interface and initialice the dialog accordingly. * * @param The * parameter given on form call must be derived from * {@link DialogInterface}. */ @Override public void onFormCall(Object parameter) { m_dialogInterface = (DialogInterface) parameter; m_dialogInterface.cancelled = false; validationRemoveHighlight(); } public void setEnableSaveButton(boolean enabled) { ImagesUtil imagesUtil = ImagesUtil.getInstance(app); Image saveImage; if (enabled) { saveImage = imagesUtil.getImage(ImagesUtil.Images.SAVE_WHITE, CommonConstants.Images.IMAGE_DPI); } else { saveImage = imagesUtil.getImage(ImagesUtil.Images.SAVE_WHITE_DISABLED, CommonConstants.Images.IMAGE_DPI); } saveButton.setImage(saveImage); saveButton.setEnabled(enabled); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.regex.Pattern; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.View.OnFocusChangeListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class ExpenseMaskWatcher extends Watcher { public ExpenseMaskWatcher(final MDEditText editText) { super(editText, Pattern.compile(CommonConstants.TimeSheet.REGEX)); editText.setDirectionRight(true); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String userInput = editText.getText().toString(); if (userInput.length() < 5) { editText.setText(""); return; } else { format(); } } else { String userInput = editText.getText().toString(); String temps[] = userInput.split(" "); if (temps.length > 1 && !TextUtils.isEmpty(temps[1])) { userInput = temps[1]; } editText.setTextAndSelection(userInput); } } }); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if (!editText.isFocused()) { editText.removeTextChangedListener(this); format(); editText.addTextChangedListener(this); } } }); } private void format() { String userInput = editText.getText().toString(); String temps[] = userInput.split(" "); if (temps.length > 1 && !TextUtils.isEmpty(temps[1])) { temps[1] = StringUtil.removeLettersAndCountDot(temps[1], '.'); if (temps[1].isEmpty()) { editText.setText(userInput); } try { Locale locale = Locale.ENGLISH; if (temps[1].contains(",")) { locale = Locale.GERMAN; } float floatValue = Float .valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(temps[1]))); if (floatValue > 999.99) { floatValue = (float) 999.99; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("##0.00", symbols); format.setMaximumFractionDigits(2); if (floatValue > 0) { temps[1] = format.format(floatValue); userInput = temps[0] + " " + temps[1]; } else { userInput = ""; } editText.setText(userInput); } catch (NumberFormatException e) { editText.setText(userInput); } catch (ParseException e) { editText.setText(userInput); } } } @Override public String toString() { format(); return super.toString(); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.util.regex.Matcher; import java.util.regex.Pattern; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class MaterialNumberMaskWatcher extends Watcher { public MaterialNumberMaskWatcher(final MDEditText materialNumber) { super(materialNumber, Pattern.compile(CommonConstants.Material.REGEX)); } protected void afterTextChanged(String value) { // 45-1234-123/12 if (beforeCharSequence < afterCharSequence) { value = StringUtil.getMaterialNoFromText(value); Matcher matcher = pattern.matcher(value.trim()); if (matcher.matches() || matcher.hitEnd()) { if (!editText.toString().equalsIgnoreCase(value)) { editText.setTextAndSelection(value); } } } if (editText.hasFocus()) { editText.clearError(); } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.TextUtils; import android.view.View; import android.view.View.OnFocusChangeListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class VehicleMaskWatcher extends Watcher { public VehicleMaskWatcher(final MDEditText editText) { super(editText, Pattern.compile(CommonConstants.TimeSheet.VEHICLE_REGEX)); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String userInput = editText.getText().toString(); if (!TextUtils.isEmpty(userInput)) { try { Locale locale = Locale.ENGLISH; if (userInput.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(userInput))); if(floatValue > 1999999.9) { floatValue = (float) 1999999.9; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("#######.00", symbols); userInput = format.format(floatValue); } catch (NumberFormatException e) { userInput = ""; } catch (ParseException e) { userInput = ""; } } editText.setTextAndSelection(userInput); } } }); } protected void afterTextChanged(String value) { // 9999999.9 if (beforeCharSequence < afterCharSequence) { if (value.length() == 7 && !StringUtil.findChar(value, '.')) { value = value + "."; //$NON-NLS-1$ editText.setTextAndSelection(value); } } Matcher matcher = pattern.matcher(value); if (!matcher.matches() && !matcher.hitEnd()) { editText.setTextAndSelection(value); } if (editText.hasFocus()) { editText.clearError(); } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks; import java.util.regex.Pattern; import android.text.Editable; import android.text.TextWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; public class Watcher implements TextWatcher{ public int beforeCharSequence; public int afterCharSequence; public MDEditText editText; public Pattern pattern; boolean active = false; public Watcher(final MDEditText editText, Pattern pattern) { this.editText = editText; this.pattern = pattern; } @Override public void afterTextChanged(Editable s) { // materialNumber.removeTextChangedListener(this); if (active) // prevent recursions return; active = true; try { // ... do 'the thing'... including a rather expensive RegEx operation // or even replace the RegEx code by a handmade algorithm afterTextChanged(s.toString()); } finally { active = false; } // materialNumber.addTextChangedListener(this); } protected void afterTextChanged(String text) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class CheckBoxListWidget extends DetailListWidget { public CheckBoxListWidget(Context context) { this(context, null); } public CheckBoxListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public CheckBoxListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public CheckBoxListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new CheckBoxListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class CheckBoxListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_LEFT_CHECK_BOX = 1070; private static final int ID_LEFT_CHECK = 1090; private Context context; public CheckBoxListWidgetAdapter(Context context, List coll) { super(context, coll); mData = coll; this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { FrameLayout frameLayout = new FrameLayout(context); LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); endFrameParams.gravity = Gravity.CENTER | Gravity.CENTER_VERTICAL; frameLayout.setLayoutParams(endFrameParams); FrameLayout.LayoutParams checkBoxParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); checkBoxParams.gravity = Gravity.CENTER ; checkBoxParams.height = 80; checkBoxParams.width = 80; final CheckBox checkBox = new CheckBox(context); checkBox.setId(ID_LEFT_CHECK_BOX); checkBox.setChecked(false); checkBox.setLayoutParams(checkBoxParams); frameLayout.addView(checkBox); FrameLayout.LayoutParams iconParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); iconParams.gravity = Gravity.CENTER ; iconParams.height = 80; iconParams.width = 80; ImageView icon = new ImageView(context); icon.setId(ID_LEFT_CHECK); icon.setLayoutParams(iconParams); frameLayout.addView(icon); return frameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final CheckBoxListWidgetItem dataSet = (CheckBoxListWidgetItem) mData.get(position); if (dataSet == null) { return; } TextView titleTextView = (TextView) view.findViewById(ID_TITLE); TextView lineOneTextView = (TextView) view.findViewById(ID_TEXE_LINE_ONE); TextView lineTwoTextView = (TextView) view.findViewById(ID_TEXE_LINE_TWO); titleTextView.setTextColor(dataSet.getTextColor()); lineOneTextView.setTextColor(dataSet.getTextColor()); lineTwoTextView.setTextColor(dataSet.getTextColor()); CheckBox leftCheckBox = (CheckBox) view.findViewById(ID_LEFT_CHECK_BOX); ImageView imageView = (ImageView) view.findViewById(ID_LEFT_CHECK); if (dataSet.isShowLeftCheckBox()) { leftCheckBox.setVisibility(View.VISIBLE); imageView.setVisibility(View.INVISIBLE); if (null != dataSet.getLeftCheckBoxTag()) { leftCheckBox.setTag(dataSet.getLeftCheckBoxTag()); } leftCheckBox.setOnClickListener(dataSet.getOnClickListener()); leftCheckBox.setFocusable(false); leftCheckBox.setChecked(dataSet.isCheck()); } else { leftCheckBox.setVisibility(View.INVISIBLE); imageView.setVisibility(View.VISIBLE); if (dataSet.getDrawable() != null) { imageView.setImageDrawable(dataSet.getDrawable()); } } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.drawable.Drawable; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class CheckBoxListWidgetItem extends DetailListWidgetItem { private boolean isShowLeftCheckBox; private String leftCheckBoxTag; private boolean isCheck; private Drawable drawable; private int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; public void isShowLeftCheckBox(boolean isShowLeftCheckBox) { this.isShowLeftCheckBox = isShowLeftCheckBox; } public boolean isShowLeftCheckBox() { return isShowLeftCheckBox; } public String getLeftCheckBoxTag() { return leftCheckBoxTag; } public void setLeftCheckBoxTag(String leftCheckBoxTag) { this.leftCheckBoxTag = leftCheckBoxTag; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } public Drawable getDrawable() { return drawable; } public void setDrawable(Drawable drawable) { this.drawable = drawable; } public int getTextColor() { return textColor; } public void setTextColor(int layoutUtils) { this.textColor = layoutUtils; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class DefaultListWidget extends StatusListWidget { public DefaultListWidget(Context context) { this(context, null); } public DefaultListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public DefaultListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public DefaultListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new DefaultListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; public class DefaultListWidgetItem extends StatusListWidgetItem { private boolean isShowCheckBox; private boolean isShowMenuIcon; private boolean isEnabledCheckBox = true; private boolean isCheck; public void isShowCheckBox(boolean isShowCheckBox) { this.isShowCheckBox = isShowCheckBox; } public boolean isShowCheckBox() { return this.isShowCheckBox; } public void isShowMenuIcon(boolean isShowMenuIcon) { this.isShowMenuIcon = isShowMenuIcon; } public boolean isShowMenuIcon() { return this.isShowMenuIcon; } public boolean isEnabledCheckBox() { return isEnabledCheckBox; } public void isEnabledCheckBox(boolean isEnabledCheckBox) { this.isEnabledCheckBox = isEnabledCheckBox; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class DetailListWidget extends ListWidget { DetailListWidgetAdapter adapter; List itemCollection = new ArrayList(); public DetailListWidget(Context context) { this(context, null); } public DetailListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public DetailListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public DetailListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); List itemCollection = new ArrayList(); adapter = new DetailListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class ImageListWidget extends ListWidget { public ImageListWidget(Context context) { this(context, null); } public ImageListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public ImageListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public ImageListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new ImageListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class ImageListWidgetAdapter extends ListWidgetAdapter { public static final int ID_DESCRIPTION = 2090; public static final int ID_TYPE = 2100; public static final int ID_STATUS = 2105; public static final int ID_IMAGE = 2110; public ImageListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { return createView(position, convertView, parent); } public View createView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { LinearLayout rootLinearLayout = new LinearLayout(context); rootLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); contentItemLayout.setBackgroundColor(color.white); contentItemLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING , LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING , LayoutUtils.DEFAULT_MIN_PADDING); contentItemLayout.addView(createMiddleLayout()); int height = 160; int width = 240; FrameLayout endFrameLayout = new FrameLayout(context); endFrameLayout.setBackgroundColor(color.holo_green_light); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); overlayParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL; overlayParams.height = height; overlayParams.width = width; endFrameLayout.setLayoutParams(overlayParams); ImageView image = new ImageView(context); image.setId(ID_IMAGE); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMinimumHeight(height); image.setMaxHeight(height); image.setMaxWidth(width); endFrameLayout.addView(image); contentItemLayout.addView(endFrameLayout); rootLinearLayout.addView(contentItemLayout); v = rootLinearLayout; } else { v = convertView; } bindView(position, v); return v; } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 2.5f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(5, 5, 5, 5); TextView descriptionTextView = new TextView(context); descriptionTextView.setId(ID_DESCRIPTION); descriptionTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); descriptionTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); descriptionTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); descriptionTextView.setEllipsize(TruncateAt.END); descriptionTextView.setMaxLines(3); midLinearLayout.addView(descriptionTextView); TextView typeTextView = new TextView(context); typeTextView.setId(ID_TYPE); typeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); typeTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); typeTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); typeTextView.setMaxLines(1); typeTextView.setSingleLine(); typeTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(typeTextView); TextView statusTextView = new TextView(context); statusTextView.setId(ID_STATUS); statusTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); statusTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); statusTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); statusTextView.setMaxLines(1); statusTextView.setSingleLine(); statusTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(statusTextView); return midLinearLayout; } public void bindView(int position, View view) { final ImageListWidgetItem dataSet = (ImageListWidgetItem)mData.get(position); if (dataSet == null) { return; } TextView desTextView = (TextView) view .findViewById(ID_DESCRIPTION); TextView typeTextView = (TextView) view .findViewById(ID_TYPE); TextView statusTextView = (TextView) view .findViewById(ID_STATUS); ImageView image = (ImageView) view .findViewById(ID_IMAGE); setViewText(desTextView, dataSet.getDescription()); setViewText(typeTextView, dataSet.getType()); setViewText(statusTextView, dataSet.getStatus()); if (null != dataSet.getImageBitmap()) { image.setImageBitmap(dataSet.getImageBitmap()); if (null != dataSet.getOnClickListener()) { image.setOnClickListener(dataSet.getOnClickListener()); } } desTextView.setMaxLines(2); typeTextView.setEllipsize(TruncateAt.END); statusTextView.setEllipsize(TruncateAt.END); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.Bitmap; public class ImageListWidgetItem extends DetailListWidgetItem{ private String description; private String type; private String status; private Bitmap imageBitmap; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Bitmap getImageBitmap() { return imageBitmap; } public void setImageBitmap(Bitmap imageBitmap) { this.imageBitmap = imageBitmap; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class ListWidget extends ListView { ListWidgetAdapter adapter; List itemCollection = new ArrayList(); public ListWidget(Context context) { this(context, null); } public ListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public ListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public ListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); adapter = new ListWidgetAdapter(context, itemCollection); this.setAdapter(adapter); } public void clean(){ itemCollection.clear(); adapter.notifyDataSetChanged(); } public void addItem(DetailListWidgetItem item){ itemCollection.add(item); adapter.notifyDataSetChanged(); } public void addItems(List items){ itemCollection.addAll(items); adapter.notifyDataSetChanged(); } public List getItems() { return itemCollection; } public void removeItem(int position){ itemCollection.remove(position); adapter.notifyDataSetChanged(); } public ListWidgetAdapter getAdapter() { return adapter; } public void setListWidgetAdapterAndCollection(ListWidgetAdapter adapter, List itemCollection) { this.adapter = adapter; this.itemCollection = itemCollection; } private OverScrollListener mOverScrollListener = null; @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { super.onOverScrolled(scrollX, scrollY, clampedX, clampedY); if (null != mOverScrollListener) { mOverScrollListener.onOverScrolled(scrollX, scrollY, clampedX, clampedY); } } public void setOnOverScrollListener(OverScrollListener listener) { mOverScrollListener = listener; } public interface OverScrollListener { void onOverScrolled(int scrollx, int scrollY, boolean clampedX, boolean clampedY); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.StringUtil; @SuppressLint("NewApi") public class ListWidgetAdapter extends BaseAdapter implements Filterable { public List mData; public List mDataTemp; public Context context; /** * Constructor * * @param context * The context where the View associated with this SimpleAdapter * is running * @param data * A List of Maps. Each entry in the List corresponds to one row * in the list. The Maps contain the data for each row, and * should include all the entries specified in "from" * @param resource * Resource identifier of a view layout that defines the views * for this list item. The layout file should include at least * those named views defined in "to" * @param from * A list of column names that will be added to the Map * associated with each item. * @param to * The views that should display column in the "from" parameter. * These should all be TextViews. The first N views in this list * are given the values of the first N columns in the from * parameter. */ public ListWidgetAdapter(Context context, List coll) { mData = coll; mDataTemp = coll; this.context = context; } /** * @see android.widget.Adapter#getCount() */ public int getCount() { return mData.size(); } /** * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return mData.get(position); } /** * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { return position; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { return null; } /** * Sets the {@link android.content.res.Resources.Theme} against which * drop-down views are inflated. *

* By default, drop-down views are inflated against the theme of the * {@link Context} passed to the adapter's constructor. * * @param theme * the theme against which to inflate drop-down views or * {@code null} to use the theme from the adapter's context * @see #getDropDownView(int, View, ViewGroup) */ @SuppressLint("NewApi") public void setDropDownViewTheme(Resources.Theme theme) { // New API } public Resources.Theme getDropDownViewTheme() { return null; } /** * Called by bindView() to set the text for a TextView but only if there is * no existing ViewBinder or if the existing ViewBinder cannot handle * binding to a TextView. * * @param v * TextView to receive text * @param text * the text to be set for the TextView */ public void setViewText(TextView v, String text) { v.setText(text); } public Filter getFilter() { return new ListWidgetAdapterFilter(); } /** * This class can be used by external clients of SimpleAdapter to bind * values to views. * * You should use this class to bind values to views that are not directly * supported by SimpleAdapter or to change the way binding occurs for views * supported by SimpleAdapter. * * @see SimpleAdapter#setViewImage(ImageView, int) * @see SimpleAdapter#setViewImage(ImageView, String) * @see SimpleAdapter#setViewText(TextView, String) */ public static interface ViewBinder { /** * Binds the specified data to the specified view. * * When binding is handled by this ViewBinder, this method must return * true. If this method returns false, SimpleAdapter will attempts to * handle the binding on its own. * * @param view * the view to bind the data to * @param data * the data to bind to the view * @param textRepresentation * a safe String representation of the supplied data: it is * either the result of data.toString() or an empty String * but it is never null * * @return true if the data was bound to the view, false otherwise */ boolean setViewValue(View view, Object data, String textRepresentation); } /** * The Filter For ListWidgetAdapter. * * @author nop */ private class ListWidgetAdapterFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { String queryTextLowerCase = constraint.toString().toLowerCase(); FilterResults results = new FilterResults(); ArrayList tempList = new ArrayList(); if (mData == null) { mData = new ArrayList(); } if (StringUtil.isNotEmpty(queryTextLowerCase)) { for (DetailListWidgetItem item : mDataTemp) { String content = (item.getTitleText() + item.getStringLine1() + item.getStringLine2()).toLowerCase(); if (content.contains(queryTextLowerCase)) { tempList.add(item); } } results.values = tempList; results.count = tempList.size(); } else { // add all objects synchronized (this) { results.values = mDataTemp; results.count = mDataTemp.size(); } } return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence contraint, FilterResults results) { mData = (ArrayList) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class MaterialListWidget extends DetailListWidget { public MaterialListWidget(Context context) { this(context, null); } public MaterialListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public MaterialListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public MaterialListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new MaterialListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.support.v7.widget.GridLayout; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class MaterialListWidgetAdapter extends DefaultListWidgetAdapter { public static final int ID_TEXT_PRICE = 2030; public static final int ID_TEXT_REPLACEMENT = 2035; public MaterialListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setMiddleView(createMiddleLayout()); return super.getView(position, convertView, parent); } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 3f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(25, 0, 0, 0); TextView titleTextView = new TextView(context); titleTextView.setId(ID_TITLE); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(titleTextView); GridLayout lineOneGridLayout = new GridLayout(context); RelativeLayout.LayoutParams lineOneGridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); lineOneGridLayoutParams.leftMargin = 0; lineOneGridLayoutParams.setMargins(0, 0, 0, 0); lineOneGridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); lineOneGridLayout.setLayoutParams(lineOneGridLayoutParams); lineOneGridLayout.setColumnCount(2); lineOneGridLayout.setUseDefaultMargins(true); TextView lineOneTextView = new TextView(context); lineOneTextView.setId(ID_TEXE_LINE_ONE); lineOneTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineOneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); lineOneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); lineOneTextView.setEllipsize(TruncateAt.END); lineOneTextView.setMaxLines(1); lineOneTextView.setSingleLine(); GridLayout.LayoutParams gridLayoutLineOneTextViewParams = new GridLayout.LayoutParams(); gridLayoutLineOneTextViewParams.width = 0; gridLayoutLineOneTextViewParams.height = LayoutParams.WRAP_CONTENT; gridLayoutLineOneTextViewParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.5f); lineOneTextView.setLayoutParams(gridLayoutLineOneTextViewParams); lineOneGridLayout.addView(lineOneTextView); RelativeLayout gridRelativeLayout = new RelativeLayout(lineOneGridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.5f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView lineOneColumnTwoTextView = new TextView(context); lineOneColumnTwoTextView.setId(ID_TEXT_PRICE); lineOneColumnTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineOneColumnTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); lineOneColumnTwoTextView.setLayoutParams(gridTextViewValueParams); gridRelativeLayout.addView(lineOneColumnTwoTextView); lineOneGridLayout.addView(gridRelativeLayout); midLinearLayout.addView(lineOneGridLayout); TextView lineTwoTextView = new TextView(context); lineTwoTextView.setId(ID_TEXE_LINE_TWO); lineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); lineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); lineTwoTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(lineTwoTextView); TextView lineThreeTextView = new TextView(context); lineThreeTextView.setId(ID_TEXT_REPLACEMENT); lineThreeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); lineThreeTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); lineThreeTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); lineThreeTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(lineThreeTextView); return midLinearLayout; } public void bindView(int position, View view) { super.bindView(position, view); final MaterialListWidgetItem dataSet = (MaterialListWidgetItem)mData.get(position); if (dataSet == null) { return; } TextView priceTextView = (TextView) view.findViewById(ID_TEXT_PRICE); priceTextView.setText(dataSet.getStringPrice()); TextView replaceMentTextView = (TextView) view.findViewById(ID_TEXT_REPLACEMENT); String replacement = dataSet.getReplacement(); if (replacement.isEmpty()) { replaceMentTextView.setVisibility(View.INVISIBLE); } else { replaceMentTextView.setVisibility(View.VISIBLE); replaceMentTextView.setText(replacement); } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; public class MaterialListWidgetItem extends DefaultListWidgetItem{ private String stringPrice; private String replacement; public String getStringPrice() { return stringPrice; } public void setStringPrice(String stringPrice) { this.stringPrice = stringPrice; } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class RadioButtonListWidget extends DetailListWidget { public RadioButtonListWidget(Context context) { this(context, null); } public RadioButtonListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public RadioButtonListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } @Override public void setChoiceMode(int choiceMode) { super.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } public RadioButtonListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); List itemCollection = new ArrayList(); adapter = new RadioButtonListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RadioButton; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class RadioButtonListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_LEFT_RADIO = 1200; private Context context; public RadioButtonListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { FrameLayout endFrameLayout = new FrameLayout(context); LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; endFrameLayout.setLayoutParams(endFrameParams); final RadioButton radioButton = new RadioButton(context); radioButton.setId(ID_LEFT_RADIO); radioButton.setChecked(false); endFrameLayout.addView(radioButton); return endFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final RadioButtonListWidgetItem dataSet = (RadioButtonListWidgetItem) mData.get(position); if (dataSet == null) { return; } RadioButton leftRadioButton = (RadioButton) view.findViewById(ID_LEFT_RADIO); if (null != dataSet.getLeftRadioButtonTag()) { leftRadioButton.setTag(dataSet.getLeftRadioButtonTag()); } leftRadioButton.setOnClickListener(dataSet.getOnClickListener()); leftRadioButton.setFocusable(false); leftRadioButton.setChecked(dataSet.isCheck()); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; public class RadioButtonListWidgetItem extends DetailListWidgetItem { private String leftRadioButtonTag; private boolean isCheck; public String getLeftRadioButtonTag() { return leftRadioButtonTag; } public void setLeftRadioButtonTag(String leftRadioButtonTag) { this.leftRadioButtonTag = leftRadioButtonTag; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * * @author Xin * */ public class StatusListWidget extends DetailListWidget { public StatusListWidget(Context context) { this(context, null); } public StatusListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public StatusListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public StatusListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new StatusListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class StatusListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_BACKGROUND_ICON = 1000; private static final int ID_STATUS_TEXT = 1010; private static final int ID_OVERLAY_ICON = 1011; private Context context; public StatusListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { FrameLayout beginFrameLayout = new FrameLayout(context); LinearLayout.LayoutParams beginFrameParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); beginFrameParams.gravity = Gravity.LEFT; beginFrameLayout.setLayoutParams(beginFrameParams); beginFrameLayout.setBackgroundColor(color.holo_green_light); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams(LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL ; ImageView backgroundIcon = new ImageView(context); backgroundIcon.setId(ID_BACKGROUND_ICON); backgroundIcon.setLayoutParams(backgroundIconParams); backgroundIcon.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); beginFrameLayout.addView(backgroundIcon); FrameLayout.LayoutParams statusTextParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); statusTextParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL ; TextView statusText = new TextView(context); statusText.setId(ID_STATUS_TEXT); statusText.setLayoutParams(statusTextParams); statusText.setTextColor(Color.WHITE); statusText.setTypeface(CommonConstants.Font.getDefaultMediumFont()); beginFrameLayout.addView(statusText); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); overlayParams.gravity = Gravity.LEFT | Gravity.TOP; // overlayParams.leftMargin = -10; // overlayParams.topMargin = -10; overlayParams.height = 40; overlayParams.width = 40; ImageView overlayIcon = new ImageView(context); overlayIcon.setId(ID_OVERLAY_ICON); overlayIcon.setLayoutParams(overlayParams); beginFrameLayout.addView(overlayIcon); return beginFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final StatusListWidgetItem dataSet = (StatusListWidgetItem)mData.get(position); if (dataSet == null) { return; } ImageView backgroundIcon = (ImageView) view.findViewById(ID_BACKGROUND_ICON); ImageView overlayIcon = (ImageView) view.findViewById(ID_OVERLAY_ICON); TextView statusText = (TextView) view.findViewById(ID_STATUS_TEXT); ImageButton imageButton = (ImageButton) view .findViewById(ID_BUTTON); if (0 != dataSet.getStatusColor()) { GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(dataSet.getStatusColor()); gradientDrawable.setCornerRadius(LayoutUtils.convertDpToPixel(view.getContext(), 50)); gradientDrawable.setStroke(2, dataSet.getStatusColor()); backgroundIcon.setBackground(gradientDrawable); } if (null != dataSet.getStatusType()) { statusText.setText(dataSet.getStatusType()); } if (null != dataSet.getOverlayIcon()) { overlayIcon.setVisibility(View.VISIBLE); overlayIcon.setBackground(dataSet.getOverlayIcon()); } else { overlayIcon.setVisibility(View.INVISIBLE); } if (null == imageButton) { return; } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.drawable.BitmapDrawable; public class StatusListWidgetItem extends DetailListWidgetItem { private int statusColor; private String statusType = null; private BitmapDrawable overlayImage; public int getStatusColor() { return statusColor; } public void setStatusColor(int backgroundIcon) { this.statusColor = backgroundIcon; } public String getStatusType() { return statusType; } public void setStatusType(String statusType) { this.statusType = statusType; } public BitmapDrawable getOverlayIcon() { return overlayImage; } public void setOverlayIcon(BitmapDrawable bitmapDrawable) { this.overlayImage = bitmapDrawable; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; /** * A scrollable list that displays an arbitrary number of {@link DetailListWidgetItem} * */ public class TimeListWidget extends DetailListWidget { public TimeListWidget(Context context) { this(context, null); } public TimeListWidget(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public TimeListWidget(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public TimeListWidget(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); // Each row in the list stores country name, currency and flag List itemCollection = new ArrayList(); adapter = new TimeListWidgetAdapter(context, itemCollection); setListWidgetAdapterAndCollection(adapter, itemCollection); this.setAdapter(adapter); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class TimeListWidgetAdapter extends DetailListWidgetAdapter { private static final int ID_Date_Title = 1090; private static final int ID_Date_Text = 1100; private Context context; public TimeListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setLeftView(createLeftLayout()); setRightView(createRightLayout()); return super.getView(position, convertView, parent); } private View createLeftLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams buttonLinearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); buttonLinearLayoutParams.gravity = Gravity.TOP; // buttonLinearLayoutParams.width = 0; buttonLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; buttonLinearLayoutParams.weight = 0.75f; midLinearLayout.setLayoutParams(buttonLinearLayoutParams); LinearLayout headerTextLayout = new LinearLayout(context); headerTextLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerTextLayout.setOrientation(LinearLayout.HORIZONTAL); headerTextLayout.setGravity(Gravity.TOP); TextView headerTextView = new TextView(context); headerTextView.setId(ID_Date_Title); headerTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); headerTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); headerTextView.setPadding(0, -5, 0, 0); headerTextLayout.addView(headerTextView); midLinearLayout.addView(headerTextLayout); LinearLayout textLineTwoTextLayout = new LinearLayout(context); textLineTwoTextLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); textLineTwoTextLayout.setOrientation(LinearLayout.HORIZONTAL); textLineTwoTextLayout.setGravity(Gravity.VERTICAL_GRAVITY_MASK); TextView textLineTwoTextView = new TextView(context); textLineTwoTextView.setId(ID_Date_Text); textLineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineTwoTextLayout.addView(textLineTwoTextView); midLinearLayout.addView(textLineTwoTextLayout); return midLinearLayout; } private View createRightLayout() { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL; endFrameLayout.setLayoutParams(endFrameParams); endFrameLayout.setBackgroundColor(color.holo_green_light); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setId(ID_BUTTON); endFrameLayout.addView(imageButton); return endFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final TimeListWidgetItem dataSet = (TimeListWidgetItem) mData.get(position); if (dataSet == null) { return; } TextView titleTextView = (TextView) view.findViewById(ID_TITLE); TextView lineOneTextView = (TextView) view.findViewById(ID_TEXE_LINE_ONE); TextView lineTwoTextView = (TextView) view.findViewById(ID_TEXE_LINE_TWO); TextView headerTextView = (TextView) view.findViewById(ID_HEADER_ITEM); TextView dateTitleTextView = (TextView) view.findViewById(ID_Date_Title); TextView dateTextTextView = (TextView) view .findViewById(ID_Date_Text); lineTwoTextView.setVisibility(View.GONE); setViewText(dateTitleTextView, dataSet.getDateTitle()); setViewText(dateTextTextView, dataSet.getDateText()); dateTitleTextView.setTextColor(dataSet.getTextColor()); dateTextTextView.setTextColor(dataSet.getTextColor()); titleTextView.setTextColor(dataSet.getTextColor()); lineOneTextView.setTextColor(dataSet.getTextColor()); if(dataSet.getHeader() != null) { headerTextView.setVisibility(View.VISIBLE); setViewText(headerTextView, dataSet.getHeader()); ((LinearLayout) headerTextView.getParent()).setBackgroundColor(dataSet.getHeaderBackgroundColor()); } LinearLayout rootLayout = ((LinearLayout) ((LinearLayout) lineOneTextView.getParent()).getParent()); rootLayout.setBackgroundColor(dataSet.getBackgroundColor()); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class TimeListWidgetItem extends DetailListWidgetItem { private String dateTitle; private String dateText; private int backgroundColor; private int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; public String getDateTitle() { return dateTitle; } public void setDateTitle(String dateTitle) { this.dateTitle = dateTitle; } public String getDateText() { return dateText; } public void setDateText(String dateText) { this.dateText = dateText; } public int getTextColor() { return textColor; } public void setTextColor(int layoutUtils) { this.textColor = layoutUtils; } public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; } public int getBackgroundColor() { return backgroundColor; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class AmountEditText extends MDEditText { private static Log log = LogFactory.getLog(AmountEditText.class); private static boolean removeDot; private static AmountEditText editText = null;; public AmountEditText(Context context) { super(context); } public static AmountEditText createDefaultEditText(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); AmountEditText editText = createEditText(context, label, required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private static AmountEditText createEditText(Context context, String label, final boolean required) { editText = new AmountEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SIX) }); // editText.setDirectionRight(false); editText.setGravity(Gravity.RIGHT); if (required) { editText.setRequired(required); } if (label != null) { editText.setHint(label); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, Mode.SRC_ATOP); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { format(); } } }); editText.addTextChangedListener(new TextWatcher() { public int beforeCharSequence; public int afterCharSequence; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } @Override public void afterTextChanged(Editable s) { String value = s.toString().trim(); if (StringUtil.isEmpty(value)) { return; } editText.removeTextChangedListener(this); if(value.contains(" ")) { value = value.replace(" ", ""); } if (beforeCharSequence < afterCharSequence) { if(value.length() >= CommonConstants.MaxLength.THREE) { if(!value.contains(".")) { value = value.substring(0,CommonConstants.MaxLength.THREE) + "." + value.substring(CommonConstants.MaxLength.THREE); } } } editText.setText(value); if (editText.hasFocus()) { editText.clearError(); } editText.addTextChangedListener(this); } }); return editText; } private static void format() { String userInput = editText.getText().toString(); if (!TextUtils.isEmpty(userInput)) { try { Locale locale = Locale.ENGLISH; if (userInput.contains(",")) { userInput = userInput.replace(",", "."); } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(userInput))); if (floatValue > 999.99) { floatValue = (float) 999.99; } if (floatValue < 1) { floatValue = (float) 1; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("###", symbols); format.setMaximumFractionDigits(2); userInput = format.format(floatValue); } catch (NumberFormatException e) { userInput = ""; } catch (ParseException e) { userInput = ""; } } editText.setText(userInput); } public void setText(String text) { setTextAndSelection(text); } public void setLabel(String label) { super.setHint(label); } @Override public String toString() { format(); return super.toString(); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class DividerView extends View { public DividerView(Context context) { super(context); LinearLayout.LayoutParams linearLayoutParam = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); setLayoutParams(linearLayoutParam); TypedArray array = context.getTheme() .obtainStyledAttributes(new int[] {android.R.attr.listDivider}); Drawable draw = array.getDrawable(0); array.recycle(); setBackground(draw); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Color; import android.provider.BaseColumns; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.Messages; public class MaterialSearchView extends SearchView { private SimpleCursorAdapter searchViewAdapter; private List suggessionList = new ArrayList(); private OnSuggestionListener onSuggestionListener; private onQueryTextListener queryTextListener; public MaterialSearchView(Context context) { super(context); // create SearchView setLayoutParams(new Toolbar.LayoutParams(Gravity.RIGHT)); setQueryHint(Messages.getString("search")); //$NON-NLS-1$ setFocusableInTouchMode(true); final String[] from = new String[] { "matNo", "matName" }; //$NON-NLS-1$ final int[] to = {android.R.id.text1, android.R.id.text2}; searchViewAdapter = new MyCursorAdapter(context, android.R.layout.simple_list_item_2, null , from, to, 0); setSuggestionsAdapter(searchViewAdapter); setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String query) { queryTextListener.onQueryTextChange(query); final MatrixCursor c = new MatrixCursor(new String[] { BaseColumns._ID, "matNo", "matName" }); //$NON-NLS-1$ for (int i = 0; i < suggessionList.size(); i++) { c.addRow(new Object[] { i, suggessionList.get(i).getNumber() , suggessionList.get(i).getName()}); } searchViewAdapter.changeCursor(c); if (suggessionList.size() == 1) { onSuggestionListener.onSuggestionClick(0); clearFocus(); setQuery("", false); //$NON-NLS-1$ } return true; } }); } @Override public void setOnSuggestionListener(OnSuggestionListener onSuggestionListener) { this.onSuggestionListener = onSuggestionListener; super.setOnSuggestionListener(onSuggestionListener); } public List getSuggessionItemList() { return suggessionList; } public void setQueryTextListener(onQueryTextListener queryTextListener) { this.queryTextListener = queryTextListener; } public interface onQueryTextListener { void onQueryTextChange(String query); } public static class SuggessionItem { private String number; private String name; public SuggessionItem(String number, String name) { setName(name); setNumber(number); } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } } private class MyCursorAdapter extends SimpleCursorAdapter{ public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) { super(context, layout, c, from, to, flags); } @Override public View getView(int position, View convertView, ViewGroup parent) { //get reference to the row View view = super.getView(position, convertView, parent); //check for odd or even to set alternate colors to the row background if(position % 2 == 0){ view.setBackgroundColor(Color.rgb(238, 233, 233)); } else { view.setBackgroundColor(Color.rgb(255, 255, 255)); } return view; } } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatAutoCompleteTextView; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextWatcher; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomAutoCompleteItemAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * A view for easy creation and use of an {@link EditText} that is embedded in a * {@link TextInputLayout} which is the way input fields are created in Material * design. * * @author cyu */ public class MDAutoComplete extends AppCompatAutoCompleteTextView { private static Log log = LogFactory.getLog(MDAutoComplete.class); /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, boolean required) { return createDefaultAutoCompleteText(context, null, required); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, boolean required, TextWatcher textWatcher) { return createDefaultAutoCompleteText(context, null, required, textWatcher); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, boolean required) { return createDefaultAutoCompleteText(context, label, 0, required); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, boolean required, TextWatcher textWatcher) { return createDefaultAutoCompleteText(context, label, 0, required, textWatcher); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, int inputType, boolean required) { return createAutoCompleteText(context, label, inputType, required, null); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(Context context, String label, int inputType, boolean required, TextWatcher textWatcher) { return createAutoCompleteText(context, label, inputType, required, textWatcher); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @return */ public static MDAutoComplete createDefaultAutoCompleteText(ViewGroup parent, String label, int inputType, boolean required) { return createDefaultAutoCompleteText(parent, label, inputType, required, null); } /** * Creates a new {@link MDAutoComplete} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDAutoComplete createDefaultAutoCompleteText(ViewGroup parent, String label, int inputType, boolean required, TextWatcher textWatcher) { if (parent == null) { return null; } Context context = parent.getContext(); MDAutoComplete editText = createAutoCompleteText(context, label, inputType, required, textWatcher); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } public MDAutoComplete(Context context) { super(context); InputFilter filter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { int type = Character.getType(source.charAt(i)); if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) { return ""; } } return null; } }; setFilters(new InputFilter[] { filter }); } public static TextInputLayout getTextInputLayout(MDAutoComplete editText) { TextInputLayout textInputLayout = new TextInputLayout(editText.getContext()); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); return textInputLayout; } private static MDAutoComplete createAutoCompleteText(Context context, final String label, final int inputType, boolean required, TextWatcher textWatcher) { final MDAutoComplete editText = new MDAutoComplete(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); if (inputType != 0) { editText.setInputType(inputType); } if (label != null) { editText.setHint(label); } if (required) { editText.setRequired(required); } if (textWatcher != null) { editText.addTextChangedListener(textWatcher); } else { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Auto-generated method stub } @Override public void afterTextChanged(Editable s) { editText.clearError(); } }); } editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (editText.getEditableText().toString().isEmpty()) { editText.showDropDown(); } } else { if (editText.getSelectedId().isEmpty()) { editText.getEditableText().clear(); } } } }); editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, // Mode.SRC_ATOP); return editText; } /** * Sets the error on the embedding {@link TextInputLayout} if it is the parent * of the receiver by calling {@link TextInputLayout#setError(CharSequence)}. * * @param error The error message to set or null to remove the * error text by calling * {@link TextInputLayout#setErrorEnabled(boolean)} with * false. */ @Override public void setError(CharSequence error) { TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { textInputLayout.setError(error); if (error == null) textInputLayout.setErrorEnabled(false); return; } super.setError(error); } /** * Returns the {@link TextInputLayout} in the views hierarchy or * null if the view is not wrapped within such a layout. * * @return */ public TextInputLayout getParentTextInputLayout() { ViewParent parent = getParent(); while (parent != null) { if (parent instanceof TextInputLayout) return (TextInputLayout) parent; parent = parent.getParent(); } return null; } /** * Clears an error. */ public void clearError() { setError(null); } private boolean required = false; /** * Adds an asterisk to the hint that was set to the receiver marking the input * field as 'required'. * * @param required */ public void setRequired(boolean required) { this.required = required; TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { String hint = textInputLayout.getHint().toString().replaceAll(" \\*", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (required) { hint = hint + " *"; //$NON-NLS-1$ } textInputLayout.setHint(hint); } } /** * Adds an asterisk to the hint that was set using * {@link MDAutoComplete#setText(CharSequence)} if {@link #setRequired(boolean)} was * set to true. * * @return */ @Override public CharSequence getHint() { return required ? super.getHint() + " *" : super.getHint(); //$NON-NLS-1$ } /** * Is required. * * @return */ public boolean isRequired() { return required; // $NON-NLS-1$ } @Override public void setEnabled(boolean enabled) { setFocusable(enabled); setClickable(enabled); setFocusableInTouchMode(enabled); super.setEnabled(enabled); // set Enabled/Disabled style. int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; if (!enabled) { textColor = LayoutUtils.DEFAULT_DISABLED_COLOR; } setTextColor(textColor); } @Override public void setFilters(InputFilter[] filters) { super.setFilters(filters); } /** * Gets selected item id. * * @return */ public String getSelectedId() { return this.selectedCustomSpinnerItem == null? "":this.selectedCustomSpinnerItem.getId(); } private CustomSpinnerItem selectedCustomSpinnerItem; private void setSelected(CustomSpinnerItem customSpinnerItem) { this.selectedCustomSpinnerItem = customSpinnerItem; } /** * Sets contents. * * @param list */ public void setContents(List list) { List customSpinnerItemList = new ArrayList(); if (list != null && list.isEmpty()) { customSpinnerItemList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, "")); } else { for (int i = 0; i < list.size(); i++) { CustomSpinnerItem item = list.get(i); if (item.getName().startsWith("Bitte w") && item.getName().endsWith("...")) { list.remove(item); if(customSpinnerItemList.isEmpty()) { customSpinnerItemList.add(item); } } } customSpinnerItemList.addAll(list); } if (this.getAdapter() != null) { this.setAdapter(null); } setThreshold(1); // handle click event and set desc on textview setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { CustomSpinnerItem customSpinnerItem = (CustomSpinnerItem) adapterView.getItemAtPosition(i); setSelected(customSpinnerItem); } }); CustomAutoCompleteItemAdapter adapter = new CustomAutoCompleteItemAdapter(this.getContext(), android.R.layout.simple_spinner_item, customSpinnerItemList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); setAdapter(adapter); setListSelection(0); } /** * Sets selection by id. * * @param id */ public void setSelectionById(String id) { CustomAutoCompleteItemAdapter adapter = (CustomAutoCompleteItemAdapter) this.getAdapter(); if (adapter == null) { return; } this.setText(adapter.getNameById(id), false); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatCheckBox; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * * A view for easy creation and use of an {@link AppCompatCheckBox} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * MDCheckBox structure: * LinearLayout * --AppCompatCheckBox * --View(Underline) * --TextView(Error message) * * * @author CYU * */ public class MDCheckBox extends AppCompatCheckBox { public MDCheckBox(Context context) { super(context); } /** * Creates a new {@link MDCheckBox} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @return */ public static MDCheckBox createDefaultCheckBox(Context context) { return createDefaultCheckBox(context, null); } /** * Creates a new {@link MDCheckBox} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @return */ public static MDCheckBox createDefaultCheckBox(Context context, String label) { return createCheckBox(context, label); } /** * Creates a new {@link MDCheckBox} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @return */ public static MDCheckBox createDefaultCheckBox(ViewGroup parent, String label) { if (parent == null) { return null; } Context context = parent.getContext(); MDCheckBox checkBox = createCheckBox(context, label); LinearLayout linearLayout = (LinearLayout) checkBox.getParent(); parent.addView(linearLayout); checkBox.setContentDescription(label); return checkBox; } private static MDCheckBox createCheckBox(Context context, final String label) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setOrientation(LinearLayout.VERTICAL); final MDCheckBox checkBox = new MDCheckBox(context); checkBox.setTag("CHECKBOX"); //$NON-NLS-1$ checkBox.setText(label); checkBox.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); checkBox.setTypeface(CommonConstants.Font.getDefaultRegularFont()); checkBox.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.addView(checkBox); View underline = new View(context); underline.setTag("UNDERLINE"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); underlineLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), LayoutUtils.convertDpToPixel(context, 8), LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); underline.setLayoutParams(underlineLinearLayout); underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); linearLayout.addView(underline); TextView errorText = new TextView(context); errorText.setTag("ERRORTEXT"); //$NON-NLS-1$ LinearLayout.LayoutParams errorTextLinearLayout = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); errorTextLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); errorText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); errorText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); errorText.setLayoutParams(errorTextLinearLayout); errorText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); errorText.setVisibility(View.GONE); linearLayout.addView(errorText); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { checkBox.clearError(); } }); return checkBox; } /** * Gets top parent. * * @return */ public View getTopParent() { return (View) this.getParent(); } /** * Sets an error. * * @param error */ @Override public void setError(CharSequence error) { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(error); errorText.setVisibility(View.VISIBLE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_ERROR_COLOR); underline.setVisibility(View.VISIBLE); } /** * Clears an error. */ public void clearError() { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(""); //$NON-NLS-1$ errorText.setVisibility(View.GONE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); } /** * Adds an asterisk to the hint that was set to the receiver marking the * input field as 'required'. * * @param required */ public void setRequired(boolean required) { MDCheckBox checkBox = getMDCheckBox(); String text = checkBox.getText().toString().replaceAll("\\*", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ checkBox.setText(text); if (required) { checkBox.setText(text + " *"); //$NON-NLS-1$ } } /** * Is required. * @return */ public boolean isRequired() { MDCheckBox checkBox = getMDCheckBox(); return checkBox.getText().toString().contains("*"); //$NON-NLS-1$ } public MDCheckBox getMDCheckBox() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(0); if (view instanceof MDCheckBox && "CHECKBOX".equals(view.getTag().toString())) { //$NON-NLS-1$ return (MDCheckBox) view; } return null; } private View getUnderline() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(1); if ("UNDERLINE".equals(view.getTag().toString())) { //$NON-NLS-1$ return view; } return null; } private TextView getErrorText() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(2); if (view instanceof TextView && "ERRORTEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnShowListener; import android.graphics.Typeface; import android.support.v7.app.AlertDialog; import android.util.TypedValue; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.impl.android.ui.UIActivity; /** * A view for easy creation and use of an {@link AlertDialog.Builder} * * @author nop */ public class MDDialog extends AlertDialog.Builder { public MDDialog(Context context) { super(context); } /** * Creates a new {@link MDDialog} * * @param title * @return */ public static MDDialog createDefaultSpinner(String title) { return createDefaultSpinner(title, null); } /** * Creates a new {@link MDDialog} * * @param title * @return */ public static MDDialog createDefaultSpinner(String title, String cancel) { return createSpinner(UIActivity.getInstance(), title, cancel); } private static MDDialog createSpinner(Context context, String title, String cancel) { TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setPadding(LayoutUtils.convertDpToPixel(context, LayoutUtils.DEFAULT_MAX_PADDING), LayoutUtils.convertDpToPixel(context, LayoutUtils.DEFAULT_MAX_PADDING), 0, 0); titleTextView.setText(title); MDDialog dialog = new MDDialog(context); dialog.setCustomTitle(titleTextView); dialog.setCancelable(false); if (StringUtil.isNotEmpty(cancel)) { dialog.setNegativeButton(cancel, new OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { dialog.dismiss(); } }); } return dialog; } private static void doKeepDialog(Dialog dialog){ WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.WRAP_CONTENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialog.getWindow().setAttributes(lp); } @Override public AlertDialog show() { final AlertDialog alert = this.create(); alert.setOnShowListener(new OnShowListener() { @Override public void onShow(android.content.DialogInterface dialog) { Button btnPositive = alert.getButton(Dialog.BUTTON_POSITIVE); btnPositive.setTextSize(CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); btnPositive.setTypeface(CommonConstants.Font.getDefaultMediumFont()); Button btnNegative = alert.getButton(Dialog.BUTTON_NEGATIVE); btnNegative.setTextSize(CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); btnNegative.setTypeface(CommonConstants.Font.getDefaultMediumFont()); } }); alert.show(); doKeepDialog(alert); return alert; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.Spanned; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.EditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.Watcher; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; /** * A view for easy creation and use of an {@link EditText} that is embedded in a * {@link TextInputLayout} which is the way input fields are created in Material * design. * * @author joerg */ public class MDEditText extends TextInputEditText { /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @return */ public static MDEditText createDefaultEditText(Context context, boolean required) { return createDefaultEditText(context, null, required); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(Context context, boolean required, TextWatcher textWatcher) { return createDefaultEditText(context, null, required, textWatcher); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @return */ public static MDEditText createDefaultEditText(Context context, String label, boolean required) { return createDefaultEditText(context, label, 0, required); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(Context context, String label, boolean required, TextWatcher textWatcher) { return createDefaultEditText(context, label, 0, required, textWatcher); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @return */ public static MDEditText createDefaultEditText(Context context, String label, int inputType, boolean required) { return createEditText(context, label, inputType, required, null); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(Context context, String label, int inputType, boolean required, TextWatcher textWatcher) { return createEditText(context, label, inputType, required, textWatcher); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @return */ public static MDEditText createDefaultEditText(ViewGroup parent, String label, int inputType, boolean required) { return createDefaultEditText(parent, label, inputType, required, null); } /** * Creates a new {@link MDEditText} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param inputType * @param required * @param textWatcher * @return */ public static MDEditText createDefaultEditText(ViewGroup parent, String label, int inputType, boolean required, TextWatcher textWatcher) { if (parent == null) { return null; } Context context = parent.getContext(); MDEditText editText = createEditText(context, label, inputType, required, textWatcher); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } public MDEditText(Context context) { super(context); InputFilter filter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { int type = Character.getType(source.charAt(i)); if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) { return ""; } } return null; } }; setFilters(new InputFilter[] { filter }); } public static TextInputLayout getTextInputLayout(MDEditText editText) { TextInputLayout textInputLayout = new TextInputLayout(editText.getContext()); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); return textInputLayout; } private static MDEditText createEditText(Context context, final String label, final int inputType, boolean required, TextWatcher textWatcher) { final MDEditText editText = new MDEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); if (inputType != 0) { editText.setInputType(inputType); } if (label != null) { editText.setHint(label); } if (required) { editText.setRequired(required); } if (textWatcher != null) { editText.addTextChangedListener(textWatcher); } else { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Auto-generated method stub } @Override public void afterTextChanged(Editable s) { editText.clearError(); } }); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, // Mode.SRC_ATOP); return editText; } /** * Sets the error on the embedding {@link TextInputLayout} if it is the parent * of the receiver by calling {@link TextInputLayout#setError(CharSequence)}. * * @param error The error message to set or null to remove the * error text by calling * {@link TextInputLayout#setErrorEnabled(boolean)} with * false. */ @Override public void setError(CharSequence error) { TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { textInputLayout.setError(error); if (error == null) textInputLayout.setErrorEnabled(false); return; } super.setError(error); } /** * Returns the {@link TextInputLayout} in the views hierarchy or * null if the view is not wrapped within such a layout. * * @return */ public TextInputLayout getParentTextInputLayout() { ViewParent parent = getParent(); while (parent != null) { if (parent instanceof TextInputLayout) return (TextInputLayout) parent; parent = parent.getParent(); } return null; } /** * Clears an error. */ public void clearError() { setError(null); } private boolean required = false; private boolean directionRight = false; /** * Adds an asterisk to the hint that was set to the receiver marking the input * field as 'required'. * * @param required */ public void setRequired(boolean required) { this.required = required; TextInputLayout textInputLayout = getParentTextInputLayout(); if (textInputLayout != null) { String hint = textInputLayout.getHint().toString().replaceAll(" \\*", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (required) { hint = hint + " *"; //$NON-NLS-1$ } textInputLayout.setHint(hint); } } /** * Adds an asterisk to the hint that was set using * {@link MDEditText#setText(CharSequence)} if {@link #setRequired(boolean)} was * set to true. * * @return */ @Override public CharSequence getHint() { return required ? super.getHint() + " *" : super.getHint(); //$NON-NLS-1$ } /** * Is required. * * @return */ public boolean isRequired() { return required; // $NON-NLS-1$ } @Override public void setEnabled(boolean enabled) { setFocusable(enabled); setClickable(enabled); setFocusableInTouchMode(enabled); super.setEnabled(enabled); // set Enabled/Disabled style. int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; if (!enabled) { textColor = LayoutUtils.DEFAULT_DISABLED_COLOR; } setTextColor(textColor); } @Override public void setFilters(InputFilter[] filters) { super.setFilters(filters); } public void setDirectionRight(final boolean setFormattedDigitNumber) { directionRight = true; setGravity(Gravity.RIGHT); addTextChangedListener(new Watcher(this, null) { @Override public void afterTextChanged(Editable editText) { removeTextChangedListener(this); //00.00 if (beforeCharSequence < afterCharSequence) { setTextAndSelection(StringUtil.getFormattedDigitNumber(editText.toString(), setFormattedDigitNumber)); } else { // select all and enter new number if (editText.toString().length() == 1 && !editText.toString().equalsIgnoreCase("0")) { if (setFormattedDigitNumber) { setTextAndSelection("00.0" + editText.toString()); } } } addTextChangedListener(this); } }); } public void setSelection(int index) { Selection.setSelection(getText(), index); } public void setText(String text) { setTextAndSelection(text); } public void setTextAndSelection(String text) { // try to fix setSelection not working from softkey. getText().clear(); append(text); append(""); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import android.content.Context; import android.support.v7.widget.AppCompatRadioButton; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * A view for easy creation and use of an {@link AppCompatRadioButton} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * MDRadioButton structure: * LinearLayout * --AppCompatRadioButton * --View(Underline) * --TextView(Error message) * * @author nop */ public class MDRadioButton extends AppCompatRadioButton { public MDRadioButton(Context context) { super(context); } /** * Creates a new {@link MDRadioButton} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @return */ public static MDRadioButton createDefaultRadioButton(Context context) { return createDefaultRadioButton(context, null); } /** * Creates a new {@link MDRadioButton} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @return */ public static MDRadioButton createDefaultRadioButton(Context context, String label) { return createRadioButton(context, label); } /** * Creates a new {@link MDRadioButton} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @return */ public static MDRadioButton createDefaultRadioButton(ViewGroup parent, String label) { if (parent == null) { return null; } Context context = parent.getContext(); MDRadioButton radioButton = createRadioButton(context, label); LinearLayout linearLayout = (LinearLayout) radioButton.getParent(); parent.addView(linearLayout); radioButton.setContentDescription(label); return radioButton; } private static MDRadioButton createRadioButton(Context context, final String label) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setOrientation(LinearLayout.VERTICAL); final MDRadioButton radioButton = new MDRadioButton(context); radioButton.setTag("RADIOBUTTON"); //$NON-NLS-1$ radioButton.setText(label); radioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); radioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioButton.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.addView(radioButton); View underline = new View(context); underline.setTag("UNDERLINE"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); underlineLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), LayoutUtils.convertDpToPixel(context, 8), LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); underline.setLayoutParams(underlineLinearLayout); underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); linearLayout.addView(underline); TextView errorText = new TextView(context); errorText.setTag("ERRORTEXT"); //$NON-NLS-1$ LinearLayout.LayoutParams errorTextLinearLayout = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); errorTextLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); errorText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); errorText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); errorText.setLayoutParams(errorTextLinearLayout); errorText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); errorText.setVisibility(View.GONE); linearLayout.addView(errorText); radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { radioButton.clearError(); } }); return radioButton; } /** * Gets top parent. * * @return */ public View getTopParent() { return (View) this.getParent(); } /** * Sets an error. * * @param error */ @Override public void setError(CharSequence error) { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(error); errorText.setVisibility(View.VISIBLE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_ERROR_COLOR); underline.setVisibility(View.VISIBLE); } /** * Clears an error. */ public void clearError() { TextView errorText = getErrorText(); if(errorText == null) return; errorText.setText(""); //$NON-NLS-1$ errorText.setVisibility(View.GONE); View underline = getUnderline(); if(underline == null) return; underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); underline.setVisibility(View.GONE); } private View getUnderline() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(1); if ("UNDERLINE".equals(view.getTag().toString())) { //$NON-NLS-1$ return view; } return null; } private TextView getErrorText() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(2); if (view instanceof TextView && "ERRORTEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.ErrorCode; import ch.mfiles.kaba.kolibri.common.businessobjects.Incident; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.util.DateUtils; public class ReportContentWidget extends Form { private Application app; private DatabaseUtil dbutil; private Context context; private Job job; private TextView timeTitle; private GridLayout timesGridLayout; private TextView reportTitle; private GridLayout reportGridLayout; private TextView materialTitle; private GridLayout materialGridLayout; private TextView messageTitle; private GridLayout messageGridLayout; private TextView imageTitle; private GridLayout imageGridLayout; private ImagesUtil imagesUtil; private EnumUtil enumUtil; public ReportContentWidget(Application app, DatabaseUtil dbutil, Context context) { this.app = app; this.dbutil = dbutil; this.context = context; this.imagesUtil = ImagesUtil.getInstance(app); this.enumUtil = EnumUtil.getInstance(dbutil); } public CardView createTimesCard() { timesGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); timesGridLayout.setLayoutParams(gridLayoutParams); timesGridLayout.setColumnCount(2); timesGridLayout.setUseDefaultMargins(true); timeTitle = new TextView(context); return createCard(timeTitle, timesGridLayout); } public CardView createReportCard() { reportGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); reportGridLayout.setLayoutParams(gridLayoutParams); reportGridLayout.setColumnCount(2); reportGridLayout.setUseDefaultMargins(true); reportTitle = new TextView(context); return createCard(reportTitle, reportGridLayout); } public CardView createMaterialCard() { materialGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); materialGridLayout.setLayoutParams(gridLayoutParams); materialGridLayout.setColumnCount(2); materialGridLayout.setUseDefaultMargins(true); materialTitle = new TextView(context); return createCard(materialTitle, materialGridLayout); } public CardView createMessageCard() { messageGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); messageGridLayout.setLayoutParams(gridLayoutParams); messageGridLayout.setColumnCount(2); messageGridLayout.setUseDefaultMargins(true); messageTitle = new TextView(context); return createCard(messageTitle, messageGridLayout); } public CardView createImageCard() { imageGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); imageGridLayout.setLayoutParams(gridLayoutParams); imageGridLayout.setColumnCount(2); imageGridLayout.setUseDefaultMargins(true); imageTitle = new TextView(context); return createCard(imageTitle, imageGridLayout); } private CardView createCard(TextView title, GridLayout gridLayout) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 0, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MAX_PADDING); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); gradientDrawable.setCornerRadius(7f); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_CARD_VIEW_SHADOW_COLOR); // cardView.setBackground(gradientDrawable); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); RelativeLayout titleRrelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams relativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); relativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); titleRrelativeLayout.setLayoutParams(relativeLayoutParams); title.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); title.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); title.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); title.setPadding(5, 10, 5, 5); title.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); titleRrelativeLayout.addView(title); linearLayout.addView(titleRrelativeLayout); linearLayout.addView(gridLayout); cardView.addView(linearLayout); ((LayoutParams) cardView.getLayoutParams()).topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; return cardView; } public void loadTimes(boolean showDate) { job.loadReports(dbutil); Report report = job.getLatestReport(); timesGridLayout.removeAllViews(); report.loadTimes(dbutil); List reportTimeList = report.getTimes(); if (reportTimeList.isEmpty()) { createTextView(timesGridLayout, Messages.getString("noTimesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } else { for (int i = 0; i < reportTimeList.size(); i++) { JobReportTime reportTime = reportTimeList.get(i); if (i == 0) timeTitle.setText(Messages.getString("timesFrom") + " " + DateTimeUtil.showDate(reportTime.getDate())); WorkType WorkType = dbutil.selectWorkTypeByJobTypeAndWorkTypeCode(job.getJobType(), reportTime.getWorkTypeCode()); String workTypeText = (WorkType == null ? "" : WorkType.getText()); String dateString = ""; if(showDate) { dateString = DateTimeUtil.showDate(reportTime.getDate()) + " "; } String stopTime = ""; if (!DateUtils.getInitialDateTime().equals(reportTime.getStopTime())) { stopTime = DateTimeUtil.showTime(reportTime.getStopTime()); } createInfoTextView(timesGridLayout, dateString + DateTimeUtil.showTime(reportTime.getStartTime()) + "-" + stopTime, workTypeText); } } } public void loadReport() { job.loadReports(dbutil); Report report = job.getLatestReport(); reportGridLayout.removeAllViews(); String date = DateTimeUtil.showDate(report.getCreateDate()); reportTitle.setText(Messages.getString("reportsFrom") + " " + date); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (job.getCurrentReport().getReportStatus().isInitial()) { createTextView(reportGridLayout, Messages.getString("noReportRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } else { job.loadAddresses(dbutil); createInfoTextView(reportGridLayout, Messages.getString("location"), report.getCommissionNumber()); //$NON-NLS-1$ Address address = job.getObjectAddress(); createInfoTextView(reportGridLayout, "", address.getLocation()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, "", address.getStreet() + " " + address.getPostalCode() + " " + address.getCity()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ createInfoTextView(reportGridLayout, Messages.getString("orderNo"), report.getOrderNumber()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("billing"), report.getBilling()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("typeOfJob"), report.getWorkType()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("orderDate"), DateTimeUtil.showDate(report.getCreateDate())); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("jobState"), report.getReportStatus().toString()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("costumerReport"), report.getCustomerSupport()); //$NON-NLS-1$ createInfoTextView(reportGridLayout, Messages.getString("checkList"), report.getChecklist()); //$NON-NLS-1$ addFailure(); addError(); createInfoTextView(reportGridLayout, Messages.getString("installationError"), report.getSystemError()); //$NON-NLS-1$ addMaintanNance(); createInfoTextView(reportGridLayout, Messages.getString("signature"), report.isSignatureInfo()? report.getSignatureInfo():""); } } private void addFailure() { Report report = job.getLatestReport(); String incidentAText = ""; //$NON-NLS-1$ String incidentBText = ""; //$NON-NLS-1$ Incident incidentA = null; Incident incidentB = null; if(!report.getIncidentAB().isEmpty()) { incidentA = dbutil.selectIncidentByFCT(report.getIncidentAB().substring(0, 2), "A"); //$NON-NLS-1$ incidentB = dbutil.selectIncidentByFCT(report.getIncidentAB().substring(2), "B"); //$NON-NLS-1$ } if(incidentA != null) { incidentAText = incidentA.getErrorCode() + " / " +incidentA.getText(); //$NON-NLS-1$ } if(incidentB != null) { incidentBText = incidentB.getErrorCode() + " / " +incidentB.getText(); //$NON-NLS-1$ } createInfoTextViewWithIcon(reportGridLayout, Messages.getString("failure"), "1 " + incidentAText); //$NON-NLS-1$ //$NON-NLS-2$ createInfoTextView(reportGridLayout, "", "2 " + incidentBText); //$NON-NLS-1$ //$NON-NLS-2$ } private void addError() { Report report = job.getLatestReport(); String error = ""; //$NON-NLS-1$ String error2 = ""; //$NON-NLS-1$ if("000".equalsIgnoreCase(report.getErrorId1())){ //$NON-NLS-1$ ErrorCode errorCode1 = dbutil.selectErrorCodeByFc(report.getErrorId1()); if(errorCode1 != null) { error = errorCode1.getErrorCode() + " / " + errorCode1.getText(); //$NON-NLS-1$ } } if("000".equalsIgnoreCase(report.getErrorId2())){ //$NON-NLS-1$ ErrorCode errorCode2 = dbutil.selectErrorCodeByFc(report.getErrorId2()); if(errorCode2 != null) { error2 = errorCode2.getErrorCode() + " / " + errorCode2.getText(); //$NON-NLS-1$ } } createInfoTextView(reportGridLayout, Messages.getString("error"), "1: " + error); //$NON-NLS-1$ //$NON-NLS-2$ createInfoTextView(reportGridLayout, "", "2: " + error2); //$NON-NLS-1$ //$NON-NLS-2$ } private void addMaintanNance(){ Report report = job.getLatestReport(); String planed = report.getServicePlanMonth1() + " " + report.getServicePlanMonth2() + " " + report.getServicePlanMonth3() //$NON-NLS-1$ //$NON-NLS-2$ + " " + report.getServicePlanMonth4() + " " + report.getServicePlanMonth5() + " " + report.getServicePlanMonth6(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String done = ""; //$NON-NLS-1$ if (report.getMonthYear().length() > 2) { if(!CommonConstants.PLEASE_SELECT.equalsIgnoreCase(report.getMonthYear().substring(0, 2))){ //$NON-NLS-1$ done = report.getMonthYear().substring(0, 2); } if(!CommonConstants.PLEASE_SELECT.equalsIgnoreCase(report.getMonthYear().substring(2, 4))){ //$NON-NLS-1$ done += " " + report.getMonthYear().substring(2, 4); //$NON-NLS-1$ } } else { if(!CommonConstants.PLEASE_SELECT.equalsIgnoreCase(report.getMonthYear())){ //$NON-NLS-1$ done = report.getMonthYear(); } } createInfoTextView(reportGridLayout, Messages.getString("Service"), Messages.getString("Planed") + ": " + planed); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ createInfoTextView(reportGridLayout, "", Messages.getString("Done") + ": " + done); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void loadMaterial() { Report report = job.getLatestReport(); materialGridLayout.removeAllViews(); materialTitle.setText(Messages.getString("material")); //$NON-NLS-1$ // Verwendetes Material (nur wenn vorhanden) List reportMatList = dbutil.selectReportMaterialList(report.getGuId()); if (!reportMatList.isEmpty()) { for (int i = 0; i < reportMatList.size(); i++) { ReportMaterial reportMat = reportMatList.get(i); Material part = dbutil.selectMaterialByMatNo(reportMat.getSparePartNumber()); String material = ""; //$NON-NLS-1$ if (part == null) { material += " " + reportMat.getProductName(); //$NON-NLS-1$ } else { material += " " + part.getMaterialShortText(); //$NON-NLS-1$ } createInfoTextView(materialGridLayout, reportMat.getAmount() + " " + reportMat.getUnit(), material); //$NON-NLS-1$ } } else { createTextView(materialGridLayout, Messages.getString("noMaterialRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } } public void loadMessage() { Report report = job.getLatestReport(); messageGridLayout.removeAllViews(); messageTitle.setText(Messages.getString("messages")); //$NON-NLS-1$ String messageId = ""; //$NON-NLS-1$ List reportTextList = dbutil.selectJobMessageListByReport(report); boolean isEmptyMessage = true; for (int i = 0; i < reportTextList.size(); i++) { JobMessage jobMessage = reportTextList.get(i); if(!jobMessage.getMessageId().equalsIgnoreCase("01")) { String message = ""; ReportMessage reportMessage = null; if(job.getJobType().isMON()) { if (jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.PROJECT_MANAGER) || jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.DISPOSITION)) { continue; } JobMonText jobMonText = dbutil.selectReportMONMessageByMsgcAndLangu(jobMessage.getMessageCode(), ""); if(jobMonText != null) { message = jobMonText.getText(); } } else { reportMessage = dbutil.selectReportMessageByMsgc(jobMessage.getMessageCode()); if(reportMessage != null) { message = reportMessage.getMessage(); } } String messageIdTemp = jobMessage.getMessageId(); // Don't display text for supervisor and KDZ-text 3 if ((!(jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.HEAD_OF_DEPARTMENT) && (reportMessage != null && reportMessage.isABTL()))) && !messageIdTemp.equalsIgnoreCase(CommonConstants.Message.KDZ3)) { String key = ""; //$NON-NLS-1$ if (!messageId.equals(messageIdTemp)) { key = enumUtil.messageRecipientEnum.get(jobMessage.getMessageId()); } if(!message.isEmpty() || !jobMessage.getFullText().isEmpty()) { isEmptyMessage = false; createInfoTextViewWithBold(messageGridLayout, key, message); createInfoTextView(messageGridLayout, "", jobMessage.getFullText()); //$NON-NLS-1$ } } } } if (isEmptyMessage) { createTextView(messageGridLayout, Messages.getString("noMessagesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } } public void loadImage() { Report report = job.getLatestReport(); imageGridLayout.removeAllViews(); imageTitle.setText(Messages.getString("image")); //$NON-NLS-1$ // String messageId = ""; //$NON-NLS-1$ // List reportTextList = dbutil.selectJobMessageListByReport(report); boolean isEmptyImage = true; // for (int i = 0; i < reportTextList.size(); i++) { // JobMessage zkdmobmsg = reportTextList.get(i); // // String value = ""; // ReportMessage reportMessage = dbutil.selectReportMessageByMsgcAndLangu(zkdmobmsg.getMessageCode(), dbutil.getUser().getLanguage()); // if(reportMessage != null) { // value = reportMessage.getMessage(); // } // // String messageIdTemp = zkdmobmsg.getMessageId(); // // Don't display text for supervisor and KDZ-text 3 // if ((!(zkdmobmsg.getMessageId().equalsIgnoreCase(CommonConstants.ZKDMOBMSG.ABTEILUNGSLEITER) // && (reportMessage != null && reportMessage.isABTL()))) && !messageIdTemp.equalsIgnoreCase(CommonConstants.ZKDMOBMSG.KDZ3)) { // String key = ""; //$NON-NLS-1$ // if (!messageId.equals(messageIdTemp)) { // key = enumUtil.messageRecipientEnum.get(zkdmobmsg.getMessageId()); // } // // if(!value.isEmpty() || !zkdmobmsg.getFullText().isEmpty()) { // isEmptyImage = false; // createInfoTextViewWithBold(imageGridLayout, key, value); // createInfoTextView(imageGridLayout, "", zkdmobmsg.getFullText()); //$NON-NLS-1$ // } // } // } if (isEmptyImage) { createTextView(imageGridLayout, Messages.getString("noImageRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } } /** * Creates info text view. * * @param gridLayout * @param key * @param value */ private void createInfoTextView(GridLayout gridLayout, String key, final String value) { createInfoTextView(gridLayout, key, value, false, false); } private void createInfoTextViewWithBold(GridLayout gridLayout, String key, final String value) { createInfoTextView(gridLayout, key, value, true, false); } private void createInfoTextViewWithIcon(GridLayout gridLayout, String key, final String value) { createInfoTextView(gridLayout, key, value, false, true); } private void createInfoTextView(GridLayout gridLayout, String key, final String value , boolean isBold, boolean isShowIcon) { TextView gridTextViewKey = new TextView(gridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.4f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout gridRelativeLayout = new RelativeLayout(gridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.6f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(gridLayout.getContext()); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(value); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(gridTextViewValue); if (isShowIcon) { ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(imagesUtil.getImage(ImagesUtil.Images.PHONE_DISABLED, CommonConstants.Images.IMAGE_DPI))); if (value != null && !value.isEmpty()) { String phoneNumber = ""; if (StringUtil.findChar(value, ' ')) { String values[] = value.split(" "); if(values.length > 1) { phoneNumber = values[1].replaceAll("\\s+","").trim();//$NON-NLS-1$ //$NON-NLS-2$ } } final String tel = phoneNumber; if(!phoneNumber.isEmpty()) { gridImageView.setImageDrawable(getBitmanDrawable(imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, CommonConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + tel)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } }); } } gridRelativeLayout.addView(gridImageView); } gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } private void createTextView(GridLayout gridLayout, String text, int color) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(text); gridTextViewKey.setTextColor(color); gridLayout.addView(gridTextViewKey); } public TextView getTimeTitle() { return timeTitle; } public void setTimeTitle(TextView timeTitle) { this.timeTitle = timeTitle; } public GridLayout getTimesGridLayout() { return timesGridLayout; } public void setTimesGridLayout(GridLayout timesGridLayout) { this.timesGridLayout = timesGridLayout; } public TextView getReportTitle() { return reportTitle; } public void setReportTitle(TextView reportTitle) { this.reportTitle = reportTitle; } public GridLayout getReportGridLayout() { return reportGridLayout; } public void setReportGridLayout(GridLayout reportGridLayout) { this.reportGridLayout = reportGridLayout; } public TextView getMaterialTitle() { return materialTitle; } public void setMaterialTitle(TextView materialTitle) { this.materialTitle = materialTitle; } public GridLayout getMaterialGridLayout() { return materialGridLayout; } public void setMaterialGridLayout(GridLayout materialGridLayout) { this.materialGridLayout = materialGridLayout; } public TextView getMessageTitle() { return messageTitle; } public void setMessageTitle(TextView messageTitle) { this.messageTitle = messageTitle; } public GridLayout getMessageGridLayout() { return messageGridLayout; } public void setMessageGridLayout(GridLayout messageGridLayout) { this.messageGridLayout = messageGridLayout; } public void setJob(Job job) { this.job = job; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; public class TimeEditText extends MDEditText { private static Log log = LogFactory.getLog(TimeEditText.class); public TimeEditText(Context context) { super(context); } public static TimeEditText createDefaultEditText(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); TimeEditText editText = createEditText(context, label, required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private static TimeEditText createEditText(Context context, String label, final boolean required) { final TimeEditText editText = new TimeEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setRawInputType(InputType.TYPE_CLASS_NUMBER); if (required) { editText.setRequired(required); } if (label != null) { editText.setHint(label); } editText.addTextChangedListener(new TextWatcher() { private int beforeCharSequence; private int afterCharSequence; private Pattern pattern = Pattern.compile(CommonConstants.TimeSheet.TIME_REGEX); @Override public void afterTextChanged(Editable s) { String value = s.toString().trim(); editText.removeTextChangedListener(this); value = value.replace("-", ""); value = value.replace(" ", ""); value = value.replace(".", ""); value = value.replace(",", ""); if(!StringUtil.isNumeric(value)) { StringUtil.removeLetters(value); } editText.setText(value); try { if (value.length() == CommonConstants.TimeSheet.COLON_POSITION && beforeCharSequence < afterCharSequence) { if(Integer.parseInt(StringUtil.getOnlyDigits(value)) > 23){ value = "23"; //$NON-NLS-1$ } value = value + ":"; //$NON-NLS-1$ editText.setText(value); } if (value.length() == CommonConstants.TimeSheet.COLON_POSITION +1 && value.charAt(CommonConstants.TimeSheet.COLON_POSITION) != ':' && beforeCharSequence < afterCharSequence) { String hour = value.substring(0, CommonConstants.TimeSheet.COLON_POSITION); String minutes = value.substring(CommonConstants.TimeSheet.COLON_POSITION, value.length()); if(Integer.parseInt(StringUtil.getOnlyDigits(minutes)) > 59){ minutes = "59"; //$NON-NLS-1$ } value = hour + ":" + minutes; //$NON-NLS-1$ editText.setText(value); } if(value.indexOf(':') > -1) { if(value.length() > 5) { value = value.substring(0, 5); } } // remove ":" position if(value.indexOf(':') != CommonConstants.TimeSheet.COLON_POSITION) { value = value.replace(":", ""); } if (value.length() > CommonConstants.TimeSheet.COLON_POSITION+1) { if(value.charAt(value.length()-1) == ':') { value = value.substring(0, value.length()-1); } else { String values[] = value.split(":"); //$NON-NLS-1$ if(Integer.parseInt(StringUtil.getOnlyDigits(values[1])) > 59){ values[1] = "59"; //$NON-NLS-1$ } editText.setText(values[0] + ":" + values[1]); //$NON-NLS-1$ } } } catch (IndexOutOfBoundsException e) { editText.setText(""); } Matcher matcher = pattern.matcher(value); if (matcher.matches() || matcher.hitEnd()) { editText.setText(value); } editText.setSelection(editText.getText().length()); if (editText.hasFocus()) { editText.clearError(); } editText.addTextChangedListener(this); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } }); editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, Mode.SRC_ATOP); return editText; } public boolean isValid() { return isMatch(getText().toString()); } private boolean isMatch(String value) { Pattern pattern = Pattern.compile(CommonConstants.TimeSheet.TIME_REGEX); Matcher matcher = pattern.matcher(value); return matcher.matches(); } public void setText(String text) { super.setText(text); } public void setLabel(String label) { super.setHint(label); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; /** * A PagerAdapter providing a static number of views. * * @author joerg * */ public class ViewPageAdapter extends PagerAdapter { private static class Page { String title; View view; Page(String title, View view) { this.view = view; this.title = title; } } private List viewPages = new ArrayList(); public void addPage(String title, View pageView) { viewPages.add(new Page(title, pageView)); notifyDataSetChanged(); } @Override public Object instantiateItem(ViewGroup container, int position) { View pageView = viewPages.get(position).view; container.addView(pageView); return pageView; } @Override public CharSequence getPageTitle(int position) { return viewPages.get(position).title; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return viewPages.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } package ch.mfiles.kaba.kolibri.common.forms; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.util.TypedValue; import android.widget.EditText; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; public class CommonUtilForm extends Form { public static Application mCurrentAplicationApp = null; public static void showValidationErrorMessageBox(Application application) { mCurrentAplicationApp.showMessageBox( Messages.getString("validationError"), //$NON-NLS-1$ Messages.getString("error"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_ERROR); //$NON-NLS-1$ } /** * Gets text view. */ public static TextView getTextView(Context context, String text) { TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textView.setText(text); textView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); return textView; } /** * Gets check box. */ public static AppCompatCheckBox getCheckBox(Context context, String text) { AppCompatCheckBox checkBox = new AppCompatCheckBox(context); checkBox.setText(text); checkBox.setContentDescription(text); checkBox.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); checkBox.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return checkBox; } /** * Gets edit text. */ public static EditText getEditText(Context context, String hint, int inputType) { EditText editText = new EditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); if (inputType != 0) { editText.setInputType(inputType); } if (hint != null) { editText.setHint(hint); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); return editText; } } package ch.mfiles.kaba.kolibri.common.forms; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.CommonApplication; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.onQueryTextListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.MaterialNumberMaskWatcher; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class MaterialSearchForm extends DialogForm { private static Log log = LogFactory.getLog(MaterialSearchForm.class); public static Application app; // don't make this CommonApplication public MaterialSearchView searchView; public MDEditText nameEditText; public MDEditText numberEditText; public String barcode; protected LinearLayout view; protected LinearLayout middleContentLinearLayout; protected MaterialNumberMaskWatcher materialNumberMaskWatcher; private LinearLayout.LayoutParams numberLayoutParams; private LinearLayout.LayoutParams cameraValueParams; protected void addContentLinearLayout(LinearLayout contentLinearLayout) { this.middleContentLinearLayout.addView(contentLinearLayout); } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setFocusable(true); view.setFocusableInTouchMode(true); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); // create SearchView searchView = new MaterialSearchView(context); searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionClick(int position) { String matnr = searchView.getSuggessionItemList().get(position).getNumber(); String matname = searchView.getSuggessionItemList().get(position).getName(); log.info("select matNo " + matnr); nameEditText.setText(matname); numberEditText.setText(matnr); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); loadMaterialsList(matnr); return true; } @Override public boolean onSuggestionSelect(int position) { return true; } }); searchView.setQueryTextListener(new onQueryTextListener() { @Override public void onQueryTextChange(String query) { loadMaterialsList(query); } }); toolbar.addView(searchView); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); nameEditText = MDEditText.createDefaultEditText(contentLinearLayout, Messages.getString("materialName"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true); //$NON-NLS-1$ nameEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout numberLinearLayout = new LinearLayout(context); numberLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams numberLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); numberLinearLayoutParams.gravity = Gravity.CENTER; numberLinearLayoutParams.width = LayoutParams.MATCH_PARENT; numberLinearLayoutParams.height = LayoutParams.MATCH_PARENT; numberLinearLayoutParams.weight = 1; numberLinearLayout.setLayoutParams(numberLinearLayoutParams); numberEditText = MDEditText.createDefaultEditText(numberLinearLayout, Messages.getString("materialNumber"), InputType.TYPE_CLASS_PHONE, true); //$NON-NLS-1$ numberEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FOURTEEN) }); materialNumberMaskWatcher = new MaterialNumberMaskWatcher(numberEditText); numberEditText.addTextChangedListener(materialNumberMaskWatcher); numberLayoutParams = new LinearLayout.LayoutParams(0, 0); numberLayoutParams.gravity = Gravity.CENTER; numberLayoutParams.width = 0; numberLayoutParams.height = LayoutParams.MATCH_PARENT; numberLayoutParams.weight = 1.0f; numberEditText.getParentTextInputLayout().setLayoutParams(numberLayoutParams); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.0f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); if (result == null) { // app.messageUtil.showMessage(Messages.getString("aborted")); } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { processBarcode(); } }; } }); cameraLinearLayout.addView(gridImageView); numberLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(numberLinearLayout); middleContentLinearLayout = new LinearLayout(context); contentLinearLayout.addView(middleContentLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); loadData(); processBarcode(); return null; } private void processBarcode() { System.out.println("barcode " + barcode); if (barcode != null && !barcode.isEmpty()) { numberEditText.setEnabled(false); String matNoQuery = StringUtil.getMaterialNoFromScan(barcode.trim()); System.out.println("matNoQuery " + matNoQuery); searchView.setQuery(matNoQuery, true); if (searchView.getSuggessionItemList().isEmpty()) { numberEditText.setText(matNoQuery); } barcode = null; } } protected void setEnabledControls(boolean enabled) { searchView.setEnabled(enabled); nameEditText.setEnabled(enabled); numberEditText.setEnabled(enabled); } protected void loadData() { resetView(); } protected void resetView() { if (!numberEditText.isEnabled()) { numberEditText.setEnabled(true); } nameEditText.clearError(); numberEditText.clearError(); nameEditText.clearFocus(); numberEditText.clearFocus(); nameEditText.setText(""); nameEditText.getText().clear(); numberEditText.getText().clear(); numberEditText.setText(""); searchView.setQuery("", false); searchView.clearFocus(); } public boolean isMatrialNumberWrongFormat(){ Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if(numberEditText.getText().length() >= 14 && !numberEditText.getText().toString().isEmpty() && !matcher.matches()) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { return null; } @Override public void runOnUIThread() { numberEditText.setError(Messages.getString("WrongFormatXX-XXXX-XXX/XX")); } }; return true; } return false; } public void setShowScanNumber(boolean isShow) { if (isShow) { numberLayoutParams.weight = 0.9f; cameraValueParams.weight = 0.1f; } } protected void loadMaterialsList(String queryText) { } } /** * */ package ch.mfiles.kaba.kolibri.common.forms; import java.util.List; import android.content.Context; import android.support.v4.widget.DrawerLayout; import android.widget.LinearLayout; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm.NavigationMenuListAdapter; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm.NavigationMenuListItem; /** * The Navigation Interface. * * @author nop * */ public interface Navigation { /** * Gets the Context. * * @return */ public Context getContext(); /** * Sets the Context. * * @param context */ public void setContext(Context context); /** * Gets the view. * * @return */ public DrawerLayout getView(); /** * Sets the view. * * @param view */ public void setView(DrawerLayout view); /** * Gets the content view. * * @return */ public LinearLayout getContentView(); /** * Sets the content view. * * @param contentView */ public void setContentView(LinearLayout contentView); /** * Gets the menu list adapter. * * @return */ public NavigationMenuListAdapter getMenuListAdapter(); /** * Sets the menu list adapter. * * @param menuListAdapter */ public void setMenuListAdapter(NavigationMenuListAdapter menuListAdapter); /** * Gets the menu list view. * * @return */ public List getMenuListView(); /** * Sets the menu list view. * * @param menuListView */ public void setMenuListView(List menuListView); /** * On menu item load. * * @param menuListView */ public void onMenuItemLoad(List menuListView); /** * On menu item load. * * @param menuListView */ public void onMenuItemClickListener(ListView menuView); /** * On menu item notify data set changed. * * @param menuListView */ public void onMenuItemNotifyDataSetChanged(); } package ch.mfiles.kaba.kolibri.common.forms; import java.util.ArrayList; import java.util.List; import android.R.color; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ui.LayoutInflater; public abstract class NavigationForm extends SuperForm implements Navigation { // initialized by the kolibri framework... public static Application app; private Context context; private DrawerLayout view; private LinearLayout contentView; private NavigationMenuListAdapter menuListAdapter; private List menuListView = new ArrayList(); @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // prepare toolbar getToolbar().setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // create content including navigation view view = new DrawerLayout(context); view.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always // show below toolbar view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // create the dialog's view hierarchy, one may use inflation instead contentView = new LinearLayout(context); contentView.setOrientation(LinearLayout.VERTICAL); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); frameLayout.addView(contentView); ListView menuView = new ListView(context); menuView.setDivider(new ColorDrawable(LayoutUtils.DEFAULT_LABEL_COLOR)); menuView.setDividerHeight(1); menuView.setBackgroundColor(Color.WHITE); menuView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); menuView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); onMenuItemClickListener(menuView); menuListAdapter = new NavigationMenuListAdapter(context, menuListView); menuView.setAdapter(menuListAdapter); // link toolbar to drawer layout (creating animated left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null,view,getToolbar(),0,0){ @Override public void onDrawerClosed(View v){ super.onDrawerClosed(v); KeyboardUtil.closeKeyboard(appman, getView()); } @Override public void onDrawerOpened(View v) { super.onDrawerOpened(v); KeyboardUtil.closeKeyboard(appman, getView()); } }; view.addDrawerListener(drawerToggle); drawerToggle.syncState(); onMenuItemLoad(getMenuListView()); // add views to drawer view.addView(frameLayout); view.addView(menuView); return view; } @Override public void onMenuItemClickListener(ListView menuView) { // Auto-generated method stub } @Override public void onMenuItemLoad(List menuListView) { // Auto-generated method stub } @Override public void onMenuItemNotifyDataSetChanged() { menuListAdapter.notifyDataSetChanged(); } @Override public Context getContext() { return context; } @Override public void setContext(Context context) { this.context = context; } @Override public DrawerLayout getView() { return view; } @Override public void setView(DrawerLayout view) { this.view = view; } @Override public LinearLayout getContentView() { return contentView; } @Override public void setContentView(LinearLayout contentView) { this.contentView = contentView; } @Override public NavigationMenuListAdapter getMenuListAdapter() { return menuListAdapter; } @Override public void setMenuListAdapter(NavigationMenuListAdapter menuListAdapter) { this.menuListAdapter = menuListAdapter; } @Override public List getMenuListView() { return menuListView; } @Override public void setMenuListView(List menuListView) { this.menuListView = menuListView; } /** * A item that has an icon on the left, a text and a tag. * * @author nop * */ public static class NavigationMenuListItem { private Drawable icon = null; private String text; private String tag; private boolean enable = true; private OnClickListener onClickListener = null; public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public boolean isEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } public OnClickListener getOnClickListener() { return onClickListener; } public void setOnClickListener(OnClickListener onClickListener) { this.onClickListener = onClickListener; } } public class NavigationMenuListAdapter extends BaseAdapter { private static final int ICON = 7777; private static final int TEXT = 8888; private static final int TAG = 9999; private List mData; private Context context; public NavigationMenuListAdapter(Context context, List coll) { mData = coll; this.context = context; } /** * @see android.widget.Adapter#getCount() */ public int getCount() { return mData.size(); } /** * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return mData.get(position); } /** * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { return position; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { return createView(position, convertView, parent); } private View createView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { LinearLayout rootLayout = new LinearLayout(context); rootLayout.setId(TAG); rootLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams rootLayoutParams = new LinearLayout.LayoutParams(0, 0); rootLayoutParams.width = LayoutParams.MATCH_PARENT; rootLayoutParams.height = LayoutUtils.convertDpToPixel(context, 65); rootLayout.setLayoutParams(rootLayoutParams); rootLayout.setBackgroundColor(color.white); rootLayout.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); LinearLayout leftIconLinearLayout = new LinearLayout(context); leftIconLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; leftIconLinearLayoutParams.width = 0; leftIconLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; leftIconLinearLayoutParams.weight = 0.5f; leftIconLinearLayoutParams.leftMargin = LayoutUtils.convertDpToPixel(context, 10); leftIconLinearLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 10); leftIconLinearLayout.setLayoutParams(leftIconLinearLayoutParams); FrameLayout beginFrameLayout = new FrameLayout(context); LinearLayout.LayoutParams beginFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); beginFrameParams.gravity = Gravity.LEFT; beginFrameLayout.setLayoutParams(beginFrameParams); beginFrameLayout.setBackgroundColor(color.holo_green_light); ImageView icon = new ImageView(context); icon.setId(ICON); icon.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); beginFrameLayout.addView(icon); leftIconLinearLayout.addView(beginFrameLayout); rootLayout.addView(leftIconLinearLayout); LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 2f; midLinearLayout.setLayoutParams(midLinearLayoutParams); TextView titleTextView = new TextView(context); titleTextView.setId(TEXT); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(titleTextView); rootLayout.addView(midLinearLayout); v = rootLayout; } else { v = convertView; } bindView(position, v); return v; } /** * Sets the {@link android.content.res.Resources.Theme} against which * drop-down views are inflated. *

* By default, drop-down views are inflated against the theme of the * {@link Context} passed to the adapter's constructor. * * @param theme * the theme against which to inflate drop-down views or * {@code null} to use the theme from the adapter's context * @see #getDropDownView(int, View, ViewGroup) */ @SuppressLint("NewApi") public void setDropDownViewTheme(Resources.Theme theme) { //Do nothings } public Resources.Theme getDropDownViewTheme() { return null; } private void bindView(int position, View view) { final NavigationMenuListItem dataSet = mData.get(position); if (dataSet == null) { return; } if (null == view) { return; } ImageView icon = (ImageView) view.findViewById(ICON); TextView text = (TextView) view.findViewById(TEXT); LinearLayout root = (LinearLayout) view; if (null != dataSet.getIcon() && icon != null) { icon.setImageDrawable(dataSet.getIcon()); } if (null != dataSet.getText() && text != null) { setViewText(text, dataSet.getText()); if (dataSet.isEnable()) { text.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); } else { text.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); } } if (null != dataSet.getTag()) { root.setTag(dataSet.getTag()); } } /** * Called by bindView() to set the text for a TextView but only if there * is no existing ViewBinder or if the existing ViewBinder cannot handle * binding to a TextView. * * @param v TextView to receive text * @param text the text to be set for the TextView */ public void setViewText(TextView v, String text) { v.setText(text); } } } package ch.mfiles.kaba.kolibri.common.forms; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.graphics.Color; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The super class of all forms within this application. Contains common * members, methods and controls. * */ public class SuperForm extends Form { /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(Context context, LayoutInflater inflater) { ListView listView = new ListView(context); listView.setBackgroundColor(Color.CYAN); listView.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); return listView; } public static void showValidationErrorMessageBox(Application application) { showErrorMessageBox(application, Messages.getString("validationError")); //$NON-NLS-1$ } public static void showErrorMessageBox(Application application, String errorMessage){ application.showMessageBox(errorMessage, Messages.getString("error"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_ERROR); } public static void showWarningMessageBox(Application application, String warningMessage){ application.showMessageBox(warningMessage, Messages.getString("warning"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); } } package ch.mfiles.kaba.kolibri.common.net; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; public class CommSetupHelper { private static final String PROD_MIDDLEWARE_URL = "http://194.209.171.40:8080/trHandler/transport/mbcp2"; private static final String PROD_BACKEND_URL = "http://kgsssapwebdisp.gilgends.com:8080/mfl/mbcp2"; /** * Sets production communication data to the runtime's registry, if there is * currently no 'backendUrl' set. *

* If a 'backendUrl' is set, nothing is changed. */ public static void setupProductionEnvironment() { // always apply/reset common settings setCommonSettings(); Registry reg = Runtime.getApplicationManager().getRegistry(null); String backendUrl = reg.getProperty("framework.net.backendUrl"); //$NON-NLS-1$ // set backend settings only once if (backendUrl != null && backendUrl.length() > 0) return; reg.setProperty("framework.net.middlewareUrl", PROD_MIDDLEWARE_URL); //$NON-NLS-1$ reg.setProperty("framework.net.backendUrl", PROD_BACKEND_URL); //$NON-NLS-1$ } public static boolean isProductionEnvironment() { Registry reg = Runtime.getApplicationManager().getRegistry(null); String backendUrl = reg.getProperty("framework.net.backendUrl"); //$NON-NLS-1$ return PROD_BACKEND_URL.equals(backendUrl); } private static void setCommonSettings() { Registry reg = Runtime.getApplicationManager().getRegistry(null); reg.deleteProperty("framework.la.url"); //$NON-NLS-1$ reg.setProperty("framework.dm.deviceTypeId", "S60"); //$NON-NLS-1$ //$NON-NLS-2$ reg.setProperty("framework.net.notify.maxRetryTimeout", "120"); //$NON-NLS-1$ //$NON-NLS-2$ reg.setProperty("framework.dm.localCycle", "720"); } /** * Sets test communication data to the runtime's registry, replacing any configuration present before. */ public static void setupDevelopmentEnvironment() { Registry reg = Runtime.getApplicationManager().getRegistry(null); reg.setProperty("framework.net.middlewareUrl", "http://194.209.171.36:8080/trHandler/transport/mbcp2"); //$NON-NLS-1$ //$NON-NLS-2$ reg.setProperty("framework.net.backendUrl", "http://kgsssapwebdisptest.gilgends.com:8080/mfl/mbcp2"); //$NON-NLS-1$ //$NON-NLS-2$ setCommonSettings(); } /** * Called in {@link Application#onApplicationStart(Object)} to setup the UI * layout corresponding to the current communication environment. */ public static void setEnvironmentLayout() { if (!isProductionEnvironment()) LayoutUtils.setDevelopmentColors(); } } package ch.mfiles.kaba.kolibri.common.net; import java.io.File; import java.text.MessageFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMATPERS; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.gen.TableCursor; /** * Handler for the separately stored master data. * * @author joerg * @@deprecated The last remaining attached master data table was remigrated to * the runtime database in release 3.3.9. The remaining * implementation checks whether the attached master data db file * still exists and migrates the contained data to the * application's runtime db when an attempt is made to attache the * master data db. * */ public class MasterDataDBHandler { private final static Log log = LogFactory.getLog(MasterDataDBHandler.class); private static MasterDataDBHandler masterDataDBHandler; public static MasterDataDBHandler getInstance() { if (masterDataDBHandler == null) masterDataDBHandler = new MasterDataDBHandler(); return masterDataDBHandler; } private final static String PERSONAL_DATA = "PERSONAL_DATA"; //$NON-NLS-1$ private final static String DB_NAME = "GilgenPersonalData"; //$NON-NLS-1$ private MasterDataDBHandler() { // singleton } private boolean m_masterDataDBAttached = false; /** * Attaches the master data database to the runtime database if it still exists, * copies the data to the runtime db, detaches the database and deletes the * file. Does nothing if the database file doen't exist (any more). */ public void attach() { if (m_masterDataDBAttached) return; // no masterdata file no attachment necessary File mdFile = new File(getDBPath(PERSONAL_DATA) + ".db3"); if (!mdFile.exists()) { log.info("Master data db does not exist - not attached..."); return; } // temporarily attach the master data file and copy the existing data to the // runtime table log.info("Migrating master data db " + PERSONAL_DATA); //$NON-NLS-1$ DBSession dbSession = Runtime.getApplicationManager().getDBSession(); dbSession.executeSql("ATTACH DATABASE '" + getDBPath(PERSONAL_DATA) + ".db3" + "' AS " + DB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ ZKDMOBMATPERS attachedMD = new ZKDMOBMATPERS(dbSession); TableCursor cursor = ZKDMOBMATPERS.query(attachedMD, "SELECT * FROM " + DB_NAME + "." + DbConstants.MaterialPerson.MATERIAL_PERSON, true); int rowsInserted = 0; dbSession.startTransaction(); try { while (cursor.next()) { attachedMD.insert(); rowsInserted += 1; } dbSession.commit(); } finally { cursor.dispose(); if (dbSession.isTransactionPending()) dbSession.rollback(); } log.info(MessageFormat.format("Copied {0} rows of table ZKDMIBMATPERS from attached database.", rowsInserted)); // detach the master data db and delete its file log.info("Detaching master data db " + PERSONAL_DATA); //$NON-NLS-1$ dbSession.executeSql("DETACH DATABASE " + DB_NAME); //$NON-NLS-1$ mdFile.delete(); m_masterDataDBAttached = true; } /** * @param PERSONAL_DATA * @return Returns the absolute path to the db without the file extension '.db3' */ private String getDBPath(String masterDB) { return Runtime.getApplicationManager().getApplicationFolder(CommonConstants.Application.COMMON_APP) + File.separator + masterDB; } /** * Does nothing. */ public void detach() { return; } } package ch.mfiles.kaba.kolibri.common.net; /** * Presence state to be used with remote transcation UPDATE_PRESENCE. * * @author joerg * */ public enum PresenceState { /** * Present, i.e. reachable at work. */ PRESENT, /** * Gone from work for today, i.e. no more reachable for today. */ GONE, /** * Gone from work for a short break, i.e. probably reachable again later that day. */ BREAK } package ch.mfiles.kaba.kolibri.common.net; public class RemoteTransactionResult { private String messageType = "S"; private String message = ""; private Status status; public enum Status { success, error } public RemoteTransactionResult(Status status, String message, String msgType) { this.message = message; this.status = status; this.messageType = msgType; } public RemoteTransactionResult(Status status) { this.status = status; } public String getMessage() { return message; } public Status getStatus() { return status; } public String getMessageType() { return messageType; } } package ch.mfiles.kaba.kolibri.common.util; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.widget.PopupMenu; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ActionUtil { private static Log log = LogFactory.getLog(ActionUtil.class); public ApplicationManager appman; public Application app; public ActionUtil(Application app) { this.app = app; this.appman = (ApplicationManager) Runtime.getApplicationManager(); } public void showPopupMenu(Context context, final ActionResult cameraActionResult, final ActionResult galleryActionResult, final ActionResult pdfActionResult) { /* * Create the context menu. see "[MIG-67] Context menu for jobs doesn't work" */ PopupMenu popupMenu = new PopupMenu(context, app.getCurrentForm().getToolbar()); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); popupMenu.getMenu() .add(Menu.NONE, CommonConstants.Menu.CAMERA, Menu.NONE, ch.mfiles.kaba.kolibri.common.Messages.getString("camera")) .setIcon(app.getCurrentForm().getBitmanDrawable(ImagesUtil.getInstance(app) .getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); popupMenu.getMenu() .add(Menu.NONE, CommonConstants.Menu.GALLERY, Menu.NONE, ch.mfiles.kaba.kolibri.common.Messages.getString("gallery")) .setIcon(app.getCurrentForm().getBitmanDrawable(ImagesUtil.getInstance(app) .getImage(ImagesUtil.Images.PHOTO_LIBRARY_BLACK, CommonConstants.Images.IMAGE_DPI))); // popupMenu.getMenu() // .add(Menu.NONE, ServiceConstants.Index.THREE, Menu.NONE, ServiceMessages.getString("pdfFiles")) // .setIcon(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PICTURE_AS_PDF_BLACK, CommonConstants.Images.IMAGE_DPI))); // forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem, cameraActionResult, galleryActionResult, pdfActionResult); return true; } }); popupMenu.show(); } private void handleMenuItemClicked(MenuItem menuItem, final ActionResult cameraActionResult, final ActionResult galleryActionResult, final ActionResult pdfActionResult) { if (menuItem.getItemId() == CommonConstants.Menu.CAMERA) { actionCamera(cameraActionResult); } else if (menuItem.getItemId() == CommonConstants.Menu.GALLERY) { actionGallery(galleryActionResult); } else if (menuItem.getItemId() == CommonConstants.Menu.PDF) { } } public void actionCamera(final ActionResult actionResult) { int permissionCheck = ContextCompat.checkSelfPermission(appman.getContext(), Manifest.permission.CAMERA); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { appman.requestPermissions( new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, CommonConstants.PERMISSION_REQUEST_CODE); } else { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String timeStamp = Long.toString(new Date().getTime()); String imageName = "IMAGE_" + timeStamp; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ final String imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) .getAbsolutePath() + "/Camera/"; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File photo = new File(imagePath, imageName + ".jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, appman.getUriForFile(photo)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); if (appman.startActivityForResult(intent) != null) { loadBitmapFromUri(actionResult, photo.getAbsolutePath(), true); } else { photo.delete(); } return null; } }; } } public void actionGallery(final ActionResult actionResult) { int permissionCheck = ContextCompat.checkSelfPermission(appman.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { appman.requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, CommonConstants.PERMISSION_REQUEST_CODE); } else { new AsyncTask(app.getCurrentForm()) { private String filePath; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_PICK); Intent result = appman.startActivityForResult(intent); if (result == null) { return null; } Uri selectedImage = result.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = appman.getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); cursor.close(); return null; } @Override protected void runOnUIThread() { loadBitmapFromUri(actionResult, filePath, false); } }; } } private void loadBitmapFromUri(final ActionResult actionResult, final String filePath, boolean broadcast) { if (filePath == null) { return; } if (broadcast) // make the new image visible in gallery asap MediaScannerConnection.scanFile(appman.getContext(), new String[] { filePath }, new String[] { "image/jpeg" }, null); BitmapLoadUtils.decodeBitmapInBackground(appman.getContext(), Uri.fromFile(new File(filePath)), new BitmapLoadUtils.BitmapLoadCallback() { @Override public void onFailure(@NonNull Exception bitmapWorkerException) { actionResult.onActionResult(null); } public void onBitmapLoaded(Bitmap bitmap, int exifOrientation) { actionResult.onActionResult(bitmap); } }); } public interface ActionResult { void onActionResult(Bitmap bitmap); } } package ch.mfiles.kaba.kolibri.common.util; import java.io.File; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.os.AsyncTask; import ch.mfiles.kaba.kolibri.common.CommonApplication; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.SimpleUserInterface; import ch.mfiles.kolibri.bu.BackupManager; import ch.mfiles.kolibri.bu.BackupMonitor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.NotificationMessage; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.BusyUIRunnable; import ch.mfiles.kolibri.util.AlertManager; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Helper class dealing with scheduling and performing a daily runtime backup. * The backup will run on some random time during the night hours from 8pm to * 6am. * * @author Joerg * */ public class BackupHandler { private static Log log = LogFactory.getLog(BackupHandler.class); /** * Makes sure, the backup manager is setup as required and all (special) * application folders are present. */ public static void setupOnPostApplicationUpgrade(final Application app) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(null); boolean bmActive = false; try { bmActive = reg.getBooleanProperty("framework.bm.active"); //$NON-NLS-1$ } catch (IllegalArgumentException ex) { } if (!bmActive) { log.info("Activating runtime's backup manager..."); //$NON-NLS-1$ // activate backup manager reg.setProperty("framework.bm.active", true); //$NON-NLS-1$ reg.setProperty("framework.bm.hideBackupAction", true); //$NON-NLS-1$ reg.setProperty("framework.bm.hideRestoreAction", true); //$NON-NLS-1$ // restart framework to activate the changes appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { app.showMessageBox(Messages.getString("BackupHandler_5"), //$NON-NLS-1$ Messages.getString("BackupHandler_6"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_INFORMATION); return appman.exitFramework(); } }, false); } // check/create application folders checkCreateAppFolder(CommonConstants.Application.COMMON_APP); checkCreateAppFolder(CommonConstants.Application.LOGIN_APP); checkCreateAppFolder(CommonConstants.Application.MATERIAL_APP); checkCreateAppFolder(CommonConstants.Application.SERVICE_APP); checkCreateAppFolder(CommonConstants.Application.TIMESHEET_APP); } private static void checkCreateAppFolder(String appFolder) { File folder = new File(Runtime.getInstallationFolder(), appFolder); if (!folder.exists()) { log.info("Creating special app folder " + folder); //$NON-NLS-1$ folder.mkdir(); } } private static BackupHandler s_instance; public static BackupHandler getInstance() { if (s_instance == null) { s_instance = new BackupHandler(); } return s_instance; } private ApplicationManager m_appman; private AlertManager m_alertManager; private Random m_random = new Random(System.currentTimeMillis()); private int m_testIntervalS = 0; private BackupHandler() { m_appman = (ApplicationManager) Runtime.getApplicationManager(); m_alertManager = m_appman.getAlertManager(); m_testIntervalS = RegistryUtil.getTestBackupEveryS(); updateBackupJob(); } private static final String BACKUP_JOB_MESSAGE = "Daily backup run"; //$NON-NLS-1$ private static final String BACKUP_JOB_ID = "CommonBackupJob"; //$NON-NLS-1$ private void updateBackupJob() { // remove the current alert m_alertManager.cancelAlert(BACKUP_JOB_ID); // get hour offset to 8pm for the backup schedule int hourOffset = (int) (m_random.nextFloat() * 10); int minuteOffset = (int) (m_random.nextFloat() * 59); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); // if we currently are past 8pm run on next day if (cal.get(Calendar.HOUR_OF_DAY) >= 20) cal.add(Calendar.DATE, 1); // set (start) time to 8pm for the/that day cal.set(Calendar.HOUR_OF_DAY, 20); cal.set(Calendar.MINUTE, 0); // add the random offset to the start time cal.add(Calendar.HOUR_OF_DAY, hourOffset); cal.add(Calendar.MINUTE, minuteOffset); Date schedule = cal.getTime(); // allow for quicker test backups if (m_testIntervalS > 0) schedule = new Date(System.currentTimeMillis() + m_testIntervalS * 1000); log.info("Next backup run planned for " + schedule); //$NON-NLS-1$ m_alertManager.addAlert(schedule, CommonApplication.class.getName(), BACKUP_JOB_ID, BACKUP_JOB_MESSAGE); Application app = (Application) m_appman.getActiveApplication(); if (app != null) app.inform(MessageFormat.format(Messages.getString("BackupHandler_11"), schedule)); //$NON-NLS-1$ } /** * Processes received messages and starts a backup if apropriate. * * @param nm * @return Returns true if the notification message was handled * (i.e. consumed) */ public boolean processNotification(NotificationMessage nm) { if (!BACKUP_JOB_ID.equals(nm.getMessageId()) || !BACKUP_JOB_MESSAGE.equals(nm.getContent())) return false; log.info("Starting daily backup..."); //$NON-NLS-1$ // register a new backup job updateBackupJob(); // run the backup runBackup((Application) m_appman.getActiveApplication()); return true; } private void runBackup(final Application app) { m_appman.inject(new BusyUIRunnable() { @Override public ApplicationEvent runBusy(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { BackupManager bm = Runtime.getBackupManager(); final BackupMonitor buMonitor = bm.backup(Messages.getString("BackupHandler_13"), monitor); //$NON-NLS-1$ if (buMonitor.getErrorMessage() != null) { log.error("Backup failed: " + buMonitor.getErrorMessage()); //$NON-NLS-1$ if (app != null) app.inform(MessageFormat.format(Messages.getString("BackupHandler_15"), //$NON-NLS-1$ buMonitor.getErrorMessage())); } // if the runtime was started only to process the backup job, exit the runtime // at the end of the backup process if (m_appman.getActiveApplication() == null) waitForBackupAndExitRuntime(buMonitor); return null; } }, false); } protected void waitForBackupAndExitRuntime(final BackupMonitor buMonitor) { new AsyncTask() { @Override protected Void doInBackground(Void... params) { log.info("Waiting for backup process to end..."); //$NON-NLS-1$ try { buMonitor.join(); } catch (InterruptedException e) { return null; } m_appman.inject(new BusyUIRunnable() { @Override public ApplicationEvent runBusy(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { // before exiting check again, if nothing was started in the meantime... if (m_appman.getActiveApplication() == null) { log.info("Backup complete - exiting runtime since it was started for backup only..."); //$NON-NLS-1$ return appman.exitFramework(); } log.info("Backup complete - leaving to running application..."); //$NON-NLS-1$ return null; } }, false); return null; } }.execute(); } /** * Returns the hours past since the last (successful) backup run. * * @return Returns the hours since the last (successful) backup run or * -1 */ private int getHoursSinceLastBackup() { Date lastBackup = Runtime.getBackupManager().getLastBackupTS(); if (lastBackup == null) return -1; return (int) ((System.currentTimeMillis() - lastBackup.getTime()) / (1000 * 3600)); } /** Timestamp of last overdue check */ private long m_lastOverdueCheckMS = 0; /** * Check if the last successful backup is too old and ask to perform a backup if * the backup is older than 24 hours and force a backup run if older than 48 * hours. */ public void checkOverdueBackup(final Application app) { // only check every 1 hour if (System.currentTimeMillis() - m_lastOverdueCheckMS < 60 * 60 * 1000) return; m_appman.inject(new BusyUIRunnable() { @Override public ApplicationEvent runBusy(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { int hours = getHoursSinceLastBackup(); if (hours >= 0 && hours <= 24) return null; if (hours >= 24 && hours <= 48) { app.inform(Messages.getString("BackupHandler_19")); //$NON-NLS-1$ return null; } else { if (hours < 0) app.inform(Messages.getString("BackupHandler_21")); //$NON-NLS-1$ else app.inform(Messages.getString("BackupHandler_23")); //$NON-NLS-1$ } runBackup(app); return null; } }, false); } } package ch.mfiles.kaba.kolibri.common.util; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; public class BitmapConverterUtil { public static String bitMapToString(Bitmap bitmap) { // TODO compress ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String temp = Base64.encodeToString(b, Base64.DEFAULT); return temp; } public static Bitmap stringToBitMap(String encodedString) { try { byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); return bitmap; } catch (Exception e) { e.getMessage(); return null; } } } package ch.mfiles.kaba.kolibri.common.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.ParcelFileDescriptor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; /** * Created by Oleksii Shliama (https://github.com/shliama). */ public class BitmapLoadUtils { private static final String TAG = "BitmapLoadUtils"; private static final int MAXIMUM_FILE_SIZE_K = 900; public interface BitmapLoadCallback { void onBitmapLoaded(@NonNull Bitmap bitmap, int exifOrientation); void onFailure(@NonNull Exception bitmapWorkerException); } public static void decodeBitmapInBackground(@NonNull Context context, @Nullable Uri uri, BitmapLoadCallback loadCallback) { new BitmapWorkerTask(context, uri, loadCallback).execute(); } static class BitmapWorkerResult { Bitmap mBitmapResult; int mExifOrientation; Exception mBitmapWorkerException; public BitmapWorkerResult(@Nullable Bitmap bitmapResult, int exifOrientation, @Nullable Exception bitmapWorkerException) { mBitmapResult = bitmapResult; mBitmapWorkerException = bitmapWorkerException; mExifOrientation = exifOrientation; } } /** * Creates and returns a Bitmap for a given Uri. * inSampleSize is calculated based on requiredWidth property. However can be adjusted if OOM occurs. * If any EXIF config is found - bitmap is transformed properly. */ static class BitmapWorkerTask extends AsyncTask { private final Context mContext; private final Uri mUri; private final BitmapLoadCallback mBitmapLoadCallback; public BitmapWorkerTask(@NonNull Context context, @Nullable Uri uri, BitmapLoadCallback loadCallback) { mContext = context; mUri = uri; mBitmapLoadCallback = loadCallback; } @Override @NonNull protected BitmapWorkerResult doInBackground(Void... params) { if (mUri == null) { return new BitmapWorkerResult(null, 0, new NullPointerException("Uri cannot be null")); } final ParcelFileDescriptor parcelFileDescriptor; try { parcelFileDescriptor = mContext.getContentResolver().openFileDescriptor(mUri, "r"); } catch (FileNotFoundException e) { return new BitmapWorkerResult(null, 0, e); } Bitmap decodeSampledBitmap = makeBitmap(mUri.getPath()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { close(parcelFileDescriptor); } int exifOrientation = getExifOrientation(mContext, mUri); int exifDegrees = exifToDegrees(exifOrientation); int exifTranslation = exifToTranslation(exifOrientation); Log.i(TAG, "Image EXIF Orientation: " + exifOrientation); Log.i(TAG, "Image EXIF Degrees: " + exifDegrees); Log.i(TAG, "Image EXIF Translation: " + exifTranslation); Matrix matrix = new Matrix(); if (exifDegrees != 0) { matrix.preRotate(exifDegrees); } if (exifTranslation != 1) { matrix.postScale(exifTranslation, 1); } if (decodeSampledBitmap == null) { return new BitmapWorkerResult(null, 0, new IllegalArgumentException("Source is not an image or not supported.")); } if (!matrix.isIdentity()) { decodeSampledBitmap = transformBitmap(decodeSampledBitmap, matrix); } // for test //writeToFile(decodeSampledBitmap); return new BitmapWorkerResult(decodeSampledBitmap, exifOrientation, null); } @Override protected void onPostExecute(@NonNull BitmapWorkerResult result) { if (result.mBitmapWorkerException == null) { mBitmapLoadCallback.onBitmapLoaded(result.mBitmapResult, result.mExifOrientation); } else { mBitmapLoadCallback.onFailure(result.mBitmapWorkerException); } } private void writeToFile(Bitmap bitmap) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 0, baos); String Path = mContext.getExternalFilesDir(null).getPath(); File dirFile = new File(Path); if (!dirFile.exists()) { dirFile.mkdir(); } File myCaptureFile = new File(Path +"/cache_" + System.currentTimeMillis() +".jpg"); FileOutputStream fi; fi = new FileOutputStream(myCaptureFile); baos.writeTo(fi); baos.flush(); baos.close(); int fileSize = baos.toByteArray().length / 1024; Log.i(TAG, "after compressed size: " + fileSize + "Kb"); Log.i(TAG, "path : " + myCaptureFile.getAbsolutePath()); } catch (FileNotFoundException e) { Log.i(TAG, e + ""); } catch (IOException e) { Log.i(TAG, e + ""); } } private Bitmap makeBitmap(String path) { long fileSize = new File(mUri.getPath()).length(); fileSize = (fileSize) / 1024;// in Kb now if (fileSize > MAXIMUM_FILE_SIZE_K) { Bitmap image = BitmapFactory.decodeFile(path); int width = image.getWidth(); int height = image.getHeight(); float bitmapRatio = (float)width / (float) height; if (bitmapRatio > 1) { width = MAXIMUM_FILE_SIZE_K; height = (int) (width / bitmapRatio); } else { height = MAXIMUM_FILE_SIZE_K; width = (int) (height * bitmapRatio); } return Bitmap.createScaledBitmap(image, width, height, true); } // Decode image size BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); final int IMAGE_MAX_SIZE = MAXIMUM_FILE_SIZE_K * 1024; // 1.2MP int scale = 1; while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) { scale++; } Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight); Bitmap pic = null; if (scale > 1) { scale--; // scale to max possible inSampleSize that still yields an image // larger than target options = new BitmapFactory.Options(); options.inSampleSize = scale; pic = BitmapFactory.decodeFile(path, options); // resize to desired dimensions int height = pic.getHeight(); int width = pic.getWidth(); float bitmapRatio = (float)width / (float) height; if (bitmapRatio > 1) { width = IMAGE_MAX_SIZE; height = (int) (width / bitmapRatio); } else { height = IMAGE_MAX_SIZE; width = (int) (height * bitmapRatio); } Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height); double y = Math.sqrt(IMAGE_MAX_SIZE / (((double) width) / height)); double x = (y / height) * width; Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true); pic.recycle(); pic = scaledBitmap; System.gc(); } else { pic = BitmapFactory.decodeFile(path); } Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight()); return pic; } } public static Bitmap transformBitmap(@NonNull Bitmap bitmap, @NonNull Matrix transformMatrix) { try { Bitmap converted = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), transformMatrix, true); if (bitmap != converted) { bitmap.recycle(); bitmap = converted; } } catch (OutOfMemoryError error) { Log.e(TAG, "transformBitmap: ", error); } return bitmap; } protected static int getExifOrientation(@NonNull Context context, @NonNull Uri imageUri) { int orientation = ExifInterface.ORIENTATION_UNDEFINED; try { InputStream stream = context.getContentResolver().openInputStream(imageUri); if (stream == null) { return orientation; } orientation = new ImageHeaderParser(stream).getOrientation(); close(stream); } catch (IOException e) { Log.e(TAG, "getExifOrientation: " + imageUri.toString(), e); } return orientation; } public static int exifToTranslation(int exifOrientation) { int translation; switch (exifOrientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: case ExifInterface.ORIENTATION_FLIP_VERTICAL: case ExifInterface.ORIENTATION_TRANSPOSE: case ExifInterface.ORIENTATION_TRANSVERSE: translation = -1; break; default: translation = 1; } return translation; } public static Bitmap rotateBitmap(@Nullable Bitmap bitmap, int degrees) { if (bitmap != null && degrees != 0) { Matrix rotateMatrix = new Matrix(); rotateMatrix.setRotate(degrees, bitmap.getWidth() / (float) 2, bitmap.getHeight() / (float) 2); Bitmap converted = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), rotateMatrix, true); if (bitmap != converted) { bitmap.recycle(); bitmap = converted; } } return bitmap; } @Nullable private static ExifInterface getExif(@NonNull Uri imageUri) { try { return new ExifInterface(imageUri.getPath()); } catch (IOException e) { Log.w(TAG, "getExif: ", e); } return null; } static int exifToDegrees(int exifOrientation) { if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; } return 0; } @SuppressWarnings("ConstantConditions") public static void close(@Nullable Closeable c) { if (c != null && c instanceof Closeable) { // java.lang.IncompatibleClassChangeError: interface not implemented try { c.close(); } catch (IOException e) { // silence } } } } java.lang.System.out.println(new java.util.Date().getTime()); java.lang.System.out.println(new java.util.Date(1326447011991L)); java.lang.System.out.println(new java.util.Date(1323959280000L)); java.lang.System.out.println("DATUM " + new java.util.Date(1347552978795L)); java.lang.System.out.println("DATUM " + new java.util.Date(1335304800000L)); java.lang.System.out.println("VON " + new java.util.Date(1323876420000L)); java.lang.System.out.println("VON " + new java.util.Date(1323959280000L)); java.lang.System.out.println("BIS " + new java.util.Date(1323876420000L)); java.lang.System.out.println("BIS " + new java.util.Date(1323959280000L)); package ch.mfiles.kaba.kolibri.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DateTimeUtil { private static Log log = LogFactory.getLog(CommonConstants.class); public static final long SECONDS_IN_MILLI = 1000; public static final long MINUTES_IN_MILLI = SECONDS_IN_MILLI * 60; public static final long HOURS_IN_MILLI = MINUTES_IN_MILLI * 60; public static final long DAYS_IN_MILLI = HOURS_IN_MILLI * 24; public static final String SHOW_TABLE_DATE_FORMAT = "dd.MM.yy"; //$NON-NLS-1$ public static final String SHOW_TIME_FORMAT = "HH:mm"; //$NON-NLS-1$ public static final String DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm"; //$NON-NLS-1$ public static final String DATE_FORMAT = "dd.MM.yyyy"; //$NON-NLS-1$ public static final String SHOW_HTML_DATE_TIME_FORMAT = "dd.MM.yyyy HH:mm"; //$NON-NLS-1$ DateTimeUtil() { } /** * Creates a Calendar Object with the current date and time including seconds and milliseconds * @return a Calendar */ public static Calendar getTimestamp() { return Calendar.getInstance(); } /** * Creates a Calendar Object with the current date and time with 00.000s * @return a Calendar */ public static Calendar getNow() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); return cal; } /** * Creates a Calendar Object with the current date and time with 00.000s * @return a Calendar */ public static Calendar getTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); return cal; } /** * Creates a Calendar Object with the current date and time from datetime with 00.000s * @return a Calendar */ public static Calendar getTime(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); return cal; } /** * Creates a Calendar Object with the current date and time 00:00:00.000 * @return a Calendar */ public static Calendar getToday() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); return cal; } /** * Creates a Calendar Object with the date from yesterday and time 00:00:00.000 * @return a Calendar */ public static Calendar getYesterday() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.add(Calendar.DAY_OF_YEAR, -1); return cal; } /** * Creates a Calendar Object with the preceding date from date and time 00:00:00.000 * @return a Calendar */ public static Calendar getYesterday(Date date) { Calendar cal = getDate(date); cal.add(Calendar.DAY_OF_YEAR, -1); return cal; } /** * Creates a Calendar Object with the date from the day before yesterday and time 00:00:00.000 * @return a Calendar */ public static Calendar getDayBeforeYesterday() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.add(Calendar.DAY_OF_YEAR, -2); return cal; } /** * Creates a Calendar Object with the consecutively (next) date from date and time 00:00:00.000 * @return a Calendar */ public static Calendar getTomorrow(Date date) { Calendar cal = getDate(date); cal.add(Calendar.DAY_OF_YEAR, 1); return cal; } /** * Creates a Calendar Object with the date from datetime and time 00:00:00.000 * @return a Calendar */ public static Calendar getDate(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); return cal; } /** * Creates a Calendar Object with the date from today and time 00:01:00.000 * @return a Calendar */ public static Calendar getTodayEarlyMorning() { Calendar cal = getToday(); cal.set(Calendar.MINUTE, 01); return cal; } /** * Creates a Calendar Object with the date from yesterday and time 23:59:00.000 * @return a Calendar */ public static Calendar getYesterdayLateNight() { Calendar cal = getYesterday(); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.HOUR_OF_DAY, 23); return cal; } /** * Creates a Calendar Object with the date from datetime and time 23:59:00.000 * @return a Calendar */ public static Calendar getLateNight(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.HOUR_OF_DAY, 23); return cal; } /** * Creates a Calendar Object with the current date and time hourOfDay : minute:00.000 * @return a Calendar */ public static Calendar setTimeOfDate(Date date, int hourOfDay, int minute) { Calendar cal = getDate(date); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.HOUR_OF_DAY, hourOfDay); return cal; } /** * Checks is datetime is a date value. Condition for a date value is time = 00:00:00.000 * @param datetime * @return true if datetime is a date. */ public static boolean isDate(Date datetime) { Calendar cal = Calendar.getInstance(); cal.setTime(datetime); return cal.get(Calendar.HOUR_OF_DAY) == 0 && cal.get(Calendar.MINUTE) == 0 && cal.get(Calendar.SECOND) == 0 && cal.get(Calendar.MILLISECOND) == 0; } /** * Checks if start and stop are within the same day * @param start * @param stop * @return true/code> if start and stop are within the same day */ public static boolean isSameDay(Date start, Date stop) { int startDay = DateTimeUtil.getDate(start).get(Calendar.DAY_OF_YEAR); int stopDay = DateTimeUtil.getDate(stop).get(Calendar.DAY_OF_YEAR); return startDay == stopDay; } /** * @param start * @param stop * @return */ public static Date calcTimeDiff(Date start, Date stop) { Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); long startDateTime = cal.getTime().getTime(); cal.setTime(stop); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); long stopDateTime = cal.getTime().getTime(); return new Date(stopDateTime - startDateTime); } /** * Gets time difference is use for calculate the difference between two Dates. * * @param start * @param stop * @return */ public static long getTimeDifference(Date start, Date stop) { if (start.getTime() == 0 || stop.getTime() == 0) return 0; Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.MILLISECOND, 0); long startDateTime = cal.getTimeInMillis(); cal.setTime(stop); cal.set(Calendar.MILLISECOND, 0); long stopDateTime = cal.getTimeInMillis(); return startDateTime - stopDateTime; } public static Date parseDateFromHHmm(String time, Date currentDate) { Date result = null; try { int hours = Integer.parseInt(time.substring(0, 2)); int minutes = Integer.parseInt(time.substring(3, 5)); result = DateTimeUtil.setTimeOfDate(currentDate, hours, minutes).getTime(); } catch (Exception e) { log.error("Error while parsing time string '" + time + "', message is: '" + e.getMessage() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(e); } return result; } public static Date parseDateFromddMMyyyy(String date) { SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, new Locale("de", "CH")); try { return format.parse(date); } catch (ParseException e) { log.info("parse date fail"); return null; } } public static String tableDate(Date date) { SimpleDateFormat format = new SimpleDateFormat(SHOW_TABLE_DATE_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String HtmlDateTime(Date date) { SimpleDateFormat format = new SimpleDateFormat(SHOW_HTML_DATE_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String showTime(long time) { if (time == 0) return "00:00"; //$NON-NLS-1$ //long diffSeconds = time / SECONDS_IN_MILLI % 60; long minutes = time / (MINUTES_IN_MILLI) % 60; long hours = time / (HOURS_IN_MILLI) % 24; //long diffDays = time / (DAYS_IN_MILLI); return String.format("%02d", hours) + ":" + String.format("%02d", minutes); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public static String showTime(Date date) { SimpleDateFormat format = new SimpleDateFormat(SHOW_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } // public static String showRoundTime(Date date) { // Calendar calendar = Calendar.getInstance(); // calendar.setTime(date); // // if(calendar.get(Calendar.SECOND) > 0) { // calendar.add(Calendar.SECOND, 1); // } // SimpleDateFormat format = new SimpleDateFormat(SHOW_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ // return format.format(calendar.getTime()); // } public static String showDate(Date date) { SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String showDateTime(Date date) { SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT, new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ return format.format(date); } public static String fileNameDate(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return format.format(date); } public static String fileNameTime(Date date) { SimpleDateFormat format = new SimpleDateFormat("HHmmss", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return format.format(date); } public static String showTimeGMT(Date date) { SimpleDateFormat format = new SimpleDateFormat("HH:mm"); //$NON-NLS-1$ return format.format(date); } public static String showDayOfMonth(Date date) { SimpleDateFormat format = new SimpleDateFormat("dd"); //$NON-NLS-1$ return format.format(date); } public static String showDayOfWeek(Date date) { SimpleDateFormat format = new SimpleDateFormat("EE"); //$NON-NLS-1$ return format.format(date); } public static String showDayMonth(Date date) { SimpleDateFormat format = new SimpleDateFormat("dd.MM"); //$NON-NLS-1$ return format.format(date); } public static String showMonthNameYear(Date date) { SimpleDateFormat format = new SimpleDateFormat("MMMM yyyy"); //$NON-NLS-1$ return format.format(date); } public static String showHHmmss(Date date) { SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); //$NON-NLS-1$ return format.format(date); } } package ch.mfiles.kaba.kolibri.common.util; import java.io.IOException; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.util.Base64; import ch.mfiles.kaba.kolibri.common.CommonApplication; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.SimpleUserInterface; import ch.mfiles.kolibri.bu.BackupManager; import ch.mfiles.kolibri.bu.BackupMonitor; import ch.mfiles.kolibri.bu.RestoreMonitor; import ch.mfiles.kolibri.bu.RestorePoint; import ch.mfiles.kolibri.db.LocalTransaction; import ch.mfiles.kolibri.net.NotificationHandler; import ch.mfiles.kolibri.net.NotificationHandler.Token; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.SubProgressMonitor; /** * The coordinator (singleton) for device mirroring. * * @author Joerg * */ public class DeviceMirrorringHandler { private static final Log log = LogFactory.getLog(DeviceMirrorringHandler.class); /** singleton */ private static DeviceMirrorringHandler instance = null; public static DeviceMirrorringHandler getInstance() { if (instance == null) instance = new DeviceMirrorringHandler(); return instance; } private Registry m_reg; private DeviceMirrorringHandler() { m_reg = Runtime.getApplicationManager().getRegistry(CommonApplication.class.getName()); } private static final String MIRROR_STATE_ACTIVE = "active"; //$NON-NLS-1$ private static final String MIRROR_STATE_INACTIVE = "inactive"; //$NON-NLS-1$ private static final String MIRROR_STATE_NOT_SET = ""; //$NON-NLS-1$ public static interface DeleteAppDataFunction { /** * Delete all (user dependent) application data. * * @param ui UI to use to present dialogs (if any) * @return Returns true if data was deleted, false * otherwise (e.g. after user cancelled the deletion) */ public boolean deleteApplicationData(SimpleUserInterface ui); } /** * Returns the mirror state from the registry. * * @return */ private String getMirrorState() { return m_reg.getProperty("mirrorState"); //$NON-NLS-1$ } /** * Sets the mirror state in the registry. * * @param mirrorState */ private void setMirrorState(String mirrorState) { m_reg.setProperty("mirrorState", mirrorState); //$NON-NLS-1$ } /** * Returns true if the last activated user's data has been * destroyed since the device was released by the user, i.e. the device data * have changed since the last backup. * * @return */ private boolean isMirrorUserdataDeleted() { return m_reg.getBooleanProperty("mirrorUserdataState"); //$NON-NLS-1$ } /** * Sets the last acitve user's data to invalid, i.e. the user's backup * * @param deleted */ private void setMirrorUserdataDeleted(boolean deleted) { m_reg.setProperty("mirrorUserdataState", deleted); //$NON-NLS-1$ } /** * Informs the mirror handler, that the last active user's data have definitly * been destroyed. */ public void setMirrorUserdataDeleted() { setMirrorUserdataDeleted(true); } /** * Get the personal token id for the given username. * * @param username * @return */ private String getPersonalTokenId(String username) { return "P@" + username; //$NON-NLS-1$ } /** * Get the username from the given personal token id. * * @param tokenId * @return */ private String getUsername(String tokenId) { return tokenId.substring(2); } /** * Returns true if the given token id is used for personal push * tokens. * * @param tokenId * @return */ private boolean isPersonalTokenId(String tokenId) { return tokenId != null && tokenId.length() > 2 && tokenId.startsWith("P@"); //$NON-NLS-1$ } /** * Returns the given restorepoint encoded as a string for use in the token * remark. * * @param restorePoint * @return */ private String getRemarkFromRP(RestorePoint restorePoint) { StringBuilder sb = new StringBuilder(); sb.append("SNAPSHOT~"); //$NON-NLS-1$ sb.append(encodeBase64(restorePoint.getKolibriId())); sb.append('~'); sb.append(encodeBase64(restorePoint.getClientId())); sb.append('~'); sb.append(restorePoint.getBackupTime().getTime()); sb.append('~'); sb.append(encodeBase64(restorePoint.getTag())); return sb.toString(); } private String encodeBase64(String data) { byte[] encoded = Base64.encode(data.getBytes(Charset.forName("utf-8")), Base64.NO_WRAP); //$NON-NLS-1$ return new String(encoded, Charset.forName("ascii")); //$NON-NLS-1$ } private String decodeBase64(String data) { byte[] decoded = Base64.decode(data.getBytes(Charset.forName("ascii")), Base64.NO_WRAP); //$NON-NLS-1$ return new String(decoded, Charset.forName("utf-8")); //$NON-NLS-1$ } /** * Returns a restore point from the given token remark. * * @param remark * @return Returns the restore point corresponding to the given token remark or * null if the remark did not contain a restore point. * * @throws IllegalArgumentException Thrown if the the remark started with the * magic word but could not be successfully * decoded into a restore point. */ private RestorePoint getRPFromRemark(String remark) throws IllegalArgumentException { if (remark == null || !remark.startsWith("SNAPSHOT~")) //$NON-NLS-1$ return null; String tokens[] = remark.split("~"); //$NON-NLS-1$ if (tokens.length != 5) throw new IllegalArgumentException(Messages.getString("DeviceMirrorringHandler.0")); //$NON-NLS-1$ String kolibriId = decodeBase64(tokens[1]); String clientId = decodeBase64(tokens[2]); Date backupTime = new Date(Long.valueOf(tokens[3])); String tag = decodeBase64(tokens[4]); return newRestorePoint(backupTime, kolibriId, clientId, tag); } private RestorePoint newRestorePoint(final Date backupTime, final String kolibriId, final String clientId, final String tag) { return new RestorePoint() { @Override public String getTag() { return tag; } @Override public Date getBackupTime() { return backupTime; } @Override public String getKolibriId() { return kolibriId; } @Override public String getClientId() { return clientId; } @Override public String toString() { StringBuilder sb = new StringBuilder("RestorePoint[kolibriId=").append(kolibriId).append(", clientId=") //$NON-NLS-1$ //$NON-NLS-2$ .append(clientId).append(", backupTime=").append(backupTime).append(", tag=").append(tag) //$NON-NLS-1$ //$NON-NLS-2$ .append("]"); //$NON-NLS-1$ return sb.toString(); } }; } /** * Process the user login. *

* Must only be called on the AM thread! * * @param username * @param ui * @return Returns true if the application can be started. */ public boolean processLogin(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { String mirrorState = getMirrorState(); if (MIRROR_STATE_ACTIVE.equals(mirrorState)) return processLoginActive(username, ui, monitor, deleteApplicationData); else if (MIRROR_STATE_NOT_SET.equals(mirrorState)) return processLoginInitial(username, ui, monitor, deleteApplicationData); return processLoginInactive(username, ui, monitor, deleteApplicationData); } /** * Process the user login in state 'initial'. * * @param username * @param deleteApplicationData * @return Returns true if the application can be started. */ private boolean processLoginInitial(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { monitor.begin(Messages.getString("DeviceMirrorringHandler.1"), 6); //$NON-NLS-1$ log.info("Processing initial user login for user " + username); //$NON-NLS-1$ // synchronize push tokens with middleware monitor.comment(Messages.getString("DeviceMirrorringHandler.2")); //$NON-NLS-1$ NotificationHandler nh = Runtime.getNotificationHandler(); String syncError = nh.synchronizeAssignedTokens(); if (syncError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.3") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", syncError); //$NON-NLS-1$//$NON-NLS-2$ log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // set state to inactive and switch to inactive login if personal push tokens // are already assigned if (PersonalTokenState.NONE_ASSIGNED != getTokenState()) { log.info("Already tokens assigned -> switching to mirror state 'inactive' and inactive login"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); return processLoginInactive(username, ui, new SubProgressMonitor(monitor, 5), deleteApplicationData); } // retrieve the personal token attributes from middleware String userTokenId = getPersonalTokenId(username); monitor.comment(Messages.getString("DeviceMirrorringHandler.5")); //$NON-NLS-1$ Token userToken = null; try { userToken = nh.getToken(userTokenId); } catch (IOException e) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.7") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", e.getLocalizedMessage()); //$NON-NLS-1$//$NON-NLS-2$ log.error(msg, e); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // create the token if it doesn't exist and assign it to the runtime if (userToken == null) { log.info("Creating and assigning personal push token"); //$NON-NLS-1$ monitor.comment(Messages.getString("DeviceMirrorringHandler.8")); //$NON-NLS-1$ String createError = nh.requestToken(userTokenId, "created on login request"); //$NON-NLS-1$ if (createError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.10") //$NON-NLS-1$ + "\n(" + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", createError); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully created personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); monitor.completed(); return true; } // bail out if the personal token is assigned to another runtime if (!userToken.isAssignable()) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.11"), //$NON-NLS-1$ username, userToken.getKolibriId()); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // restore runtime if the token remark contains a restore point RestorePoint rp = null; try { rp = getRPFromRemark(userToken.getRemark()); } catch (IllegalArgumentException ex) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.13") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") //$NON-NLS-1$ + " ''{0}''", ex.getLocalizedMessage()); //$NON-NLS-1$ log.error(msg); log.info("Token remark: " + userToken.getRemark()); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // if personal user token contains a restore point, confirm possible data loss, // switch // to mirror state inactive and continue with inactive login if (rp != null) { log.info("Personal push token restore point: " + rp); //$NON-NLS-1$ if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox( Messages.getString("DeviceMirrorringHandler.15") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.16"), //$NON-NLS-1$ Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_WARNING)) { log.info("User aborted initial login"); //$NON-NLS-1$ return false; } log.info("User confirmed -> switching to mirror state 'inactive' and inactive login"); //$NON-NLS-1$ // set preliminary state 'inactive' setMirrorState(MIRROR_STATE_INACTIVE); return processLoginInactive(username, ui, new SubProgressMonitor(monitor, 3), deleteApplicationData); } monitor.worked(2); // request personal user token and set mirror state to active in a single db // transaction monitor.comment(Messages.getString("DeviceMirrorringHandler.17")); //$NON-NLS-1$ LocalTransaction trans = new LocalTransaction(Runtime.getApplicationManager().getDBSession()); try { String requestError = nh.requestToken(userTokenId, "requested by login"); //$NON-NLS-1$ if (requestError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.18") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", //$NON-NLS-1$ //$NON-NLS-2$ requestError); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully requested personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); trans.commit(); monitor.worked(1); } finally { if (trans.isPending()) trans.rollback(); } return true; } /** * Process the user login in state 'inactive'. * * @param username * @param deleteApplicationData * @return Returns true if the application can be started. */ private boolean processLoginInactive(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { monitor.begin(Messages.getString("DeviceMirrorringHandler.1"), 4); //$NON-NLS-1$ log.info("Processing inactive user login for user " + username); //$NON-NLS-1$ // synchronize push tokens with middleware monitor.comment(Messages.getString("DeviceMirrorringHandler.2")); //$NON-NLS-1$ NotificationHandler nh = Runtime.getNotificationHandler(); String syncError = nh.synchronizeAssignedTokens(); if (syncError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.20") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", syncError); //$NON-NLS-1$//$NON-NLS-2$ log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // handle already assigned tokens List assignedUsernames = getAssignedPersonalTokenUsernames(); // issue error if more than one personal token is assigned if (assignedUsernames.size() > 1) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.24"), //$NON-NLS-1$ getAssignedPersonalTokenUsernames()); log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // issue error if device seems to belong to another user if (assignedUsernames.size() == 1 && !assignedUsernames.get(0).equalsIgnoreCase(username)) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.26"), //$NON-NLS-1$ assignedUsernames.get(0)); log.error("processLoginInactive() failed: " + msg); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // set state to active if logged in user is already assigned if (assignedUsernames.size() == 1) { log.info("User token already assigned -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); return true; } // retrieve the personal token attributes from middleware monitor.comment(Messages.getString("DeviceMirrorringHandler.28")); //$NON-NLS-1$ String userTokenId = getPersonalTokenId(username); Token userToken = null; try { userToken = nh.getToken(userTokenId); } catch (IOException e) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.23") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", e.getLocalizedMessage()); //$NON-NLS-1$//$NON-NLS-2$ log.error(msg, e); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // create the token if it doesn't exist and assign it to the runtime if (userToken == null) { log.info("Creating and assigning personal push token"); //$NON-NLS-1$ monitor.comment(Messages.getString("DeviceMirrorringHandler.31")); //$NON-NLS-1$ String createError = nh.requestToken(userTokenId, "created on login request"); //$NON-NLS-1$ if (createError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.27") //$NON-NLS-1$ + "\n(" + Messages.getString("DeviceMirrorringHandler.29") + " ''{0}'')", createError); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully created personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); monitor.completed(); return true; } // bail out if the personal token is already assigned (to another runtime) if (!userToken.isAssignable()) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.35"), //$NON-NLS-1$ userToken.getKolibriId()); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // restore runtime if the token remark contains a restore point RestorePoint rp = null; try { rp = getRPFromRemark(userToken.getRemark()); } catch (IllegalArgumentException ex) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.30") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") //$NON-NLS-1$ + " ''{0}''", ex.getLocalizedMessage()); //$NON-NLS-1$ log.error(msg); log.info("Token remark: " + userToken.getRemark()); //$NON-NLS-1$ ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } // trigger runtime restore if token remark contains a restore point otherwise // set mirror state to active if (rp == null) { log.info( "No restore point mentioned in user token remark -> deleting application data and skipping restore..."); //$NON-NLS-1$ if (!deleteApplicationData.deleteApplicationData(ui)) return false; monitor.worked(1); } else { // check if restore point corresponds to the last backup of the runtime -> // restore not necessary; otherwise restore to the remark's restore point BackupManager bm = Runtime.getBackupManager(); log.info("Personal push token restore point: " + rp); //$NON-NLS-1$ // set preliminary state 'inactive' log.info("preliminariliy switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); if (rp.getKolibriId().equals(Runtime.getTransactionHandler().getKolibriId()) && rp.getBackupTime().equals(bm.getLastBackupTS()) && !isMirrorUserdataDeleted()) { log.info("Restore point equals last backup snapshot -> no restore necessary"); //$NON-NLS-1$ monitor.worked(1); } else { // check restore point availability boolean rpAvailable = false; List availableRestorePoints; try { availableRestorePoints = bm.getRestorePoints(rp.getKolibriId()); } catch (IOException ex) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.34") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", ex.getLocalizedMessage()); //$NON-NLS-1$//$NON-NLS-2$ log.error(msg, ex); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } for (RestorePoint restorePoint : availableRestorePoints) { if (restorePoint.getBackupTime().equals(rp.getBackupTime())) { rpAvailable = true; break; } } // perform restore if restore point exists, delete application data otherwise if (!rpAvailable) { log.info( "Restore point doen't exist any more -> deleting application data and skipping restore..."); //$NON-NLS-1$ if (!deleteApplicationData.deleteApplicationData(ui)) return false; monitor.worked(1); } else { log.info("Restoring to restore point: " + rp); //$NON-NLS-1$ if (!restoreRuntime(rp, ui, new SubProgressMonitor(monitor, 1))) return false; } } } // request personal user token and set mirror state to active in a single db // transaction monitor.comment(Messages.getString("DeviceMirrorringHandler.41")); //$NON-NLS-1$ LocalTransaction trans = new LocalTransaction(Runtime.getApplicationManager().getDBSession()); try { String requestError = nh.requestToken(userTokenId, "requested by login"); //$NON-NLS-1$ if (requestError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.37") + "\n(" //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}'')", //$NON-NLS-1$ //$NON-NLS-2$ requestError); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } log.info("Successfully requested personal push token -> switching to mirror state 'active'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_ACTIVE); trans.commit(); monitor.worked(1); } finally { if (trans.isPending()) trans.rollback(); } return true; } private boolean m_mirrorRestoreActive = false; private boolean restoreRuntime(RestorePoint rp, SimpleUserInterface ui, ProgressMonitor monitor) { String restoreMsg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.39") //$NON-NLS-1$ + "\n\n" + Messages.getString("DeviceMirrorringHandler.16"), //$NON-NLS-1$ //$NON-NLS-2$ rp.getKolibriId(), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(rp.getBackupTime())); if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox(restoreMsg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, SimpleUserInterface.MBOX_ICON_QUESTION)) { log.info("User canceled restore to personal push token restore point"); //$NON-NLS-1$ return false; } BackupManager bm = Runtime.getBackupManager(); try { // set mirror restore flag m_mirrorRestoreActive = true; RestoreMonitor rmon = bm.restore(rp, monitor); if (rmon.getErrorMessage() != null) { String msg; if (rmon.getMissingAppAD() != null) msg = Messages.getString("DeviceMirrorringHandler.9") + " " //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.14"); //$NON-NLS-1$ else if (rmon.getVersionMismatchAppAD() != null) msg = Messages.getString("DeviceMirrorringHandler.19") + " " //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.14"); //$NON-NLS-1$ else msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.42") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", //$NON-NLS-1$ //$NON-NLS-2$ rmon.getErrorMessage()); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return false; } ui.inform(Messages.getString("DeviceMirrorringHandler.50")); //$NON-NLS-1$ return true; } finally { m_mirrorRestoreActive = false; } } /** * Set mirror state to 'inactive' if restoring in the context of a device * migration. * * @param monitor * @param restoredTables */ public void onDbRestored(RestoreMonitor monitor, Set restoredTables) { if (m_mirrorRestoreActive) { log.info("DB restore complete -> switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); } } /** * Process the user login in state 'active'. * * @param username * @param deleteApplicationData * @return Returns true if the application can be started. */ private boolean processLoginActive(String username, SimpleUserInterface ui, ProgressMonitor monitor, DeleteAppDataFunction deleteApplicationData) { log.info("Processing active user login for user " + username); //$NON-NLS-1$ // check if the authenticated user's personal push token is currently assigned NotificationHandler nh = Runtime.getNotificationHandler(); String userTokenId = getPersonalTokenId(username); List assignedTokens = nh.getAssignedTokens(); boolean userTokenAssigned = false; String assignedUser = null; for (Token token : assignedTokens) { if (isPersonalTokenId(token.getTokenId())) { assignedUser = getUsername(token.getTokenId()); if (userTokenId.equals(token.getTokenId())) { // user token already assigned userTokenAssigned = true; break; } } } if (!userTokenAssigned) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.51") + "\n\n" //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.53"), //$NON-NLS-1$ username, assignedUser); if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.4"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, SimpleUserInterface.MBOX_ICON_QUESTION)) { return false; } // release currently assigned user and do an inactive login for the logged in // user if (assignedUser != null) { log.info("Releasing currently assigned user " + assignedUser); //$NON-NLS-1$ monitor.begin(2); if (!releaseDevice(assignedUser, ui, new SubProgressMonitor(monitor, 1))) return false; } else { log.info("No user currently assigned!? -> switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); monitor.begin(1); } log.info("Performing inactive login for user " + username); //$NON-NLS-1$ return processLoginInactive(username, ui, new SubProgressMonitor(monitor, 1), deleteApplicationData); } log.info("Personal push token already assigned -> starting normal"); //$NON-NLS-1$ return true; } /** * Process the device release on behalv of the logged in user. * * @param username * @param ui * @return Returns true if the application was released * successfully. */ public boolean releaseDevice(String username, SimpleUserInterface ui, ProgressMonitor monitor) { log.info("Processing device release for user " + username); //$NON-NLS-1$ monitor.begin(Messages.getString("DeviceMirrorringHandler.55"), 4); //$NON-NLS-1$ // synchronize the push token list and make sure, that the authenticated // user's personal push token is still assigned monitor.comment(Messages.getString("DeviceMirrorringHandler.56")); //$NON-NLS-1$ NotificationHandler nh = Runtime.getNotificationHandler(); String syncError = nh.synchronizeAssignedTokens(); if (syncError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.44") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", //$NON-NLS-1$ //$NON-NLS-2$ syncError); log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } List assignedTokens = nh.getAssignedTokens(); String personalTokenId = getPersonalTokenId(username); boolean personalTokenFound = false; for (Token token : assignedTokens) { if (personalTokenId.equalsIgnoreCase(token.getTokenId())) { personalTokenFound = true; break; } } if (!personalTokenFound || PersonalTokenState.MULTIPLE_ASSIGNED == getTokenState()) { String msg; if (!personalTokenFound) msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.59"), username); //$NON-NLS-1$ else msg = Messages.getString("DeviceMirrorringHandler.60"); //$NON-NLS-1$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return false; } monitor.worked(1); // stop push notification delivery nh.stopReception(); try { // backup the runtime monitor.comment(Messages.getString("DeviceMirrorringHandler.62")); //$NON-NLS-1$ RestorePoint rp = backupRuntime(username, ui, monitor); if (rp == null) return false; monitor.worked(1); // release push tokens of other users monitor.comment(Messages.getString("DeviceMirrorringHandler.63")); //$NON-NLS-1$ // release the personal push token of the logged in user and // set mirror state to inactive in a single db transaction String userTokenId = getPersonalTokenId(username); LocalTransaction trans = new LocalTransaction(Runtime.getApplicationManager().getDBSession()); try { String remark = getRemarkFromRP(rp); String releaseError = nh.releaseToken(userTokenId, remark); setMirrorUserdataDeleted(false); log.info("Personal push token released -> switching to mirror state 'inactive'"); //$NON-NLS-1$ setMirrorState(MIRROR_STATE_INACTIVE); trans.commit(); if (releaseError != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.48") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", releaseError); //$NON-NLS-1$ //$NON-NLS-2$ log.error(msg); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), //$NON-NLS-1$ SimpleUserInterface.MBOX_BUTTON_OK, SimpleUserInterface.MBOX_ICON_ERROR); return true; } monitor.worked(1); monitor.completed(); return true; } finally { if (trans.isPending()) trans.rollback(); } } finally { // restart push notification reception nh.startReception(); } } private enum PersonalTokenState { /** * No personal push token assigned. */ NONE_ASSIGNED, /** * Exactly one personal push token assigned. */ ONE_ASSIGNED, /** * Multiple personal push tokens assigned. */ MULTIPLE_ASSIGNED } private PersonalTokenState getTokenState() { NotificationHandler nh = Runtime.getNotificationHandler(); List assignedTokens = nh.getAssignedTokens(); boolean tokenFound = false; for (Token token : assignedTokens) { if (!isPersonalTokenId(token.getTokenId())) continue; if (tokenFound) return PersonalTokenState.MULTIPLE_ASSIGNED; tokenFound = true; } if (tokenFound) return PersonalTokenState.ONE_ASSIGNED; return PersonalTokenState.NONE_ASSIGNED; } private List getAssignedPersonalTokenUsernames() { NotificationHandler nh = Runtime.getNotificationHandler(); ArrayList result = new ArrayList(); List assignedTokens = nh.getAssignedTokens(); for (Token token : assignedTokens) { if (isPersonalTokenId(token.getTokenId())) result.add(getUsername(token.getTokenId())); } return result; } private RestorePoint backupRuntime(String username, SimpleUserInterface ui, ProgressMonitor monitor) { if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox( MessageFormat.format(Messages.getString("DeviceMirrorringHandler.66") //$NON-NLS-1$ + "\n\n" + Messages.getString("DeviceMirrorringHandler.68"), //$NON-NLS-1$ //$NON-NLS-2$ username), Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_QUESTION)) { log.info("User canceled backup"); //$NON-NLS-1$ return null; } BackupManager bm = Runtime.getBackupManager(); String tag = "application release / device mirroring"; //$NON-NLS-1$ final BackupMonitor bmon = bm.backup(tag, new SubProgressMonitor(monitor, 1)); try { bmon.join(); } catch (InterruptedException e) { return null; } if (bmon.getErrorMessage() != null) { String msg = MessageFormat.format(Messages.getString("DeviceMirrorringHandler.52") + " " //$NON-NLS-1$//$NON-NLS-2$ + Messages.getString("DeviceMirrorringHandler.6") + " ''{0}''", //$NON-NLS-1$ //$NON-NLS-2$ bmon.getErrorMessage()); ui.showMessageBox(msg, Messages.getString("DeviceMirrorringHandler.58"), SimpleUserInterface.MBOX_BUTTON_OK, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_ERROR); return null; } ui.inform(Messages.getString("DeviceMirrorringHandler.72")); //$NON-NLS-1$ return newRestorePoint(bmon.getBackupStart(), Runtime.getTransactionHandler().getKolibriId(), Runtime.getLicenseAdapter().getClientId(), tag); } /** * Abort the running backup if the application is not in mirror state 'active'. * * @param monitor */ public void onCreateSnapshot(BackupMonitor monitor) { if (MIRROR_STATE_ACTIVE.equals(getMirrorState())) return; monitor.abort(Messages.getString("DeviceMirrorringHandler.73")); //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.common.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.AddressType; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.InvoiceCode; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.JobPriority; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.JobStatusName; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.LoginMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.MessageRecipient; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.Month; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.NoSignatureReason; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.ReportSendType; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.Titel; import ch.mfiles.kaba.kolibri.common.businessobjects.enums.VariousExpens; public class EnumUtil { public static final Log log = LogFactory.getLog(EnumUtil.class); private static EnumUtil instance = null; private DatabaseUtil dbutil; private EnumUtil() { } public static final EnumUtil getInstance(DatabaseUtil dbutil) { if (instance == null) { instance = new EnumUtil(); } instance.dbutil = dbutil; instance.initializeLocalizedTexts(); return instance; } public JobType jobTypeEnum; public JobStatusName jobStatusNameEnum; public JobPriority jobPriorityEnum; public Titel titelEnum; public AddressType addressTypeEnum; public NoSignatureReason noSignatureReasonEnum; public ReportSendType reportSendTypeEnum; public Month monthEnum; public MessageRecipient messageRecipientEnum; public VariousExpens variousExpensEnum; public InvoiceCode invoiceCodeEnum; public LoginMessage loginMessageEnum; private void initializeLocalizedTexts() { jobTypeEnum = new JobType(dbutil); jobStatusNameEnum = new JobStatusName(dbutil); jobPriorityEnum = new JobPriority(dbutil); titelEnum = new Titel(dbutil); addressTypeEnum = new AddressType(dbutil); noSignatureReasonEnum = new NoSignatureReason(dbutil); reportSendTypeEnum = new ReportSendType(dbutil); monthEnum = new Month(dbutil); messageRecipientEnum = new MessageRecipient(dbutil); variousExpensEnum = new VariousExpens(dbutil); invoiceCodeEnum = new InvoiceCode(dbutil); loginMessageEnum = new LoginMessage(dbutil); } } java.lang.String timeStamp = java.lang.String.valueOf(new java.util.Date().getTime()); java.lang.String time = ""; for (int i = 0; i < timeStamp.length(); i++) { time = time.concat("3").concat(timeStamp.substring(i, i+1)); } System.out.println(timeStamp + " / " + time); package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Bitmap; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.Runtime; public class FileUtils { public static final Log log = LogFactory.getLog(FileUtils.class); /** * Gets the absolute folder path name for the given application. * @param applicationName * * @return absolute file path name */ public static String getAbsoluteAppPathName(String applicationName) { return Runtime.getInstallationFolder() + "/" //$NON-NLS-1$ + applicationName; } /** * Gets the absolute file path name. * * @param packageName * the package name * @param fileName * the file name * * @param createDir * set to True in order to automatically create the directory if * it doesn't exist yet * * * @return absolute file path name */ public static String getAbsoluteFilePathName(String applicationName, String packageName, String fileName, boolean createDir) { if (!createDir) { return getAbsoluteAppPathName(applicationName) + "/" //$NON-NLS-1$ + packageName + "/" + fileName; //$NON-NLS-1$ } else { String absoluteImagePathName = getAbsoluteAppPathName(applicationName) + "/" //$NON-NLS-1$ + packageName + "/" + fileName; //$NON-NLS-1$ FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(absoluteImagePathName); } catch (FileNotFoundException e) { log.error(e); if(log.isDebugEnabled()) log.debug("directory not found"); //$NON-NLS-1$ absoluteImagePathName = createDirectory(applicationName,packageName, fileName); if(log.isDebugEnabled()) log.debug("new directory /" //$NON-NLS-1$ + absoluteImagePathName + "/ created"); //$NON-NLS-1$ } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // ignore log.error(e); } } } return absoluteImagePathName; } } /** * Create all needed sub-directories and return CanonicalPath * * @param packageName * package name to be create the directory * @param fileName * file name to be create * @return the full file path name */ public static String createDirectory(String applicationName, String packageName, String fileName) { String destinationPath = getAbsoluteAppPathName(applicationName); // create the destination root directory if it doesn't exist yet File destinationRootDirectory = new File(destinationPath); destinationRootDirectory.mkdir(); File destinationFileDir = new File(destinationRootDirectory + "/" //$NON-NLS-1$ + packageName); // create all needed sub-directories destinationFileDir.mkdirs(); File destinationFile = null; try { destinationFile = new File(destinationFileDir.getCanonicalPath() + "/" + fileName); } catch (IOException e) { throw new ApplicationException(e); } try { destinationPath = destinationFile.getCanonicalPath(); } catch (IOException e) { throw new ApplicationException(e); } return destinationPath; } public static void writeFile(String filePath, String data) throws IOException { BufferedWriter writer = null; FileWriter fr = null; try { fr = new FileWriter(filePath); writer = new BufferedWriter(fr); writer.write(data); } finally { try { if (writer != null) { writer.close(); } if (fr != null) { fr.close(); } } catch (IOException e) { log.error(e); } } } /** * Extracts a file from the classpath and saves it to the filesystem in a * path relative to the installation directory. * * Each application has it's own base directory (Application) * * Note: Use getAbsoluteFilePathName to get the absolute path to the file * * @param Application * the base directory of the application * * @param packageName * the name of the package where the file is located * @param fileName * the relative name of the file */ public void extractFileFromJar(String Application, String packageName, String fileName) { if(log.isDebugEnabled()) log.debug("extractFileFromJar/" + packageName + "/" + fileName + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ InputStream inputStream = getClass().getClassLoader() .getResourceAsStream(packageName + "/" + fileName); //$NON-NLS-1$ if (inputStream == null) throw new ApplicationException(MessageFormat.format( Messages.getString("FileUtils_0"), //$NON-NLS-1$ new Object[] { packageName + "/" + fileName })); //$NON-NLS-1$ FileOutputStream outputStream = null; try { String absoluteFilePathName = getAbsoluteFilePathName(Application, packageName, fileName, true); outputStream = new FileOutputStream(absoluteFilePathName); if(log.isDebugEnabled()) log.debug(MessageFormat.format("extracting {0} to {1}", //$NON-NLS-1$ new Object[] { packageName + "/" + fileName, //$NON-NLS-1$ absoluteFilePathName })); int aByte = 0; // write byte by byte while ((aByte = inputStream.read()) != -1) { outputStream.write(aByte); } } catch (IOException e) { throw new ApplicationException(e); } finally { try { inputStream.close(); } catch (IOException e) { log.error(e); // ignore } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { log.error(e); // ignore } } } } public static class Packages { public static final String DATA = "data"; //$NON-NLS-1$ } public static class FileNames { public static final String FIXED_MASTERDATA = "fixed-master-data.txt"; //$NON-NLS-1$ } public static void writeBitmapToFile(String imagePath, Bitmap bitmap) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); File myCaptureFile = new File(imagePath); FileOutputStream fi; fi = new FileOutputStream(myCaptureFile); baos.writeTo(fi); baos.flush(); baos.close(); int fileSize = baos.toByteArray().length / 1024; log.info("after compressed size: " + fileSize + " Kb"); log.info("path : " + myCaptureFile.getAbsolutePath()); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } } } package ch.mfiles.kaba.kolibri.common.util; import android.R; import android.content.Context; import android.content.res.TypedArray; public class FormUtil { private Context context; public FormUtil(Context context) { this.context = context; } public int getDisplayHeight() { return context.getResources().getDisplayMetrics().heightPixels; } public int getDisplayWidth() { return context.getResources().getDisplayMetrics().widthPixels; } public int getFormHeight() { return getDisplayHeight() - getStatusBarHeight() - getToolBarHeight(); } public int getStatusBarHeight() { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } public int getToolBarHeight() { int[] attrs = new int[] { R.attr.actionBarSize }; TypedArray ta = context.obtainStyledAttributes(attrs); int toolBarHeight = ta.getDimensionPixelSize(0, -1); ta.recycle(); return toolBarHeight; } public int getNavigationBarHeight() { int navigationBarHeight = 0; int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navigationBarHeight = context.getResources().getDimensionPixelSize(resourceId); } return navigationBarHeight; } } package ch.mfiles.kaba.kolibri.common.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.os.StrictMode; /** * * Just a temporary solution, not sure if there is a better approach for this ... * * 1. (0-7) IPAddress as HEX - 8 bytes * 2. (8-19) CurrentTimeMillis() as HEX - Display all 12 bytes * 3. (20-23) SecureRandom() as HEX - Keep only 4 significant bytes. Since this is "random" it doesn't really matter how many bytes you keep or eliminate * 4. (24-31) System.identityHashCode as Hex - 8 bytes * * * @author Administrator * */ public class GuidGenerator { private static Log log = LogFactory.getLog(GuidGenerator.class); /** * Generates a 32 byte GUID * @return * @throws UnknownHostException * @throws NoSuchAlgorithmException */ public String generate() throws UnknownHostException, NoSuchAlgorithmException { String result = ""; //$NON-NLS-1$ String temp; /* * for solve exception: * android.os.NetworkOnMainThreadException * android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303) * * see "[MIG-52] implement of "search job"" also * see this link:"http://stackoverflow.com/questions/13136539/caused-by-android-os-networkonmainthreadexception" */ if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Get IPAddress Segment InetAddress addr = InetAddress.getLocalHost(); if(log.isDebugEnabled()) log.debug("IP /" + addr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ byte[] ipaddr = addr.getAddress(); for (int i = 0; i < ipaddr.length; i++) { Byte b = new Byte(ipaddr[i]); temp = Integer.toHexString(b.intValue() & 0x000000ff); while (temp.length() < 2) { temp = '0' + temp; } result += temp; } // Get CurrentTimeMillis() segment temp = Long.toHexString(System.currentTimeMillis()); while (temp.length() < 12) { temp = '0' + temp; } result += temp; // Get Random Segment SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$ temp = Integer.toHexString(prng.nextInt()); while (temp.length() < 8) { temp = '0' + temp; } result += temp.substring(4); // Get IdentityHash() segment temp = Long.toHexString(System.identityHashCode((Object) this)); while (temp.length() < 8) { temp = '0' + temp; } result += temp; return result.toUpperCase(); } public String getIP() throws UnknownHostException{ return InetAddress.getLocalHost().toString(); } public static void main(String[] args) throws Exception { log.info(new GuidGenerator().generate()); } } package ch.mfiles.kaba.kolibri.common.util; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.ApplicationException; /* * Java HTML Tidy - JTidy * HTML parser and pretty printer * * Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts * Institute of Technology, Institut National de Recherche en * Informatique et en Automatique, Keio University). All Rights * Reserved. * * Contributing Author(s): * * Dave Raggett * Andy Quick (translation to Java) * Gary L Peskin (Java development) * Sami Lempinen (release management) * Fabrizio Giustina * Vlad Skarzhevskyy (JTidy servlet development) * * The contributing author(s) would like to thank all those who * helped with testing, bug fixes, and patience. This wouldn't * have been possible without all of you. * * COPYRIGHT NOTICE: * * This software and documentation is provided "as is," and * the copyright holders and contributing author(s) make no * representations or warranties, express or implied, including * but not limited to, warranties of merchantability or fitness * for any particular purpose or that the use of the software or * documentation will not infringe any third party patents, * copyrights, trademarks or other rights. * * The copyright holders and contributing author(s) will not be * liable for any direct, indirect, special or consequential damages * arising out of any use of the software or documentation, even if * advised of the possibility of such damage. * * Permission is hereby granted to use, copy, modify, and distribute * this source code, or portions hereof, documentation and executables, * for any purpose, without fee, subject to the following restrictions: * * 1. The origin of this source code must not be misrepresented. * 2. Altered versions must be plainly marked as such and must * not be misrepresented as being the original source. * 3. This Copyright notice may not be removed or altered from any * source or altered source distribution. * * The copyright holders and contributing author(s) specifically * permit, without fee, and encourage the use of this source code * as a component for supporting the Hypertext Markup Language in * commercial products. If you use this source code in a product, * acknowledgment is not required but would be appreciated. * */ /** * Converts a String to HTML by converting all special characters to HTML-entities. * @author Vlad Skarzhevskyy skarzhevskyy@gmail.com * @version $Revision: 1.2 $ ($Author: bpauli $) */ public class HTMLEncode { /** * j2se 1.4 encode method, used by reflection if available. */ private static Method encodeMethod14; public static final Log log = LogFactory.getLog(HTMLEncode.class); static { // URLEncoder.encode(String) has been deprecated in J2SE 1.4. // Take advantage of the new method URLEncoder.encode(String, enc) if J2SE 1.4 is used. try { Class urlEncoderClass = Class.forName("java.net.URLEncoder"); //$NON-NLS-1$ encodeMethod14 = urlEncoderClass.getMethod("encode", new Class[]{String.class, String.class}); //$NON-NLS-1$ } catch (Exception ex) { // encodeMethod14 will be null if exception log.error(ex); } } /** * Utility class, don't instantiate. */ private HTMLEncode() { // unused } private static final String[] ENTITIES = { ">", //$NON-NLS-1$ ">", //$NON-NLS-1$ "<", //$NON-NLS-1$ "<", //$NON-NLS-1$ "&", //$NON-NLS-1$ "&", //$NON-NLS-1$ "\"", //$NON-NLS-1$ """, //$NON-NLS-1$ "'", //$NON-NLS-1$ "'", //$NON-NLS-1$ "\\", //$NON-NLS-1$ "\", //$NON-NLS-1$ "\u00a9", //$NON-NLS-1$ "©", //$NON-NLS-1$ "\u00ae", //$NON-NLS-1$ "®"}; //$NON-NLS-1$ private static HashMap entityTableEncode = null; protected static synchronized void buildEntityTables() { entityTableEncode = new HashMap(ENTITIES.length); for (int i = 0; i < ENTITIES.length; i += 2) { if (!entityTableEncode.containsKey(ENTITIES[i])) { entityTableEncode.put(ENTITIES[i], ENTITIES[i + 1]); } } } /** * Converts a String to HTML by converting all special characters to HTML-entities. */ public final static String encode(String s) { return encode(s, "\n"); //$NON-NLS-1$ } /** * Converts a String to HTML by converting all special characters to HTML-entities. */ public final static String encode(String s, String cr) { if (entityTableEncode == null) { buildEntityTables(); } if (s == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(s.length() * 2); char ch; for (int i = 0; i < s.length(); ++i) { ch = s.charAt(i); if ((ch >= 63 && ch <= 90) || (ch >= 97 && ch <= 122) || (ch == ' ')) { sb.append(ch); } else if (ch == '\n') { sb.append(cr); } else { String chEnc = encodeSingleChar(String.valueOf(ch)); if (chEnc != null) { sb.append(chEnc); } else { // Not 7 Bit use the unicode system sb.append("&#"); //$NON-NLS-1$ sb.append(ch); sb.append(';'); } } } return sb.toString(); } /** * Converts a single character to HTML */ private static String encodeSingleChar(String ch) { return entityTableEncode.get(ch); } /** * Converts a String to valid HTML HREF by converting all special characters to HTML-entities. * @param url url to be encoded * @return encoded url. */ protected static String encodeHREFParam(String url) { if (encodeMethod14 != null) { Object[] methodArgs = new Object[2]; methodArgs[0] = url; methodArgs[1] = "UTF8"; //$NON-NLS-1$ try { return (String) encodeMethod14.invoke(null, methodArgs); } catch (Exception e) { log.error(e); throw new ApplicationException(Messages.getString("HTMLEncode_0") + e); //$NON-NLS-1$ } } // must use J2SE 1.3 version return URLEncoder.encode(url); } protected static String encodeHREFParamJava13(String value) { return URLEncoder.encode(value); } public static String encodeQuery(String url, String[] args) { return encodeHREFQuery(url, args, false); } public static String encodeHREFQuery(String url, String[] args) { return encodeHREFQuery(url, args, true); } public static String encodeHREFQuery(String url, String[] args, boolean forHtml) { StringBuilder out = new StringBuilder(128); out.append(url); if ((args != null) && (args.length > 0)) { out.append("?"); //$NON-NLS-1$ for (int i = 0; i < (args.length + 1) / 2; i++) { int k = i * 2; if (k != 0) { if (forHtml) { out.append("&"); //$NON-NLS-1$ } else { out.append("&"); //$NON-NLS-1$ } } out.append(encodeHREFParam(args[k])); if (k + 1 < args.length) { out.append("="); //$NON-NLS-1$ out.append(encodeHREFParam(args[k + 1])); } } } return out.toString(); } public static String encodeHREFQuery(String url, Map args, boolean forHtml) { StringBuilder out = new StringBuilder(128); out.append(url); if ((args != null) && (args.size() > 0)) { out.append("?"); //$NON-NLS-1$ int k = 0; for (Iterator i = args.keySet().iterator(); i.hasNext();) { if (k != 0) { if (forHtml) { out.append("&"); //$NON-NLS-1$ } else { out.append("&"); //$NON-NLS-1$ } } String name = (String) i.next(); out.append(encodeHREFParam(name)); out.append("="); //$NON-NLS-1$ out.append(encodeHREFParam((String) args.get(name))); k++; } } return out.toString(); } } package ch.mfiles.kaba.kolibri.common.util; public class HtmlUtil { private StringBuilder mHeadStringBuilder = new StringBuilder(); private StringBuilder mCSSStringBuilder = new StringBuilder(); private StringBuilder mHtmlStringBuilder = new StringBuilder(); private StringBuilder mTableStringBuilder = new StringBuilder(); private StringBuilder mRowsStringBuilder = new StringBuilder(); private StringBuilder mBodyStringBuilder = new StringBuilder(); private String mTitle=""; //$NON-NLS-1$ private String mBackgroundColour=""; //$NON-NLS-1$ private String mTextcolour=""; //$NON-NLS-1$ private int mFontSize; public HtmlUtil(){ this.setBackgroundColour("#2554C7"); //$NON-NLS-1$ this.setFontSize(10); this.setTextColour("white"); //$NON-NLS-1$ } public HtmlUtil(HtmlUtil htmlUtil) { this.setBackgroundColour(htmlUtil.getBackgroundColour()); this.setFontSize(htmlUtil.getFontSize()); this.setTextColour(htmlUtil.getTextcolour()); this.setTitle(htmlUtil.getTitle()); } public int getFontSize() { return mFontSize; } public void setFontSize(int fontSize) { mFontSize = fontSize; } private void generateHtml(){ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""+mTitle+""); //$NON-NLS-1$ //$NON-NLS-2$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(HTMLEncode.encode(mHeadStringBuilder.toString())); mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ } private void endHtml(){ mHtmlStringBuilder.append(""); //$NON-NLS-1$ mHtmlStringBuilder.append(""); //$NON-NLS-1$ } public void setbody(String body){ mBodyStringBuilder.append(body); } public void generateTable(String width, int border, int cellspacing, int cellpadding){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ mTableStringBuilder.append(mRowsStringBuilder.toString()); mHtmlStringBuilder.append(""); //$NON-NLS-1$ } public void generateTable(String width, int border, int cellspacing, int cellpadding, String option){ mTableStringBuilder.append("
"); //$NON-NLS-1$ mTableStringBuilder.append(mRowsStringBuilder.toString()); mHtmlStringBuilder.append(""); //$NON-NLS-1$ } public void appendRow(String option ){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ } public void appendRow(){ mTableStringBuilder.append(""); //$NON-NLS-1$ } public void endRow(){ mTableStringBuilder.append(""); //$NON-NLS-1$ } public void appendColumn(String text, String option ){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void appendColumn(String text){ mTableStringBuilder.append(""); //$NON-NLS-1$ //$NON-NLS-2$ } public void endTable(){ mTableStringBuilder.append("
" + text + "" + text + "
"); //$NON-NLS-1$ mBodyStringBuilder.append(mTableStringBuilder.toString()); } public String getHtml(){ generateHtml(); mHtmlStringBuilder.append(mBodyStringBuilder.toString()); endHtml(); return mHtmlStringBuilder.toString(); } public void setTitle(String title){ mTitle = title; } public String getTitle(){ return mTitle; } public String getTextcolour() { return mTextcolour; } public void setTextColour(String textcolour) { mTextcolour = textcolour; } public String getBackgroundColour() { return mBackgroundColour; } public void setBackgroundColour(String backgroundColour) { mBackgroundColour = backgroundColour; } public StringBuilder getCSSStringBuilder() { return mCSSStringBuilder; } public void setCSSStringBuilder(StringBuilder StringBuilder) { mCSSStringBuilder = StringBuilder; } public StringBuilder getHeadStringBuilder() { return mHeadStringBuilder; } public void setHeadStringBuilder(StringBuilder headStringBuilder) { mHeadStringBuilder = headStringBuilder; } public String replaceHtmlWhiteSpace(String text){ if(text.length() == 0){ return " "; //$NON-NLS-1$ }else{ return text; } } }
package ch.mfiles.kaba.kolibri.common.util; import android.media.ExifInterface; import android.text.TextUtils; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; /** * A class for parsing the exif orientation from an image header. */ public class ImageHeaderParser { private static final String TAG = "ImageHeaderParser"; /** * A constant indicating we were unable to parse the orientation from the image either because * no exif segment containing orientation data existed, or because of an I/O error attempting to * read the exif segment. */ public static final int UNKNOWN_ORIENTATION = -1; private static final int EXIF_MAGIC_NUMBER = 0xFFD8; // "MM". private static final int MOTOROLA_TIFF_MAGIC_NUMBER = 0x4D4D; // "II". private static final int INTEL_TIFF_MAGIC_NUMBER = 0x4949; private static final String JPEG_EXIF_SEGMENT_PREAMBLE = "Exif\0\0"; private static final byte[] JPEG_EXIF_SEGMENT_PREAMBLE_BYTES = JPEG_EXIF_SEGMENT_PREAMBLE.getBytes(Charset.forName("UTF-8")); private static final int SEGMENT_SOS = 0xDA; private static final int MARKER_EOI = 0xD9; private static final int SEGMENT_START_ID = 0xFF; private static final int EXIF_SEGMENT_TYPE = 0xE1; private static final int ORIENTATION_TAG_TYPE = 0x0112; private static final int[] BYTES_PER_FORMAT = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; private final Reader reader; public ImageHeaderParser(InputStream is) { reader = new StreamReader(is); } /** * Parse the orientation from the image header. If it doesn't handle this image type (or this is * not an image) it will return a default value rather than throwing an exception. * * @return The exif orientation if present or -1 if the header couldn't be parsed or doesn't * contain an orientation * @throws IOException */ public int getOrientation() throws IOException { final int magicNumber = reader.getUInt16(); if (!handles(magicNumber)) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Parser doesn't handle magic number: " + magicNumber); } return UNKNOWN_ORIENTATION; } else { int exifSegmentLength = moveToExifSegmentAndGetLength(); if (exifSegmentLength == -1) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Failed to parse exif segment length, or exif segment not found"); } return UNKNOWN_ORIENTATION; } byte[] exifData = new byte[exifSegmentLength]; return parseExifSegment(exifData, exifSegmentLength); } } private int parseExifSegment(byte[] tempArray, int exifSegmentLength) throws IOException { int read = reader.read(tempArray, exifSegmentLength); if (read != exifSegmentLength) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to read exif segment data" + ", length: " + exifSegmentLength + ", actually read: " + read); } return UNKNOWN_ORIENTATION; } boolean hasJpegExifPreamble = hasJpegExifPreamble(tempArray, exifSegmentLength); if (hasJpegExifPreamble) { return parseExifSegment(new RandomAccessReader(tempArray, exifSegmentLength)); } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Missing jpeg exif preamble"); } return UNKNOWN_ORIENTATION; } } private boolean hasJpegExifPreamble(byte[] exifData, int exifSegmentLength) { boolean result = exifData != null && exifSegmentLength > JPEG_EXIF_SEGMENT_PREAMBLE_BYTES.length; if (result) { for (int i = 0; i < JPEG_EXIF_SEGMENT_PREAMBLE_BYTES.length; i++) { if (exifData[i] != JPEG_EXIF_SEGMENT_PREAMBLE_BYTES[i]) { result = false; break; } } } return result; } /** * Moves reader to the start of the exif segment and returns the length of the exif segment or * {@code -1} if no exif segment is found. */ private int moveToExifSegmentAndGetLength() throws IOException { short segmentId, segmentType; int segmentLength; while (true) { segmentId = reader.getUInt8(); if (segmentId != SEGMENT_START_ID) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unknown segmentId=" + segmentId); } return -1; } segmentType = reader.getUInt8(); if (segmentType == SEGMENT_SOS) { return -1; } else if (segmentType == MARKER_EOI) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Found MARKER_EOI in exif segment"); } return -1; } // Segment length includes bytes for segment length. segmentLength = reader.getUInt16() - 2; if (segmentType != EXIF_SEGMENT_TYPE) { long skipped = reader.skip(segmentLength); if (skipped != segmentLength) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to skip enough data" + ", type: " + segmentType + ", wanted to skip: " + segmentLength + ", but actually skipped: " + skipped); } return -1; } } else { return segmentLength; } } } private static int parseExifSegment(RandomAccessReader segmentData) { final int headerOffsetSize = JPEG_EXIF_SEGMENT_PREAMBLE.length(); short byteOrderIdentifier = segmentData.getInt16(headerOffsetSize); final ByteOrder byteOrder; if (byteOrderIdentifier == MOTOROLA_TIFF_MAGIC_NUMBER) { byteOrder = ByteOrder.BIG_ENDIAN; } else if (byteOrderIdentifier == INTEL_TIFF_MAGIC_NUMBER) { byteOrder = ByteOrder.LITTLE_ENDIAN; } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unknown endianness = " + byteOrderIdentifier); } byteOrder = ByteOrder.BIG_ENDIAN; } segmentData.order(byteOrder); int firstIfdOffset = segmentData.getInt32(headerOffsetSize + 4) + headerOffsetSize; int tagCount = segmentData.getInt16(firstIfdOffset); int tagOffset, tagType, formatCode, componentCount; for (int i = 0; i < tagCount; i++) { tagOffset = calcTagOffset(firstIfdOffset, i); tagType = segmentData.getInt16(tagOffset); // We only want orientation. if (tagType != ORIENTATION_TAG_TYPE) { continue; } formatCode = segmentData.getInt16(tagOffset + 2); // 12 is max format code. if (formatCode < 1 || formatCode > 12) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got invalid format code = " + formatCode); } continue; } componentCount = segmentData.getInt32(tagOffset + 4); if (componentCount < 0) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Negative tiff component count"); } continue; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got tagIndex=" + i + " tagType=" + tagType + " formatCode=" + formatCode + " componentCount=" + componentCount); } final int byteCount = componentCount + BYTES_PER_FORMAT[formatCode]; if (byteCount > 4) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Got byte count > 4, not orientation, continuing, formatCode=" + formatCode); } continue; } final int tagValueOffset = tagOffset + 8; if (tagValueOffset < 0 || tagValueOffset > segmentData.length()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Illegal tagValueOffset=" + tagValueOffset + " tagType=" + tagType); } continue; } if (byteCount < 0 || tagValueOffset + byteCount > segmentData.length()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Illegal number of bytes for TI tag data tagType=" + tagType); } continue; } //assume componentCount == 1 && fmtCode == 3 return segmentData.getInt16(tagValueOffset); } return -1; } private static int calcTagOffset(int ifdOffset, int tagIndex) { return ifdOffset + 2 + 12 * tagIndex; } private static boolean handles(int imageMagicNumber) { return (imageMagicNumber & EXIF_MAGIC_NUMBER) == EXIF_MAGIC_NUMBER || imageMagicNumber == MOTOROLA_TIFF_MAGIC_NUMBER || imageMagicNumber == INTEL_TIFF_MAGIC_NUMBER; } private static class RandomAccessReader { private final ByteBuffer data; public RandomAccessReader(byte[] data, int length) { this.data = (ByteBuffer) ByteBuffer.wrap(data) .order(ByteOrder.BIG_ENDIAN) .limit(length); } public void order(ByteOrder byteOrder) { this.data.order(byteOrder); } public int length() { return data.remaining(); } public int getInt32(int offset) { return data.getInt(offset); } public short getInt16(int offset) { return data.getShort(offset); } } private interface Reader { int getUInt16() throws IOException; short getUInt8() throws IOException; long skip(long total) throws IOException; int read(byte[] buffer, int byteCount) throws IOException; } private static class StreamReader implements Reader { private final InputStream is; // Motorola / big endian byte order. public StreamReader(InputStream is) { this.is = is; } @Override public int getUInt16() throws IOException { return (is.read() << 8 & 0xFF00) | (is.read() & 0xFF); } @Override public short getUInt8() throws IOException { return (short) (is.read() & 0xFF); } @Override public long skip(long total) throws IOException { if (total < 0) { return 0; } long toSkip = total; while (toSkip > 0) { long skipped = is.skip(toSkip); if (skipped > 0) { toSkip -= skipped; } else { // Skip has no specific contract as to what happens when you reach the end of // the stream. To differentiate between temporarily not having more data and // having finished the stream, we read a single byte when we fail to skip any // amount of data. int testEofByte = is.read(); if (testEofByte == -1) { break; } else { toSkip--; } } } return total - toSkip; } @Override public int read(byte[] buffer, int byteCount) throws IOException { int toRead = byteCount; int read; while (toRead > 0 && ((read = is.read(buffer, byteCount - toRead, toRead)) != -1)) { toRead -= read; } return byteCount - toRead; } } public static void copyExif(ExifInterface originalExif, int width, int height, String imageOutputPath) { String[] attributes = new String[]{ ExifInterface.TAG_APERTURE, ExifInterface.TAG_DATETIME, ExifInterface.TAG_DATETIME_DIGITIZED, ExifInterface.TAG_EXPOSURE_TIME, ExifInterface.TAG_FLASH, ExifInterface.TAG_FOCAL_LENGTH, ExifInterface.TAG_GPS_ALTITUDE, ExifInterface.TAG_GPS_ALTITUDE_REF, ExifInterface.TAG_GPS_DATESTAMP, ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LATITUDE_REF, ExifInterface.TAG_GPS_LONGITUDE, ExifInterface.TAG_GPS_LONGITUDE_REF, ExifInterface.TAG_GPS_PROCESSING_METHOD, ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_ISO, ExifInterface.TAG_MAKE, ExifInterface.TAG_MODEL, ExifInterface.TAG_SUBSEC_TIME, ExifInterface.TAG_SUBSEC_TIME_DIG, ExifInterface.TAG_SUBSEC_TIME_ORIG, ExifInterface.TAG_WHITE_BALANCE }; try { ExifInterface newExif = new ExifInterface(imageOutputPath); String value; for (String attribute : attributes) { value = originalExif.getAttribute(attribute); if (!TextUtils.isEmpty(value)) { newExif.setAttribute(attribute, value); } } newExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, String.valueOf(width)); newExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, String.valueOf(height)); newExif.setAttribute(ExifInterface.TAG_ORIENTATION, "0"); newExif.saveAttributes(); } catch (IOException e) { Log.d(TAG, e.getMessage()); } } } package ch.mfiles.kaba.kolibri.common.util; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; import ch.mfiles.kolibri.ApplicationManager; public class KeyboardUtil { KeyboardUtil() { } /** * Closes the keyboard (if open). * @param appman * @param v */ public static void closeKeyboard(ApplicationManager appman, View v) { // close the keyboard (if open) InputMethodManager imm = (InputMethodManager) appman.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } package ch.mfiles.kaba.kolibri.common.util; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.util.DisplayMetrics; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class LayoutUtils { public static final int DEFAULT_RED = 0xFFFF1818; public static final int DEFAULT_GREEN = 0xFF518E39; public static final int DEFAULT_BROWN = 0xFF5D433F; public static final int DEFAULT_PURPLE = 0xFF6A2DB4; public static final int DEFAULT_DARK_GRAY = 0xFF556770; public static final int DEFAULT_LIGHT_GRAY = 0xFFD2D2D2; public static final int DEFAULT_ORANGE = 0xFFEE5425; public static final int DEFAULT_WHITE = Color.WHITE; private static final int PRIMARY_COLOR_YELLOW = 0xFFF9A825; // Yellow 800 private static final int ACCENT_COLOR_INDIGO = 0xFF536DFE; // Indigo 200 private static final int ACCENT_COLOR_RED = 0xFFD50000; // Red 700 private static final int ERROR_MESSAGES_COLOR = 0xFFd50000; public static int DEFAULT_TOOL_BAR_COLOR = ACCENT_COLOR_INDIGO; // Indigo 500 public static final int DEFAULT_TAB_COLOR = DEFAULT_TOOL_BAR_COLOR; public static final int DEFAULT_TAB_SELECTED_TEXT_COLOR = DEFAULT_WHITE; public static final int DEFAULT_TAB_TEXT_COLOR = 0xFF7986CB; // Indigo 300 public static final int DEFAULT_CONTENT_AREA_COLOR = DEFAULT_WHITE; public static final int DEFAULT_TEXT_COLOR = Color.BLACK; public static final int DEFAULT_LABEL_COLOR = 0xFF737373; public static final int DEFAULT_ERROR_COLOR = ERROR_MESSAGES_COLOR; public static final int DEFAULT_BUTON_COLOR = 0xFFD2D2D2; public static final int DEFAULT_HIGHLIGHT = PRIMARY_COLOR_YELLOW; public static final int DEFAULT_DISABLED_COLOR = Color.DKGRAY; public static final int DEFAULT_CARD_VIEW_SHADOW_COLOR = 0xFFEEEEEE; public static final int DEFAULT_UNDERLINE_COLOR = 0xFF7E7E7E; public static final int DEFAULT_UNDERLINE_DISABLED_COLOR = 0xFFEEEEEE; public static final int DEFAULT_SEARCH_COLOR = 0XFFF5F5F5; public static final int DEFAULT_MIN_MARGIN = 5; public static final int DEFAULT_MAX_MARGIN = 10; public static final int DEFAULT_MIN_PADDING = 5; public static final int DEFAULT_MAX_PADDING = 16; public static final int DEFAULT_NEW_COLOR = DEFAULT_RED; public static final int DEFAULT_RECEIVED_COLOR = DEFAULT_GREEN; public static final int DEFAULT_FORWARDED_COLOR = DEFAULT_BROWN; public static final int DEFAULT_INPROGRESS_COLOR = DEFAULT_PURPLE; public static final int DEFAULT_FINALIZED_COLOR = DEFAULT_DARK_GRAY; public static final int DEFAULT_PARTLY_DONE_COLOR = DEFAULT_ORANGE; LayoutUtils() { } public static final int DEFAULT_MATERIAL_COLOR = 0xFF37474f; public static final LinearLayout.LayoutParams DEFAULT_MATCH_PARENT_PARAMS() { return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } public static final LinearLayout.LayoutParams DEFAULT_WRAP_CONTENT_PARAMS() { return new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } public static final LinearLayout.LayoutParams DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT() { return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } public static final LinearLayout.LayoutParams DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT() { return new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); } public static final void setDevelopmentColors() { DEFAULT_TOOL_BAR_COLOR = ACCENT_COLOR_RED; } /** * Converts DP To Pixel. * @param context * @param dp * @return */ public static int convertDpToPixel(Context context, float dp) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return Math.round(px); } } package ch.mfiles.kaba.kolibri.common.util; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.common.util.messages"; //$NON-NLS-1$ public static String FileUtils_11; public static String TranslationFileConverter_2; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } } package ch.mfiles.kaba.kolibri.common.util; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Color; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.Toast; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Runtime; public class MessageUtil { private Log log = LogFactory.getLog(MessageUtil.class); private static List snackBarList = new ArrayList(); private static List messageList = new ArrayList(); private static MessageUtil instance; public static final MessageUtil getInstance() { if (instance == null) { instance = new MessageUtil(); } return instance; } public void showMessage(String message) { ApplicationManager appman = (ApplicationManager)Runtime.getApplicationManager(); Application app = (appman != null) ? (Application)appman.getActiveApplication() : null; Form form = (app != null) ? (Form)app.getCurrentForm() : null; View view = (form != null) ? form.getView() : null; // fallback to a simple toast if no view is currently active if (view == null) { if (appman == null) log.warn("Couldn't toast message (ApplicationManager not started!): " + message, new IllegalStateException()); else Toast.makeText(appman.getContext(), message, Toast.LENGTH_LONG); return; } Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG); snackbar.setDuration(4000); // Change the action button text color snackbar.setActionTextColor(Color.GREEN); //if true set onDismiss CallBack snackbar.setCallback(new Snackbar.Callback() { @Override public void onDismissed(Snackbar currentSnackbar, int event) { super.onDismissed(currentSnackbar, event); //first remove current snackBar in List, then if List not empty show the first one snackBarList.remove(currentSnackbar); messageList.clear(); if (!snackBarList.isEmpty()) snackBarList.get(0).show(); } }); //add (set callback) snackBar to List snackBarList.add(snackbar); messageList.add(message); //the beginning if (snackBarList.size() == 1){ snackBarList.get(0).show(); } } public void showMessage(String message, boolean forceClear) { if(forceClear) { clearMessage(); } showMessage(message); } public void showContinueMessage() { if(!messageList.isEmpty()) { for (Snackbar snackbar : snackBarList) { snackbar.dismiss(); } snackBarList.clear(); List messages = new ArrayList(); messages.addAll(messageList); messageList.clear(); for (String message : messages) { showMessage(message); } } } public void clearMessage() { for (Snackbar snackbar : snackBarList) { snackbar.dismiss(); } snackBarList.clear(); messageList.clear(); } } package ch.mfiles.kaba.kolibri.common.util; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Icon; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.NotificationCompat; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Form; /** * The notifications for incoming job and short message. * * @author nop */ public class Notifications extends Form { private Application app; private ImagesUtil imagesUtil; private BroadcastReceiver brReceiver = null; public Notifications(Application application) { this.app = application; this.appman = application.appman; this.imagesUtil = ImagesUtil.getInstance(app); } /** * Registers thr BroadcastReceiver, called onApplicationStart() */ public void registerBroadcastReceiver() { if (brReceiver != null) return; brReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { /* * -called on main (UI-) thread! * -show UI if hidden; api method available * -since runtime release 1.2(1p201705281441) */ appman.bringToFront(); } }; IntentFilter intentFilter = new IntentFilter(CommonConstants.Notification.BROADCAST_ACTION); appman.getContext().registerReceiver(brReceiver, intentFilter); } /** * Unregisters thr BroadcastReceiver, called onApplicationExit() */ public void unregisterBroadcastReceiver() { LocalBroadcastManager bm = LocalBroadcastManager.getInstance(appman.getContext()); bm.unregisterReceiver(brReceiver); brReceiver = null; } /** * Gets a custom notification * * @param notificationId * @param message * @return */ @TargetApi(Build.VERSION_CODES.M) private Notification getNotification(int notificationId, String message) { Notification.Builder notification = new Notification.Builder(appman.getContext()); // set pending intent to trigger our broadcast receiver notification.setContentIntent(PendingIntent.getBroadcast(appman.getContext(), notificationId, new Intent(CommonConstants.Notification.BROADCAST_ACTION), 0)); notification.setContentTitle(Messages.getString("messages")); //$NON-NLS-1$ notification.setContentText(message); notification.setPriority(NotificationCompat.PRIORITY_HIGH); notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notification.setAutoCancel(false); notification.setOngoing(true); Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); notification.setSound(alarmSound); BitmapDrawable image = getBitmanDrawable(imagesUtil.getImage(ImagesUtil.Images.INFO_OUTLINE_WHITE)); notification.setSmallIcon(Icon.createWithBitmap(image.getBitmap())); return notification.build(); } /** * Updates the notification for a new job. * @param message */ public void newJobNotification(String message) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); nfManager.notify(CommonConstants.Notification.NEW_JOB, getNotification(CommonConstants.Notification.NEW_JOB, message)); } /** * Updates the notification for a short message. * @param message */ public void shortMessageNotification(String message) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); nfManager.notify(CommonConstants.Notification.SHORT_MESSAGE, getNotification(CommonConstants.Notification.SHORT_MESSAGE, message)); } /** * Updates the notification for a Incoming article. * @param message */ public void IncomingArticleNotification(String message) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); nfManager.notify(CommonConstants.Notification.INCOMING_ARTICLE, getNotification(CommonConstants.Notification.INCOMING_ARTICLE, message)); } /** * Removes the notification for a new job and a short message */ public void removeNotification() { removeNotification(0); } /** * Removes the notification. * @param notificationId */ public void removeNotification(int notificationId) { NotificationManager nfManager = (NotificationManager) appman.getContext().getSystemService(Context.NOTIFICATION_SERVICE); if (notificationId == 0) { nfManager.cancel(CommonConstants.Notification.NEW_JOB); nfManager.cancel(CommonConstants.Notification.SHORT_MESSAGE); nfManager.cancel(CommonConstants.Notification.INCOMING_ARTICLE); } else { nfManager.cancel(notificationId); } } } package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; public class PropertiesFileConverter { public static final Log log = LogFactory.getLog(PropertiesFileConverter.class); private static PropertiesFileConverter pfc; private static final String EN_FILE_NAME = "Messages.properties"; //$NON-NLS-1$ // private static final String DE_FILE_NAME = "Messages_de_CH.properties"; private static final String DE_FILE_NAME = "Messages_de.properties"; //$NON-NLS-1$ // private static final String FR_FILE_NAME = "Messages_fr_CH.properties"; private static final String FR_FILE_NAME = "Messages_fr.properties"; //$NON-NLS-1$ private static final String CSV_FILE_NAME = "Messages.txt"; //$NON-NLS-1$ private static String startPath = null; public static void main(String[] args) throws IOException { pfc = new PropertiesFileConverter(); startPath = "C:/MyData/workspace_KolibriFramework/"; //$NON-NLS-1$ traverse(new File(startPath), pfc.new DirectoryPrintVisitor()); log.info("Convert SQL complete."); //$NON-NLS-1$ } static void traverse(File dir, DirectoryVisitor visitor) { if (!dir.isDirectory()) { throw new IllegalArgumentException(Messages.getString("PropertiesFileConverter.0") + dir.getName()); //$NON-NLS-1$ } visitor.enterDirectory(dir); File[] entries = dir.listFiles(new FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName() .toLowerCase() .endsWith("messages.properties") && f.getPath() //$NON-NLS-1$ .indexOf("i18n") > -1 && f.getPath() //$NON-NLS-1$ .indexOf(".svn") == -1; //$NON-NLS-1$ } }); for (int i = 0; i < entries.length; ++i) { if (entries[i].isDirectory()) { traverse(entries[i], visitor); } else { PropertiesFileConverter.readPropertiesFile(entries[i].getParent() + "\\"); //$NON-NLS-1$ visitor.visitFile(entries[i]); } } visitor.leaveDirectory(dir); } public static void readPropertiesFile(String inputPath) { FileOutputStream fos = null; Writer out = null; // Default Datei öffnen StringBuilder buffer = new StringBuilder(); String msgEn = ""; //$NON-NLS-1$ String msgKey; FileInputStream fis1; FileInputStream fis2; FileInputStream fis3; try { fis1 = new FileInputStream(inputPath + EN_FILE_NAME); InputStreamReader isr1 = new InputStreamReader(fis1, "ISO-8859-1"); //$NON-NLS-1$ MsgPropertyReader inEn = pfc.new MsgPropertyReader(isr1); fis2 = new FileInputStream(inputPath + DE_FILE_NAME); InputStreamReader isr2 = new InputStreamReader(fis2, "ISO-8859-1"); //$NON-NLS-1$ MsgPropertyReader inDe = pfc.new MsgPropertyReader(isr2); fis3 = new FileInputStream(inputPath + FR_FILE_NAME); InputStreamReader isr3 = new InputStreamReader(fis3, "ISO-8859-1"); //$NON-NLS-1$ MsgPropertyReader inFr = pfc.new MsgPropertyReader(isr3); while ((msgEn = inEn.readLine()) != null) { String msgDe = ""; //$NON-NLS-1$ String msgFr = ""; //$NON-NLS-1$ if (msgEn.indexOf('=') > -1) { msgKey = msgEn.substring(0, msgEn.indexOf('=')); // inDe = pfc.new TranslationFileReader(isr2); msgDe = getMsg(msgKey, inDe); msgFr = getMsg(msgKey, inFr); // TAB getrennte Zeile erstellen buffer.append(msgKey) .append('\t') .append(msgEn.substring(msgEn.indexOf('=') + 1)) .append('\t') .append(msgDe) .append('\t') .append(msgFr) .append('\n'); inDe.close(); inFr.close(); fis1.close(); fis2.close(); fis3.close(); } } fos = new FileOutputStream(inputPath + CSV_FILE_NAME); out = new OutputStreamWriter(fos, "UTF8"); //$NON-NLS-1$ out.write(buffer.toString()); inEn.close(); fos.close(); } catch (IOException e) { log.error(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { log.error(e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { log.error(e); } } } } private static String getMsg(String msgKey, MsgPropertyReader inDe) throws IOException { String msgDe; while ((msgDe = inDe.readLine()) != null ) { if (msgDe.indexOf(msgKey) > -1) { try { msgDe = msgDe.substring(msgDe.indexOf('=') + 1); } catch (IndexOutOfBoundsException e) { log.error(e); msgDe = ""; //$NON-NLS-1$ } break; } else { return ""; //$NON-NLS-1$ } } return msgDe; } interface DirectoryVisitor { public void enterDirectory(File dir); public void leaveDirectory(File dir); public void visitFile(File file); } class DirectoryPrintVisitor implements DirectoryVisitor { String indent = ""; //$NON-NLS-1$ @Override public void enterDirectory(File dir) { indent += " "; //$NON-NLS-1$ } @Override public void leaveDirectory(File dir) { indent = indent.substring(2); } @Override public void visitFile(File file) { log.info(file.getAbsolutePath()); } } class MsgPropertyReader extends BufferedReader { public MsgPropertyReader(Reader in) { super(in); } public String readLine() throws NumberFormatException, IOException { String line; int index; if ((line = super.readLine()) != null) { while ((index = line.indexOf("\\u")) > -1) { //$NON-NLS-1$ char specialChar = (char) Integer.parseInt(line.substring(index + 2, index + 6), 16); line = line.substring(0, index) + specialChar + line.substring(index + 6); } return line; } else { return null; } } } } package ch.mfiles.kaba.kolibri.common.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; public class RegistryUtil { public static final Log log = LogFactory.getLog(RegistryUtil.class); RegistryUtil() { } public static final class RegistryProperties { RegistryProperties() { } public static final int MIN_INTERVAL = 1; public static final int MAX_INTERVAL = 99; public static final int DEFAULT_INTERVAL = 10; public static final String INTERVAL_PROPERTY_NAME = "NotificationInterval"; //$NON-NLS-1$ public static final String JOB_LIST_STYLE_PROPERTY_NAME = "JobListStyle"; //$NON-NLS-1$ public static final String MASTER_DATA_REFRESH_DATE_PROPERTY_NAME = "MasterDataRefreshDate"; //$NON-NLS-1$ public static final String INCOMING_ARTICLE_NAME = "IncomingArticle"; //$NON-NLS-1$ public static final int MIN_VOLUME = 0; public static final int MAX_VOLUME = 10; public static final int DEFAULT_MASTER_DATA_REFRESH_DATE = 0; public static final int DEFAULT_INVOMING_ARTICLE = 0; public static final String[] JOB_LIST_STYLE_VALUES = {"REP_SAV", "MON"}; //$NON-NLS-1$ //$NON-NLS-2$ public static final String DEFAULT_JOB_LIST_STYLE = JOB_LIST_STYLE_VALUES[0]; public static final String TEST_BACKUP_EVERY_S = "testBackupEveryS"; //$NON-NLS-1$ public static final String GENERIC_FORM_DRAFT_DOWNLOAD = "genericFormsDraftDownload"; //$NON-NLS-1$ } public static String getJobListStyleProperty(Application app) { ApplicationManager appman = app.appman; String jobListStyle = RegistryProperties.DEFAULT_JOB_LIST_STYLE; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { try { jobListStyle = reg.getProperty(RegistryProperties.JOB_LIST_STYLE_PROPERTY_NAME); } catch (IllegalArgumentException e) { log.warn("No JobListStyle-property found"); //$NON-NLS-1$ log.error(e); } } return jobListStyle; } public static long getMasterDataRefreshDateProperty(Application app) { ApplicationManager appman = app.appman; long masterDataRefreshDate = RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { try { masterDataRefreshDate = reg.getLongProperty(RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME); } catch (IllegalArgumentException e) { log.warn("No " + RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME + "-property found"); //$NON-NLS-1$ //$NON-NLS-2$ log.error(e); } } return masterDataRefreshDate; } public static void setJobListStyleProperty(Application app, String jobListStyle) { ApplicationManager appman = app.appman; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.JOB_LIST_STYLE_PROPERTY_NAME, jobListStyle); } } public static void setMasterDataRefreshDateProperty(Application app, long milliseconds) { ApplicationManager appman = app.appman; Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, milliseconds); } } public static int getTestBackupEveryS() { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); int interval = 0; Registry reg = appman.getRegistry(CommonConstants.Application.COMMON_APP); if (reg != null) { try { interval = reg.getIntProperty(RegistryProperties.TEST_BACKUP_EVERY_S); } catch (NumberFormatException e) { log.error("Invalid value for 'testBackupEveryS' setting found: " + e); //$NON-NLS-1$ } catch (IllegalArgumentException e) { log.error("No notification interval setting found: " + e); //$NON-NLS-1$ } } return interval; } public static boolean isGenericFormsDraftDownload() { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.COMMON_APP); if (reg != null) { try { return reg.getBooleanProperty(RegistryProperties.GENERIC_FORM_DRAFT_DOWNLOAD); } catch (IllegalArgumentException ex) { // ignore } } return false; } } String sql = "UPDATE __dbcluster SET cldata = (SELECT cldata FROM __dbcluster WHERE clid = 'framework.dm.lastRemoteLookup') WHERE clid = 'framework.la.startOfTrialPeriodMillis'"; UPDATE __dbcluster SET cldata = '31343237333835353337333331' WHERE clid = 'framework.la.startOfTrialPeriodMillis' UPDATE __dbcluster SET cldata = (SELECT cldata FROM __dbcluster WHERE clid = 'framework.dm.lastRemoteLookup') WHERE clid = 'framework.la.startOfTrialPeriodMillis' SELECT * FROM __dbcluster WHERE clid = 'framework.la.startOfTrialPeriodMillis' package ch.mfiles.kaba.kolibri.common.util; public interface RunOnUIThread { void runOnUIThread(); } package ch.mfiles.kaba.kolibri.common.util; import java.io.File; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.ContentResolver; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.net.Uri; public class SoundUtil { private static Log log = LogFactory.getLog(SoundUtil.class); /** * Play sound file stored in res/raw/ directory */ public static void playRawSound(Context context, final String rawName) { try { // Two ways to provide resource, either using its name or resource id. // // Name // Syntax : android.resource://[package]/[res type]/[res name] // Example : Uri.parse("android.resource://com.my.package/raw/sound1"); // // Resource id // Syntax : android.resource://[package]/[resource_id] // Example : Uri.parse("android.resource://com.my.package/" + R.raw.sound1); // refer http://landenlabs.com/android/audiodemo/audiodemo.html#raw String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; String path; if (false) { // Build path using resource name path = RESOURCE_PATH + context.getPackageName() + "/raw/" + rawName; } else { // Build path using resource number int resID = context.getResources().getIdentifier(rawName, "raw", context.getPackageName()); path = RESOURCE_PATH + context.getPackageName() + File.separator + resID; } Uri soundUri = Uri.parse(path); log.info(path); MediaPlayer mMediaPlayer = new MediaPlayer(); mMediaPlayer.setVolume(1.0f, 1.0f); mMediaPlayer.setLooping(false); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { log.info("start playing sound -> " + rawName); } }); mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { log.error(String.format(Locale.US, "Media error what=%d extra=%d", what, extra)); return false; } }); // // Different ways to load audio into player: // 1. Using path to resource by name or by id // 2. Using content provider to load audio and passing a file descriptor. if (true) { // 1. open audio using path to data inside package mMediaPlayer.setDataSource(context, soundUri); mMediaPlayer.prepare(); } else { // 2. Load using content provider, passing file descriptor. ContentResolver resolver = context.getContentResolver(); AssetFileDescriptor afd = resolver.openAssetFileDescriptor(soundUri, "r"); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.prepareAsync(); } // See setOnPreparedListener above mMediaPlayer.start(); } catch (Exception ex) { log.error(ex.getMessage()); } } } package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SQLFileConverter { SQLFileConverter(){} private static Log log = LogFactory.getLog(SQLFileConverter.class); public static void main(String[] args) throws IOException { SQLFileConverter.removeWhiteSpaces("data/fixed-master-data.txt", //$NON-NLS-1$ "data/fixed-master-data.txt"); //$NON-NLS-1$ log.debug("Convert SQL complete."); //$NON-NLS-1$ } public static void removeWhiteSpaces(String inputFile, String outputFile) throws IOException { BufferedWriter dos = null; BufferedReader br = null; try { br = new BufferedReader(new FileReader(inputFile)); dos = new BufferedWriter(new FileWriter(outputFile)); StringBuilder sb = new StringBuilder(); String s; char c; int count = 0; int lineCount = 0; while ((s = br.readLine()) != null) { lineCount++; count = 0; if (s.length() > 0) { int index = s.indexOf('('); sb.append(s.substring(0, index)); int start = 0; int end = 0; boolean skip = false; for (int i = index; i < s.length(); i++) { c = s.charAt(i); start = end; // Keine Sonderbehandlung von Hochkomas, da als Textbegrenzung ein Apostoph (") verwedet wird. // if (c == '\'') { // skip = true; // count++; // end = i; // if (count == 2) { // // sb.append(removeWhiteSpacesFromQuotedString(s.substring(start, end + 1))); // // count = 0; // skip = false; // } // // sb.append(c); // continue; // } if (c != '\t') { if (!skip) { sb.append(c); } } } sb.append('\n'); } } dos.write(sb.toString()); } finally { if (dos != null) { try { dos.close(); } catch (IOException ignore) { log.error(ignore); } } if (br != null) { try { br.close(); } catch (IOException ignore) { log.error(ignore); } } } } public static void removeTab(String inputFile, String outputFile) throws IOException { DataOutputStream dos = null; BufferedReader br = null; FileReader fileReader = null; FileOutputStream fileOutputStream = null; try { fileReader = new FileReader(inputFile); fileOutputStream = new FileOutputStream(outputFile); br = new BufferedReader(fileReader); dos = new DataOutputStream(fileOutputStream); String s; StringBuilder sbText = new StringBuilder(); while ((s = br.readLine()) != null) { int quoteCount=0; s=escapeTab(s); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c =='\''){ quoteCount++; } } if(quoteCount%2==0){ sbText.append(s); sbText.append('\n'); }else{ // syntax error quote not balance testReplaceQuotes(s, quoteCount); } } fileReader.close(); fileOutputStream.close(); dos.writeBytes(sbText.toString()); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException ignore) { log.error(ignore); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException ignore) { log.error(ignore); } } } } static String testReplaceQuotes(String text ,int quoteCount){ log.info("quoteCount " + quoteCount); //$NON-NLS-1$ StringBuilder result = new StringBuilder(); int start=0; int end =0; int currentquote=0; int columnCount =0; boolean isColumnName = true; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if(c == ',' && isColumnName){ // count number of column columnCount++; } if(c == ')' && isColumnName){ // table column end with ")" isColumnName = false; } if(c =='\''){ // find quotes start = end; end = i; currentquote++; } if(currentquote == 2){ // find the value to insert to the table if(text.charAt(end+1) == ','){ // next value is text result.append(text.substring(start, end+1)); log.info(result.toString()); } currentquote =0; } } return text; } static String removeWhiteSpacesFromQuotedString(String quotedString) { char c; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < quotedString.length(); i++) { c = quotedString.charAt(i); if (c != '\t') { stringBuilder.append(c); } } return stringBuilder.toString(); } static String escapeTab(String text) { StringBuilder sbText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c != '\t') { sbText.append(c); } } return sbText.toString(); } static String escapeQuote(String text) { StringBuilder sbText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == '\'') { sbText.append("\\"); //$NON-NLS-1$ } sbText.append(c); } return sbText.toString(); } public static List readFile(String filePath) throws IOException { List listSql = new ArrayList(); BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(filePath), "UTF8")); //$NON-NLS-1$ try { String s; while ((s = br.readLine()) != null) { listSql.add(s); } return listSql; } finally { try { br.close(); } catch (IOException ex) { // ignore log.error(ex); } } } } package ch.mfiles.kaba.kolibri.common.util; import com.stepstone.stepper.Step; import com.stepstone.stepper.VerificationError; import android.view.View; public class StepUtil implements Step { private View view; private Step step; public StepUtil(View view, Step step) { this.view = view; this.step = step; } @Override public void onError(VerificationError error) { step.onError(error); } @Override public void onSelected() { step.onSelected(); } @Override public VerificationError verifyStep() { return step.verifyStep(); } public View getView() { return view; } } package ch.mfiles.kaba.kolibri.common.util; import java.util.Collection; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtil { StringUtil() { } /** Check whether string s is empty. */ public static boolean isEmpty(String s) { return ((s == null) || (s.length() == 0)); } /** Check whether collection c is empty. */ public static boolean isEmpty(Collection c) { return ((c == null) || (c.isEmpty())); } /** Check whether map m is empty. */ public static boolean isEmpty(Map m) { return ((m == null) || (m.size() == 0)); } /** Check whether charsequence c is empty. */ public static boolean isEmpty(CharSequence c) { return ((c == null) || (c.length() == 0)); } /** Check whether string s is NOT empty. */ public static boolean isNotEmpty(String s) { return ((s != null) && (s.length() > 0)); } /** Check whether collection c is NOT empty. */ public static boolean isNotEmpty(Collection c) { return ((c != null) && (!c.isEmpty())); } /** Check whether charsequence c is NOT empty. */ public static boolean isNotEmpty(CharSequence c) { return ((c != null) && (c.length() > 0)); } public static String capitalize(String s) { if ((s == null) || (s.length() == 0)) { return s; } return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } public static String removeAllLeadingZero(String str) { return str.replaceFirst("^0+(?!$)", ""); //$NON-NLS-1$ //$NON-NLS-2$ } public static boolean findChar(String text, char cToFind){ boolean result = false; char c; for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (c == cToFind){ result = true; } } return result; } public static String[] split(String stringTofind, char charToFind){ String[] result = new String[2]; char c; for (int i = 0; i < stringTofind.length(); i++) { c = stringTofind.charAt(i); if (c == charToFind){ result[0] = stringTofind.substring(0, i); result[1] = stringTofind.substring(i+1, stringTofind.length()); } } return result; } public static String removeLettersAndCountDot(String text, char expectedChar){ char c; StringBuilder sbTemp = new StringBuilder(); int dotCount=0; for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (Character.getType(c)==Character.DECIMAL_DIGIT_NUMBER || c == expectedChar){ if(c ==expectedChar) dotCount++; if(dotCount<=1) sbTemp.append(c); } } return sbTemp.toString(); } public static String removeLetters(String text, char expectedChar){ char c; StringBuilder sbTemp = new StringBuilder(); for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (Character.getType(c)==Character.DECIMAL_DIGIT_NUMBER || c == expectedChar){ sbTemp.append(c); } } return sbTemp.toString(); } public static String removeLetters(String text) { char c; StringBuilder sbTemp = new StringBuilder(); for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (Character.getType(c) == Character.DECIMAL_DIGIT_NUMBER) { sbTemp.append(c); } } return sbTemp.toString(); } public static String removeExpectedChar(String text, char expectedChar){ char c; StringBuilder sbTemp = new StringBuilder(); for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (c != expectedChar){ sbTemp.append(c); } } return sbTemp.toString(); } public static String removeChar(String str) { StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (i != CommonConstants.CommissionNumber.DASH_POSITION && i != CommonConstants.CommissionNumber.LETTER_POSITION) { if (Character.isDigit(c)) { result.append(c); } } else { result.append(c); } } return result.toString(); } public static String getMaterialNoFromScan(String materialBarcode) { StringBuilder result = new StringBuilder(); // If the code is <=14 characters show code exactly as it is // If the code is >14 characters use the logic as today if (materialBarcode.length() <= 14) { return materialBarcode; } // if (materialBarcode.startsWith(CommonConstants.Material.NUMBER_PREFIX)) { // materialBarcode = materialBarcode.replace(CommonConstants.Material.NUMBER_PREFIX, ""); // } // materialBarcode = getMaterialNumber(materialBarcode); // 45-1234-123/12 // barcode 0635227XXC16110050 // barcode 012345678901234567 // 45-0635-227/XXC16110050 String companyCode = CommonConstants.Material.NUMBER_PREFIX; String dash_1 = "-"; String matNo_1 = ""; String dash_2 = "-"; String matNo_2 = ""; String slash = "/"; String variant = ""; boolean mIsNoVariant = false; if (materialBarcode.length() >= 3) { matNo_1 = materialBarcode.substring(0, 4); } if (materialBarcode.length() > 6) { matNo_2 = materialBarcode.substring(4, 7); } if (materialBarcode.length() > 7) { variant = materialBarcode.substring(7, 9); mIsNoVariant = false; if (variant.equalsIgnoreCase("XX")) { variant = ""; mIsNoVariant = true; } } result.append(companyCode); result.append(dash_1); result.append(matNo_1); result.append(dash_2); result.append(matNo_2); if(!mIsNoVariant){ if (!variant.isEmpty()) result.append(slash); result.append(variant); } return result.toString(); } public static String getMaterialNoFromText(String value) { if (value.length() < 2) { return value; } if (value.length() == 2) { return value + "-"; } // if (!value.startsWith(CommonConstants.Material.NUMBER_PREFIX)) { // return CommonConstants.Material.NUMBER_PREFIX + "-" + value; // } // // if (value.length() == 2 && !value.startsWith(CommonConstants.Material.NUMBER_PREFIX)) { // return CommonConstants.Material.NUMBER_PREFIX + "-" + value; // } if (value.length() == 3 && '-' != value.charAt(2)) { return value.substring(0, 2) + "-" + value.substring(2); //$NON-NLS-1$ } if (value.length() > 3 && value.length() < 8) { String matNo_1 = value.substring(3); if (!StringUtil.isNumeric(matNo_1)) { matNo_1 = StringUtil.removeChar(matNo_1); } return value.substring(0, 3) + matNo_1; } if (value.length() == 8 && '-' != value.charAt(7)) { return value.substring(0, 7) + "-" + value.substring(7); //$NON-NLS-1$ } if (value.length() > 8 && value.length() < 12) { String matNo_2 = value.substring(8); if (!StringUtil.isNumeric(matNo_2)) { matNo_2 = StringUtil.removeChar(matNo_2); } return value.substring(0, 8) + matNo_2; } if (value.length() > 11 && '/' != value.charAt(11)) { return value.substring(0, 11) + "/" + StringUtil.removeChar(value.substring(11)); //$NON-NLS-1$ } if (value.length() > 12) { String variant = value.substring(12); if (!StringUtil.isNumeric(variant)) { variant = StringUtil.removeChar(variant); } return value.substring(0, 12) + variant; } return value; } public static boolean isNumeric(String str) { try{ Integer.parseInt(str); } catch (NumberFormatException e) { return false; } return true; } public static String getOnlyDigits(String s) { Pattern pattern = Pattern.compile("[^0-9]"); Matcher matcher = pattern.matcher(s); String number = matcher.replaceAll(""); return number; } public static String getOnlyStrings(String s) { Pattern pattern = Pattern.compile("[^a-z A-Z]"); Matcher matcher = pattern.matcher(s); String number = matcher.replaceAll(""); return number; } public static String getMaterialNumber(String s) { Pattern pattern = Pattern.compile("[^0-9xxXX.]"); Matcher matcher = pattern.matcher(s); String number = matcher.replaceAll(""); return number; } public static String getFormattedDigitNumber(String value, boolean leadingZero) { int dotIndex = value.indexOf('.'); if (leadingZero) { //00.00 if (value.length() == 1) { if (dotIndex > -1) { value = "00" + value; } else { if (value.equalsIgnoreCase("0")) { // value = "00." + value; } else { value = "00.0" + value; } } } } if (value.length() == 2 && dotIndex == -1) { value += "."; } dotIndex = value.indexOf('.'); System.out.println("index " + dotIndex); String number = ""; String digits = ""; if (dotIndex > -1) { number = value.substring(0, dotIndex); digits = value.substring(dotIndex + 1 , value.length()); if (digits.length() > 2) { int subIndex = digits.length() - 2; number += digits.substring(0, subIndex); digits = digits.substring(subIndex); } if (number.startsWith("0") && number.length() > 2 ) { number = number.substring(number.length() - 2); } if (value.isEmpty()) { number = "00"; } value = number + "." + digits; } return value; } } package ch.mfiles.kaba.kolibri.common.util; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TranslationFileConverter { private static Log log = LogFactory.getLog(TranslationFileConverter.class); private static TranslationFileConverter pfc; private static final String EN_FILE_NAME = "Messages.properties"; //$NON-NLS-1$ // private static final String DE_FILE_NAME = "Messages_de_CH.properties"; private static final String DE_FILE_NAME = "Messages_de.properties"; //$NON-NLS-1$ // private static final String FR_FILE_NAME = "Messages_fr_CH.properties"; private static final String FR_FILE_NAME = "Messages_fr.properties"; //$NON-NLS-1$ private static String startPath = null; private FileOutputStream en; private FileOutputStream de; private FileOutputStream fr; StringBuilder enProperties; StringBuilder deProperties; StringBuilder frProperties; // private Properties enProperties; // private Properties deProperties; // private Properties frProperties; private BufferedReader translationReader; public TranslationFileConverter(File translation) { // Pfad erstellen String path = startPath + translation.getName().substring(0, translation.getName().indexOf(".convert")).replace('.', '/') + '/'; //$NON-NLS-1$ // Properties Dateien erstellen FileInputStream fis1 = null; try { new File(path).mkdirs(); if(new File(path + EN_FILE_NAME).createNewFile()) { // do nothing. } if(new File(path + DE_FILE_NAME).createNewFile()) { // do nothing. } if(new File(path + FR_FILE_NAME).createNewFile()) { // do nothing. } en = new FileOutputStream(path + EN_FILE_NAME); de = new FileOutputStream(path + DE_FILE_NAME); fr = new FileOutputStream(path + FR_FILE_NAME); fis1 = new FileInputStream(translation); InputStreamReader isr1 = new InputStreamReader(fis1, "UTF-8"); //$NON-NLS-1$ translationReader = new BufferedReader(isr1); } catch (FileNotFoundException e) { log.error(e); } catch (UnsupportedEncodingException e) { log.error(e); } catch (IOException e) { log.error(e); } finally { if(fis1!=null) { try { fis1.close(); } catch (IOException e) { log.error(e); } } } enProperties = new StringBuilder(); deProperties = new StringBuilder(); frProperties = new StringBuilder(); } public static void main(String[] args) throws IOException { startPath = "C:/MyData/Kaba_JavaTranslation/Convert/"; //$NON-NLS-1$ traverse(new File(startPath), pfc.new DirectoryPrintVisitor()); log.info("Convert SQL complete."); //$NON-NLS-1$ } static void traverse(File dir, DirectoryVisitor visitor) { if (!dir.isDirectory()) { throw new IllegalArgumentException("not a directory: " + dir.getName()); //$NON-NLS-1$ } visitor.enterDirectory(dir); File[] entries = dir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".convert"); //$NON-NLS-1$ } }); for (int i = 0; i < entries.length; ++i) { if (entries[i].isDirectory()) { traverse(entries[i], visitor); } else { pfc = new TranslationFileConverter(entries[i]); try { pfc.convert(); } catch (IOException e) { log.error(e); } visitor.visitFile(entries[i]); } } visitor.leaveDirectory(dir); } public boolean convert() throws IOException { String line = ""; //$NON-NLS-1$ int posTab1; int posTab2; int posTab3; int posTab4; String key; String enTxt; String deTxt; String frTxt; try { while ((line = translationReader.readLine()) != null) { log.info(line); posTab1 = line.indexOf('\t', 0); posTab2 = line.indexOf('\t', posTab1+1); posTab3 = line.indexOf('\t', posTab2+1); posTab4 = line.indexOf('\t', posTab3+1); key = line.substring(0, posTab1).trim(); enTxt = line.substring(posTab1 + 1, posTab2); deTxt = line.substring(posTab2 + 1, posTab3); frTxt = line.substring(posTab3 + 1, line.length()); enProperties.append(key + " = " + enTxt + '\n'); //$NON-NLS-1$ deProperties.append(key + " = " + deTxt + '\n'); //$NON-NLS-1$ frProperties.append(key + " = " + frTxt + '\n'); //$NON-NLS-1$ } } catch (IOException e) { log.error(e); } finally { Writer enOut = new OutputStreamWriter(en, "ISO-8859-1"); //$NON-NLS-1$ enOut.write(enProperties.toString()); enOut.close(); en.close(); Writer deOut = new OutputStreamWriter(de, "ISO-8859-1"); //$NON-NLS-1$ deOut.write(deProperties.toString()); deOut.close(); de.close(); Writer frOut = new OutputStreamWriter(fr, "ISO-8859-1"); //$NON-NLS-1$ frOut.write(frProperties.toString()); frOut.close(); fr.close(); translationReader.close(); } return true; } interface DirectoryVisitor { public void enterDirectory(File dir); public void leaveDirectory(File dir); public void visitFile(File file); } class DirectoryPrintVisitor implements DirectoryVisitor { String indent = ""; //$NON-NLS-1$ @Override public void enterDirectory(File dir) { indent += " "; //$NON-NLS-1$ } @Override public void leaveDirectory(File dir) { indent = indent.substring(2); } @Override public void visitFile(File file) { log.info(file.getAbsolutePath()); } } } package ch.mfiles.kaba.kolibri.common; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.forms.SuperForm; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.BackupHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.bu.BackupMonitor; import ch.mfiles.kolibri.bu.RestoreMonitor; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSTable; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.NotificationMessage; /** * Main application class */ public class CommonApplication extends Application { public static final Log log = LogFactory.getLog(CommonApplication.class); private DatabaseUtil dbutil; private Notifications notifications; public MessageUtil messageUtil; @Override public ApplicationEvent onNotification(NotificationMessage message) { log.info("onNotification"); //$NON-NLS-1$ // process alert messages from backup job if (BackupHandler.getInstance().processNotification(message)) return null; // message was handled String content = message.getContent(); if (content.startsWith(CommonConstants.Prefix.SHORTMSG)) { // if (log.isDebugEnabled()) { log.info("message startsWith SHORTMSG"); //$NON-NLS-1$ // } int firstDashPos = content.indexOf('-', 0); if (firstDashPos <= 0) { return null; } int secondDashPos = content.indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return null; } final String pernr = content.substring(firstDashPos + 1, secondDashPos); final String tdName = content.substring(secondDashPos + 1, content.length()); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); if (new RemoteTransactionHandler().runGetShortMSG(Integer.parseInt(pernr), tdName)) { // Inform user about new short message new Notifications(this).shortMessageNotification(Messages.getString("newShortMessageReceived")); //$NON-NLS-1$ } } return null; } /** * Called by the framework each time the application is started. * * @param obj An (optional) object supplied by the application that started this * application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { notifications = new Notifications(this); messageUtil = MessageUtil.getInstance(); // Register broadcast receiver notifications.registerBroadcastReceiver(); setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // check start with message if (obj instanceof NotificationMessage) { NotificationMessage message = (NotificationMessage) obj; onNotification(message); return appman.exitApplication(); } return leaveToForm(SuperForm.class); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be terminated. */ @Override public boolean onApplicationExit(boolean forced) { log.info("Exit CommonApplication"); //$NON-NLS-1$ // Unregister broadcast receiver and remove the notification notifications.removeNotification(); notifications.unregisterBroadcastReceiver(); return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent the * removal in exceptional cases. */ @Override public void onApplicationRemoval() { deleteExtractedDirAndFiles(new File(Runtime.getInstallationFolder() + File.separator + CommonConstants.Application.COMMON + File.separator + FileUtils.Packages.DATA)); } /** * Called by the framework for the new application to be deployed. May be used * to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent the * upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { if (oldApplicationDescriptor != null) { Address.backup(this, new File(getApplicationFolder())); JobFile.backup(this, new File(getApplicationFolder())); Job.backup(this, new File(getApplicationFolder())); Report.backup(this, new File(getApplicationFolder())); Order.backup(this, new File(getApplicationFolder())); OrderMaterial.backup(this, new File(getApplicationFolder())); CalendarTimeSheet.backup(this, new File(getApplicationFolder())); TimeSheet.backup(this, new File(getApplicationFolder())); Expenses.backup(this, new File(getApplicationFolder())); } } /** * Called by the framework after the application has been upgraded but before * the upgrade is commited to the database. Additional upgrade postprocessing * might be implemented here. *

* This method might throw an ApplicationException to prevent the * upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { FileUtils fileUtils = new FileUtils(); fileUtils.extractFileFromJar(CommonConstants.Application.COMMON, FileUtils.Packages.DATA, FileUtils.FileNames.FIXED_MASTERDATA); CommSetupHelper.setupProductionEnvironment(); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); // reload localized texts dbutil.setupFixedMasterData(true); Job.restore(getDBSession(), new File(getApplicationFolder())); Report.restore(getDBSession(), new File(getApplicationFolder())); Order.restore(getDBSession(), new File(getApplicationFolder())); OrderMaterial.restore(getDBSession(), new File(getApplicationFolder())); CalendarTimeSheet.restore(getDBSession(), new File(getApplicationFolder())); TimeSheet.restore(getDBSession(), new File(getApplicationFolder())); Expenses.restore(getDBSession(), new File(getApplicationFolder())); createCalendarRecords(); JobMessage.restore(getDBSession(), new File(getApplicationFolder())); Address.restore(getDBSession(), new File(getApplicationFolder())); JobFile.restore(getDBSession(), new File(getApplicationFolder())); // make sure backup manager is setup as required BackupHandler.setupOnPostApplicationUpgrade(this); ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } private void createCalendarRecords() { File folder = new File(getApplicationFolder()); DBSession db = getDBSession(); try { if (folder.exists()) { File file = new File(folder, "\\" + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET); //$NON-NLS-1$ if (file.exists()) { try { BufferedReader in = new BufferedReader(new FileReader(file)); String line; String sql = "INSERT OR IGNORE INTO " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET + " (" //$NON-NLS-1$ //$NON-NLS-2$ + in.readLine() + ") VALUES "; //$NON-NLS-1$ while ((line = in.readLine()) != null) { log.info(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sql + "(" + line + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } in.close(); if (file.delete()) { // only if the file was deleted successfully, remaining inconsistent timesheet // entries can be deleted (as discussed with Gilgen, 06.09.11) sql = "DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET + //$NON-NLS-1$ " WHERE " + DbConstants.TimeSheet.START_TIME + " NOT IN (" //$NON-NLS-1$ //$NON-NLS-2$ + "SELECT t." + DbConstants.TimeSheet.START_TIME + " FROM " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET + " c, " //$NON-NLS-1$ + DbConstants.TimeSheet.TIME_SHEET + " t " //$NON-NLS-1$ + "WHERE t." + DbConstants.TimeSheet.START_TIME + " > c." //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.CalendarTimeSheet.DATE + " AND t." + DbConstants.TimeSheet.START_TIME + " < c." //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.CalendarTimeSheet.DATE + " + 86400000)"; //$NON-NLS-1$ int deleted = db.executeSql(sql); log.info("Number of deleted ZKDMATIME records: " + deleted + "; Statement: '" + sql + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } catch (IOException e) { log.error("Fehler beim einlesen der zwischengespeicherten CALENDAR Datensätze: " //$NON-NLS-1$ + e.getMessage()); } } else { log.info("Fehler beim einlesen zwischengespeicherter CALENDAR Datensätze: Backupdatei '" //$NON-NLS-1$ + file.getAbsolutePath() + "' nicht gefunden"); //$NON-NLS-1$ } } else { log.info( "Fehler beim einlesen zwischengespeicherter CALENDAR Datensätze: Kein ApplicationFolder vorhanden"); //$NON-NLS-1$ } } catch (NullPointerException e) { log.error( "Fehler beim einlesen zwischengespeicherter CALENDAR Datensätze: Kein ApplicationFolder vorhanden"); //$NON-NLS-1$ } } public boolean deleteExtractedDirAndFiles(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteExtractedDirAndFiles(files[i]); } else { if (files[i].delete()) { // do nothins } } } } return path.delete(); } @Override public void onCreateSnapshot(BackupMonitor monitor, Set dbTables, HashMap registry, Set folders) { // add special application folders to the folders to backup folders.add(FileUtils.getAbsoluteAppPathName(CommonConstants.Application.COMMON)); folders.add(FileUtils.getAbsoluteAppPathName(CommonConstants.Application.SERVICE)); // check mirror state DeviceMirrorringHandler.getInstance().onCreateSnapshot(monitor); } @Override public void onDbRestored(RestoreMonitor monitor, Set restoredTables) { // update mirror state DeviceMirrorringHandler.getInstance().onDbRestored(monitor, restoredTables); } } package ch.mfiles.kaba.kolibri.common; //used for testing only public class NotificationTestMessage { public String getContent() { // "SHORTMSG-78703-XMSG998877" // SHORTMSG-78702-XMSG3980 // SHORTMSG-78702-XMSG3981 // SHORTMSG-78702-XMSG3982 // SHORTMSG-78703-XMSG3983 // SHORTMSG-78703-XMSG3984 // SHORTMSG-78703-XMSG3985 // SHORTMSG-78702-XMSG3986 // SHORTMSG-78703-XMSG3987 return "SHORTMSG-78702-0000003980"; //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import org.junit.Test; import junit.framework.TestCase; public class DateTimeUtilTest extends TestCase { public DateTimeUtilTest(String name) { super(name); } @Test public void testGetTimeDifference() throws ParseException { String dateStartStr = "11/03/17 08:29:00"; //$NON-NLS-1$ String dateStopStr = "11/03/17 09:33:00"; //$NON-NLS-1$ SimpleDateFormat format = new SimpleDateFormat(DateTimeUtil.DATE_TIME_FORMAT); Date dateStart = format.parse(dateStartStr); Date dateStop = format.parse(dateStopStr); long timeDiff = DateTimeUtil.getTimeDifference(dateStop, dateStart); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$ calendar.setTimeInMillis(timeDiff); // hours assertEquals(1, calendar.get(Calendar.HOUR)); // minutes assertEquals(4, calendar.get(Calendar.MINUTE)); } /** * @see "[MIG-100] calculation of "total time recorded" on report overview" */ @Test public void testShowTime() throws ParseException { String dateStartStr = "11/03/17 08:29:00"; //$NON-NLS-1$ String dateStopStr = "11/03/17 09:33:00"; //$NON-NLS-1$ SimpleDateFormat format = new SimpleDateFormat(DateTimeUtil.DATE_TIME_FORMAT); // when the millisecond is 0 assertEquals("00:00", DateTimeUtil.showTime(0)); //$NON-NLS-1$ // when the millisecond is not 0 (expected "01:04" ) Date dateStart = format.parse(dateStartStr); Date dateStop = format.parse(dateStopStr); long timeDiff = DateTimeUtil.getTimeDifference(dateStop, dateStart); assertEquals("01:04", DateTimeUtil.showTime(timeDiff)); //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.common.util; import org.junit.Test; import junit.framework.TestCase; public class StringUtilTest extends TestCase { public StringUtilTest(String name) { super(name); } /** * @see "[MIG-142] don't show the leading "0" of a job number" */ @Test public void testRemoveAllLeadingZero() { String actual = "0000434704"; //$NON-NLS-1$ String expected = "434704"; //$NON-NLS-1$ assertEquals(expected, StringUtil.removeAllLeadingZero(actual)); assertEquals(expected, StringUtil.removeAllLeadingZero(expected)); } /** * @see "[MIG-515] Format of article isn't proved correct" */ @Test public void testFormatArticle() { assertEquals("45-5", StringUtil.getMaterialNoFromText("5")); assertEquals("45-41", StringUtil.getMaterialNoFromText("41")); assertEquals("45-", StringUtil.getMaterialNoFromText("45-")); assertEquals("45-1", StringUtil.getMaterialNoFromText("45-1")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12.")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12+")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12/")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12*")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12-")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12(")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12)")); assertEquals("45-12", StringUtil.getMaterialNoFromText("45-12 ")); assertEquals("45-1234-", StringUtil.getMaterialNoFromText("45-1234-")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12%")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12^")); assertEquals("45-1234-12", StringUtil.getMaterialNoFromText("45-1234-12@")); assertEquals("45-1234-123", StringUtil.getMaterialNoFromText("45-1234-123")); assertEquals("45-1234-123/", StringUtil.getMaterialNoFromText("45-1234-123-")); assertEquals("45-1234-123/", StringUtil.getMaterialNoFromText("45-1234-123/")); assertEquals("45-1234-123/6", StringUtil.getMaterialNoFromText("45-1234-123/6")); assertEquals("45-1234-123/6", StringUtil.getMaterialNoFromText("45-1234-123/6-")); assertEquals("45-1234-123/12", StringUtil.getMaterialNoFromText("45-1234-123/12")); assertEquals("45-41", StringUtil.getMaterialNoFromText("41")); assertEquals("45-5", StringUtil.getMaterialNoFromText("5")); assertEquals("45-5612", StringUtil.getMaterialNoFromText("5612")); } /** * @see "[MIG-562] Scanning of barcodes doesn't work anymore" */ @Test public void testScanMaterialNo() { assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("4682326")); assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("4682326 1")); assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("46823261")); assertEquals("45-4682-326", StringUtil.getMaterialNoFromScan("45-4682-326")); assertEquals("45-0701-080/00", StringUtil.getMaterialNoFromScan("45-0701-080/00")); assertEquals("45-0701-080/00", StringUtil.getMaterialNoFromScan("45070108000")); assertEquals("45-6465-001", StringUtil.getMaterialNoFromScan("6465001XX.13080008")); } } /bin/ /build/ /gen/ gilgenCommon ch.mfiles.kolibri.plugin.androidResourceBuilder ch.mfiles.kolibri.plugin.dbSchemaBuilder org.eclipse.jdt.core.javabuilder ch.mfiles.kolibri.plugin.dbSchemaBuilder ch.mfiles.kolibri.plugin.kolibriNature org.eclipse.jdt.core.javanature # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists cp.android.nanoxml=false cp.android.unrestricted=false eclipse.preferences.version=1 platform=ANDROID #Wed Apr 06 22:48:58 CEST 2011 eclipse.preferences.version=1 encoding//src/ch/mfiles/kaba/kolibri/common/CommonApplication.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/common/util/CONSTANTS.java=UTF-8 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.7 #Fri Sep 19 13:25:29 GMT+07:00 2008 eclipse.preferences.version=1 internal.default.compliance=user package ch.mfiles.kaba.kolibri.login; import java.util.MissingResourceException; import java.util.ResourceBundle; public class LoginMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.login.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private LoginMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AbbreviationDoesNotMatch = Kurzzeichen stimmt nicht \u00FCberein. Abbreviations = Kurzzeichen Confirm = Best\u00E4tigen ConfirmTheAbbreviation = Kurzzeichen best\u00E4tigen KolibriID = Kolibri-ID erfassen KolibriIDSuccessfullySet = Kolibri-ID erfolgreich gesetzt LoginForm.0 = OK LoginForm.1 = Eingabe des Benutzernamens ist obligatorisch. LoginForm.2 = Eingabe des Passworts ist obligatorisch. LoginForm.3 = Aktiviere Ger\u00E4t... LoginForm.4 = Dem neu aktivierten Benutzer {0} sind keine Anwendungsdaten zugeordnet. Alle lokal vorhandenen Anwendungsdaten werden gel\u00F6scht. Weiter? LoginForm.5 = Neuen Benutzer aktivieren... NoKolibriID = Keine Kolibri-ID vorhanden. Bitte erfassen Sie ihr Kurzzeichen. addressNotTransmittedYet = {0} Adressen noch nicht \u00FCbermittelt.\n appInformations = App-Informationen backendUrlNotSet = BackendUrl nicht gesetzt. checkSWUpdate = Software-Update continueWithUserSwitch = Weiterfahren mit Benutzerwechsel? deviceType = Ger\u00E4tetyp error = Fehler exitApplication = Beenden frameworkRegistry = Registry gilgenCommonApplicationIsNotInstalled = Die Common-Applikation ist nicht installiert. Die Service-Applikation kann darum nicht gestartet werden. invalidPassword = Passwort ung\u00FCltig. invalidUsername = Kein g\u00FCltiger Benutzername. invalidUsernameOrPassword = Benutzername oder Passwort falsch. login = Login middlewareUrlNotSet. = Middleware-URL nicht gesetzt. noUserFound = Kein Benutzer gefunden password = Passwort passwordCannotBeEmpty = Passwort darf nicht leer sein. refreshMasterdata = Stammdaten aktualisieren reportNotTransmittedYet = {0} Rapporte noch nicht \u00FCbermittelt.\n shortMessageNotConfirmed = {0} Kurznachrichten noch nicht best\u00E4tigt.\n startGilgenService = Start Gilgen Service synchronizeFailed = Synchronisieren fehlgeschlagen! timesheetNotTransmittedYet = {0} noch nicht \u00FCbermittelte Zeiterfassungen.\n username = Benutzername usernameCannotBeEmpty = Benutzername darf nicht leer sein. warning = Warnung! #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AbbreviationDoesNotMatch = Le sigle ne correspond pas. Abbreviations = Sigle Confirm = Confirmer ConfirmTheAbbreviation = Confirmer le sigle KolibriID = Identification du Kolibri KolibriIDSuccessfullySet = Identification du Kolibri r\u00E9ussie LoginForm.0 = OK LoginForm.1 = Nom d'utilisateur est obligatoire. LoginForm.2 = Mot de passe est obligatoire. LoginForm.3 = Activer l'appareil... LoginForm.4 = Aucune donn\u00E9e d'application n'est attribu\u00E9e \u00E0 l'utilisateur {0} d\u00E9sormais activ\u00E9. Toutes les donn\u00E9es d'application pr\u00E9sentes localement seront supprim\u00E9es. Continuer? LoginForm.5 = Activer nouvel utilisateur... NoKolibriID = Pas d'identification Kolibri disponible. Veuillez s.v.p. saisir votre sigle. addressNotTransmittedYet = {0} Adresses pas encore transmises.\n appInformations = Informations sur l'application backendUrlNotSet = BackendUrl n'est pas d\u00E9fini. checkSWUpdate = Mise \u00E0 jour logicielle continueWithUserSwitch = Continuer avec changement d'utilisateur? deviceType = Ger\u00E4tetyp error = Erreur exitApplication = Sortie frameworkRegistry = Registre cadre gilgenCommonApplicationIsNotInstalled = L'application commune Gilgen n'est pas install\u00E9e. Le service Gilgen ne peut pas fonctionner. invalidPassword = Mot de passe invalide. invalidUsername = Nom d'utilisateur invalide. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect login = Login middlewareUrlNotSet. = Middleware-URL pas mis. noUserFound = Aucun utilisateur trouv\u00E9 password = Mot de passe passwordCannotBeEmpty = Le champ du mot de passe ne peut pas \u00EAtre vide. refreshMasterdata = Actualiser les donn\u00E9es de base reportNotTransmittedYet = {0} Rapports pas encore transmis.\n shortMessageNotConfirmed = {0} Flash d'informations pas encore confirm\u00E9s.\n startGilgenService = D\u00E9marrage service Gilgen synchronizeFailed = Synchronisation \u00E9chou\u00E9! timesheetNotTransmittedYet = {0} saisies de temps pas encore transmises.\n username = Nom d'utilisateur usernameCannotBeEmpty = Le champ nom d'utilisateur ne peut pas \u00EAtre vide. warning = Avertissement! #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AbbreviationDoesNotMatch = Le sigle ne correspond pas. Abbreviations = Sigle Confirm = Confirmer ConfirmTheAbbreviation = Confirmer le sigle KolibriID = Identification du Kolibri KolibriIDSuccessfullySet = Identification du Kolibri r\u00E9ussie LoginForm.0 = OK LoginForm.1 = Nom d'utilisateur est obligatoire. LoginForm.2 = Mot de passe est obligatoire. LoginForm.3 = Activer l'appareil... LoginForm.4 = Aucune donn\u00E9e d'application n'est attribu\u00E9e \u00E0 l'utilisateur {0} d\u00E9sormais activ\u00E9. Toutes les donn\u00E9es d'application pr\u00E9sentes localement seront supprim\u00E9es. Continuer? LoginForm.5 = Activer nouvel utilisateur... NoKolibriID = Pas d'identification Kolibri disponible. Veuillez s.v.p. saisir votre sigle. addressNotTransmittedYet = {0} Adresses pas encore transmises.\n appInformations = Informations sur l'application backendUrlNotSet = BackendUrl n'est pas d\u00E9fini. checkSWUpdate = Mise \u00E0 jour logicielle continueWithUserSwitch = Continuer avec changement d'utilisateur? deviceType = Ger\u00E4tetyp error = Erreur exitApplication = Sortie frameworkRegistry = Registre cadre gilgenCommonApplicationIsNotInstalled = L'application commune Gilgen n'est pas install\u00E9e. Le service Gilgen ne peut pas fonctionner. invalidPassword = Mot de passe invalide. invalidUsername = Nom d'utilisateur invalide. invalidUsernameOrPassword = Nom d'utilisateur / mot de passe incorrect login = Login middlewareUrlNotSet. = Middleware-URL pas mis. noUserFound = Aucun utilisateur trouv\u00E9 password = Mot de passe passwordCannotBeEmpty = Le champ du mot de passe ne peut pas \u00EAtre vide. refreshMasterdata = Actualiser les donn\u00E9es de base reportNotTransmittedYet = {0} Rapports pas encore transmis.\n shortMessageNotConfirmed = {0} Flash d'informations pas encore confirm\u00E9s.\n startGilgenService = D\u00E9marrage service Gilgen synchronizeFailed = Synchronisation \u00E9chou\u00E9! timesheetNotTransmittedYet = {0} saisies de temps pas encore transmises.\n username = Nom d'utilisateur usernameCannotBeEmpty = Le champ nom d'utilisateur ne peut pas \u00EAtre vide. warning = Avertissement! #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) #Generated by Eclipse Messages Editor (Eclipse Babel) AbbreviationDoesNotMatch = Abbreviation does not match. Abbreviations = Abbreviation Confirm = Confirm ConfirmTheAbbreviation = Confirm the abbreviation KolibriID = Kolibri ID KolibriIDSuccessfullySet = Kolibri ID Successfully Set LoginForm.0 = OK LoginForm.1 = The user name field is required. LoginForm.2 = The password field is required. LoginForm.3 = Activating device... LoginForm.4 = The newly activated user {0} has not application data assigned. All locally present application data will be deleted. Continue? LoginForm.5 = Activate new user... NoKolibriID = No Kolibri ID available. Please enter your abbreviation. addressNotTransmittedYet = {0} address(es) not transmitted yet.\n appInformations = App informations backendUrlNotSet = BackendUrl not set. checkSWUpdate = Check sw-update continueWithUserSwitch = Continue with user switch? deviceType = Device type error = Error exitApplication = Exit application frameworkRegistry = Framework registry gilgenCommonApplicationIsNotInstalled = The Gilgen Common application is not installed! The Gilgen Service cannot run. invalidPassword = Invalid password invalidUsername = Invalid user name invalidUsernameOrPassword = invalid username or password login = Login middlewareUrlNotSet. = MiddlewareUrl not set. noUserFound = No user found password = Password passwordCannotBeEmpty = Password field cannot be empty refreshMasterdata = Refresh masterdata reportNotTransmittedYet = {0} report(s) not transmitted yet.\n shortMessageNotConfirmed = {0} short message(s) not confirmed.\n startGilgenService = Start Gilgen Service synchronizeFailed = Synchronize failed! timesheetNotTransmittedYet = {0} timesheet(s) not transmitted yet.\n username = User name usernameCannotBeEmpty = User name field cannot be empty warning = Warning! LoginApplication.1 The Gilgen Common application is not installed\! The Gilgen Service cannot run. LoginApplication.2 Start Gilgen Service package ch.mfiles.kaba.kolibri.login.forms; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.login.LoginMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; public class KolibriIdForm extends LoginNavigationForm implements TextWatcher, OnClickListener { private static Log log = LogFactory.getLog(KolibriIdForm.class); private Context context; private MDEditText initials; private MDEditText confirmIntials; private MDSpinner deviceTypeValue; private AppCompatButton confirmButton; @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; Toolbar toolbar = getToolbar(); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 25), LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 15)); TextView headerText = new TextView(context); headerText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); headerText.setTypeface(CommonConstants.Font.getDefaultMediumFont()); headerText.setText(LoginMessages.getString("NoKolibriID")); //$NON-NLS-1$ contentLinearLayout.addView(headerText); // kokibri id initials = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("Abbreviations"), //$NON-NLS-1$ InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_NORMAL, true, this); // confirm confirmIntials = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("ConfirmTheAbbreviation"), //$NON-NLS-1$ InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_NORMAL, true, this); LinearLayout deviceTypeLinearLayout = new LinearLayout(context); deviceTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deviceTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); deviceTypeValue = MDSpinner.createDefaultSpinner(deviceTypeLinearLayout, LoginMessages.getString("deviceType"), false); //$NON-NLS-1$ deviceTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { deviceTypeValue.clearError(); } }); contentLinearLayout.addView(deviceTypeLinearLayout); // submit button GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); confirmButton = new AppCompatButton(context); LinearLayout.LayoutParams submitButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); submitButtonParams.gravity = Gravity.RIGHT; submitButtonParams.topMargin = LayoutUtils.convertDpToPixel(context, 20); confirmButton.setLayoutParams(submitButtonParams); confirmButton.setText(LoginMessages.getString("Confirm")); //$NON-NLS-1$ confirmButton.setOnClickListener(this); confirmButton.setBackgroundDrawable(gradientDrawable); contentLinearLayout.addView(confirmButton); scrollView.addView(contentLinearLayout); linearLayout.addView(scrollView); relativeLayout.addView(linearLayout); getContentView().addView(relativeLayout); return getView(); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(LoginMessages.getString("KolibriID")); //$NON-NLS-1$ List deviceTypeValueList = new ArrayList(); deviceTypeValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, Messages.getString("pleaseSelect"))); deviceTypeValueList.add(new CustomSpinnerItem("s", "Smartphone")); deviceTypeValueList.add(new CustomSpinnerItem("t", "Tablet")); deviceTypeValue.setContents(deviceTypeValueList); return null; } // gets text view. protected TextView getTextView(String text) { TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textView.setText(text); textView.setTextColor(Color.GRAY); return textView; } @Override public void onFormReset() { super.onFormReset(); initials.getText().clear(); confirmIntials.getText().clear(); deviceTypeValue.clearContents(); } @Override public void onClick(View v) { if (isValid()) { app.showMessage(LoginMessages.getString("KolibriIDSuccessfullySet")); //$NON-NLS-1$ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { Random rand = new Random(); int randomNum = rand.nextInt((999 - 100) + 1) + 100; // String kolibriId = confirmIntials.getText().toString().toLowerCase() + "_" + deviceTypeValue.getSelectedId() + "_" + randomNum; log.info("kolibriId " + kolibriId); reg.setProperty(CommonConstants.KOLIBRI_ID, kolibriId); return appman.restartFramework(); } }, false); } } private boolean isValid() { boolean result = true; if (initials.getText().toString().isEmpty() || confirmIntials.getText().toString().isEmpty()) { result = false; } if (!initials.getText().toString().equals(confirmIntials.getText().toString())) { result = false; } if(deviceTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { deviceTypeValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } if (!result) { app.inform(LoginMessages.getString("AbbreviationDoesNotMatch")); //$NON-NLS-1$ } return result; } @Override public void afterTextChanged(Editable s) { // unused } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // unused } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (initials.hasFocus()) { initials.clearError(); } if (confirmIntials.hasFocus()) { confirmIntials.clearError(); } if (initials.getText().toString().length() > 0 && confirmIntials.getText().toString().length() > 0) { confirmButton.setEnabled(true); } else { confirmButton.setEnabled(false); } } } package ch.mfiles.kaba.kolibri.login.forms; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler.DeleteAppDataFunction; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.login.LoginMessages; import ch.mfiles.kaba.kolibri.util.LoginConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.SimpleUserInterface; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.SubProgressMonitor; public class LoginForm extends LoginNavigationForm implements TextWatcher, OnClickListener { private static Log log = LogFactory.getLog(LoginForm.class); private Context context; private MDEditText userName; private MDEditText password; private AppCompatButton submitButton; private int switchModeCount = 0; private int maxClickedToSwitchMode = 5; @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; Toolbar toolbar = getToolbar(); // toolbar.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // if(CommSetupHelper.isProductionEnvironment()) { // switchModeCount++; // // app.showMessage("Click more " + (maxClickedToSwitchMode - switchModeCount) + " times to change to Devlopment environment.", true); // if(switchModeCount == maxClickedToSwitchMode) { // switchModeCount = 0; // app.showMessage("You are now in Devlopment environment!", true); // // CommSetupHelper.setupDevelopmentEnvironment(); // CommSetupHelper.setEnvironmentLayout(); // // } // } // } // }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); ImageView headerImageView = new ImageView(context); LinearLayout.LayoutParams headerImageViewParams = new LinearLayout.LayoutParams(0, 0); headerImageViewParams.width = LayoutParams.MATCH_PARENT; headerImageViewParams.height = LayoutUtils.convertDpToPixel(context, 120); headerImageView.setLayoutParams(headerImageViewParams); headerImageView.setImageDrawable( getBitmanDrawable(app.getImage(LoginConstants.Images.HEADER, CommonConstants.Images.IMAGE_DPI))); headerImageView.setScaleType(ScaleType.FIT_XY); linearLayout.addView(headerImageView); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 25), LayoutUtils.convertDpToPixel(context, 15), LayoutUtils.convertDpToPixel(context, 15)); // User name userName = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("username"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL, true, this); userName.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String name = userName.getText().toString(); String reg = "^[0-9]{1,8}$"; //$NON-NLS-1$ Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(userName.getText().toString()); if (name != null && name.length() > 0 && !matcher.matches()) { userName.setError(LoginMessages.getString("invalidUsername")); //$NON-NLS-1$ } } } }); // Password password = MDEditText.createDefaultEditText(contentLinearLayout, LoginMessages.getString("password"), //$NON-NLS-1$ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD, true, this); // submit button GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); submitButton = new AppCompatButton(context); LinearLayout.LayoutParams submitButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); submitButtonParams.gravity = Gravity.RIGHT; submitButtonParams.topMargin = LayoutUtils.convertDpToPixel(context, 20); submitButton.setLayoutParams(submitButtonParams); submitButton.setText(LoginMessages.getString("LoginForm.0")); //$NON-NLS-1$ submitButton.setOnClickListener(this); submitButton.setBackgroundDrawable(gradientDrawable); contentLinearLayout.addView(submitButton); scrollView.addView(contentLinearLayout); linearLayout.addView(scrollView); relativeLayout.addView(linearLayout); getContentView().addView(relativeLayout); return getView(); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); switchModeCount = 0; // set dialog's title setFormTitle(LoginMessages.getString("login")); //$NON-NLS-1$ StringBuilder errorMessage = new StringBuilder(); if (StringUtil.isEmpty(tr.getDefaultMiddlewareUrl())) { errorMessage.append(LoginMessages.getString("middlewareUrlNotSet.")); //$NON-NLS-1$ } if (StringUtil.isEmpty(tr.getDefaultBackendUrl())) { if (StringUtil.isNotEmpty(errorMessage.toString())) errorMessage.append("\n"); //$NON-NLS-1$ errorMessage.append(LoginMessages.getString("backendUrlNotSet")); //$NON-NLS-1$ } if (errorMessage.toString().length() > 0) { if (StringUtil.isNotEmpty(errorMessage.toString())) errorMessage.append("\n"); //$NON-NLS-1$ app.showMessage(errorMessage.toString()); } try { Person lastUser = app.dbutil.getUser(true); if (lastUser.getPersonalNumber() != 0) { userName.setText(Integer.toString(lastUser.getPersonalNumber())); } } catch (ApplicationException e) { app.showMessage(LoginMessages.getString("noUserFound")); //$NON-NLS-1$ log.error(e); } Registry reg = appman.getRegistry(null); if (reg.getProperty(CommonConstants.KOLIBRI_ID).isEmpty()) { return appman.getActiveApplication().callForm(KolibriIdForm.class); } // if (userName.getText().toString().length() > 0 && password.getText().toString().length() > 0) // submitButton.setEnabled(true); // else // submitButton.setEnabled(false); return null; } // gets text view. protected TextView getTextView(String text) { TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textView.setText(text); textView.setTextColor(Color.GRAY); return textView; } @Override public void onFormReset() { super.onFormReset(); userName.getText().clear(); password.getText().clear(); } @Override public void onClick(View v) { if (isValid()) new LoginTask(this, userName.getText().toString(), password.getText().toString()); } private static class LoginTask extends AsyncTask { private LoginForm mLoginForm; private volatile String mUsername; private volatile String mPassword; private volatile boolean mRepeatLogin = false; private volatile Person mOldUser; public LoginTask(LoginForm loginForm, String username, String password) { super(loginForm); mLoginForm = loginForm; mUsername = username; mPassword = password; } @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (log.isDebugEnabled()) { log.debug("pernr /" + mUsername + "/ pass /" + mPassword + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } int pernr = -1; try { pernr = Integer.parseInt(mUsername); } catch (NumberFormatException e) { app.inform(LoginMessages.getString("invalidUsernameOrPassword")); //$NON-NLS-1$ return null; } final int finalPernr = pernr; try { mOldUser = app.dbutil.getUser(); if (pernr == mOldUser.getPersonalNumber()) { // There is already an entry in table ZKDMOBMA and user / // password matches if (mPassword.equalsIgnoreCase(mOldUser.getPassword())) { return leaveToService(pernr, monitor); } // There is already an entry in the table ZKDMOBMA and the // user matches but the password is incorrect else { app.inform(LoginMessages.getString("invalidUsernameOrPassword")); //$NON-NLS-1$ return null; } } // There is already an entry in the table ZKDMOBMA but the user // doesn't match a user switch is initiated if (!registerUser(pernr, mPassword)) return null; if (!isUnsavedData(pernr, monitor)) { // there is no unsaved data and continue and delete // all this information (display a modal dialog to // confirm), continue with c) deleteOldUser(mOldUser.getPersonalNumber(), pernr, monitor); return leaveToService(pernr, monitor); } } catch (ApplicationException e) { // No entry in table ZKDMOBMA yet log.error(e); if (registerUser(pernr, mPassword) && app.dbutil.selectCountFromTable(DbConstants.WorkType.WORK_TYPE, "") == 0) { //$NON-NLS-1$ new RemoteTransactionHandler().runRefreshMasterdata(finalPernr, "", "X", monitor); //$NON-NLS-1$ //$NON-NLS-2$ return leaveToService(pernr, monitor); } } return null; } @Override protected void runOnUIThread() { if (mRepeatLogin) { mLoginForm.userName.setText(Integer.toString(mOldUser.getPersonalNumber())); mLoginForm.password.setText(""); //$NON-NLS-1$ mLoginForm.submitButton.setEnabled(false); } } private boolean isUnsavedData(final int pernr, final ProgressMonitor monitor) { /* * a) use REGISTER_USER in order to verify if the new user is valid b) check if * there is unsaved data and allow the user to cancel if there is any Display a * form with the following information: - number of unsaved addresses - number * of unsaved reports (REPORTSTATUS = 0) - number of unsaved timesheets - number * of unsaved material orders - number of not confirmed shortmessages */ int unsavedAddresses = app.dbutil.countUnsavedAddresses(); int unsavedReports = app.dbutil.countUnsavedReport(); int unsavedTimesheets = app.dbutil.countUnsavedCalendar(app.dbutil.getUser().getPersonalNumber()); int notConfirmedShortSMS = app.dbutil.countNotConfirmedSHortMSG(); boolean unsavedData = false; final StringBuilder sbUnsavedData = new StringBuilder(); if (unsavedAddresses > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("addressNotTransmittedYet"), //$NON-NLS-1$ new Object[] { Integer.toString(unsavedAddresses) })); unsavedData = true; } if (unsavedReports > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("reportNotTransmittedYet"), //$NON-NLS-1$ new Object[] { Integer.toString(unsavedReports) })); unsavedData = true; } if (unsavedTimesheets > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("timesheetNotTransmittedYet"), //$NON-NLS-1$ new Object[] { Integer.toString(unsavedTimesheets) })); unsavedData = true; } if (notConfirmedShortSMS > 0) { sbUnsavedData.append(MessageFormat.format(LoginMessages.getString("shortMessageNotConfirmed"), //$NON-NLS-1$ new Object[] { Integer.toString(notConfirmedShortSMS) })); unsavedData = true; } if (unsavedData) { if (app.showMessageBox(sbUnsavedData.toString() + LoginMessages.getString("continueWithUserSwitch"), //$NON-NLS-1$ LoginMessages.getString("warning"), Application.MBOX_BUTTON_OK_CANCEL, //$NON-NLS-1$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { // b2) continue and delete all this // information(display a modal dialog to // confirm), continue with c) deleteOldUser(mOldUser.getPersonalNumber(), mOldUser.getPersonalNumber(), monitor); app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return leaveToService(pernr, monitor); } }, false); } else { // b1) cancel and go back to the Login // Form (in order to login with the old user) app.dbutil.deleteNewUser(Integer.parseInt(mUsername)); mRepeatLogin = true; } } return unsavedData; } private ApplicationEvent leaveToService(final int pernr, final ProgressMonitor monitor) { monitor.begin(LoginMessages.getString("LoginForm.3"), 100); //$NON-NLS-1$ // process device activation after a successful user login if (!DeviceMirrorringHandler.getInstance().processLogin(String.valueOf(pernr), app, new SubProgressMonitor(monitor, 80), new DeleteAppDataFunction() { @Override public boolean deleteApplicationData(SimpleUserInterface ui) { if (SimpleUserInterface.MBOX_RESULT_YES != ui.showMessageBox(MessageFormat.format( LoginMessages.getString("LoginForm.4"), //$NON-NLS-1$ pernr), LoginMessages.getString("LoginForm.5"), SimpleUserInterface.MBOX_BUTTON_YES_NO_CANCEL, //$NON-NLS-1$ SimpleUserInterface.MBOX_ICON_WARNING)) return false; deleteOldUser(-1, pernr, monitor); return true; } })) { // activation failed - repeat login monitor.completed(); return null; } // continue login by switching to the service application app.dbutil.setupFixedMasterData(false); monitor.worked(10); // Server time synchronization new RemoteTransactionHandler().runSynchronize(app.dbutil.getUser().getPersonalNumber()); monitor.completed(); return app.appman.leaveToApplication(CommonConstants.Application.SERVICE_APP, null); } private boolean registerUser(final int user, final String passeord) { return new RemoteTransactionHandler().runRegisterUser(user, passeord); } private void deleteOldUser(final int oldUserPernr, final int newUserPernr, ProgressMonitor monitor) { // c) delete the data of the old user according to the table in chapter // 2.1.1 in Transaktionslogik_20090203.doc app.dbutil.deleteOldUser(oldUserPernr); app.dbutil.deleteAllJob(); app.dbutil.deleteAllAddress(); app.dbutil.deleteAllHistory(); app.dbutil.deleteAllReport(); app.dbutil.deleteAllJobMessage(); app.dbutil.deleteAllReportMaterial(); app.dbutil.deleteAllJobReportTime(); app.dbutil.deleteAllTimeSheet(); app.dbutil.deleteAllExpenses(); app.dbutil.deleteAllOrderMaterial(); app.dbutil.deleteAllOrder(); app.dbutil.deleteAllShortMessage(); app.dbutil.deleteAllWorkTypeT(); app.dbutil.deleteAllErrorCode(); app.dbutil.deleteAllMaterial(); app.dbutil.deleteAllEmployee(); app.dbutil.deleteAllMaterialOfPerson(); app.dbutil.deleteAllServerJob(); app.dbutil.deleteAllReason(); app.dbutil.deleteAllJobReason(); app.dbutil.deleteAllJobMonText(); app.dbutil.deleteAllIncident(); app.dbutil.deleteAllJobFormDesc(); app.dbutil.deleteAllJobNoForm(); app.dbutil.deleteAllReportMessage(); app.dbutil.deleteAllDrive(); app.dbutil.deleteAllBilling(); app.dbutil.deleteAllFormInstance(); // inform mirror handler, that user data has been destroyed DeviceMirrorringHandler.getInstance().setMirrorUserdataDeleted(); new RemoteTransactionHandler().runRefreshMasterdata(newUserPernr, "", "X", monitor); //$NON-NLS-1$ //$NON-NLS-2$ // if old and new user are identical, delete the user again, since master data refresh will // also refresh the user profile and thus recreate it unexpectedly if (oldUserPernr == newUserPernr) app.dbutil.deleteOldUser(oldUserPernr); } } private boolean isValid() { boolean result = true; if (userName.getText().toString().trim().isEmpty()) { userName.setError(LoginMessages.getString("LoginForm.1")); //$NON-NLS-1$ result = false; } if (password.getText().toString().trim().isEmpty()) { password.setError(LoginMessages.getString("LoginForm.2")); //$NON-NLS-1$ result = false; } return result; } @Override public void afterTextChanged(Editable s) { // unused } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // unused } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (userName.hasFocus()) { userName.clearError(); } if (password.hasFocus()) { password.clearError(); } if (userName.getText().toString().length() > 0 && password.getText().toString().length() > 0) { submitButton.setEnabled(true); } else { submitButton.setEnabled(false); } } } package ch.mfiles.kaba.kolibri.login.forms; import java.text.MessageFormat; import java.util.List; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.login.LoginApplication; import ch.mfiles.kaba.kolibri.login.LoginMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.RuntimeReleaseInfos; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The super class of all forms within this application. Contains common * members, methods and controls. * */ public abstract class LoginNavigationForm extends NavigationForm { // initialized by the kolibri framework... public static LoginApplication app; @Override public void onMenuItemClickListener(ListView menuView) { super.onMenuItemClickListener(menuView); menuView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, final View innerView, int position, long id) { onMenuItemClicked(innerView); } }); } private void onMenuItemClicked(final View innerView) { new AsyncTask(LoginNavigationForm.this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if ("REFRESH_MASTER_DATA".equals(innerView.getTag())) { //$NON-NLS-1$ Person crrentUser = app.dbutil.getUser(); new RemoteTransactionHandler() .runRefreshMasterdata(crrentUser.getPersonalNumber(), "", "X", monitor); //$NON-NLS-1$ //$NON-NLS-2$ } else if ("EXIT_APP".equals(innerView.getTag())) { //$NON-NLS-1$ return appman.exitApplication(); } else if ("CHECK_SOFTWARE_UPDATE".equals(innerView.getTag())) { //$NON-NLS-1$ switch(Runtime.getDeploymentManager().processDeployments(app, true, false, true)) { case PREPARED_NEED_RESTART: return appman.restartFramework(); case PREPARED_NEED_SHUTDOWN: return appman.exitFramework(); } } else if ("APP_INFORMATION".equals(innerView.getTag())) { //$NON-NLS-1$ app.showMessageBox(getVersionInfo(), "", Application.MBOX_BUTTON_OK, 0); //$NON-NLS-1$ } return null; } }; getView().closeDrawers(); } /** * Creates version information from currently deployed applications. * * @return */ private String getVersionInfo() { String loginVersion = getAppVersion("ch.mfiles.kaba.kolibri.login.LoginApplication"); //$NON-NLS-1$ String commonVersion = getAppVersion("ch.mfiles.kaba.kolibri.common.CommonApplication"); //$NON-NLS-1$ String materialVersion = getAppVersion("ch.mfiles.kaba.kolibri.material.MaterialApplication"); //$NON-NLS-1$ String serviceVersion = getAppVersion("ch.mfiles.kaba.kolibri.service.ServiceApplication"); //$NON-NLS-1$ String timeVersion = getAppVersion("ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication"); //$NON-NLS-1$ String appVersion; if (loginVersion.equals(commonVersion) && loginVersion.equals(materialVersion) && loginVersion.equals(serviceVersion) && loginVersion.equals(timeVersion)) // if all versions equal simply show *the* version appVersion = loginVersion; else // if one version differs, show all apps seperatly appVersion = MessageFormat.format( "\n - Common App: {0}\n - Login App: {1}\n - Material App: {2}\n - Service App: {3}\n - Timesheet App: {4}", //$NON-NLS-1$ commonVersion, loginVersion, materialVersion, serviceVersion, timeVersion); return MessageFormat.format("{0}: {1}({2})\n\nApp-Version: {3}", RuntimeReleaseInfos.getProduct(), //$NON-NLS-1$ RuntimeReleaseInfos.getRelease(), RuntimeReleaseInfos.getBuild(), appVersion); } private String getAppVersion(String app) { ApplicationDescriptor ad = appman.getApplicationDescriptor(app); if (ad == null) return "n/a"; //$NON-NLS-1$ return ad.getVersion(); } @Override public void onMenuItemLoad(List menuListView) { // App informations NavigationMenuListItem appInformations = new NavigationMenuListItem(); appInformations.setTag("APP_INFORMATION"); //$NON-NLS-1$ appInformations.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.INFORMATION, CommonConstants.Images.IMAGE_DPI))); appInformations.setText(LoginMessages.getString("appInformations")); //$NON-NLS-1$ menuListView.add(appInformations); // Refresh Master Data NavigationMenuListItem refreshMasterData = new NavigationMenuListItem(); refreshMasterData.setTag("REFRESH_MASTER_DATA"); //$NON-NLS-1$ refreshMasterData.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.UPDATE, CommonConstants.Images.IMAGE_DPI))); refreshMasterData.setText(LoginMessages.getString("refreshMasterdata")); //$NON-NLS-1$ menuListView.add(refreshMasterData); // Check sw-update NavigationMenuListItem checkSoftwareUpdate = new NavigationMenuListItem(); checkSoftwareUpdate.setTag("CHECK_SOFTWARE_UPDATE"); //$NON-NLS-1$ checkSoftwareUpdate.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.SYSTEM_UPDATE, CommonConstants.Images.IMAGE_DPI))); checkSoftwareUpdate.setText(LoginMessages.getString("checkSWUpdate")); //$NON-NLS-1$ menuListView.add(checkSoftwareUpdate); // Exit Service Application NavigationMenuListItem exitServiceApplication = new NavigationMenuListItem(); exitServiceApplication.setTag("EXIT_APP"); //$NON-NLS-1$ exitServiceApplication.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EXIT, CommonConstants.Images.IMAGE_DPI))); exitServiceApplication.setText(LoginMessages.getString("exitApplication")); //$NON-NLS-1$ menuListView.add(exitServiceApplication); onMenuItemNotifyDataSetChanged(); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { View view = super.onFormLoad(context, inflater); setRuntimeMenuHidden(true); return view; } } package ch.mfiles.kaba.kolibri.login; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.login.forms.LoginForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; /** * Main application class. */ public class LoginApplication extends Application { public static final Log log = LogFactory.getLog(LoginApplication.class); public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public MessageUtil messageUtil; /** * Called by the framework each time the application is started. * * @param obj * An (optional) object supplied by the application that started * this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); messageUtil = MessageUtil.getInstance(); // make sure the common plugin exists if (null == appman.getApplicationDescriptor(CommonConstants.Application.COMMON_APP)) { showMessageBox(LoginMessages.getString("gilgenCommonApplicationIsNotInstalled"), LoginMessages.getString("startGilgenService"), MBOX_BUTTON_OK, MBOX_ICON_ERROR); //$NON-NLS-1$ //$NON-NLS-2$ return appman.exitApplication(); } setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); return leaveToForm(LoginForm.class); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { // do nothings } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // do nothings } /** * Called by the framework after the application has been upgraded but * before the upgrade is commited to the database. Additional upgrade * postprocessing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { Registry reg = appman.getRegistry(null); reg.setProperty("framework.appman.startupApplication", "ch.mfiles.kaba.kolibri.login.LoginApplication"); //$NON-NLS-1$ //$NON-NLS-2$ ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry serviceReg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (serviceReg != null) { serviceReg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } // do nothings } public void showMessage(String message) { messageUtil.showMessage(message); } public void showMessage(String message, boolean forceClear) { messageUtil.showMessage(message, forceClear); } } package ch.mfiles.kaba.kolibri.util; public class LoginConstants { private LoginConstants() { } public static final class Images { private Images() { } public static final String HEADER = "images/header.jpg"; //$NON-NLS-1$ } } /bin/ /build/ gilgenLogin ch.mfiles.kolibri.plugin.androidResourceBuilder org.eclipse.jdt.core.javabuilder ch.mfiles.kolibri.plugin.kolibriNature org.eclipse.jdt.core.javanature plugins { id("ch.mfiles.kolibri-application") } dependencies { implementation(project(":common")) } # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23 cp.android.nanoxml=false cp.android.unrestricted=false eclipse.preferences.version=1 platform=ANDROID #Wed Apr 06 22:48:58 CEST 2011 eclipse.preferences.version=1 encoding//src/ch/mfiles/kaba/kolibri/common/CommonApplication.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/common/util/CONSTANTS.java=UTF-8 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.7 #Fri Sep 19 13:25:29 GMT+07:00 2008 eclipse.preferences.version=1 internal.default.compliance=user package ch.mfiles.kaba.kolibri.material; import java.util.MissingResourceException; import java.util.ResourceBundle; public class MaterialMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.material.Messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private MaterialMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface EnterAValidValueIsGreateThan = G\u00FCltigen Wert erfassen: {0} ist gr\u00F6\u00DFer als {1}! MaterialSaved = Material gespeichert OrderMaterialForm.0 = abgebrochen\u2026 OrderMaterialNewEditForm.0 = Suchen add = Hinzuf\u00FCgen amount = Anzahl artNo = Art. Nr. clear = Reset delete = L\u00F6schen deleteMaterial = Artikel l\u00F6schen? deleteOrder = Bestellung l\u00F6schen? detected = Erfasst doYouWantToDeleteOrder = Auftrag l\u00F6schen? duplicatedMaterialNumber = Artikel {0} schon verhanden {1} kann nicht hinzugef\u00FCgt werden. employee = Mitarbeiter exit = Beenden exp = Exp express = Express materialWasDeleted = Artikel wurde gel\u00F6scht. materialWithThisNameAlreadyExists = Material mit diesem Namen existiert bereits. materialWithThisNumberAlreadyExists = Material mit dieser Nummer existiert bereits. name = Bezeichnung nbr = Anz. noOrderAvailable = Kein Auftrag vorhanden notYetSubmitted = Noch nicht \u00FCbermittelt order = Bestellungen orderFrom = Bestellung vom orderIsDeleted = Die Bestellung wurde gel\u00F6scht save = Speichern send = Senden sent = Gesendet sparePartsAndExpress = {0} Artikel, {1} Express submittedOn = \u00DCbermittelt am unit = Einheit warning = Warnung! wrongFormArgument = Falscher Form\u00FCbergabeparameter wrongFormatXX-XXXX-XXX/XX" = Falsches Format (XX-XXXX-XXX/XX). #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface EnterAValidValueIsGreateThan = Entrez une valeur valable: {0} est sup\u00E9rieur \u00E0 {1}! MaterialSaved = Mat\u00E9riel m\u00E9moris\u00E9 OrderMaterialForm.0 = annul\u00E9\u2026 OrderMaterialNewEditForm.0 = Chercher add = Ajouter amount = Nombre artNo = No d'art. clear = Remettre delete = Effacer deleteMaterial = Effacer l'article? deleteOrder = Effacer la commande? detected = Enregistr\u00E9 doYouWantToDeleteOrder = Effacer la commande? duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur exit = Fermer exp = Exp. express = Express materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. name = D\u00E9signation nbr = Nbre. noOrderAvailable = Pas de commande disponible notYetSubmitted = Pas encore re\u00E7u order = Commandes orderFrom = Commande de orderIsDeleted = Commande a \u00E9t\u00E9 supprim\u00E9 save = Enregistre send = Envoyer sent = Envoy\u00E9 sparePartsAndExpress = {0} Articles, d\u00E9tect\u00E9s Express {1} submittedOn = Pr\u00E9sent\u00E9 sur unit = Unit\u00E9 warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect wrongFormatXX-XXXX-XXX/XX" = Format incorrect (XX-XXXX-XXX/XX). #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface EnterAValidValueIsGreateThan = Entrez une valeur valable: {0} est sup\u00E9rieur \u00E0 {1}! MaterialSaved = Mat\u00E9riel m\u00E9moris\u00E9 OrderMaterialForm.0 = annul\u00E9\u2026 OrderMaterialNewEditForm.0 = Chercher add = Ajouter amount = Nombre artNo = No d'art. clear = Remettre delete = Effacer deleteMaterial = Effacer l'article? deleteOrder = Effacer la commande? detected = Enregistr\u00E9 doYouWantToDeleteOrder = Effacer la commande? duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. employee = Collaborateur exit = Fermer exp = Exp. express = Express materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. name = D\u00E9signation nbr = Nbre. noOrderAvailable = Pas de commande disponible notYetSubmitted = Pas encore re\u00E7u order = Commandes orderFrom = Commande de orderIsDeleted = Commande a \u00E9t\u00E9 supprim\u00E9 save = Enregistre send = Envoyer sent = Envoy\u00E9 sparePartsAndExpress = {0} Articles, d\u00E9tect\u00E9s Express {1} submittedOn = Pr\u00E9sent\u00E9 sur unit = Unit\u00E9 warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect wrongFormatXX-XXXX-XXX/XX" = Format incorrect (XX-XXXX-XXX/XX). #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) EnterAValidValueIsGreateThan = Enter a valid value: {0} is greater than {1}! MaterialSaved = Material saved OrderMaterialForm.0 = aborted... OrderMaterialNewEditForm.0 = Search add = Add amount = Amount artNo = Art. No. clear = Clear delete = Delete deleteMaterial = Do you want to delete this material? deleteOrder = Do you want to delete this Order? detected = Detected doYouWantToDeleteOrder = Do you want to delete order? duplicatedMaterialNumber = There is MaterialNumber {0} duplicated {1} can not insert. employee = Employee exit = Exit exp = Exp express = Express materialWasDeleted = Material was deleted. materialWithThisNameAlreadyExists = Material with this name already exists materialWithThisNumberAlreadyExists = Material with this number already exists. name = Name nbr = Nbr. noOrderAvailable = No Order Available notYetSubmitted = Not yet submitted order = Orders orderFrom = Order from orderIsDeleted = Order is deleted save = Save send = Send sent = Sent sparePartsAndExpress = {0} Spare parts, {1} Express submittedOn = Submitted on unit = Unit warning = Warning! wrongFormArgument = Wrong form argument class found in form wrongFormatXX-XXXX-XXX/XX" = Wrong format(XX-XXXX-XXX/XX) package ch.mfiles.kaba.kolibri.material.forms; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.material.MaterialMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class OrderListForm extends SuperForm { private static Log log = LogFactory.getLog(OrderListForm.class); private DefaultListWidget listWidget; private LinearLayout emptyMessageView; private boolean isServiceApp; @Override public void onFormCall(Object argument) { if (argument instanceof Boolean) { isServiceApp = Boolean.valueOf(argument.toString()); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(MaterialMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create add action ActionCtrl addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); listWidget = new DefaultListWidget(context); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); listWidget.setVisibility(View.GONE); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); view.setFocusable(true); view.setFocusableInTouchMode(true); view.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = new TextView(context); textView.setText(MaterialMessages.getString("noOrderAvailable")); //$NON-NLS-1$ textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); emptyMessageView.setVisibility(View.GONE); view.addView(emptyMessageView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); if (emptyMessageView.getChildCount() > 0) { emptyMessageView.removeAllViewsInLayout(); } setFormTitle(MaterialMessages.getString("order")); //$NON-NLS-1$ loadTable(); return null; } private void loadTable() { listWidget.clean(); List matOrderList = app.dbutil.selectOrderListByPerNo(app.dbutil.getUser().getPersonalNumber()); if (!matOrderList.isEmpty()) { ArrayList items = new ArrayList(); for (int i = 0; i < matOrderList.size(); i++) { final Order order = matOrderList.get(i); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.isShowEllipInTextEnd(true); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.MENU, CommonConstants.Images.IMAGE_MAX_DPI))); item.setStatusColor(order.getStatusColor()); item.setTitleText(MaterialMessages.getString("orderFrom") + " " + order.getOrderCreateDate()); //$NON-NLS-1$ //$NON-NLS-2$ List matList = app.dbutil.selectOrderMaterialList(order); int countExpress = 0; for (OrderMaterial orderMaterial : matList) { if (orderMaterial.isExpressFlag()) { countExpress++; } } item.setStringLine1(MessageFormat.format(MaterialMessages.getString("sparePartsAndExpress"), new Object[] { matList.size(), countExpress })); //$NON-NLS-1$ String lineTwo = MaterialMessages.getString("notYetSubmitted"); //$NON-NLS-1$ if (order.isSent()) { lineTwo = MaterialMessages.getString("submittedOn") + " " + order.getOrderSentDate(); //$NON-NLS-1$ //$NON-NLS-2$ } item.setStringLine2(lineTwo); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showPopupMenu(v, order); } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(matOrderList)); } listWidget.addItems(items); listWidget.setVisibility(View.VISIBLE); emptyMessageView.setVisibility(View.GONE); } else { listWidget.setVisibility(View.GONE); emptyMessageView.setVisibility(View.VISIBLE); } } private void showPopupMenu(View v, final Order order) { ImageButton imageButton = (ImageButton) v; PopupMenu popupMenu = new PopupMenu(context, imageButton); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); // send Images acceptStatusImage = ImagesUtil.Images.SEND_DISABLED_BLACK; if (order.isNew() && !app.dbutil.selectOrderMaterialList(order).isEmpty()) { acceptStatusImage = ImagesUtil.Images.SEND_BLACK; } addPopupMenuItem(popupMenu, 1, MaterialMessages.getString("send"), acceptStatusImage); //$NON-NLS-1$ // Delete addPopupMenuItem(popupMenu, 2, MaterialMessages.getString("delete"), ImagesUtil.Images.DELETE_BLACK); //$NON-NLS-1$ // forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem, order); return true; } }); popupMenu.show(); } private void addPopupMenuItem(PopupMenu popupMenu, int index, String label, Images image) { popupMenu.getMenu().add(Menu.NONE, index, Menu.NONE, label).setIcon(getBitmanDrawable(app.imagesUtil.getImage(image, CommonConstants.Images.IMAGE_DPI))); } private void handleMenuItemClicked(MenuItem menuItem, Order order) { if (menuItem.getItemId() == 1) { if (!app.dbutil.selectOrderMaterialList(order).isEmpty()) { actionSend(order); } } else if (menuItem.getItemId() == 2) { actionDelete(order); } } private OnItemClickListener createOnItemClickListener(final List msgList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(OrderMaterialForm.class, new FormArguments((Order) msgList.get(position))); } }, false); } }; } private void actionSend(final Order order) { if (order.isNew()) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { new RemoteTransactionHandler().saveMaterial(app.dbutil.getUser().getPersonalNumber(), order); return app.leaveToForm(OrderListForm.class); } }, false); } } private void actionDelete(final Order order) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(MaterialMessages.getString("deleteOrder"), MaterialMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES) { app.dbutil.deleteOrder(order); List listMaterialOrder = app.dbutil.selectOrderMaterialList(order); if (!listMaterialOrder.isEmpty()) { for (int i = 0; i < listMaterialOrder.size(); i++) { app.dbutil.deleteOrderMaterial((OrderMaterial) listMaterialOrder.get(i)); } } app.showMessage(MaterialMessages.getString("orderIsDeleted")); //$NON-NLS-1$ } return app.leaveToForm(OrderListForm.class); } }, false); } @Override public ApplicationEvent onBackPressed() { if (isServiceApp) { return appman.leaveToApplication(CommonConstants.Application.SERVICE_APP, null); } else { return appman.exitApplication(); } } @Override public void onFormReset() { super.onFormReset(); setFormTitle(null); } protected ApplicationEvent onAddPressed() { hideSoftInputFromWindow(); return app.leaveToForm(OrderMaterialForm.class, new FormArguments(null)); } /** * The Order Form Arguments Class. * * @author nop */ public static class FormArguments { private Order order; public FormArguments(Order order) { this.order = order; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } } } package ch.mfiles.kaba.kolibri.material.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.material.MaterialMessages; import ch.mfiles.kaba.kolibri.material.forms.OrderListForm.FormArguments; import ch.mfiles.kaba.kolibri.material.forms.OrderMaterialNewEditForm.OrderMaterialNewEditFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class OrderMaterialForm extends SuperForm { private static Log log = LogFactory.getLog(OrderMaterialForm.class); private DefaultListWidget listWidget; private LinearLayout emptyMessageView; private Order selectedMaterialOrder; private OrderMaterial selectedOrderMaterial; private boolean isNewMaterial; private ActionCtrl scanButton; private ActionCtrl addButton; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.selectedMaterialOrder = formArguments.getOrder(); if (this.selectedMaterialOrder == null) { this.isNewMaterial = true; } else { this.isNewMaterial = false; } } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(MaterialMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create scan action scanButton = addActionCtrl(false, true, 1, "onScanPressed"); //$NON-NLS-1$ scanButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); // create add action addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); listWidget = new DefaultListWidget(context); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); listWidget.setVisibility(View.GONE); view.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = new TextView(context); textView.setText(MaterialMessages.getString("noOrderAvailable")); //$NON-NLS-1$ textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); emptyMessageView.setVisibility(View.GONE); view.addView(emptyMessageView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); if (emptyMessageView.getChildCount() > 0) { emptyMessageView.removeAllViewsInLayout(); } setFormTitle(MaterialMessages.getString("order")); //$NON-NLS-1$ loadTable(); if(selectedMaterialOrder!= null && selectedMaterialOrder.isSent()) { setEnableButtons(false); } else { setEnableButtons(true); } return null; } private void setEnableButtons(boolean isEnabled) { if(isEnabled) { scanButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); } else { scanButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); } scanButton.setEnabled(isEnabled); addButton.setEnabled(isEnabled); } private void loadTable() { listWidget.clean(); if (!isNewMaterial) { List matList = app.dbutil.selectOrderMaterialList(selectedMaterialOrder); if (!matList.isEmpty()) { ArrayList items = new ArrayList(); for (int i = 0; i < matList.size(); i++) { final OrderMaterial orderMaterial = matList.get(i); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.isShowEllipInTextEnd(true); item.setStatusColor(orderMaterial.getStatusColor()); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(orderMaterial.getMaterialNumber(), orderMaterial.getVariousMaterial()); String statusType = "P"; //$NON-NLS-1$ if (!materialList.isEmpty()) { statusType = "N"; //$NON-NLS-1$ } item.setStatusType(statusType); item.setTitleText(orderMaterial.getVariousMaterial()); item.setStringLine1(orderMaterial.getAmount() + " " + orderMaterial.getUnit()); //$NON-NLS-1$ String expressMeg = ""; //$NON-NLS-1$ if (orderMaterial.isExpressFlag()) { expressMeg = MaterialMessages.getString("express"); //$NON-NLS-1$ } item.setStringLine2(expressMeg); if(selectedMaterialOrder!= null && selectedMaterialOrder.isSent()) { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(selectedMaterialOrder!= null && selectedMaterialOrder.isSent()) { return; } selectedOrderMaterial = orderMaterial; if (v instanceof ImageButton) { onDeletePressed(); } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(matList)); } listWidget.addItems(items); listWidget.setVisibility(View.VISIBLE); emptyMessageView.setVisibility(View.GONE); } else { listWidget.setVisibility(View.GONE); emptyMessageView.setVisibility(View.VISIBLE); } } } private OnItemClickListener createOnItemClickListener(final List matList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { OrderMaterialNewEditFormArguments formArguments = new OrderMaterialNewEditFormArguments(selectedMaterialOrder, matList.get(position), null); return appman.getActiveApplication().leaveToForm(OrderMaterialNewEditForm.class, formArguments); } }, false); } }; } private void onDeletePressed() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(MaterialMessages.getString("deleteMaterial"), MaterialMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES) { app.dbutil.deleteOrderMaterial(selectedOrderMaterial); app.showMessage(MaterialMessages.getString("materialWasDeleted")); //$NON-NLS-1$ } return app.leaveToForm(OrderMaterialForm.class); } }, false); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(OrderListForm.class); } @Override public void onFormReset() { super.onFormReset(); setFormTitle(null); } protected ApplicationEvent onScanPressed() { new AsyncTask(this) { String materialNumber; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(OrderMaterialForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { app.showMessage(MaterialMessages.getString("OrderMaterialForm.0")); //$NON-NLS-1$ return null; } else { app.showMessage(result.toString()); materialNumber = result.getContents(); log.info("scan result -> " + result.getContents()); //$NON-NLS-1$ } if (materialNumber != null) { OrderMaterialNewEditFormArguments formArguments = new OrderMaterialNewEditFormArguments(selectedMaterialOrder, null, materialNumber); return appman.getActiveApplication().leaveToForm(OrderMaterialNewEditForm.class, formArguments); } return null; } }; return null; } protected ApplicationEvent onAddPressed() { hideSoftInputFromWindow(); OrderMaterialNewEditFormArguments formArguments = new OrderMaterialNewEditFormArguments(selectedMaterialOrder, null, null); return appman.getActiveApplication().leaveToForm(OrderMaterialNewEditForm.class, formArguments); } } package ch.mfiles.kaba.kolibri.material.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.material.MaterialApplication; import ch.mfiles.kaba.kolibri.material.MaterialMessages; import ch.mfiles.kaba.kolibri.material.forms.OrderListForm.FormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class OrderMaterialNewEditForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(OrderMaterialNewEditForm.class); public static MaterialApplication app; // don't make this CommonApplication private Order selectedMaterialOrder; private OrderMaterial selectedOrderMaterial; private AmountEditText amountEditText; private MDEditText unitEditText; private MDEditText sizeEditText; private AppCompatCheckBox expressCheckBox; public Button deleteButton; private Material selectedMaterial = null; private MaterialPerson selectedMaterialPerson = null; @Override public void onFormCall(Object argument) { if (argument instanceof OrderMaterialNewEditFormArguments) { OrderMaterialNewEditFormArguments formArguments = (OrderMaterialNewEditFormArguments) argument; selectedMaterialOrder = formArguments.getMaterialOrder(); selectedOrderMaterial = formArguments.getMaterial(); barcode = formArguments.getBarcode(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(MaterialMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); saveButton.setVisible(false); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } if (!isMatrialNumberWrongFormat()) { numberEditText.clearError(); loadMaterialsList(numberEditText.getText().toString()); if(selectedMaterial != null || selectedMaterialPerson != null) { MessageUtil.getInstance().showMessage(MaterialMessages.getString("materialWithThisNumberAlreadyExists"), true); } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); if(selectedMaterial != null || selectedMaterialPerson != null) { MessageUtil.getInstance().showMessage(MaterialMessages.getString("materialWithThisNameAlreadyExists"), true); } } else { nameEditText.clearError(); } } }); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout stockItemLinearLayout = new LinearLayout(context); stockItemLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams stockLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); stockLinearLayoutParams.gravity = Gravity.LEFT; stockLinearLayoutParams.width = LayoutParams.MATCH_PARENT; stockLinearLayoutParams.weight = 0.7f; stockItemLinearLayout.setLayoutParams(stockLinearLayoutParams); amountEditText = AmountEditText.createDefaultEditText(stockItemLinearLayout, MaterialMessages.getString("amount"), true); LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.LEFT; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); // unit unitEditText = MDEditText.createDefaultEditText(stockItemLinearLayout, MaterialMessages.getString("unit"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ unitEditText.setTag("UNIT"); //$NON-NLS-1$ LinearLayout.LayoutParams unitInputLayoutParams = new LinearLayout.LayoutParams(0, 0); unitInputLayoutParams.gravity = Gravity.LEFT; unitInputLayoutParams.width = 0; unitInputLayoutParams.height = LayoutParams.MATCH_PARENT; unitInputLayoutParams.weight = 0.3f; unitEditText.getParentTextInputLayout().setLayoutParams(unitInputLayoutParams); sizeEditText = MDEditText.createDefaultEditText(stockItemLinearLayout, Messages.getString("Containersize"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ sizeEditText.setTag("SIZE"); //$NON-NLS-1$ sizeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); sizeEditText.setEnabled(false); LinearLayout.LayoutParams sizeInputLayoutParams = new LinearLayout.LayoutParams(0, 0); sizeInputLayoutParams.gravity = Gravity.LEFT; sizeInputLayoutParams.width = 0; sizeInputLayoutParams.height = LayoutParams.MATCH_PARENT; sizeInputLayoutParams.weight = 0.3f; sizeEditText.getParentTextInputLayout().setLayoutParams(sizeInputLayoutParams); contentLinearLayout.addView(stockItemLinearLayout); expressCheckBox = CommonUtilForm.getCheckBox(context, MaterialMessages.getString("express")); //$NON-NLS-1$ contentLinearLayout.addView(expressCheckBox); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(Messages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (selectedOrderMaterial == null) { resetView(); return; } appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(MaterialMessages.getString("deleteMaterial"), MaterialMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES) { DatabaseUtil.getInstance().deleteOrderMaterial(selectedOrderMaterial); return app.leaveToForm(OrderMaterialForm.class, new FormArguments(selectedMaterialOrder)); } return null; } }, false); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); addContentLinearLayout(contentLinearLayout); return view; } @Override public void setEnabledControls(boolean enabled) { searchView.setEnabled(enabled); deleteButton.setEnabled(enabled); nameEditText.setEnabled(enabled); numberEditText.setEnabled(enabled); amountEditText.setEnabled(enabled); unitEditText.setEnabled(enabled); expressCheckBox.setEnabled(enabled); } @Override protected void loadData() { super.loadData(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); selectedMaterial = null; selectedMaterialPerson = null; if (selectedOrderMaterial == null) { resetView(); deleteButton.setText(MaterialMessages.getString("clear")); //$NON-NLS-1$ searchView.setVisibility(View.VISIBLE); } else { nameEditText.setText(selectedOrderMaterial.getVariousMaterial()); numberEditText.setText(selectedOrderMaterial.getMaterialNumber()); amountEditText.setText(selectedOrderMaterial.getAmount()); //$NON-NLS-1$ //$NON-NLS-2$ unitEditText.setText(selectedOrderMaterial.getUnit()); expressCheckBox.setChecked(selectedOrderMaterial.isExpressFlag()); deleteButton.setText(MaterialMessages.getString("delete")); //$NON-NLS-1$ searchView.setVisibility(View.INVISIBLE); } } @Override protected void resetView() { super.resetView(); amountEditText.clearError(); selectedMaterial = null; selectedMaterialPerson = null; amountEditText.getText().clear(); unitEditText.getText().clear(); expressCheckBox.setChecked(false); } @Override public ApplicationEvent onBackPressed() { if (nameEditText.getText().toString().isEmpty() && numberEditText.getText().toString().isEmpty()) { return app.leaveToForm(OrderMaterialForm.class, new FormArguments(selectedMaterialOrder)); } new AsyncTask(this) { private List editErrorList = new ArrayList(); @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { editErrorList.clear(); if (nameEditText.getText().toString().isEmpty()) { editErrorList.add(nameEditText); } if (numberEditText.getText().toString().isEmpty()) { editErrorList.add(numberEditText); } else { if(isMatrialNumberWrongFormat()) { app.showMessageBox(Messages.getString("WrongFormatXX-XXXX-XXX/XX"), Messages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ editErrorList.add(numberEditText); } } if (amountEditText.isRequired() && amountEditText.getText().toString().isEmpty()) { editErrorList.add(amountEditText); } if (editErrorList.isEmpty()) { if (selectedOrderMaterial != null) { updateMaterial(); } else { if(isDuplicatedMaterial()) { Object[] arguments = new Object[] { numberEditText.getText().toString(), nameEditText.getText().toString() }; String errorMessage = MessageFormat.format(MaterialMessages.getString("duplicatedMaterialNumber"), arguments); app.showMessageBox(errorMessage, Messages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ return null; } // add material person if not exist. addMaterialPerson(); // insert new material. insertNewMaterial(); } return app.leaveToForm(OrderMaterialForm.class, new FormArguments(selectedMaterialOrder)); } return null; } @Override public void runOnUIThread() { amountEditText.clearFocus(); numberEditText.clearError(); nameEditText.clearError(); amountEditText.clearError(); if (!editErrorList.isEmpty()) { for (MDEditText errorText : editErrorList) { errorText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ } } } }; return null; } private void insertNewMaterial() { if (selectedMaterialOrder == null) { // there is no order yet. selectedMaterialOrder = new Order(); selectedMaterialOrder.setStatus(CommonConstants.Order.Status.NEW_ORDER); selectedMaterialOrder.setANZ(""); //$NON-NLS-1$ selectedMaterialOrder.setCreateDate(DateTimeUtil.getTimestamp().getTime()); selectedMaterialOrder.setSentDate(DateUtils.getInitialDateTime()); selectedMaterialOrder.setPersonalNumber(DatabaseUtil.getInstance().getUser().getPersonalNumber()); DatabaseUtil.getInstance().insertOrder(selectedMaterialOrder); } OrderMaterial newOrderMaterial = new OrderMaterial(); newOrderMaterial.setDate(DateTimeUtil.getTimestamp().getTime()); newOrderMaterial.setExpressFlag(expressCheckBox.isChecked()); newOrderMaterial.setVariousMaterial(nameEditText.getText().toString()); newOrderMaterial.setMaterialNumber(numberEditText.getText().toString()); newOrderMaterial.setPersonalNumber(DatabaseUtil.getInstance().getUser().getPersonalNumber()); newOrderMaterial.setAmount(amountEditText.getText().toString()); newOrderMaterial.setUnit(unitEditText.getText().toString()); newOrderMaterial.setOrderDate(selectedMaterialOrder.getCreateDate()); DatabaseUtil.getInstance().insertOrderMaterial(newOrderMaterial); } private void updateMaterial() { selectedOrderMaterial.setExpressFlag(expressCheckBox.isChecked()); selectedOrderMaterial.setAmount(amountEditText.getText().toString()); selectedOrderMaterial.setUnit(unitEditText.getText().toString()); DatabaseUtil.getInstance().updateOrderMaterial(selectedOrderMaterial); } private void addMaterialPerson() { // Mat: sum of the articles from the excise and the pers. Mat table (exact match of article number necessary!) Material mat = DatabaseUtil.getInstance().selectMaterialByMatNo(numberEditText.getText().toString()); MaterialPerson matPerson = DatabaseUtil.getInstance().selectMaterialPersonByMatNo(numberEditText.getText().toString()); if (mat == null && matPerson == null) { // Article does not yet exist and can be used as Pers. Mat if (isMatrialNumberWrongFormat()) { app.showMessageBox(Messages.getString("WrongFormatXX-XXXX-XXX/XX"), Messages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ return; } selectedMaterialPerson = new MaterialPerson(); selectedMaterialPerson.setMaterialNumber(numberEditText.getText().toString()); selectedMaterialPerson.setMaterialShortText(nameEditText.getText().toString()); DatabaseUtil.getInstance().insertMaterialPerson(selectedMaterialPerson); MessageUtil.getInstance().showMessage(MaterialMessages.getString("MaterialSaved"), true); } } private boolean isDuplicatedMaterial() { if (selectedMaterialOrder != null) { List mListZKDMAMAT = DatabaseUtil.getInstance().selectOrderMaterialList(selectedMaterialOrder); for (int i = 0; i < mListZKDMAMAT.size(); i++) { OrderMaterial zkdmamat = mListZKDMAMAT.get(i); if (zkdmamat.getMaterialNumber().equalsIgnoreCase(numberEditText.getText().toString()) || zkdmamat.getVariousMaterial().equalsIgnoreCase(nameEditText.getText().toString())) { return true; } } } return false; } public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(queryText, queryText); List materialPersonList = app.dbutil.selectMaterialPersonListByMatNoAndMatName(queryText, queryText); for (Material matPart : materialList) { searchView.getSuggessionItemList().add(new SuggessionItem(matPart.getMaterialNumber(), matPart.getMaterialShortText())); } for (MaterialPerson zkdmobmatpers : materialPersonList) { searchView.getSuggessionItemList().add(new SuggessionItem(zkdmobmatpers.getMaterialNumber(), zkdmobmatpers.getMaterialShortText())); } int matHits = materialList.size() + materialPersonList.size(); if (matHits > 0 && matHits == 1) { // Exactly found an article from the StammMat if (materialList.size() == 1) { selectedMaterial = materialList.get(0); } else if (materialPersonList.size() == 1) { // Exactly found an article from PersMat selectedMaterialPerson = materialPersonList.get(0); } } if (selectedMaterial != null) { amountEditText.getText().clear(); sizeEditText.setText(selectedMaterial.getSize()); expressCheckBox.setChecked(false); } amountEditText.getText().clear(); expressCheckBox.setChecked(false); } public static class OrderMaterialNewEditFormArguments { private Order materialOrder; private OrderMaterial material; private String barcode; public OrderMaterialNewEditFormArguments(Order materialOrder, OrderMaterial material, String barcode) { this.materialOrder =materialOrder; this.material = material; this.barcode = barcode != null ? barcode : ""; //$NON-NLS-1$ } public Order getMaterialOrder() { return materialOrder; } public OrderMaterial getMaterial() { return material; } public String getBarcode() { return barcode; } } } package ch.mfiles.kaba.kolibri.material.forms; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.material.MaterialApplication; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class SuperForm extends DialogForm { protected Context context; protected LinearLayout view; // initialized by the kolibri framework... public static MaterialApplication app; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); view.setFocusable(true); view.setFocusableInTouchMode(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image clearImage = imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(clearImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); return view; } /** * Closes the keyboard (if open) */ protected void hideSoftInputFromWindow() { KeyboardUtil.closeKeyboard(appman, getView()); } /** * Clears the error messages. */ protected void clearErrorMessages() { // do nothings } } package ch.mfiles.kaba.kolibri.material; import java.util.Set; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.material.forms.OrderListForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; /** * Main application class. */ public class MaterialApplication extends Application { public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public EnumUtil enumUtil; public MessageUtil messageUtil; /** * Called by the framework each time the application is started. * * @param obj * An (optional) object supplied by the application that started * this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); enumUtil = EnumUtil.getInstance(this.dbutil); messageUtil = MessageUtil.getInstance(); boolean isServiceApp = false; if (obj !=null && Boolean.valueOf(obj.toString())) { isServiceApp = true; } setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); return leaveToForm(OrderListForm.class, isServiceApp); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { // do nothings } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // do nothings } /** * Called by the framework after the application has been upgraded but * before the upgrade is commited to the database. Additional upgrade * postprocessing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } public void showMessage(String message) { messageUtil.showMessage(message); } public void showMessage(String message, boolean forceClear) { messageUtil.showMessage(message, forceClear); } public void showWarningMessageBox(final String warningMessage){ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { showMessageBox(warningMessage, MaterialMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } } /bin/ /gen/ /build/ gilgenMaterial ch.mfiles.kolibri.plugin.androidResourceBuilder org.eclipse.jdt.core.javabuilder ch.mfiles.kolibri.plugin.kolibriNature org.eclipse.jdt.core.javanature plugins { id("ch.mfiles.kolibri-application") } dependencies { implementation(project(":common")) } # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23 eclipse.preferences.version=1 platform=ANDROID eclipse.preferences.version=1 encoding//src/ch/mfiles/kaba/kolibri/common/CommonApplication.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/common/util/CONSTANTS.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/service/forms/ReportEditForm.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/service/util/CONSTANTS.java=UTF-8 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.7 #Tue Sep 23 11:08:24 GMT+07:00 2008 eclipse.preferences.version=1 internal.default.compliance=user eclipse.preferences.version=1 org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false package ch.mfiles.kaba.kolibri.service; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class ServiceMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.service.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private ServiceMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static String getString(Locale locale, String key) { try { ResourceBundle resourceBundleLocale = ResourceBundle .getBundle(BUNDLE_NAME, locale); return resourceBundleLocale.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceNotification; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceType; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class AbsenceNotificationListForm extends SuperForm { private static Log log = LogFactory.getLog(AbsenceNotificationListForm.class); protected Job job; private Toolbar toolbar; protected DetailListWidget listWidget; private ActionCtrl addButton; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { // if (argument != null) { // if (argument instanceof AbsenceNotificationListFormArguments) { // AbsenceNotificationListFormArguments formArguments = (AbsenceNotificationListFormArguments) argument; // job = formArguments.getJob(); // } else { // log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ // throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ // } // } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new DetailListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noAbsencesRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("absences")); //$NON-NLS-1$ loadImageAttachmentsList(); return null; } private void loadImageAttachmentsList() { listWidget.clean(); List absenceNotificationList = app.dbutil.selectAbsencesNotificationList(); view.removeAllViews(); if(absenceNotificationList.isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); for (AbsenceNotification absenceNotification : absenceNotificationList) { final DetailListWidgetItem item = new DetailListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); String title = "-"; String line1 = "-"; String line2 = ""; AbsenceType absenceType = app.dbutil.selectAbsenceType(absenceNotification.getAbsenceType()); if (absenceType != null && !absenceType.getAbsenceType().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { title = absenceType.getText(); } line1 = DateTimeUtil.showDate(absenceNotification.getDateFrom()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(absenceNotification.getTimeFrom()) + " to " //$NON-NLS-1$ + DateTimeUtil.showDate(absenceNotification.getDateTo()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(absenceNotification.getTimeTo()); line2 = absenceNotification.getText(); item.setTitleText(title); item.setStringLine1(line1); item.setStringLine2(line2); items.add(item); } listWidget.setOnItemClickListener(createOnItemClickListener(absenceNotificationList)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List absenceNotificationList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { app.injectAndLeaveToForm(AbsenceNotificationNewEditForm.class, new AbsenceNotificationNewEditForm.AbsenceNotificationNewEditFormArguments(absenceNotificationList.get(position))); //$NON-NLS-1$ } }; } protected ApplicationEvent onAddPressed() { return app.leaveToForm(AbsenceNotificationNewEditForm.class, new AbsenceNotificationNewEditForm.AbsenceNotificationNewEditFormArguments(null)); } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.content.DialogInterface.OnDismissListener; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceNotification; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; public class AbsenceNotificationNewEditForm extends DialogForm { private static Log log = LogFactory.getLog(AbsenceNotificationNewEditForm.class); // initialized by the kolibri framework... public static ServiceApplication app; protected ActionCtrl sendButton; private AbsenceNotification absenceNotification; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil actionUtil; private MDSpinner absenceTypeValue; private MDSpinner dateFromValue; private TimeEditText fromText; private MDSpinner dateToValue; private TimeEditText toText; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.EIGHTY_TWO; private Button deleteButton; private boolean isExistTime; private String defaultTime = "00:00"; @Override public void onFormCall(Object argument) { if (argument instanceof AbsenceNotificationNewEditFormArguments) { AbsenceNotificationNewEditFormArguments formArguments = (AbsenceNotificationNewEditFormArguments) argument; absenceNotification = formArguments.getAbsenceNotification(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; actionUtil = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); sendButton = addActionCtrl(false, true, 2, "onSendPressed"); //$NON-NLS-1$ sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout fromLinearLayout = new LinearLayout(context); fromLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; fromLinearLayout.setLayoutParams(leftIconLinearLayoutParams); final LinearLayout formDateLinearLayout = new LinearLayout(context); formDateLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams formDateValueParams = new LinearLayout.LayoutParams(0, 0); formDateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; formDateValueParams.width = 0; formDateValueParams.height = LayoutParams.MATCH_PARENT; formDateValueParams.weight = 0.5f; formDateLinearLayout.setLayoutParams(formDateValueParams); // date dateFromValue = MDSpinner.createDefaultSpinner(formDateLinearLayout, ServiceMessages.getString("dateFrom"), true); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) dateFromValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateFromValue.getUnderline().setLayoutParams(underlineLinearLayout); fromLinearLayout.addView(formDateLinearLayout); dateFromValue.setFocusable(false); dateFromValue.setFocusableInTouchMode(false); dateFromValue.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { showDatePickerDialog(dateFromValue); return true; } }); fromText = TimeEditText.createDefaultEditText(fromLinearLayout,ServiceMessages.getString("timeFrom"), true); //$NON-NLS-1$ LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; fromText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); contentLinearLayout.addView(fromLinearLayout); LinearLayout toLinearLayout = new LinearLayout(context); toLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams toLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); toLinearLayoutParams.gravity = Gravity.CENTER; toLinearLayoutParams.width = LayoutParams.MATCH_PARENT; toLinearLayoutParams.weight = 1; toLinearLayout.setLayoutParams(toLinearLayoutParams); final LinearLayout toDateLinearLayout = new LinearLayout(context); toDateLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams toDateValueParams = new LinearLayout.LayoutParams(0, 0); toDateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; toDateValueParams.width = 0; toDateValueParams.height = LayoutParams.MATCH_PARENT; toDateValueParams.weight = 0.5f; toDateLinearLayout.setLayoutParams(toDateValueParams); // date dateToValue = MDSpinner.createDefaultSpinner(toDateLinearLayout, ServiceMessages.getString("dateTo"), true); //$NON-NLS-1$ dateToValue.setTag("DATUM"); //$NON-NLS-1$ LinearLayout.LayoutParams dateToLinearLayout = (LinearLayout.LayoutParams) dateToValue.getUnderline().getLayoutParams(); dateToLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateToValue.getUnderline().setLayoutParams(dateToLinearLayout); toLinearLayout.addView(toDateLinearLayout); dateToValue.setFocusable(false); dateToValue.setFocusableInTouchMode(false); dateToValue.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { showDatePickerDialog(dateToValue); return true; } }); toText = TimeEditText.createDefaultEditText(toLinearLayout, ServiceMessages.getString("timeTo"), true); //$NON-NLS-1$ toText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); LinearLayout.LayoutParams toInputLayoutParams = new LinearLayout.LayoutParams(0, 0); toInputLayoutParams.gravity = Gravity.CENTER; toInputLayoutParams.width = 0; toInputLayoutParams.height = LayoutParams.MATCH_PARENT; toInputLayoutParams.weight = 0.5f; toText.getParentTextInputLayout().setLayoutParams(toInputLayoutParams); contentLinearLayout.addView(toLinearLayout); LinearLayout absenceTypeLinearLayout = new LinearLayout(context); absenceTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); absenceTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // work type absenceTypeValue = MDSpinner.createDefaultSpinner(absenceTypeLinearLayout, ServiceMessages.getString("absenceType"), true); //$NON-NLS-1$ absenceTypeValue.setTag("ARBEITSART"); //$NON-NLS-1$ absenceTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (position != 0) absenceTypeValue.clearError(); } }); contentLinearLayout.addView(absenceTypeLinearLayout); messages = MDEditText.createDefaultEditText(contentLinearLayout, "description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } private void showDatePickerDialog(final MDSpinner dateValue) { Calendar calendar = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDate(dateValue, year, monthOfYear, dayOfMonth); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.setButton(android.content.DialogInterface.BUTTON_NEGATIVE, ServiceMessages.getString("cancel"), new android.content.DialogInterface.OnClickListener() { //$NON-NLS-1$ @Override public void onClick(android.content.DialogInterface dialog, int which) { if (which == android.content.DialogInterface.BUTTON_NEGATIVE) { dateValue.setEnabled(true); dialog.dismiss(); } } }); datePickerDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(android.content.DialogInterface dialog) { dateValue.setEnabled(true); } }); datePickerDialog.show(); dateValue.setEnabled(false); } private void setDate(MDSpinner dateValue, int year, int monthOfYear, int dayOfMonth) { Calendar calendar = DateTimeUtil.getToday(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); List dateTypeValueList = new ArrayList(); String date = DateTimeUtil.showDate(calendar.getTime()); dateTypeValueList.add(new CustomSpinnerItem(date, date)); dateValue.setContents(dateTypeValueList); // if (absenceNotification == null) { dateValue.setEnabled(true); // } } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("absenceNotification")); //$NON-NLS-1$ resetView(); List absenceTypeValueList = new ArrayList(); List absenceTypes = app.dbutil.selectAbsenceTypeList(); for (AbsenceType absenceType : absenceTypes) { absenceTypeValueList.add(new CustomSpinnerItem((String) absenceType.getAbsenceType(), (String) absenceType.getText())); } absenceTypeValue.setContents(absenceTypeValueList); messages.getText().clear(); Calendar calendar = Calendar.getInstance(); if (absenceNotification == null) { setEnabled(true); setDate(dateFromValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); setDate(dateToValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } else { calendar.setTime(absenceNotification.getDateFrom()); setDate(dateFromValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(absenceNotification.getDateTo()); setDate(dateToValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); setEnabled(false); fromText.setText(DateTimeUtil.showTimeGMT(absenceNotification.getTimeFrom())); fromText.clearFocus(); toText.setText(DateTimeUtil.showTimeGMT(absenceNotification.getTimeTo())); toText.clearFocus(); absenceTypeValue.setSelectionById(absenceNotification.getAbsenceType()); messages.setText(absenceNotification.getText()); } return null; } private void setEnabled(boolean enabled) { sendButton.setEnabled(enabled); Images sendImage = ImagesUtil.Images.SEND_DISABLED_WHITE; if (enabled) { sendImage = ImagesUtil.Images.SEND_WHITE; } sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(sendImage, CommonConstants.Images.IMAGE_DPI))); dateFromValue.setEnabled(enabled); fromText.setEnabled(enabled); dateToValue.setEnabled(enabled); toText.setEnabled(enabled); absenceTypeValue.setEnabled(enabled); messages.setEnabled(enabled); } private void resetView() { absenceTypeValue.clearError(); absenceTypeValue.setSelection(0); dateFromValue.clearError(); fromText.clearError(); fromText.getText().clear(); dateToValue.clearError(); toText.clearError(); toText.getText().clear(); messages.clearError(); messages.getText().clear(); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(AbsenceNotificationListForm.class); } public ApplicationEvent onSendPressed() { boolean error = false; final Date dateFrom = DateTimeUtil.parseDateFromddMMyyyy(dateFromValue.getSelectedName()); final Date timeFrom = DateTimeUtil.parseDateFromHHmm(fromText.getText().toString(), dateFrom); final Date dateTo = DateTimeUtil.parseDateFromddMMyyyy(dateToValue.getSelectedName()); final Date timeTo = DateTimeUtil.parseDateFromHHmm(toText.getText().toString(), dateTo); if (dateFrom == null) { dateFromValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); error = true; } if (dateTo == null) { dateToValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); error = true; } if (timeFrom == null) { fromText.setError(ServiceMessages.getString("pleaseEnterValidTime")); error = true; } if (timeTo == null) { toText.setError(ServiceMessages.getString("pleaseEnterValidTime")); error = true; } if (dateTo.before(dateFrom)) { dateToValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); error = true; } if (timeTo != null && ((timeFrom != null && timeTo.before(timeFrom)) || timeTo.before(dateFrom))) { toText.setError(ServiceMessages.getString("pleaseEnterValidTime")); error = true; } if(absenceTypeValue.isRequired() && absenceTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { absenceTypeValue.setError(Messages.getString("pleaseSelectValue")); error = true; } if (error) { return null; } KeyboardUtil.closeKeyboard(appman, getView()); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("sendAbsenceNotification"), ServiceMessages.getString("reportAbsence"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } AbsenceNotification absenceNotification = new AbsenceNotification(); try { GuidGenerator guidGenerator = new GuidGenerator(); absenceNotification.setGuid(guidGenerator.generate()); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } absenceNotification.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); absenceNotification.setAbsenceDate(DateTimeUtil.getNow().getTime()); absenceNotification.setDateFrom(dateFrom); absenceNotification.setTimeFrom(timeFrom); absenceNotification.setDateTo(dateTo); absenceNotification.setTimeTo(timeTo); absenceNotification.setAbsenceType(absenceTypeValue.getSelectedId()); absenceNotification.setText(messages.getText().toString()); app.dbutil.insertAbsenceNotification(absenceNotification); new RemoteTransactionHandler().runSaveAbsence(absenceNotification.getAbsenceDate(), absenceNotification.getPersonalNumber(), absenceNotification.getGuId()); return app.leaveToForm(AbsenceNotificationListForm.class); } }, false); return null; } public static class AbsenceNotificationNewEditFormArguments { private AbsenceNotification absenceNotification; public AbsenceNotificationNewEditFormArguments(AbsenceNotification absenceNotification) { this.absenceNotification = absenceNotification; } public AbsenceNotification getAbsenceNotification() { return absenceNotification; } public void setAbsenceNotification(AbsenceNotification absenceNotification) { this.absenceNotification = absenceNotification; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ui.LayoutInflater; public class AddressEditSuperForm extends SuperForm implements TextWatcher { private static Log log = LogFactory.getLog(AddressEditSuperForm.class); protected Job job; protected LinearLayout linearLayout; protected LinearLayout emailLinearLayout; protected MDEditText location; protected MDEditText street; protected MDEditText zip; protected MDEditText city; protected MDEditText tel1; protected MDEditText tel2; protected MDEditText fax; protected MDEditText email; protected List emailTextList; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArguments = (JobDetailFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); // Location location = MDEditText.createDefaultEditText(linearLayout, Messages.getString("location"),InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ location.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); // Str./No. street = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("street"),InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ street.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.SIXTY)}); // ZIP zip = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("zip"),InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ zip.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE)}); // City city = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("city"),InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ city.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); // Tel. 1 tel1 = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("tel1"),InputType.TYPE_CLASS_PHONE, false, this); //$NON-NLS-1$ tel1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY)}); // Tel. 2 tel2 = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("tel2"),InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ tel2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY)}); // Fax fax = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("fax"),InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ fax.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY)}); // Email email = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("email"),InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS, false); //$NON-NLS-1$ email.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus && !isEmailValid(email)) { email.setSelected(true); app.showWarningMessageBox(CommonConstants.Regex.EMAIL_VALIDATION_MSG); } } }); emailLinearLayout = new LinearLayout(context); emailLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); emailLinearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(emailLinearLayout); return view; } public void generateEmailContete(int emailSize) { emailTextList.clear(); emailLinearLayout.removeAllViews(); for (int i = 0; i < emailSize; i++) { MDEditText emailText = MDEditText.createDefaultEditText(emailLinearLayout, ServiceMessages.getString("email") + " " + (i+2) ,InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS, false); //$NON-NLS-1$ emailText.setEnabled(false); emailTextList.add(emailText); } } @Override public ApplicationEvent onFormShow() { super.onFormShow(); emailTextList = new ArrayList(); loadData(); return null; } /** * Loads data. */ public void loadData() { //Loads data. } @Override public void onFormReset() { super.onFormReset(); location.getText().clear(); street.getText().clear(); zip.getText().clear(); city.getText().clear(); tel1.getText().clear(); tel2.getText().clear(); fax.getText().clear(); email.getText().clear(); emailTextList.clear(); } @Override public ApplicationEvent onBackPressed() { return appman.getActiveApplication().leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 1)); } @Override protected boolean isValid() { boolean result = true; String errorMessage = Messages.getString("pleaseProvideValue"); //$NON-NLS-1$ if (street.isRequired() && street.getText().toString().trim().isEmpty()) { street.setError(errorMessage); result = false; } if (zip.isRequired() && zip.getText().toString().trim().isEmpty()) { zip.setError(errorMessage); result = false; } if (city.isRequired() && city.getText().toString().trim().isEmpty()) { city.setError(errorMessage); result = false; } if (tel1.isRequired() && tel1.getText().toString().trim().isEmpty()) { tel1.setError(errorMessage); result = false; } if (!email.getText().toString().trim().isEmpty() && !isEmailValid(email)) { result = false; } for (MDEditText editText : emailTextList) { editText.getText().clear(); if (!editText.getText().toString().trim().isEmpty() && !isEmailValid(editText)) { result = false; } } // success return result; } private boolean isEmailValid(MDEditText email) { if (!email.getText().toString().trim().isEmpty()) { Pattern pattern = Pattern.compile(CommonConstants.Regex.EMAIL_VALIDATOR); Matcher matcher = pattern.matcher(email.getText().toString()); if(!matcher.matches()) { email.setError(CommonConstants.Regex.EMAIL_VALIDATION_MSG); return false; } } return true; } @Override public void afterTextChanged(Editable s) { // Do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(street.hasFocus()) street.clearError(); if(zip.hasFocus()) zip.clearError(); if(city.hasFocus()) city.clearError(); if(tel1.hasFocus()) tel1.clearError(); } @Override public void clearErrorMessages() { super.clearErrorMessages(); street.clearError(); zip.clearError(); city.clearError(); tel1.clearError(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.DeliveryStatus; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ArticleListForm.ArticleListFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ArticleDetailForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(ArticleDetailForm.class); public static ServiceApplication app; // don't make this CommonApplication public LinearLayout contentLinearLayout; public MDEditText orderNumberEditText; public MDEditText orderPositionEditText; public AmountEditText amountEditText; public MDEditText unitEditText; public MDEditText stockEditText; public MDEditText priceEditText; public MDEditText deliverDateEditText; public MDEditText deliverEditText; private Article article; private DeliveryList deliveryList; private MaterialMovement materialMovement; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleDetailFormArguments) { ArticleDetailFormArguments formArguments = (ArticleDetailFormArguments) argument; deliveryList = formArguments.getArticle(); materialMovement = formArguments.getMaterialMovement(); article = new Article(formArguments.getMaterialMovement(), formArguments.getArticle()); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); getToolbar().setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } else { loadMaterialsList(numberEditText.getText().toString()); // if(searchView.isMaterialSelected() && selectedMaterial != null || selectedMaterialPerson != null) { //// hideSoftInputFromWindow(); // // } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); } else { nameEditText.clearError(); } } }); contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout orderLinearLayout = new LinearLayout(context); orderLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); orderLinearLayout.setOrientation(LinearLayout.HORIZONTAL); orderNumberEditText = MDEditText.createDefaultEditText(orderLinearLayout, ServiceMessages.getString("orderNo"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ orderNumberEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout.LayoutParams orderNumberInputLayoutParams = new LinearLayout.LayoutParams(0, 0); orderNumberInputLayoutParams.gravity = Gravity.CENTER; orderNumberInputLayoutParams.width = 0; orderNumberInputLayoutParams.height = LayoutParams.MATCH_PARENT; orderNumberInputLayoutParams.weight = 0.3f; orderNumberEditText.getParentTextInputLayout().setLayoutParams(orderNumberInputLayoutParams); orderPositionEditText = MDEditText.createDefaultEditText(orderLinearLayout, ServiceMessages.getString("orderPosition"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ orderPositionEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout.LayoutParams orderPositionInputLayoutParams = new LinearLayout.LayoutParams(0, 0); orderPositionInputLayoutParams.gravity = Gravity.CENTER; orderPositionInputLayoutParams.width = 0; orderPositionInputLayoutParams.height = LayoutParams.MATCH_PARENT; orderPositionInputLayoutParams.weight = 0.3f; orderPositionEditText.getParentTextInputLayout().setLayoutParams(orderPositionInputLayoutParams); contentLinearLayout.addView(orderLinearLayout); LinearLayout detailLinearLayout = new LinearLayout(context); detailLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); detailLinearLayout.setOrientation(LinearLayout.HORIZONTAL); amountEditText = AmountEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("amount"), true); //$NON-NLS-1$ amountEditText.setTag("AMOUNT"); //$NON-NLS-1$ amountEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SEVEN) }); LinearLayout.LayoutParams amountInputLayoutParams = new LinearLayout.LayoutParams(0, 0); amountInputLayoutParams.gravity = Gravity.CENTER; amountInputLayoutParams.width = 0; amountInputLayoutParams.height = LayoutParams.MATCH_PARENT; amountInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(amountInputLayoutParams); // Unit unitEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("unit"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ unitEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); unitEditText.setTag("UNIT"); //$NON-NLS-1$ unitEditText.setEnabled(false); LinearLayout.LayoutParams unitInputLayoutParams = new LinearLayout.LayoutParams(0, 0); unitInputLayoutParams.gravity = Gravity.LEFT; unitInputLayoutParams.width = 0; unitInputLayoutParams.height = LayoutParams.MATCH_PARENT; unitInputLayoutParams.weight = 0.2f; unitEditText.getParentTextInputLayout().setLayoutParams(unitInputLayoutParams); stockEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("duration"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ stockEditText.setTag("STOCK"); //$NON-NLS-1$ stockEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); stockEditText.setEnabled(false); LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.LEFT; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; stockEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); priceEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("price"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ priceEditText.setTag("PRICE"); //$NON-NLS-1$ priceEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT) }); priceEditText.setEnabled(false); priceEditText.setDirectionRight(true); LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); priceInputLayoutParams.gravity = Gravity.CENTER; priceInputLayoutParams.width = 0; priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; priceInputLayoutParams.weight = 0.2f; priceEditText.getParentTextInputLayout().setLayoutParams(priceInputLayoutParams); contentLinearLayout.addView(detailLinearLayout); LinearLayout deliverLinearLayout = new LinearLayout(context); deliverLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deliverLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deliverDateEditText = MDEditText.createDefaultEditText(deliverLinearLayout, ServiceMessages.getString("deliverDate"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ deliverDateEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.ELEVEN) }); LinearLayout.LayoutParams deliverDateInputLayoutParams = new LinearLayout.LayoutParams(0, 0); deliverDateInputLayoutParams.gravity = Gravity.CENTER; deliverDateInputLayoutParams.width = 0; deliverDateInputLayoutParams.height = LayoutParams.MATCH_PARENT; deliverDateInputLayoutParams.weight = 0.15f; deliverDateEditText.getParentTextInputLayout().setLayoutParams(deliverDateInputLayoutParams); deliverEditText = MDEditText.createDefaultEditText(deliverLinearLayout, ServiceMessages.getString("delivered"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, true); //$NON-NLS-1$ deliverEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SEVEN) }); LinearLayout.LayoutParams deliverInputLayoutParams = new LinearLayout.LayoutParams(0, 0); deliverInputLayoutParams.gravity = Gravity.CENTER; deliverInputLayoutParams.width = 0; deliverInputLayoutParams.height = LayoutParams.MATCH_PARENT; deliverInputLayoutParams.weight = 0.15f; deliverEditText.getParentTextInputLayout().setLayoutParams(deliverInputLayoutParams); contentLinearLayout.addView(deliverLinearLayout); addContentLinearLayout(contentLinearLayout); nameEditText.setEnabled(false); numberEditText.setEnabled(false); orderNumberEditText.setEnabled(false); orderPositionEditText.setEnabled(false); amountEditText.setEnabled(false); deliverDateEditText.setEnabled(false); searchView.setVisibility(View.INVISIBLE); // searchView.setOnSearchClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // saveButton.setVisible(false); // } // }); // searchView.setOnCloseListener(new OnCloseListener() { // // @Override // public boolean onClose() { // saveButton.setVisible(true); // return false; // } // }); saveButton.setTitle(ServiceMessages.getString("save")); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); resetView(); setShowScanNumber(false); if (deliveryList != null) { // Article list setEnableSaveButton(false); // amountEditText.setEnabled(true); // Active: Only if ZKDMOBFZGDELVRY.LGORT_TO = and, if delivered, ZKDMOBFZGDELVRY.KNZDLVRY = T, G log.info("delivery to " + article.getTo() + " deliver status " + article.getStatus().getCode()); if (article.getTo().equalsIgnoreCase(app.dbutil.getUser().getWarehouseNumber()) && (article.getStatus().isPART_DELIVERED() || article.getStatus().isDELIVERED())) { setEnableSaveButton(true); } } else { // push message //Active and shown: Only if ZKDMOBFZGMBEW.GUID = if(article.getGuid().isEmpty()) { getToolbar().setNavigationIcon(getBitmanDrawable(app.imagesUtil.getImage(Images.BACK_WHITE_DISABLED, CommonConstants.Images.IMAGE_DPI))); } else { getToolbar().setNavigationIcon(getBitmanDrawable(app.imagesUtil.getImage(Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI))); } } setFormTitle(ServiceMessages.getString("incomingArticleTitle")); nameEditText.setRequired(false); numberEditText.setRequired(false); nameEditText.getParentTextInputLayout().setHint(ServiceMessages.getString("articleName")); numberEditText.getParentTextInputLayout().setHint(ServiceMessages.getString("articleNumber")); deliverEditText.setRequired(false); deliverEditText.setEnabled(false); log.info("article from " + article.getWarehouse() + " status " + article.getStatus().getCode()); if (article.getWarehouse().equalsIgnoreCase("HLG") && !article.getStatus().isINITIAL()) { //Active: Only if ZKDMOBFZGDELVRY.LGKNZ = HLG and ZKDMOBFZGDELVRY.KNZDLVRY = O, T or G deliverEditText.setEnabled(true); deliverEditText.setRequired(true); } log.info("article OrderNumber " + article.getOrderNumber()); log.info("article Position " + article.getOrderPosition()); nameEditText.setText(article.getMaterialName()); numberEditText.setText(article.getMaterialNumber()); orderNumberEditText.setText(article.getOrderNumber()); orderPositionEditText.setText(article.getOrderPosition() + ""); log.info("EntryCount " + article.getEntryCount()); amountEditText.setText(article.getEntryCount()); unitEditText.setText(article.getEntryUnit()); VehicleInventory vehicleInventory = app.dbutil.selectVehicleInventoryByMatNr(article.getMaterialNumber()); stockEditText.setText(vehicleInventory == null ? "":vehicleInventory.getStockOfMaterial()); deliverDateEditText.setText(DateTimeUtil.showDate(article.getDate())); deliverEditText.setText(article.getEntryCount()); deliverEditText.setEnabled(true); Material material = app.dbutil.selectMaterialByMatNo(article.getMaterialNumber()); if (material != null) { priceEditText.setText(material.getNewPrice()); } return null; } @Override protected void resetView() { super.resetView(); orderNumberEditText.clearError(); orderNumberEditText.getText().clear(); orderPositionEditText.clearError(); orderPositionEditText.getText().clear(); priceEditText.clearError(); amountEditText.clearError(); stockEditText.clearError(); unitEditText.clearError(); priceEditText.getText().clear(); amountEditText.getText().clear(); stockEditText.getText().clear(); unitEditText.getText().clear(); deliverEditText.clearError(); deliverEditText.getText().clear(); } @Override public ApplicationEvent onBackPressed() { if(deliveryList == null) { return null; } return app.leaveToForm(ArticleListForm.class); } @Override protected ApplicationEvent onSavePressed() { KeyboardUtil.closeKeyboard(appman, getView()); if (isValid()) { onSave(); } return null; } protected boolean isValid() { boolean result = true; return result; } @Override protected boolean onSave() { setEnableSaveButton(false); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (materialMovement == null) { materialMovement = new MaterialMovement(); materialMovement.setGuid(article.getGuid()); materialMovement.setOrderNumber(article.getOrderNumber()); materialMovement.setOrderPosition(article.getOrderPosition()); } int pernr = app.dbutil.getUser().getPersonalNumber(); materialMovement.setPersonalNumber(pernr); materialMovement.setPersonalNumberConfirmed(pernr); materialMovement.setMaterialNumber(numberEditText.getText().toString()); materialMovement.setEntryUnit(unitEditText.getText().toString()); materialMovement.setEntryCount(deliverEditText.getText().toString()); if(new RemoteTransactionHandler().runConfirmMaterialMoveMent(materialMovement)) { if(new RemoteTransactionHandler().runGetDeliveryList(pernr, monitor)) { // has been deleted after confirm } } return null; } @Override protected void runOnUIThread() { // need to wait until transaction success (data in table delayed) DeliveryList selectedArticle = app.dbutil.selectArticleByMatnr(article.getOrderNumber(), article.getMaterialNumber()); if (selectedArticle != null && !selectedArticle.getEntryCount().equalsIgnoreCase(materialMovement.getEntryCount())) { selectedArticle.setEntryCount(materialMovement.getEntryCount()); app.dbutil.updateArticleEntryCount(selectedArticle.getOrderNumber(), selectedArticle.getMaterialNumber(), selectedArticle.getEntryCount()); } app.injectAndLeaveToForm(ArticleListForm.class, new ArticleListFormArgument()); } }; return false; } public static class ArticleDetailFormArguments { private DeliveryList article; private MaterialMovement materialMovement; public ArticleDetailFormArguments(DeliveryList article) { this.article = article; } public ArticleDetailFormArguments(MaterialMovement materialMovement) { this.materialMovement = materialMovement; } public DeliveryList getArticle() { return this.article; } public MaterialMovement getMaterialMovement() { return this.materialMovement; } } private class Article { private MaterialMovement materialMovement; private DeliveryList deliveryList; private Material material; Article(MaterialMovement materialMovement, DeliveryList deliveryList) { this.materialMovement = materialMovement; this.deliveryList = deliveryList; if (materialMovement != null) { material = app.dbutil.selectMaterialByMatNo(materialMovement.getMaterialNumber()); } } public String getGuid() { return materialMovement != null ? materialMovement.getGuid():deliveryList.getGuid(); } public String getOrderNumber() { return materialMovement != null ? materialMovement.getOrderNumber():deliveryList.getOrderNumber(); } public int getOrderPosition() { return materialMovement != null ? materialMovement.getOrderPosition() : deliveryList.getOrderPosition(); } public int getPersonalNumber() { return materialMovement != null ? materialMovement.getPersonalNumber():deliveryList.getPersonalNumber(); } public String getMaterialNumber() { return materialMovement != null ? materialMovement.getMaterialNumber():deliveryList.getMaterialNumber(); } public String getMaterialName() { return materialMovement != null ? material.getMaterialShortText():deliveryList.getMaterialName(); } public String getFrom() { return materialMovement != null ? materialMovement.getFrom():deliveryList.getFrom(); } public String getTo() { return materialMovement != null ? materialMovement.getTo():deliveryList.getTo(); } public Date getDate() { return materialMovement != null ? new Date():deliveryList.getDate(); } public String getEntryCount() { return materialMovement != null ? materialMovement.getEntryCount():deliveryList.getEntryCount(); } public String getEntryUnit() { return materialMovement != null ? materialMovement.getEntryUnit():deliveryList.getEntryUnit(); } public DeliveryStatus getStatus() { return materialMovement != null ? new DeliveryStatus():deliveryList.getStatus(); } public String getWarehouse() { return materialMovement != null ? "":deliveryList.getWarehouse(); } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.ReceiptOfGoods; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDAutoComplete; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ArticleIncomningForm extends ArticleSearchForm { private static Log log = LogFactory.getLog(ArticleIncomningForm.class); public static ServiceApplication app; public MDSpinner reasonValue; public MDAutoComplete fromInventoryAutoComplete; private Material selectedMaterial; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleIncomingFormFormArguments) { ArticleIncomingFormFormArguments formArguments = (ArticleIncomingFormFormArguments) argument; } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); reasonValue = MDSpinner.createDefaultSpinner(contentLinearLayout, ServiceMessages.getString("reasongIncomingArticle"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { reasonValue.clearError(); } }); fromInventoryAutoComplete = MDAutoComplete.createDefaultAutoCompleteText(contentLinearLayout, ServiceMessages.getString("fromImventory"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true); fromInventoryAutoComplete.setTag("INVENTORY"); //$NON-NLS-1$ return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("incomingArticleWithoutListEntry")); loadData(); return null; } @Override public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(queryText, queryText); for (Material matPart : materialList) { searchView.getSuggessionItemList().add(new SuggessionItem(matPart.getMaterialNumber(), matPart.getMaterialShortText())); } stockEditText.setText("0"); if (materialList.size() > 0 && materialList.size() == 1) { // Exactly found an article from the StammMat if (materialList.size() == 1) { selectedMaterial = materialList.get(0); } } if (selectedMaterial != null) { unitEditText.setText(selectedMaterial.getUnit()); List vehicleInventories = app.dbutil.selectVehicleInventoryListByMatNrAndMatName(selectedMaterial.getMaterialNumber(), selectedMaterial.getMaterialShortText()); if (vehicleInventories.size() > 0) { VehicleInventory vehicleInventory = vehicleInventories.get(0); stockEditText.setText(vehicleInventory.getStockOfMaterial()); } priceEditText.setText(selectedMaterial.getNewPrice()); // sizeEditText.setText(selectedMaterial.getSize()); // expressCheckBox.setChecked(false); saveButton.setVisible(true); } } @Override protected void loadData() { super.loadData(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); fillResonCombo(); fillInventoryCombo(); } private void fillResonCombo() { List receiptOfGoodValueList = new ArrayList(); List receiptOfGoods = app.dbutil.selectReceiptOfGoodsList(); for (ReceiptOfGoods receiptOfGood : receiptOfGoods) { receiptOfGoodValueList.add(new CustomSpinnerItem((String) receiptOfGood.getCode(), receiptOfGood.getText())); } reasonValue.setContents(receiptOfGoodValueList); } private void fillInventoryCombo() { List receiptOfGoodValueList = new ArrayList(); List inventoryList = app.dbutil.selectExternalInventoryList(); for (Inventory inventory : inventoryList) { receiptOfGoodValueList.add(new CustomSpinnerItem((String) inventory.getWarehouseNumber(), inventory.getName())); } fromInventoryAutoComplete.setContents(receiptOfGoodValueList); } @Override protected void resetView() { super.resetView(); reasonValue.setSelection(0); reasonValue.clearError(); fromInventoryAutoComplete.setSelection(0); fromInventoryAutoComplete.clearError(); } protected boolean isValid() { boolean result = super.isValid(); String errorMessage = Messages.getString("pleaseProvideValue"); if (reasonValue.isRequired() && reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { reasonValue.setError(errorMessage); result = false; } log.info("inventory " + fromInventoryAutoComplete.getSelectedId()); if (fromInventoryAutoComplete.isRequired() && (fromInventoryAutoComplete.getEditableText().toString().isEmpty() || fromInventoryAutoComplete.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) || fromInventoryAutoComplete.getSelectedId().equalsIgnoreCase("0000"))) { fromInventoryAutoComplete.setError(errorMessage); result = false; } return result; } @Override protected boolean onSave() { super.onSave(); materialMovement.setReceiptOfGoods(reasonValue.getSelectedId()); materialMovement.setFrom(fromInventoryAutoComplete.getSelectedId()); materialMovement.setTo(app.dbutil.getUser().getWarehouseNumber()); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(new RemoteTransactionHandler().runSaveMaterialMoveMent(materialMovement)) { } return onBackPressed(); } }; return false; } public static class ArticleIncomingFormFormArguments { public ArticleIncomingFormFormArguments() { } } } package ch.mfiles.kaba.kolibri.service.forms; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnCloseListener; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.RelativeLayout.LayoutParams; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ArticleDetailForm.ArticleDetailFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ArticleListForm extends SuperForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(ArticleListForm.class); private SearchView searchView; private TextView inventoryNameText; private String queryText = ""; private ActionCtrl outgoingAction; private ActionCtrl searchAction; private ActionCtrl contextMenuAction; private RelativeLayout mainView; protected DefaultListWidget listWidget; private LinearLayout emptyMessageView; private AHBottomNavigation bottomNavigation; private int bottomNavigationTabSelected; private Inventory inventory; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleListFormArgument) { ArticleListFormArgument formArgument = (ArticleListFormArgument) argument; } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create SearchView searchView = new SearchView(context); searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END)); searchView.setOnQueryTextListener(this); searchView.setOnCloseListener(new OnCloseListener() { @Override public boolean onClose() { closeSearchView(); return false; } }); // toolbar.addView(searchView); // hide runtime menu items setRuntimeMenuHidden(true); // checkout article action outgoingAction = addActionCtrl(false, true, 0, "actionOutgoing"); //$NON-NLS-1$ outgoingAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SHOPPING_CART_WHITE, CommonConstants.Images.IMAGE_DPI))); // create search action searchAction = addActionCtrl(false, true, 0, "actionSearch"); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); contextMenuAction = addActionCtrl(false, true, 0, "actionCcontextMenu"); //$NON-NLS-1$ contextMenuAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.MENU_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); // contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout inventoryNameLayout = new LinearLayout(context); inventoryNameLayout.setOrientation(LinearLayout.VERTICAL); inventoryNameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); inventoryNameLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); inventoryNameText = CommonUtilForm.getTextView(context, ""); inventoryNameText.setTextColor(Color.WHITE); inventoryNameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); inventoryNameText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; textViewParams.bottomMargin = LayoutUtils.DEFAULT_MAX_MARGIN; inventoryNameText.setLayoutParams(textViewParams); inventoryNameLayout.addView(inventoryNameText); contentLinearLayout.addView(inventoryNameLayout); RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget = new DefaultListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); LinearLayout.LayoutParams noDataTextViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); noDataTextViewParams.gravity = Gravity.CENTER; noDataTextViewParams.topMargin = 20; textView.setLayoutParams(noDataTextViewParams); emptyMessageView.addView(textView); mainFormView.addView(emptyMessageView); contentLinearLayout.addView(mainFormView); mainView.addView(contentLinearLayout); mainView.addView(createBottomNavigation(context)); mainView.addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { boolean widthChanged = (right - left) != (oldRight - oldLeft); if (widthChanged) { // width has changed } boolean heightChanged = (bottom - top) != (oldBottom - oldTop); if (heightChanged) { // height has changed loadTable(); } } }); view.addView(mainView); return view; } private View createBottomNavigation(Context context) { bottomNavigation = new AHBottomNavigation(context); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); bottomNavigation.setLayoutParams(params); // Create items AHBottomNavigationItem item1 = new AHBottomNavigationItem(ServiceMessages.getString("transit") , getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.TRUCK_WHITE, CommonConstants.Images.IMAGE_DPI))); AHBottomNavigationItem item3 = new AHBottomNavigationItem(ServiceMessages.getString("open") , getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DONE_WHITE, CommonConstants.Images.IMAGE_DPI))); // Add items bottomNavigation.addItem(item1); // bottomNavigation.addItem(item2); bottomNavigation.addItem(item3); // Change colors bottomNavigation.setAccentColor(Color.parseColor("#00796B")); //$NON-NLS-1$ bottomNavigation.setInactiveColor(Color.parseColor("#757575")); //$NON-NLS-1$ // Manage titles bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW); // Set listener bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() { @Override public boolean onTabSelected(final int position, boolean wasSelected) { bottomNavigationTabSelected = position; loadTable(); return true; } }); return bottomNavigation; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("vehicleInventory")); closeSearchView(); inventory = app.dbutil.selectInventoryByPersonalNrAndWarehouseNr(); inventoryNameText.setText(ServiceMessages.getString("nameOfInventory") + " " + (inventory == null? "-":inventory.getName())); inventoryNameText.setText(ServiceMessages.getString("nameOfInventory") + " " + (inventory == null? "-":inventory.getName() + " - " + ServiceMessages.getString("incomingArticle"))); bottomNavigation.refresh(); bottomNavigation.setCurrentItem(0); app.messageUtil.showContinueMessage(); // need to wait until transaction success (data in table delayed) new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { loadTable(); } }; return null; } private void closeSearchView() { getToolbar().removeView(searchView); hideSoftInputFromWindow(); setVisibleAction(true); queryText = ""; } private void loadTable() { // bottom navigation selected // bottomNavigationTabSelected // bottomNavigation: 0 -> Transit , 1 -> Open List articleList = app.dbutil.selectArticleList(bottomNavigationTabSelected == 1); int listWidgetHeight = view.getHeight() - inventoryNameText.getHeight() - bottomNavigation.getHeight(); if(listWidget.getHeight() > 0 && listWidget.getHeight() != listWidgetHeight) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, listWidgetHeight); listWidget.setLayoutParams(params); } ((RelativeLayout.LayoutParams) listWidget.getLayoutParams()).height -= ((LinearLayout.LayoutParams) inventoryNameText.getLayoutParams()).topMargin; ((RelativeLayout.LayoutParams) listWidget.getLayoutParams()).height -= ((LinearLayout.LayoutParams) inventoryNameText.getLayoutParams()).bottomMargin; listWidget.clean(); ArrayList items = new ArrayList(); // if (articleList.isEmpty()) { // DeliveryList deliveryList = new DeliveryList(); // deliveryList.setGuid("7F000001018E2B1A192467BF0BEA31B6"); // deliveryList.setWarehouse("AAA"); // deliveryList.setMaterialNumber("45-0645-327"); // deliveryList.setMaterialName("Antrieb DBX"); // deliveryList.setEntryCount("3.000"); // deliveryList.setEntryUnit("STK"); // deliveryList.setStatus("O"); // articleList.add(deliveryList); // // DeliveryList deliveryList2 = new DeliveryList(); // deliveryList2.setGuid("7F000001018E2B1A192467BF0BEA75B6"); // deliveryList2.setWarehouse("AAA"); // deliveryList2.setMaterialNumber("45-0645-867"); // deliveryList2.setMaterialName("Antrieb DHX"); // deliveryList2.setEntryCount("4.000"); // deliveryList2.setEntryUnit("STK"); // deliveryList2.setStatus("T"); // articleList.add(deliveryList2); // // DeliveryList deliveryList3 = new DeliveryList(); // deliveryList3.setGuid("7F000001018E2B1A192467BF0BE8431B6"); // deliveryList3.setWarehouse("AAA"); // deliveryList3.setMaterialNumber("45-07545-327"); // deliveryList3.setMaterialName("Antrieb SBX"); // deliveryList3.setEntryCount("1.000"); // deliveryList3.setEntryUnit("STK"); // deliveryList3.setStatus("G"); // articleList.add(deliveryList3); // // DeliveryList deliveryList4 = new DeliveryList(); // deliveryList4.setGuid("7F000001018E2B1A642467BF0BE8431B6"); // deliveryList4.setWarehouse("AAA"); // deliveryList4.setMaterialNumber("45-0t545-327"); // deliveryList4.setMaterialName("Bedix SBX"); // deliveryList4.setEntryCount("1.000"); // deliveryList4.setEntryUnit("STK"); // articleList.add(deliveryList4); // // DeliveryList deliveryList5 = new DeliveryList(); // deliveryList5.setGuid("7F000001018E2B1A642467GF0BE8431B6"); // deliveryList5.setWarehouse("AAA"); // deliveryList5.setMaterialNumber("45-0t945-727"); // deliveryList5.setMaterialName("Bedix SBX"); // deliveryList5.setEntryCount("1.000"); // deliveryList5.setEntryUnit("STK"); // articleList.add(deliveryList5); // // DeliveryList deliveryList6 = new DeliveryList(); // deliveryList6.setGuid("7F00000101VD2B1A192467BF0BE8431B6"); // deliveryList6.setWarehouse("AAA"); // deliveryList6.setMaterialNumber("45-07345-367"); // deliveryList6.setMaterialName("Antrieb SBX"); // deliveryList6.setEntryCount("1.000"); // deliveryList6.setEntryUnit("STK"); // deliveryList6.setStatus("G"); // articleList.add(deliveryList6); // // // DeliveryList deliveryList7 = new DeliveryList(); // deliveryList7.setGuid("7F000001018E2B1A38246FDF0BEA75B6"); // deliveryList7.setWarehouse("AAA"); // deliveryList7.setMaterialNumber("45-0645-867"); // deliveryList7.setMaterialName("Antrieb DHX"); // deliveryList7.setEntryCount("4.000"); // deliveryList7.setEntryUnit("STK"); // deliveryList7.setStatus("T"); // articleList.add(deliveryList7); // // DeliveryList deliveryList8 = new DeliveryList(); // deliveryList8.setGuid("7F00000101742B1A195667BF0BE8431B6"); // deliveryList8.setWarehouse("AAA"); // deliveryList8.setMaterialNumber("45-06545-387"); // deliveryList8.setMaterialName("Antrieb SBX"); // deliveryList8.setEntryCount("1.000"); // deliveryList8.setEntryUnit("STK"); // deliveryList8.setStatus("G"); // articleList.add(deliveryList8); // // DeliveryList deliveryList9 = new DeliveryList(); // deliveryList9.setGuid("7F03064101742B1A295668BF0BE8431B6"); // deliveryList9.setWarehouse("AAA"); // deliveryList9.setMaterialNumber("45-36515-387"); // deliveryList9.setMaterialName("Antrieb SBX"); // deliveryList9.setEntryCount("1.000"); // deliveryList9.setEntryUnit("STK"); // deliveryList9.setStatus("G"); // articleList.add(deliveryList9); // } for (DeliveryList article : articleList) { final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setData(article); item.setStatusColor(article.getStatusColor()); // item.setStatusType(msg.getConfirmedMsg()); item.isShowCheckBox(false); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(article.getMaterialName()); item.setStringLine1(ServiceMessages.getString("materialNumber") + ": " + article.getMaterialNumber()); // ZKDMOBFZGDELVRY.ENTRY_UOM> item.setStringLine2(ServiceMessages.getString("orderedArticles") + ": " + article.getEntryCount() + " " + article.getEntryUnit() ); items.add(item); } if (items.isEmpty()) { emptyMessageView.setVisibility(View.VISIBLE); } else { emptyMessageView.setVisibility(View.GONE); listWidget.setOnItemClickListener(createOnItemClickListener()); listWidget.addItems(items); } if (searchView.getVisibility() == View.VISIBLE) { filter(queryText); } } private OnItemClickListener createOnItemClickListener() { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { DeliveryList deliveryListClicked = (DeliveryList) ((DefaultListWidgetItem) listWidget.getAdapter().getItem(position)).getData(); app.injectAndLeaveToForm(ArticleDetailForm.class, new ArticleDetailFormArguments(deliveryListClicked)); } }; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } @Override public boolean onQueryTextSubmit(String queryText) { filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { filter(queryText); return true; } private void filter(String queryText) { this.queryText = queryText; if (searchView.getVisibility() == View.VISIBLE) { listWidget.getAdapter().getFilter().filter(queryText); } } private void setVisibleAction(boolean visible) { outgoingAction.setVisible(visible); contextMenuAction.setVisible(visible); searchAction.setVisible(visible); searchView.setVisibility(visible ? View.INVISIBLE:View.VISIBLE); } protected ApplicationEvent actionOutgoing() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { Person crrentUser = app.dbutil.getUser(); new RemoteTransactionHandler().runGetInventryStock(crrentUser.getPersonalNumber(), crrentUser.getWarehouseNumber(), crrentUser.getLanguage()); return app.leaveToForm(ArticleOutgoingForm.class); } }; return null; } protected ApplicationEvent actionSearch() { KeyboardUtil.closeKeyboard(appman, getView()); getToolbar().addView(searchView); // hide menu setVisibleAction(false); searchView.setIconified(false); return null; } protected ApplicationEvent actionCcontextMenu() { PopupMenu popupMenu = new PopupMenu(context, getToolbar()); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); addPopupMenuItem(popupMenu, ServiceConstants.Index.ONE, ServiceMessages.getString("articleScan"), ImagesUtil.Images.CAMERA_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.TWO, ServiceMessages.getString("incomingArticle"), ImagesUtil.Images.SHOPPING_CART_ADD_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.THREE, ServiceMessages.getString("outgoingArticlesList"), ImagesUtil.Images.SHOPPING_CART_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.FOUR, ServiceMessages.getString("inventoryStock"), ImagesUtil.Images.TRUCK_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.FIVE, ServiceMessages.getString("inventoryInformations"), ImagesUtil.Images.INFO); //forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem); return true; } }); popupMenu.show(); return null; } private void handleMenuItemClicked(final MenuItem menuItem) { new AsyncTask(this) { private String barcode; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (menuItem.getItemId() == ServiceConstants.Index.ONE) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(ArticleListForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } else if (menuItem.getItemId() == ServiceConstants.Index.TWO) { // Nav to Incoming article without list entry return app.leaveToForm(ArticleIncomningForm.class); } else if (menuItem.getItemId() == ServiceConstants.Index.THREE) { // Nav to List of outgoing articles (booked) return app.leaveToForm(ArticleOutgoingListForm.class); } else if (menuItem.getItemId() == ServiceConstants.Index.FOUR) { // Nav to Inventory Stock return app.leaveToForm(InventoryStockForm.class); } else if (menuItem.getItemId() == ServiceConstants.Index.FIVE) { // Nav to Inventory informations return app.leaveToForm(InventoryInformationsForm.class, new InventoryInformationsForm.FormArguments(new Inventory())); } return null; } @Override public void runOnUIThread() { if (menuItem.getItemId() == ServiceConstants.Index.ONE) { if (barcode != null && !barcode.isEmpty()) { actionSearch(); System.out.println("barcode " + barcode); String matNoQuery = StringUtil.getMaterialNoFromScan(barcode.trim()); System.out.println("matNoQuery " + matNoQuery); searchView.setQuery(matNoQuery, true); } } return; } }; } private void addPopupMenuItem(PopupMenu popupMenu, int index, String label, Images image) { popupMenu.getMenu() .add(Menu.NONE, index, Menu.NONE, label) .setIcon(getBitmanDrawable(app.imagesUtil.getImage(image, CommonConstants.Images.IMAGE_DPI))); } public static class ArticleListFormArgument { private int tabSelected; private Date selectedDate; public int getTabSelected() { return tabSelected; } protected ArticleListFormArgument() { } public ArticleListFormArgument(Date selectedDate, int tabSelect) { this.tabSelected = tabSelect; this.selectedDate = selectedDate; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public Date getDate() { return this.selectedDate; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDAutoComplete; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ArticleOutgoingForm extends ArticleSearchForm { private static Log log = LogFactory.getLog(ArticleOutgoingForm.class); public static ServiceApplication app; public MDAutoComplete inventoryAutoComplete; public MDEditText codeReturnInventoryEditText; public MDEditText reasonReturnDeliveryEditText; private VehicleInventory selectedVehicleInventory; private DeliveryList deliveryList; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleOutgoingFormArguments) { ArticleOutgoingFormArguments formArguments = (ArticleOutgoingFormArguments) argument; deliveryList = formArguments.getDeliveryList(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && !searchView.getQueryHint().toString().equalsIgnoreCase(Messages.getString("search"))) { searchView.setQueryHint(Messages.getString("search")); } } }); inventoryAutoComplete = MDAutoComplete.createDefaultAutoCompleteText(contentLinearLayout, ServiceMessages.getString("newInventory"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true); inventoryAutoComplete.setTag("INVENTORY"); //$NON-NLS-1$ LinearLayout codeReturnInventoryLinearLayout = new LinearLayout(context); codeReturnInventoryLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams codeReturnInventoryLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); codeReturnInventoryLinearLayoutParams.gravity = Gravity.CENTER; codeReturnInventoryLinearLayoutParams.width = LayoutParams.MATCH_PARENT; codeReturnInventoryLinearLayoutParams.height = LayoutParams.MATCH_PARENT; codeReturnInventoryLinearLayoutParams.weight = 1; codeReturnInventoryLinearLayout.setLayoutParams(codeReturnInventoryLinearLayoutParams); codeReturnInventoryEditText = MDEditText.createDefaultEditText(codeReturnInventoryLinearLayout, ServiceMessages.getString("codeReturnDelivery"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ codeReturnInventoryEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); LinearLayout.LayoutParams codeReturnInventoryLayoutParams = new LinearLayout.LayoutParams(0, 0); codeReturnInventoryLayoutParams.gravity = Gravity.CENTER; codeReturnInventoryLayoutParams.width = 0; codeReturnInventoryLayoutParams.height = LayoutParams.MATCH_PARENT; codeReturnInventoryLayoutParams.weight = 0.9f; codeReturnInventoryEditText.getParentTextInputLayout().setLayoutParams(codeReturnInventoryLayoutParams); codeReturnInventoryEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { codeReturnInventoryEditText.clearError(); if (codeReturnInventoryEditText.getText().toString().isEmpty()) { reasonReturnDeliveryEditText.setRequired(false); reasonReturnDeliveryEditText.clearError(); } else { reasonReturnDeliveryEditText.setRequired(true); } } }); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.1f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { private String barcode = ""; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { if (!barcode.isEmpty()) { codeReturnInventoryEditText.setInputType(InputType.TYPE_CLASS_TEXT); codeReturnInventoryEditText.setText(barcode); codeReturnInventoryEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } } }; } }); cameraLinearLayout.addView(gridImageView); codeReturnInventoryLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(codeReturnInventoryLinearLayout); reasonReturnDeliveryEditText = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("reasonReturnDelivery"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ reasonReturnDeliveryEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY) }); reasonReturnDeliveryEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { reasonReturnDeliveryEditText.clearError(); } }); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("outgoingArticle")); searchView.setIconified(true); if (deliveryList != null) { searchView.setVisibility(View.INVISIBLE); loadMaterialsList(deliveryList.getMaterialNumber()); if (selectedVehicleInventory == null) { nameEditText.setText(deliveryList.getMaterialName()); numberEditText.setText(deliveryList.getMaterialNumber()); unitEditText.setText(deliveryList.getEntryUnit()); stockEditText.setText(deliveryList.getEntryCount()); Material material = app.dbutil.selectMaterialByMatNo(deliveryList.getMaterialNumber()); priceEditText.setText(material==null? "":material.getNewPrice()); inventoryAutoComplete.setSelectionById(deliveryList.getTo()); saveButton.setVisible(true); // nameEditText.setTag(deliveryList.getMaterialName()); // numberEditText.setTag(deliveryList.getMaterialNumber()); // // unitEditText.setText(deliveryList.getEntryUnit()); // stockEditText.setText(deliveryList.getEntryCount()); // Material material = app.dbutil.selectMaterialByMatNo(deliveryList.getMaterialNumber()); // // priceEditText.setText(material==null? "":material.getNewPrice()); // saveButton.setVisible(true); } } else { searchView.setVisibility(View.VISIBLE); } return null; } @Override public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List vehicleInventoryList = app.dbutil.selectVehicleInventoryListByMatNrAndMatName(queryText, queryText); for (VehicleInventory vehicleInventory : vehicleInventoryList) { searchView.getSuggessionItemList().add(new SuggessionItem(vehicleInventory.getMaterialNumber(), vehicleInventory.getMaterialName())); } if (vehicleInventoryList.size() > 0 && vehicleInventoryList.size() == 1) { // Exactly found an article from the StammMat if (vehicleInventoryList.size() == 1) { selectedVehicleInventory = vehicleInventoryList.get(0); } } if (selectedVehicleInventory != null) { if (nameEditText.getText().toString().isEmpty()) { nameEditText.setText(selectedVehicleInventory.getMaterialName()); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(selectedVehicleInventory.getMaterialNumber()); } unitEditText.setText(selectedVehicleInventory.getUnit()); stockEditText.setText(selectedVehicleInventory.getStockOfMaterial()); saveButton.setVisible(true); //article is in the inventory (ZKDMOBFZLGSYNC and/or ZKDMOBDELVRYLIST) but NOT in the masterdata (ZDKMOBMAT). Material material = app.dbutil.selectMaterialByMatNo(selectedVehicleInventory.getMaterialNumber()); if (material == null) { searchView.setQueryHint(ServiceMessages.getString("noArticleFound")); app.showMessage(ServiceMessages.getString("noArticleFound")); app.messageUtil.showContinueMessage(); } else { priceEditText.setText(material.getNewPrice()); } } } @Override protected void loadData() { super.loadData(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); fillInventoryCombo(); reasonReturnDeliveryEditText.setRequired(!codeReturnInventoryEditText.getText().toString().isEmpty()); } private void fillInventoryCombo() { List receiptOfGoodValueList = new ArrayList(); List inventoryList = app.dbutil.selectNotExternalInventoryList(); for (Inventory inventory : inventoryList) { receiptOfGoodValueList.add(new CustomSpinnerItem((String) inventory.getWarehouseNumber(), inventory.getName())); } inventoryAutoComplete.setContents(receiptOfGoodValueList); } @Override protected void resetView() { super.resetView(); log.info("resetView "); inventoryAutoComplete.setSelection(0); inventoryAutoComplete.clearError(); codeReturnInventoryEditText.clearError(); codeReturnInventoryEditText.getText().clear(); reasonReturnDeliveryEditText.clearError(); reasonReturnDeliveryEditText.getText().clear(); } protected boolean isValid() { boolean result = super.isValid(); String errorMessage = Messages.getString("pleaseProvideValue"); if (isMatrialNumberWrongFormat()) { result = false; } if (reasonReturnDeliveryEditText.isRequired() && reasonReturnDeliveryEditText.getText().toString().isEmpty()) { reasonReturnDeliveryEditText.setError(errorMessage); result = false; } log.info("inventory " + inventoryAutoComplete.getSelectedId()); if (inventoryAutoComplete.isRequired() && (inventoryAutoComplete.getEditableText().toString().isEmpty() || inventoryAutoComplete.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) || inventoryAutoComplete.getSelectedId().equalsIgnoreCase("0000"))) { inventoryAutoComplete.setError(errorMessage); result = false; } return result; } @Override public ApplicationEvent onBackPressed() { // clear deliveryList = null; selectedVehicleInventory = null; return super.onBackPressed(); } @Override protected boolean onSave() { super.onSave(); materialMovement.setTo(inventoryAutoComplete.getSelectedId()); materialMovement.setBarcode(codeReturnInventoryEditText.getText().toString()); materialMovement.setBarcodeText(reasonReturnDeliveryEditText.getText().toString()); new AsyncTask(this) { private Material material = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (selectedVehicleInventory == null) { //Check, if the chosen article is existing in table ZKDMOBFZLGSYNC (article name and article number): if (app.showMessageBox(ServiceMessages.getString("TheSelectedItemIsNotInStockContinue"), ServiceMessages.getString("articleNotINInventory"), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } } else { //If an selected article is not in masterdata, show a different dialog: // "Artikel nicht in Stammdaten vorhanden. Bitte Support kontaktieren" with the only option "OK". material = app.dbutil.selectMaterialByMatNo(numberEditText.getText().toString()); if (material == null) { if (app.showMessageBox(ServiceMessages.getString("TheSelectedArticleIsNotInMasterdata"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { selectedVehicleInventory = null; return null; } } } if(new RemoteTransactionHandler().runSaveMaterialMoveMent(materialMovement)) { } return onBackPressed(); } @Override public void runOnUIThread() { if (material == null) { resetView(); } return; } }; return false; } public static class ArticleOutgoingFormArguments { private DeliveryList deliveryList; public ArticleOutgoingFormArguments() { } public ArticleOutgoingFormArguments(DeliveryList deliveryList) { this.deliveryList = deliveryList; } public DeliveryList getDeliveryList() { return this.deliveryList; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class ArticleOutgoingListForm extends SuperForm { private static Log log = LogFactory.getLog(ArticleOutgoingListForm.class); private TextView inventoryNameText; private RelativeLayout mainView; protected DefaultListWidget listWidget; private LinearLayout emptyMessageView; private Inventory inventory; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleListFormArgument) { ArticleListFormArgument formArgument = (ArticleListFormArgument) argument; } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // toolbar.addView(searchView); // hide runtime menu items setRuntimeMenuHidden(true); // set invisible save button saveButton.setVisible(false); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); // contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout inventoryNameLayout = new LinearLayout(context); inventoryNameLayout.setOrientation(LinearLayout.VERTICAL); inventoryNameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); inventoryNameLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); inventoryNameText = CommonUtilForm.getTextView(context, ""); inventoryNameText.setTextColor(Color.WHITE); inventoryNameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); inventoryNameText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; textViewParams.bottomMargin = LayoutUtils.DEFAULT_MAX_MARGIN; inventoryNameText.setLayoutParams(textViewParams); inventoryNameLayout.addView(inventoryNameText); contentLinearLayout.addView(inventoryNameLayout); RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget = new DefaultListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); LinearLayout.LayoutParams noDataTextViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); noDataTextViewParams.gravity = Gravity.CENTER; noDataTextViewParams.topMargin = 20; textView.setLayoutParams(noDataTextViewParams); emptyMessageView.addView(textView); mainFormView.addView(emptyMessageView); contentLinearLayout.addView(mainFormView); mainView.addView(contentLinearLayout); mainView.addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { boolean widthChanged = (right - left) != (oldRight - oldLeft); if (widthChanged) { // width has changed } boolean heightChanged = (bottom - top) != (oldBottom - oldTop); if (heightChanged) { // height has changed loadTable(); } } }); view.addView(mainView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("vehicleInventory")); inventory = app.dbutil.selectInventoryByPersonalNrAndWarehouseNr(); inventoryNameText.setText(ServiceMessages.getString("nameOfInventory") + " " + (inventory == null? "-":inventory.getName() + " - " + ServiceMessages.getString("outgoingArticles"))); loadTable(); return null; } private void loadTable() { List articleList = app.dbutil.selectOutgoingArticleList(); listWidget.clean(); ArrayList items = new ArrayList(); // if (articleList.isEmpty()) { // DeliveryList deliveryList = new DeliveryList(); // deliveryList.setGuid("7F000001018E2B1A192467BF0BEA31B6"); // deliveryList.setWarehouse("AAA"); // deliveryList.setMaterialNumber("45-0645-327"); // deliveryList.setMaterialName("Antrieb DBX"); // deliveryList.setEntryCount("3.000"); // deliveryList.setEntryUnit("STK"); // deliveryList.setStatus("O"); // articleList.add(deliveryList); // // DeliveryList deliveryList2 = new DeliveryList(); // deliveryList2.setGuid("7F000001018E2B1A192467BF0BEA75B6"); // deliveryList2.setWarehouse("AAA"); // deliveryList2.setMaterialNumber("45-0548-117"); // deliveryList2.setMaterialName("Antrieb DHX"); // deliveryList2.setEntryCount("4.000"); // deliveryList2.setEntryUnit("STK"); // deliveryList2.setStatus("T"); // articleList.add(deliveryList2); // // DeliveryList deliveryList3 = new DeliveryList(); // deliveryList3.setGuid("7F000001018E2B1A192467BF0BE8431B6"); // deliveryList3.setWarehouse("AAA"); // deliveryList3.setMaterialNumber("45-0755-327"); // deliveryList3.setMaterialName("Antrieb SBX"); // deliveryList3.setEntryCount("1.000"); // deliveryList3.setEntryUnit("STK"); // deliveryList3.setStatus("G"); // articleList.add(deliveryList3); // // DeliveryList deliveryList4 = new DeliveryList(); // deliveryList4.setGuid("7F000001018E2B1A642467BF0BE8431B6"); // deliveryList4.setWarehouse("AAA"); // deliveryList4.setMaterialNumber("45-0345-327"); // deliveryList4.setMaterialName("Bedix SBX"); // deliveryList4.setEntryCount("1.000"); // deliveryList4.setEntryUnit("STK"); // articleList.add(deliveryList4); // } for (DeliveryList article : articleList) { final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setData(article); item.setStatusColor(article.getStatusColor()); // item.setStatusType(msg.getConfirmedMsg()); item.isShowCheckBox(false); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(article.getMaterialName()); item.setStringLine1(ServiceMessages.getString("materialNumber") + ": " + article.getMaterialNumber()); // ZKDMOBFZGDELVRY.ENTRY_UOM> item.setStringLine2(ServiceMessages.getString("deliveredArticles") + ": " + article.getEntryCount() + " " + article.getEntryUnit() ); items.add(item); } if (items.isEmpty()) { emptyMessageView.setVisibility(View.VISIBLE); } else { emptyMessageView.setVisibility(View.GONE); // listWidget.setOnItemClickListener(createOnItemClickListener()); listWidget.addItems(items); } } // private OnItemClickListener createOnItemClickListener() { // return new OnItemClickListener() { // // @Override // public void onItemClick(AdapterView parent, View view, final int position, final long id) { // DeliveryList deliveryListClicked = (DeliveryList) ((DefaultListWidgetItem) listWidget.getAdapter().getItem(position)).getData(); // app.injectAndLeaveToForm(ArticleOutgoingForm.class, new ArticleOutgoingFormArguments(deliveryListClicked)); // } // }; // } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ArticleListForm.class); } public static class ArticleListFormArgument { private int tabSelected; private Date selectedDate; public int getTabSelected() { return tabSelected; } protected ArticleListFormArgument() { } public ArticleListFormArgument(Date selectedDate, int tabSelect) { this.tabSelected = tabSelect; this.selectedDate = selectedDate; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public Date getDate() { return this.selectedDate; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.SearchView.OnCloseListener; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ArticleSearchForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(ArticleSearchForm.class); public static ServiceApplication app; // don't make this CommonApplication public LinearLayout contentLinearLayout; public AmountEditText amountEditText; public MDEditText unitEditText; public MDEditText stockEditText; public MDEditText priceEditText; public MaterialMovement materialMovement; @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } else { loadMaterialsList(numberEditText.getText().toString()); // if(searchView.isMaterialSelected() && selectedMaterial != null || selectedMaterialPerson != null) { //// hideSoftInputFromWindow(); // // } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); } else { nameEditText.clearError(); } } }); contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout detailLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); detailLinearLayout.setOrientation(LinearLayout.HORIZONTAL); amountEditText = AmountEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("amount"), true); //$NON-NLS-1$ LinearLayout.LayoutParams amountInputLayoutParams = new LinearLayout.LayoutParams(0, 0); amountInputLayoutParams.gravity = Gravity.CENTER; amountInputLayoutParams.width = 0; amountInputLayoutParams.height = LayoutParams.MATCH_PARENT; amountInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(amountInputLayoutParams); // Unit unitEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("unit"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ unitEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); unitEditText.setTag("UNIT"); //$NON-NLS-1$ unitEditText.setEnabled(false); LinearLayout.LayoutParams unitInputLayoutParams = new LinearLayout.LayoutParams(0, 0); unitInputLayoutParams.gravity = Gravity.LEFT; unitInputLayoutParams.width = 0; unitInputLayoutParams.height = LayoutParams.MATCH_PARENT; unitInputLayoutParams.weight = 0.2f; unitEditText.getParentTextInputLayout().setLayoutParams(unitInputLayoutParams); stockEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("duration"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ stockEditText.setTag("STOCK"); //$NON-NLS-1$ stockEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); stockEditText.setEnabled(false); LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.LEFT; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; stockEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); priceEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("price"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ priceEditText.setTag("PRICE"); //$NON-NLS-1$ priceEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT) }); priceEditText.setEnabled(false); priceEditText.setDirectionRight(true); LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); priceInputLayoutParams.gravity = Gravity.CENTER; priceInputLayoutParams.width = 0; priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; priceInputLayoutParams.weight = 0.2f; priceEditText.getParentTextInputLayout().setLayoutParams(priceInputLayoutParams); contentLinearLayout.addView(detailLinearLayout); addContentLinearLayout(contentLinearLayout); searchView.setOnSearchClickListener(new OnClickListener() { @Override public void onClick(View v) { saveButton.setVisible(false); } }); searchView.setOnCloseListener(new OnCloseListener() { @Override public boolean onClose() { saveButton.setVisible(true); return false; } }); saveButton.setTitle(ServiceMessages.getString("save")); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); resetView(); setShowScanNumber(true); return null; } @Override protected void loadData() { super.loadData(); } @Override protected void resetView() { super.resetView(); priceEditText.clearError(); amountEditText.clearError(); stockEditText.clearError(); priceEditText.getText().clear(); amountEditText.getText().clear(); stockEditText.getText().clear(); unitEditText.setSelection(0); unitEditText.clearError(); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ArticleListForm.class); } @Override protected ApplicationEvent onSavePressed() { KeyboardUtil.closeKeyboard(appman, getView()); if (isValid()) { onSave(); } return null; } protected boolean isValid() { boolean result = true; String errorMessage = Messages.getString("pleaseProvideValue"); if (nameEditText.isRequired() && nameEditText.getText().toString().isEmpty()) { nameEditText.setError(errorMessage); result = false; } if (numberEditText.isRequired() && numberEditText.getText().toString().isEmpty()) { numberEditText.setError(errorMessage); result = false; } if (amountEditText.isRequired() && amountEditText.getText().toString().isEmpty()) { amountEditText.setError(errorMessage); result = false; } return result; } @Override protected boolean onSave() { materialMovement = new MaterialMovement(); Person user = app.dbutil.getUser(); int pernr = user.getPersonalNumber(); GuidGenerator generator = new GuidGenerator(); try { materialMovement.setGuid(generator.generate()); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } materialMovement.setPersonalNumber(pernr); materialMovement.setPersonalNumberConfirmed(pernr); materialMovement.setFrom(user.getWarehouseNumber()); materialMovement.setMaterialNumber(numberEditText.getText().toString()); materialMovement.setEntryCount(amountEditText.getText().toString()); materialMovement.setEntryUnit(unitEditText.getText().toString()); return false; } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobListForm.JobListFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The Employee List Form Class. * * @author nop (02-03-2017) * * @see "[MIG-49] implement of "Mitarbeiterliste" (list of employees)" */ public class EmployeeListForm extends SuperForm implements OnQueryTextListener{ private static Log log = LogFactory.getLog(EmployeeListForm.class); protected Job job; protected DetailListWidget listWidget; @Override public void onFormCall(Object argument) { if (argument instanceof JobListFormArguments) { JobListFormArguments formArguments = (JobListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); listWidget = new DetailListWidget(context); // Search View SearchView searchView = new SearchView(context); searchView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); searchView.setQueryHint(Messages.getString("search")); //$NON-NLS-1$ searchView.setFocusable(true); searchView.setFocusableInTouchMode(true); searchView.setBackgroundColor(LayoutUtils.DEFAULT_SEARCH_COLOR); searchView.setOnQueryTextListener(this); contentLinearLayout.addView(searchView); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); contentLinearLayout.addView(listWidget); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("listOfEmployees")); //$NON-NLS-1$ listWidget.clean(); final List employeeList = app.dbutil.selectEmployeeList(app.dbutil.getUser(), ""); //$NON-NLS-1$ ArrayList items = new ArrayList(); for (int i = 0; i < employeeList.size(); i++) { final Employee employee = employeeList.get(i); final DetailListWidgetItem item = new DetailListWidgetItem(); log.info("emp " + employee.getFirstName() + employee.getSpecificFunction()); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); String specificFunction = ""; if (!employee.getSpecificFunction().getText().isEmpty()) { specificFunction = " (" + employee.getSpecificFunction().getText() + ")"; } item.setTitleText(employee.getLastName() + " " + employee.getFirstName() + specificFunction); //$NON-NLS-1$ item.setStringLine1(ServiceMessages.getString("telWColon") + employee.getPhoneNumber()); //$NON-NLS-1$ item.setStringLine2(ServiceMessages.getString("personalNumber") + ":" + employee.getPersonalNumber()); //$NON-NLS-1$ //$NON-NLS-2$ item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton && employee.getPhoneNumber() != null) { String phoneNumber = employee.getPhoneNumber().replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } }); items.add(item); } listWidget.addItems(items); return null; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } } package ch.mfiles.kaba.kolibri.service.forms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class InventoryInformationsForm extends SuperForm { private static Log log = LogFactory.getLog(InventoryInformationsForm.class); private MDEditText name; private MDEditText number; private MDEditText user; private MDEditText personalNumber; private Inventory inventory; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.inventory = formArguments.getInventory(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ArticleListForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); name = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("inventoryName"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); // name.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); number = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("inventoryNumber"), //$NON-NLS-1$ InputType.TYPE_TEXT_VARIATION_PERSON_NAME , false); // number.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SIXTY) }); user = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("UserName"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); // user.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); personalNumber = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("personalNumber"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER , false); personalNumber.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT) }); ScrollView scroll = new ScrollView(context); scroll.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scroll.addView(contentLinearLayout); relativeLayout.addView(scroll); view = new LinearLayout(context); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("inventoryInformations")); //$NON-NLS-1$ inventory = app.dbutil.selectInventoryByPersonalNrAndWarehouseNr(); name.setText(inventory == null? "-":inventory.getName()); number.setText(inventory == null? "-":inventory.getWarehouseNumber()); Person crrentUser = app.dbutil.getUser(); user.setText(crrentUser.getFirstName() + " " + crrentUser.getLastName()); personalNumber.setText(crrentUser.getPersonalNumber() + ""); setEnable(false); return null; } private void setEnable(boolean enabled) { name.setEnabled(enabled); number.setEnabled(enabled); user.setEnabled(enabled); personalNumber.setEnabled(enabled); } public static class FormArguments { private Inventory inventory; public FormArguments(Inventory inventory) { this.inventory = inventory; } public Inventory getInventory() { return inventory; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnCloseListener; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.types.Warehouse; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class InventoryStockForm extends SuperForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(InventoryStockForm.class); protected Job job; private SearchView searchView; private ActionCtrl refreshAction; private ActionCtrl scanAction; private ActionCtrl searchAction; protected DetailListWidget listWidget; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set navigation image and listener Image backImage = ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); // create SearchView searchView = new SearchView(context); searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END)); searchView.setOnQueryTextListener(this); searchView.setOnCloseListener(new OnCloseListener() { @Override public boolean onClose() { getToolbar().removeView(searchView); setVisibleAction(true); return false; } }); // toolbar.addView(searchView); // hide runtime menu items setRuntimeMenuHidden(true); // create refresh action refreshAction = addActionCtrl(false, true, 0, "actionRefresh"); //$NON-NLS-1$ // refreshAction.setTitle(ServiceMessages.getString("refresh")); //$NON-NLS-1$ refreshAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.UPDATE_WHITE, CommonConstants.Images.IMAGE_DPI))); // create scan action scanAction = addActionCtrl(false, true, 0, "actionScan"); //$NON-NLS-1$ // scanAction.setTitle(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); // create search action searchAction = addActionCtrl(false, true, 0, "actionSearch"); //$NON-NLS-1$ // searchAction.setTitle(ServiceMessages.getString("search")); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); setVisibleAction(true); listWidget = new DetailListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); // set invisible save button saveButton.setVisible(false); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("inventoryStock")); actionRefresh(); return null; } private void loadInventoryStockList() { listWidget.clean(); List inventoryStockList = app.dbutil.selectVehicleInventoryList(); view.removeAllViews(); if(inventoryStockList.isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); for (VehicleInventory inventoryStock : inventoryStockList) { final DetailListWidgetItem item = new DetailListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(inventoryStock.getMaterialName()); item.setStringLine1(ServiceMessages.getString("materialNumber") + ": " + inventoryStock.getMaterialNumber()); item.setStringLine2("Bestand: " + inventoryStock.getStockOfMaterial() + " " + inventoryStock.getUnit()); items.add(item); } // listWidget.setOnItemClickListener(createOnItemClickListener(inventoryStockList)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List inventoryStockList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { VehicleInventory inventoryStock = inventoryStockList.get(position); //TODO remove for test only Inventory inventory = new Inventory(); inventory.setWarehouseNumber("0102152"); inventory.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); inventory.setName(inventoryStock.getMaterialName()); inventory.setWarehouse(new Warehouse()); inventory.setRefreshFlag(""); app.injectAndLeaveToForm(InventoryInformationsForm.class, new InventoryInformationsForm.FormArguments(inventory)); } }; } protected ApplicationEvent onAddPressed() { return null; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.leaveToForm(ArticleListForm.class); } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } private void setVisibleAction(boolean visible) { searchAction.setVisible(visible); refreshAction.setVisible(visible); scanAction.setVisible(visible); searchView.setVisibility(visible ? View.INVISIBLE:View.VISIBLE); } protected ApplicationEvent actionRefresh() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { Person crrentUser = app.dbutil.getUser(); new RemoteTransactionHandler().runGetInventryStock(crrentUser.getPersonalNumber(), crrentUser.getWarehouseNumber(), crrentUser.getLanguage()); return null; } @Override protected void runOnUIThread() { loadInventoryStockList(); } }; return null; } protected ApplicationEvent actionScan() { new AsyncTask(this) { private String barcode; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(InventoryStockForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { app.showMessage(result.toString()); barcode = result.getContents(); log.info("scan result -> " + barcode); //$NON-NLS-1$ } return null; } }; return null; } protected ApplicationEvent actionSearch() { KeyboardUtil.closeKeyboard(appman, getView()); getToolbar().addView(searchView); // hide menu setVisibleAction(false); searchView.setIconified(false); return null; } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReturnReason; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class JobDeleteForm extends DialogForm { private static Log log = LogFactory.getLog(JobDeleteForm.class); // initialized by the kolibri framework... public static ServiceApplication app; private Job job; protected Context context; protected LinearLayout view; private ActionCtrl deleteButton; private MDSpinner reasonValue; @Override public void onFormCall(Object argument) { if (argument instanceof JobDeleteFormArguments) { JobDeleteFormArguments formArguments = (JobDeleteFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); saveButton.setVisible(false); deleteButton = addActionCtrl(false, true, 1, "onDeletePressed"); //$NON-NLS-1$ deleteButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // reason reasonValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { reasonValue.setError(null); reasonValue.clearError(); } @Override public void onNothingSelected(AdapterView arg0) { } }); contentLinearLayout.addView(workTypeLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("reasonForDelete")); //$NON-NLS-1$ List reasonValueList = new ArrayList(); List reasonList = app.dbutil.selectJobDeleteReasonList(); for (int i = 0; i < reasonList.size(); i++) { Reason reason = reasonList.get(i); reasonValueList.add(new CustomSpinnerItem(reason.getReasonText(), reason.getText(), reason.getText())); } reasonValue.setContents(reasonValueList); return null; } protected ApplicationEvent onDeletePressed() { if(reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { reasonValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ return null; } new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(app.showConfirmDeleteDialog()) { if (new RemoteTransactionHandler().updateStatus(db, job, JobStatus.DELETED, JobStatus.SAP_Deleted, reasonValue.getSelectedId())) { log.info("after updateStatus" + job.getStatus().toString()); log.info("after reloadSelectedJob" + job.getStatus().toString()); if (JobStatus.RECEIVED.equals(JobStatus.DELETED)) { // remove existing a new job notification new Notifications(app).removeNotification(CommonConstants.Notification.NEW_JOB); } } if (job.getStatus().isDeleted() && app.dbutil.deleteJob(job)) { app.showMessage(ServiceMessages.getString("jobDeleted"), true); //$NON-NLS-1$ } return onBackPressed(); } return null; } }; return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobListForm.class); } public static class JobDeleteFormArguments { private Job job; public JobDeleteFormArguments(Job zkdmob) { this.job = zkdmob; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.impl.android.ui.UIActivity; /** * The address form for job details. * * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public class JobDetailAddressForm extends GridLayoutForm { private static Log log = LogFactory.getLog(JobDetailAddressForm.class); private Job job; private RelativeLayout addressRelativeLayout; private LinearLayout cardLinearLayout; public JobDetailAddressForm(Context context, ServiceApplication app) { super(context, app); } /** * Gets view. * * @param job * @param title */ public View getView(Job job) { this.job = job; createLayoutAndContents(); return getParentView(addressRelativeLayout); } /** * Creates layout and contents. * * @param job * @param title */ public void createLayoutAndContents() { addressRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams addressRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); addressRelativeLayoutParams.setMargins(0, 0, 0, LayoutUtils.DEFAULT_MAX_MARGIN); addressRelativeLayout.setLayoutParams(addressRelativeLayoutParams); cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); // Address type "Object" (ZKDMOB.OBJNR) // // MON: // Address type "Contact" (ZKDMOB.PARAPNR) // Address type "Customer" (ZKDMOB.PARZSNR) // Address type "Receiver" (ZKDMOB.PARZANR) // // REP/SAV: // Address type "Partner" (ZKDMOB.PARAPNR) // Address type "Customer" (ZKDMOB.PARANMNR) // Address type "Owner" (ZKDMOB.PARZANR) // Address type "Estate Management" (ZKDMOB.PARZRNR) // Address type "Client" (ZKDMOB.PARZSNR) // OBJNR - ObjectAddress // PARAPNR - PartnerOfInstallAddress // PARZSNR - CustomerKdnErrorAddress // PARZANR - OwnerAddress // // PARAPNR - PartnerOfInstallAddress // PARANMNR - PartnerAddress // PARZANR - OwnerAddress // PARZRNR - KdnServiceAddress // PARZSNR - CustomerKdnErrorAddress log.info("Object -> OBJNR ->" + job.getObjectAddressId()); createAddressContents(ServiceMessages.getString("Object"), job.getObjectAddress()); //$NON-NLS-1$ if(job.getJobType().isMON()) { log.info("Contact -> PARAPNR ->" + job.getPartnerAddressId()); log.info("Customer -> PARZSNR ->" + job.getCustomerAddressId()); log.info("Receiver -> PARZANR ->" + job.getOwnerAddressId()); createAddressContents(ServiceMessages.getString("Contact"), job.getPartnerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Customer"), job.getCustomerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Receiver"), job.getOwnerAddress()); //$NON-NLS-1$ } else { log.info("Partner -> PARAPNR ->" + job.getPartnerOfInstallAddressId()); log.info("Customer -> PARANMNR ->" + job.getPartnerAddressId()); log.info("Owner -> PARZANR ->" + job.getOwnerAddressId()); log.info("EstateManagement -> PARZRNR ->" + job.getKdnServiceAddressId()); log.info("Client -> PARZSNR ->" + job.getCustomerAddressId()); createAddressContents(ServiceMessages.getString("Partner"), job.getPartnerOfInstallAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Customer"), job.getPartnerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Owner"), job.getOwnerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("EstateManagement"), job.getKdnServiceAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Client"), job.getCustomerAddress()); //$NON-NLS-1$ } addressRelativeLayout.addView(cardLinearLayout); } /** * Creates address contents. * * @param gridLayout * @param address */ private void createAddressContents(String titleText, Address address) { if(address.getJobNumber().isEmpty()) { // no address return; } GridLayout gridLayout = createGridLayout(titleText, job, address); // Client number createAddressTextView(gridLayout, ServiceMessages.getString("ClientNumber"), address.getCustomerNumber()); // Title String title = app.enumUtil.titelEnum.get(address.getTitle()) == null ? "" : app.enumUtil.titelEnum.get(address.getTitle()); //$NON-NLS-1$ createAddressTextView(gridLayout, ServiceMessages.getString("title"), title); //$NON-NLS-1$ // First name String firsrName = address.isPrivate() ? ServiceMessages.getString("firstName") : ServiceMessages.getString("enterprise"); //$NON-NLS-1$ //$NON-NLS-2$ createAddressTextView(gridLayout, firsrName, address.getName1()); // LastName String lastName = address.isPrivate() ? ServiceMessages.getString("lastName") : ServiceMessages.getString("name"); //$NON-NLS-1$ //$NON-NLS-2$ createAddressTextView(gridLayout, lastName, address.getName2()); // Addition createAddressTextView(gridLayout, ServiceMessages.getString("addition"), address.getName3()); //$NON-NLS-1$ // Location createAddressTextView(gridLayout, Messages.getString("location"), address.getLocation()); //$NON-NLS-1$ // Str./No. createAddressTextView(gridLayout, ServiceMessages.getString("street"), address.getStreet()); //$NON-NLS-1$ // ZIP createAddressTextView(gridLayout, ServiceMessages.getString("zip"), address.getPostalCode()); //$NON-NLS-1$ // City createAddressTextView(gridLayout, ServiceMessages.getString("city"), address.getCity()); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Tel. 1 createAddressTextView(gridLayout, ServiceMessages.getString("tel1"), address.getTelNumber1(), true); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Tel. 2 createAddressTextView(gridLayout, ServiceMessages.getString("tel2"), address.getTelNumber2(), true); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Fax createAddressTextView(gridLayout, ServiceMessages.getString("fax"), address.getFaxNumber()); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Email createAddressTextView(gridLayout, ServiceMessages.getString("email"), address.getEmail()); //$NON-NLS-1$ List emailList = app.dbutil.selectEmailListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); if (!emailList.isEmpty()) { for (int i = 0; i < emailList.size(); i++) { Email email = emailList.get(i); log.info("JobNumber " + email.getJobNumber() + " PartnerNummer " + email.getPartnerNummer() + " JobType " + email.getJobType().getCode() + " Email " + email.getEmail()); createAddressTextView(gridLayout, ServiceMessages.getString("email") + " " + (i+2), email.getEmail()); //$NON-NLS-1$ } } cardLinearLayout.addView(cardView); } /** * Creates address text view. * * @param gridLayout * @param key * @param value */ private void createAddressTextView(final GridLayout gridLayout, final String key, final String value) { createAddressTextView(gridLayout, key, value, false); } /** * Creates address text view. * * @param gridLayout * @param key * @param value * @param iconTypeName */ private void createAddressTextView(final GridLayout gridLayout, final String key, final String value, boolean isShowIcon) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.2f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.8f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(context); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(value); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(gridTextViewValue); if (isShowIcon) { ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); if (value != null && value.trim().length() > 0) { gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phoneNumber = value.replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } }); } else { gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE_DISABLED, CommonConstants.Images.IMAGE_DPI))); } gridRelativeLayout.addView(gridImageView); } gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } public static class AddressFormArguments { private Job job; private Address address; protected AddressFormArguments() { } protected AddressFormArguments(Job job) { } public AddressFormArguments(Job job, Address address) { this.job = job; this.address = address; } public Job getJob() { return job; } public Address getAddress() { return address; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.forms.widgets.ViewPageAdapter; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.OnTimeAction; import ch.mfiles.kaba.kolibri.service.forms.SignatureForm.Arguments; import ch.mfiles.kaba.kolibri.service.util.ReportUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class JobDetailForm extends SuperForm { private static Log log = LogFactory.getLog(JobDetailForm.class); private Job job; private JobReportTime selectedJobTime; private LinearLayout mainView; private JobDetailInfoForm infoForm; private JobDetailAddressForm addressForm; private JobDetailReportForm reportForm; private ActionCtrl jobEditActioni; private ActionCtrl commissionNumberAction; private ActionCtrl finalizedReportsAction; private ActionCtrl signatureAction; private ActionCtrl sendAction; private TabLayout tabLayout; private int pageSelected = 0; private Toolbar toolbar; public JobReportTime getSelectedJobtime() { return selectedJobTime; } public void setSelectedJobTime(JobReportTime jobTime) { selectedJobTime = jobTime; } public void setSelectedJob(Job job) { this.job = job; this.job.loadAddresses(app.dbutil); this.job.loadReports(app.dbutil); } public void reloadSelectedJob() { this.job = app.dbutil.selectJobByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); this.job.loadReports(app.dbutil); } @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArgument = (JobDetailFormArgument)argument; job = formArgument.getJob(); job.loadAddresses(app.dbutil); job.loadReports(app.dbutil); pageSelected = formArgument.getTabSelected(); }else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context The context to user for creating UI widgets. * @param inflater The inflater to use to inflate the application's layouts from XML resource ids. * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); setFormTitle(ServiceMessages.getString("jobDetails")); //$NON-NLS-1$ // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationContentDescription("Back"); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); /* create the "Job Edit" in context menu. * * @see "[MIG-46] implement of "create job"" */ jobEditActioni = addActionCtrl(false, false, 2, "onJobEdit"); //$NON-NLS-1$ jobEditActioni.setTitle(ServiceMessages.getString("customizeYourInfo")); //$NON-NLS-1$ jobEditActioni.setEnabled(false); // create the "Kom-No." in context menu. commissionNumberAction = addActionCtrl(false, false, 2, "onCommissionNumber"); //$NON-NLS-1$ commissionNumberAction.setTitle(ServiceMessages.getString("wrongComm")); //$NON-NLS-1$ commissionNumberAction.setEnabled(false); finalizedReportsAction = addActionCtrl(false, true, 1, "onFinalizedReports"); //$NON-NLS-1$ finalizedReportsAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_FILE_BLACK, CommonConstants.Images.IMAGE_DPI))); finalizedReportsAction.setVisible(false); signatureAction = addActionCtrl(false, true, 1, "onSignature"); //$NON-NLS-1$ signatureAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_BLACK, CommonConstants.Images.IMAGE_DPI))); signatureAction.setVisible(false); sendAction = addActionCtrl(false, true, 1, "onSendingReport"); //$NON-NLS-1$ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setVisible(false); // set invisible save button saveButton.setVisible(false); mainView = new LinearLayout(context); mainView.setOrientation(LinearLayout.VERTICAL); mainView.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS())); LinearLayout.LayoutParams checkFinalizeLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); mainView.setLayoutParams(checkFinalizeLayoutParams); infoForm = new JobDetailInfoForm(context, app); addressForm = new JobDetailAddressForm(context, app); reportForm = new JobDetailReportForm(context, app); reportForm.setOnTimeActionListener(new OnTimeAction() { @Override public void runOnTimeAction() { changeActionSend(); pageSelected = 2; onFormShow(); } }); view.addView(mainView); return view; } /** * This event is received every time the form is shown. This happens if the * form is called by the framework, another form or if reactivated from the * application's form stack. <p/> * * The application developer has to set all member variables (reset the * state of the form) at this point because the framework reuses the forms * (every form is instantiated exactly once during the lifetime of an * application) *

* * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); app.messageUtil.showContinueMessage(); if (mainView.getChildCount() > 0) { mainView.removeAllViewsInLayout(); mainView.invalidate(); } toolbar.setEnabled(true); View contentView = createTabContentView(context); mainView.addView(contentView); tabLayout.getTabAt(pageSelected).select(); view.invalidate(); return null; } /** * Handles on click event for job edit. * * @return * * @see "[MIG-46] implement of "create job"" */ public ApplicationEvent onJobEdit() { pageSelected = 0; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { tabLayout.getTabAt(pageSelected).select(); ch.mfiles.kaba.kolibri.service.forms.JobEditForm.FormArguments formArguments = new JobEditForm.FormArguments(false, job.getCommissionNumber(), job, job.getObjectAddress(), job.getPartnerAddress()); return app.callForm(JobEditForm.class, formArguments); } }, false); return null; } /** * Handles on click event for commission number. * * @return * * @see "[MIG-43] implement of "Falsche Kommissionsnummer"" */ public ApplicationEvent onCommissionNumber() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobDetailInfoCommissionNumberForm.class, new JobDetailForm.JobDetailFormArgument(job)); } }, false); return null; } public ApplicationEvent onFinalizedReports() { pageSelected = 2; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { List jobList = new ArrayList(); jobList.add(job); return app.callForm(ReportSummaryForm.class, new Arguments(jobList, false)); } }, false); return null; } /** * Handles on click event for signature. * * @return */ public ApplicationEvent onSignature() { pageSelected = 2; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { List jobList = new ArrayList(); jobList.add(job); return appman.getActiveApplication().callForm(SignatureForm.class, new SignatureForm.Arguments(jobList, false)); } }, false); return null; } /** * Handles on click event for sending report. * * @return */ public ApplicationEvent onSendingReport() { sendAction.setEnabled(false); log.info("sending report PARANMNR " + job.getPartnerAddressId() + " PARAPNR " + job.getObjectAddressId()); log.info("address PARANMNR " + job.getPartnerAddress().getPartnerNummer() + " PARAPNR " + job.getObjectAddress().getPartnerNummer()); ReportUtil reportUtil = new ReportUtil(this, app); reportUtil.onSendingReport(job); changeActionSend(); return null; } protected void changeActionFinalizedReport() { JobStatus jobStatus = job.getStatus(); finalizedReportsAction.setVisible(true); finalizedReportsAction.setEnabled(false); finalizedReportsAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_FILE_DISABLED, CommonConstants.Images.IMAGE_DPI))); if (jobStatus.isPartlyDone() || jobStatus.isFinalized()) { finalizedReportsAction.setEnabled(true); finalizedReportsAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_FILE_BLACK, CommonConstants.Images.IMAGE_DPI))); } } /** * Displays "Signature" button (POS5) depending on * @param form * @param job */ protected void changeActionSignature() { JobStatus jobStatus = job.getStatus(); signatureAction.setVisible(true); signatureAction.setEnabled(false); signatureAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); if (jobStatus.isReceived() || jobStatus.isPartlyDone() || jobStatus.isInProgress()) { List jobs = getBundledJobList(job); if (!jobs.isEmpty()) { boolean enabled = true; // fill the report status into a HasSet HashSet reportStatusSet = new HashSet(); Iterator itr = jobs.iterator(); while (itr.hasNext()) { Report report = itr.next().getLatestReport(); reportStatusSet.add(report.getReportStatus().getCode()); } /* 1. if there is at least one report in initial state, signature button is disabled this is because a report can not be signed before it exists * 2. if all reports are sent signature button is disabled * */ if (reportStatusSet.contains(ReportStatus.INITIAL) || (reportStatusSet.contains(ReportStatus.RECEIVED) && reportStatusSet.size() == 1)) { enabled = false; } // ..in all other situations, signature button remains enabled if (enabled) { signatureAction.setEnabled(true); signatureAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_BLACK, CommonConstants.Images.IMAGE_DPI))); } } } signatureAction.setValidate(true); } protected List getBundledJobList(Job job) { List jobList = new ArrayList(); // reload report because they can be changed! job.loadReports(app.dbutil); String signguId = job.getLatestReport().getSignatureGuId(); // add only the current job to the list if it was not signed together with others if (StringUtil.isEmpty(signguId)) jobList.add(job); // load jobs which have been signed together else { jobList = new ArrayList(app.dbutil.selectJobBySignGUID(signguId)); Iterator itr = jobList.iterator(); while (itr.hasNext()) { Job bundledJob = itr.next(); bundledJob.loadReports(app.dbutil); } } return jobList; } /** * Displays "Send" button (POS4) depending on * @param job */ private void changeActionSend() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { Person currentUser = app.dbutil.getUser(); Report report = job.getCurrentReport(); sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(false); if (currentUser != null && !report.getReportStatus().isInitial()) { setSelectedJobTime(app.dbutil.selectJobReportTimeByGuid(job.getCurrentReportGuId(app.dbutil))); if (report.getReportStatus().isNew()){ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(true); if (getSelectedJobtime() != null && getSelectedJobtime().getStopTime().equals(new Date(0))) { sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(false); } } } sendAction.setValidate(true); return null; } }, false); } protected void changeActions() { changeActionSignature(); changeActionSend(); } private View createTabContentView(Context context) { if (pageSelected == 0) { contextMenuActionState(true); } signatureAction.setVisible(false); sendAction.setVisible(false); finalizedReportsAction.setVisible(false); // create vertical linear view to hold TabLayout and ViewPager LinearLayout contentView = new LinearLayout(context); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentView.setOrientation(LinearLayout.VERTICAL); // create TabLayout tabLayout = new TabLayout(context); LinearLayout.LayoutParams tabLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); tabLayout.setLayoutParams(tabLayoutParams); tabLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); tabLayout.setTabTextColors(LayoutUtils.DEFAULT_TAB_TEXT_COLOR, LayoutUtils.DEFAULT_TAB_SELECTED_TEXT_COLOR); tabLayout.setSelectedTabIndicatorColor(LayoutUtils.DEFAULT_HIGHLIGHT); contentView.addView(tabLayout); // create 3 simple pages and add them to a page adapter ViewPageAdapter pagerAdapter = new ViewPageAdapter(); // info content tab pagerAdapter.addPage(ServiceMessages.getString("jobInfo"), infoForm.getView(job, ServiceMessages.getString("information"))); //$NON-NLS-1$ //$NON-NLS-2$ // address content tab pagerAdapter.addPage(ServiceMessages.getString("addresses"), addressForm.getView(job)); //$NON-NLS-1$ // report content tab pagerAdapter.addPage(ServiceMessages.getString("report"), reportForm.getView(job)); //$NON-NLS-1$ // ViewPager for PageAdapter ViewPager viewPager = new ViewPager(context); viewPager.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentView.addView(viewPager); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { if (position == 0 ) { // info contextMenuActionState(true); } else { contextMenuActionState(false); } if (position == 1) { // Address // do nothings } if (position == 2) { // Report signatureAction.setVisible(true); changeActionFinalizedReport(); changeActionSignature(); job.getLatestReport().checkIfTimeStartOverOndDay(app.dbutil); sendAction.setVisible(true); finalizedReportsAction.setVisible(true); changeActionSend(); } else { signatureAction.setVisible(false); sendAction.setVisible(false); finalizedReportsAction.setVisible(false); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Auto-generated method stub } @Override public void onPageScrollStateChanged(int state) { // Auto-generated method stub } }); // link TabLayout to ViewPager tabLayout.setupWithViewPager(viewPager); return contentView; } @Override public ApplicationEvent onBackPressed() { if (toolbar.isEnabled()) { toolbar.setEnabled(false); return app.leaveToForm(JobListForm.class, null); } return null; } private void contextMenuActionState(boolean state) { jobEditActioni.setVisible(state); jobEditActioni.setValidate(state); commissionNumberAction.setVisible(state); commissionNumberAction.setValidate(state); if (state) { if (job.getJobType().isREP() && job.isLocalJob() && app.dbutil.getUser().getPersonalNumber() == job.getPersonalNumber()) { jobEditActioni.setEnabled(true); } else { jobEditActioni.setEnabled(false); } if (job.getJobType().isREP() && (job.getCurrentReport() == null || job.getCurrentReport().getReportStatus().isInitial())) { commissionNumberAction.setEnabled(true); } else { commissionNumberAction.setEnabled(false); } } } public static class JobDetailFormArgument { private Job job; private int tabSelected; public int getTabSelected() { return tabSelected; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } protected JobDetailFormArgument() { } public JobDetailFormArgument(Job job) { this.job = job; } public JobDetailFormArgument(Job job, int tabSelect) { this.job = job; this.tabSelected = tabSelect; } public Job getJob() { return job; } } }
package ch.mfiles.kaba.kolibri.service.forms; import java.util.List; import android.content.Context; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.History; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; /** * The history form for job details. * * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public class JobDetailHistoryForm extends GridLayoutForm { public JobDetailHistoryForm(Context context, ServiceApplication app) { super(context, app); } /** * Sets view. * * @param job * @param targetLinearLayout */ public void setView(Job job, LinearLayout targetLinearLayout) { createBemerkungenLayoutAndContents(job, targetLinearLayout, ServiceMessages.getString("remarks")); //$NON-NLS-1$ createHistoryLayoutAndContents(job, targetLinearLayout, ServiceMessages.getString("history")); //$NON-NLS-1$ } /** * Creates bemerkungen layout and contents. * * @param job * @param targetLinearLayout * @param title */ private void createBemerkungenLayoutAndContents(Job job, LinearLayout targetLinearLayout, String title) { GridLayout gridLayout = createGridLayout(title); gridLayout.setColumnCount(1); if (!job.getStatus().isInitial()) { if (job.getDescription().length() > 0) { createHistoryTextView(gridLayout, job.getDescription()); } else { createHistoryTextView(gridLayout, "-"); //$NON-NLS-1$ } if (job.getInformation().length() > 0) { createHistoryTextView(gridLayout, job.getInformation()); } else { createHistoryTextView(gridLayout, "-"); //$NON-NLS-1$ } } else { createHistoryTextView(gridLayout, ServiceMessages.getString("noReportAvailable")); //$NON-NLS-1$ } targetLinearLayout.addView(cardView); } /** * Creates history layout and contents. * * @param job * @param targetLinearLayout * @param title */ private void createHistoryLayoutAndContents(Job job, LinearLayout targetLinearLayout, String title) { GridLayout gridLayout = createGridLayout(title); gridLayout.setColumnCount(1); if (!job.getStatus().isInitial()) { List historieList = app.dbutil.selectHistoryList(job.getJobNumber(), job.getJobType().getCode()); if (!historieList.isEmpty()) { for (int i = 0; i < historieList.size(); i++) { History zkdhist = historieList.get(i); if (zkdhist.getText().length() > 0) { createHistoryTextView(gridLayout, zkdhist.getText()); } else { createHistoryTextView(gridLayout, "-"); //$NON-NLS-1$ } } } } else { createHistoryTextView(gridLayout, ServiceMessages.getString("noReportAvailable")); //$NON-NLS-1$ } targetLinearLayout.addView(cardView); } /** * Creates history text view. * * @param gridLayout * @param text */ private void createHistoryTextView(GridLayout gridLayout, String text) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(text.replace("\\n", System.getProperty("line.separator"))); //$NON-NLS-1$ //$NON-NLS-2$ gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridLayout.addView(gridTextViewKey); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.regex.Pattern; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.GridLayout; import android.text.Html; import android.text.util.Linkify; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; /** * The info form for job details. * * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public class JobDetailInfoForm extends GridLayoutForm { private JobDetailHistoryForm historyForm; private RelativeLayout infoRelativeLayout; public JobDetailInfoForm(Context context, ServiceApplication app) { super(context, app); this.historyForm = new JobDetailHistoryForm(context, app); } /** * Gets view. * * @param job * @param title */ public View getView(Job job, String title) { createLayoutAndContents(job, title); return getParentView(infoRelativeLayout); } /** * Creates layout and contents. * * @param job * @param title */ public void createLayoutAndContents(Job job, String title) { createInfoLayoutAndContents(job, title); } /** * Creates info layout and contents. * * @param job * @param title */ private void createInfoLayoutAndContents(Job job, String title) { infoRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams infoRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); infoRelativeLayoutParams.setMargins(0, 0, 0, LayoutUtils.DEFAULT_MAX_MARGIN); infoRelativeLayout.setLayoutParams(infoRelativeLayoutParams); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); addImportantContents(job, linearLayout); if (job.getJobType().isMON()) { createMONInfoContents(job, createGridLayout(title)); } else { createREPSAVInfoContents(job, createGridLayout(title)); } ((LayoutParams) cardView.getLayoutParams()).topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; linearLayout.addView(cardView); // add history historyForm.setView(job, linearLayout); infoRelativeLayout.addView(linearLayout); } /** * Creates MON info contents. * * @param gridLayout * @param gridLayout */ private void createMONInfoContents(Job job, GridLayout gridLayout) { addJobStatus(job, gridLayout); addJobNumber(job, gridLayout); addAppointment(job, gridLayout); addLink(job, gridLayout); addBackOffice(job, gridLayout); addEmptyRow(gridLayout); addInstallationNo(job, gridLayout); addDriveUnit(job, gridLayout); addResponsible(job, gridLayout); addSalesperson(job, gridLayout); addAllowedTime(job, gridLayout); } /** * Creates REP/SAV info contents. * * @param gridLayout * @param gridLayout */ private void createREPSAVInfoContents(Job job, GridLayout gridLayout) { addJobStatus(job, gridLayout); addJobNumber(job, gridLayout); addJobPriority(job, gridLayout); addAppointment(job, gridLayout); addOnCallService(job, gridLayout); addLink(job, gridLayout); addBackOffice(job, gridLayout); addJobCreationDate(job, gridLayout); addEmptyRow(gridLayout); addInstallationNo(job, gridLayout); addDriveUnit(job, gridLayout); addErrorMsgCode(job, gridLayout); addEmptyRow(gridLayout); addCheckCycles(job, gridLayout); addDocumentRequired(job, gridLayout); addSAV(job, gridLayout); addEmptyRow(gridLayout); addResponsibleSAN(job, gridLayout); addMoreInformations(job, gridLayout); } private void createInfoTextView(GridLayout gridLayout, String key, TextView gridTextViewValue) { TextView gridTextViewKey = new TextView(gridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.4f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout gridRelativeLayout = new RelativeLayout(gridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.6f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(gridTextViewValue); gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } /** * Creates info text view. * * @param gridLayout * @param key * @param value */ private void createInfoTextView(GridLayout gridLayout, String key, String value) { TextView gridTextViewValue = createTextView(gridLayout); gridTextViewValue.setText(value); createInfoTextView(gridLayout, key, gridTextViewValue); } private void createLinkTextView(GridLayout gridLayout, String key, final String url) { TextView gridTextViewValue = createTextView(gridLayout); Pattern pattern = Pattern.compile(url); Linkify.addLinks(gridTextViewValue, pattern, "http://"); gridTextViewValue.setText(Html.fromHtml("http://"+url+"")); gridTextViewValue.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("googlechrome://navigate?url="+ url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); createInfoTextView(gridLayout, key, gridTextViewValue); } private TextView createTextView(GridLayout gridLayout) { TextView gridTextViewValue = new TextView(gridLayout.getContext()); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); return gridTextViewValue; } private void addJobStatus(Job job, GridLayout gridLayout) { String jobStatus = app.enumUtil.jobStatusNameEnum.get(job.getStatus().getCode()); if (job.getStatus().isForwarded()) { Employee employee = app.dbutil.selectEmployeeByPerNr(job.getJobForward()); if (employee != null) { jobStatus += " an " + employee.getLastName() + "" + employee.getFirstName(); //$NON-NLS-1$ //$NON-NLS-2$ } } createInfoTextView(gridLayout, ServiceMessages.getString("state"), jobStatus); //$NON-NLS-1$ } private void addJobNumber(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, Messages.getString("orderNo"), job.getJobType() + " " + StringUtil.removeAllLeadingZero(job.getJobNumber())); //$NON-NLS-1$ //$NON-NLS-2$ } private void addJobPriority(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("priority"), app.enumUtil.jobPriorityEnum.get(job.getPriority())); //$NON-NLS-1$ } private void addAppointment(Job job, GridLayout gridLayout) { // Ternim String atpointmentText = ServiceMessages.getString("appointment"); //$NON-NLS-1$ String appointmentLabel = atpointmentText; String appointmentValue = ServiceMessages.getString("noAppointmentKnown"); //$NON-NLS-1$ if (job.getWeek() == 0 && !job.isFixed()) { appointmentLabel = atpointmentText; appointmentValue = job.getAppointmentDateAsString(); } else if (job.getWeek() == 0 && job.isFixed()) { appointmentLabel = ServiceMessages.getString("appointmentDefined"); //$NON-NLS-1$ appointmentValue = job.getHtmlAppointmentDate(); } else if (job.getWeek() > 0) { appointmentLabel = atpointmentText; appointmentValue = ServiceMessages.getString("week") + Integer.toString(job.getWeek()); //$NON-NLS-1$ } createInfoTextView(gridLayout, appointmentLabel, appointmentValue); if (job.isAppointment()) { createInfoTextView(gridLayout, "", ServiceMessages.getString("coordinateAppointment")); //$NON-NLS-1$ //$NON-NLS-2$ } } private void addOnCallService(Job job, GridLayout gridLayout) { String onCallService = "-"; //$NON-NLS-1$ if (job.getJobType().isREP()) { if (job.isCallServiceFlag()) { onCallService = ServiceMessages.getString("yes"); } else { onCallService = ServiceMessages.getString("no"); } } createInfoTextView(gridLayout, ServiceMessages.getString("onCall"), onCallService); //$NON-NLS-1$ } private void addLink(Job job, GridLayout gridLayout) { if (job.getLink().isEmpty()) { createInfoTextView(gridLayout, ServiceMessages.getString("link"), "-"); } else { createLinkTextView(gridLayout, ServiceMessages.getString("link"), job.getLink()); } } private void addBackOffice(Job job, GridLayout gridLayout) { String backOfficeLabel; if (job.getJobType().isMON()) { backOfficeLabel = ServiceMessages.getString("projectLeader"); //$NON-NLS-1$ } else { backOfficeLabel = ServiceMessages.getString("backOffice"); //$NON-NLS-1$ } createInfoTextView(gridLayout, backOfficeLabel, job.getStaffName()); createInfoTextView(gridLayout, "", job.getStaffPhoneNumber()); //$NON-NLS-1$ } private void addJobCreationDate(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("receipt"), job.getHtmlDateTimeNewJobDate()); //$NON-NLS-1$ } private void addInstallationNo(Job job, GridLayout gridLayout) { String vbeln = "-"; //$NON-NLS-1$ if (job.getCommissionNumber().length() > 0) { vbeln = job.getCommissionNumber(); } createInfoTextView(gridLayout, Messages.getString("commNo"), vbeln); //$NON-NLS-1$ } private void addDriveUnit(Job job, GridLayout gridLayout) { String driveUnit = "-"; //$NON-NLS-1$ if (job.getDriveType().length() > 0) { driveUnit = job.getDriveType(); } createInfoTextView(gridLayout, ServiceMessages.getString("drive"), driveUnit); //$NON-NLS-1$ } private void addResponsible(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("caseHandler"), job.getTechnicalName()); //$NON-NLS-1$ createInfoTextView(gridLayout, "", job.getTechnicalPhoneNumber()); //$NON-NLS-1$ } private void addSalesperson(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("salesPerson"), job.getSellerName()); //$NON-NLS-1$ createInfoTextView(gridLayout, "", job.getSellerPhoneNumber()); //$NON-NLS-1$ } private void addAllowedTime(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("allowedTime"), job.getDefaultTime() + ServiceMessages.getString("hrs")); //$NON-NLS-1$ //$NON-NLS-2$ } private void addErrorMsgCode(Job job, GridLayout gridLayout) { String errorMsgCode = "-"; //$NON-NLS-1$ if (job.getJobType().isREP()) { errorMsgCode = job.getErrorId(); } createInfoTextView(gridLayout, ServiceMessages.getString("errorCode"), errorMsgCode); //$NON-NLS-1$ } private void addCheckCycles(Job job, GridLayout gridLayout) { String checkCycles = "-"; //$NON-NLS-1$ if (job.isCycleOfInstallationFlag()) { checkCycles = ServiceMessages.getString("yes"); } else { checkCycles = ServiceMessages.getString("no"); } createInfoTextView(gridLayout, ServiceMessages.getString("checkCycles"), checkCycles); //$NON-NLS-1$ } private void addDocumentRequired(Job job, GridLayout gridLayout) { String documentRequired = ""; String formDesc1 = getFormDesc(job.getFormDesc1()); String formDesc2 = getFormDesc(job.getFormDesc2()); String formDesc3 = getFormDesc(job.getFormDesc3()); documentRequired += documentRequired.isEmpty() ? formDesc1:(formDesc1.isEmpty() ? "": ", " + formDesc1); documentRequired += documentRequired.isEmpty() ? formDesc2:(formDesc2.isEmpty() ? "": ", " + formDesc2); documentRequired += documentRequired.isEmpty() ? formDesc3:(formDesc3.isEmpty() ? "": ", " + formDesc3); createInfoTextView(gridLayout, ServiceMessages.getString("Document"), documentRequired); //$NON-NLS-1$ } private String getFormDesc(String formDesc) { String result = ""; JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(formDesc); if (jobFormDesc != null && !jobFormDesc.getFormDesc().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { result = jobFormDesc.getText(); } return result; } private void addSAV(Job job, GridLayout gridLayout) { // Title createInfoTextView(gridLayout, ServiceMessages.getString("SAV"), ""); //$NON-NLS-1$ //$NON-NLS-2$ // SAV Code createInfoTextView(gridLayout, ServiceMessages.getString("maintenanceCode"), job.getMaintenanceContractType()); //$NON-NLS-1$ // SAV geplant createInfoTextView(gridLayout, ServiceMessages.getString("maintenancePlanned"), job.getServicePlanMonth1() + " " //$NON-NLS-1$ //$NON-NLS-2$ + job.getServicePlanMonth2() + " " //$NON-NLS-1$ + job.getServicePlanMonth3() + " " //$NON-NLS-1$ + job.getServicePlanMonth4() + " " //$NON-NLS-1$ + job.getServicePlanMonth5() + " " //$NON-NLS-1$ + job.getServicePlanMonth6() + " "); //$NON-NLS-1$ // SAV offen createInfoTextView(gridLayout, ServiceMessages.getString("openMaintenance"), job.getServiceOpen()); //$NON-NLS-1$ } private void addResponsibleSAN(Job job, GridLayout gridLayout) { String responsibleSan = "-"; //$NON-NLS-1$ if (job.getContactName().length() > 0) { responsibleSan = job.getContactName(); } createInfoTextView(gridLayout, ServiceMessages.getString("SAVResponsible"), responsibleSan); //$NON-NLS-1$ if (job.getContactPhoneNumber().length() > 0) { createInfoTextView(gridLayout, "", job.getContactPhoneNumber()); //$NON-NLS-1$ } } private void addMoreInformations(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("moreInformations"), ServiceMessages.getString(job.isMoreInformationsFlag() == true ? "yes" : "no")); } private void addEmptyRow(GridLayout gridLayout) { createInfoTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Adds Notes layout and contents. * * @param job * @param targetLinearLayout */ private void addImportantContents(Job job, LinearLayout targetLinearLayout) { GridLayout gridLayout = createGridLayout(ServiceMessages.getString("Important")); gridLayout.setColumnCount(1); addNoteTextView(gridLayout, job.getDescription()); addNoteTextView(gridLayout, job.getInformation()); targetLinearLayout.addView(cardView); } private void addNoteTextView(GridLayout gridLayout, String text) { if (text.isEmpty()) { return; } TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewParams = new GridLayout.LayoutParams(); gridTextViewParams.width = 0; gridTextViewParams.height = LayoutParams.WRAP_CONTENT; gridTextViewParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); textView.setLayoutParams(gridTextViewParams); textView.setText(text.replace("\\n", System.getProperty("line.separator"))); //$NON-NLS-1$ //$NON-NLS-2$ textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridLayout.addView(textView); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.businessobjects.ServerJob; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobSearchListForm.JobSearchListFormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The Job Download Result Form. * * * @see "[MIG-451] Visualize already downloaded jobs by job search" */ public class JobDownloadResultForm extends SuperForm{ private static Log log = LogFactory.getLog(JobDownloadResultForm.class); private String jobType; private CheckBoxListWidget checkBoxListWidget; private List selectedList; private Map downloadErrorMap; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.jobType = formArguments.getJobType(); this.selectedList = formArguments.getSelectedList(); this.downloadErrorMap = formArguments.getDownloadErrorMap(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } public static class FormArguments { private String jobType; private List selectedList; private Map downloadErrorMap; public FormArguments(String jobType, List selectedList, Map downloadErrorMap) { this.jobType = jobType; this.selectedList = selectedList; this.downloadErrorMap = downloadErrorMap; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public List getSelectedList() { return selectedList; } public void setSelectedList(List selectedList) { this.selectedList = selectedList; } public Map getDownloadErrorMap() { return downloadErrorMap; } public void setDownloadErrorMap(Map downloadErrorMap) { this.downloadErrorMap = downloadErrorMap; } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); saveButton.setVisible(false); // create download action ActionCtrl downloadButton = addActionCtrl(false, true, 1, "onConfirmonPressed"); //$NON-NLS-1$ downloadButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DONE_WHITE, CommonConstants.Images.IMAGE_DPI))); downloadButton.setTitle(ServiceMessages.getString("confirm")); //$NON-NLS-1$ RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); checkBoxListWidget = new CheckBoxListWidget(context); checkBoxListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); checkBoxListWidget.setDividerHeight(1); checkBoxListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // set empty items ArrayList items = new ArrayList(); checkBoxListWidget.addItems(items); contentLinearLayout.addView(checkBoxListWidget); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { setFormTitle(jobType + " " + ServiceMessages.getString("download")); //$NON-NLS-1$ //$NON-NLS-2$ app.messageUtil.showContinueMessage(); checkBoxListWidget.clean(); ArrayList items = new ArrayList(); for (String jobNumber : selectedList) { ServerJob data = app.dbutil.selectServerJob(jobNumber); final CheckBoxListWidgetItem item = new CheckBoxListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(StringUtil.removeAllLeadingZero(data.getJobNumber()) + ": " + data.getStreet() + " " + data.getPostalCode() + " " + data.getCity()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ item.setStringLine1(JobType.MON.equals(jobType)?data.getcommissionNumberNoLeadingZero():data.getCommissionNumber() + " " + data.getLocation()); //$NON-NLS-1$ item.setCheck(false); if (downloadErrorMap.containsKey(jobNumber)) { // show error message item.setTextColor(LayoutUtils.DEFAULT_RED); item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_ERROR, CommonConstants.Images.IMAGE_DPI))); item.setStringLine2(downloadErrorMap.get(jobNumber)); } else { item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_SUCCESS, CommonConstants.Images.IMAGE_DPI))); item.setStringLine2(jobType + "-Code: " + data.getServiceContractType() + "*/ " + data.getMonthYear() + "**" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } items.add(item); } checkBoxListWidget.addItems(items); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobSearchListForm.class, new JobSearchListFormArguments(jobType)); } protected ApplicationEvent onConfirmonPressed() { return app.closeForm(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.res.ColorStateList; import android.support.v7.widget.AppCompatRadioButton; import android.text.InputFilter; import android.text.InputType; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.businessobjects.Drive; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The job new/edit form class. * * @author nop (02-03-2017) * * @see "[MIG-46] implement of "create job" */ public class JobEditForm extends AddressEditSuperForm implements OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(JobEditForm.class); protected String vbeln; protected int personalNumber; protected String commissionFormat; protected boolean isNewJob = false; protected Address objectAddress; protected Address partnerAddress; protected MDSpinner zantrtypValue; protected MDEditText zantrtypDescription; protected AppCompatRadioButton firmaRadioButton; protected AppCompatRadioButton personRadioButton; protected MDSpinner personTitleValue; protected MDEditText personFirstName; protected MDEditText personLastName; protected MDEditText personAddition; protected MDSpinner companyTitleValue; protected MDEditText company; protected MDEditText companyName; protected MDEditText companyAddition; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; vbeln = formArguments.getVbeln(); job = formArguments.getJob(); objectAddress = job.getObjectAddress(); partnerAddress = job.getPartnerAddress(); job.setCommissionNumber(vbeln); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); return view; } public View createJobDetailNewEditView(Context context) { RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout headerLinearLayout = new LinearLayout(context); headerLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerLinearLayout.setOrientation(LinearLayout.VERTICAL); // zantrty zantrtypValue = MDSpinner.createDefaultSpinner(headerLinearLayout, ServiceMessages.getString("drive"), true); //$NON-NLS-1$ zantrtypValue.setTag("ZANTRTYP"); //$NON-NLS-1$ zantrtypValue.setOnItemSelectedListener(this); // zantrty description zantrtypDescription = MDEditText.createDefaultEditText(context, false); zantrtypDescription.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); zantrtypDescription.setEnabled(false); zantrtypDescription.setFocusable(true); zantrtypDescription.setFocusableInTouchMode(true); headerLinearLayout.addView(zantrtypDescription); contentLinearLayout.addView(headerLinearLayout); RadioGroup radioGroup = new RadioGroup(context); LinearLayout.LayoutParams radioGroupParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); radioGroupParams.topMargin = 10; radioGroupParams.bottomMargin = 10; radioGroup.setLayoutParams(radioGroupParams); radioGroup.setPadding(10, 0, 10, 10); radioGroup.setOrientation(LinearLayout.HORIZONTAL); radioGroup.setOnCheckedChangeListener(this); contentLinearLayout.addView(radioGroup); ColorStateList colorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_enabled } }, new int[] { LayoutUtils.DEFAULT_TEXT_COLOR }); firmaRadioButton = new AppCompatRadioButton(context); firmaRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 3f)); firmaRadioButton.setText(ServiceMessages.getString("enterprise")); //$NON-NLS-1$ firmaRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); firmaRadioButton.setSupportButtonTintList(colorStateList); firmaRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); firmaRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(firmaRadioButton); personRadioButton = new AppCompatRadioButton(context); personRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); personRadioButton.setText(ServiceMessages.getString("person")); //$NON-NLS-1$ personRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); personRadioButton.setSupportButtonTintList(colorStateList); personRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); personRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(personRadioButton); RelativeLayout formRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams formRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); formRelativeLayoutParams.topMargin = 10; formRelativeLayout.setLayoutParams(formRelativeLayoutParams); formRelativeLayout.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); // person title personTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ personTitleValue.setTag("PERSON_TITLE"); //$NON-NLS-1$ personTitleValue.setOnItemSelectedListener(this); linearLayout.addView(personTitleValue.getTopParent(), 0); personFirstName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("firstName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ personFirstName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(personFirstName), 1); personLastName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("lastName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true, this); //$NON-NLS-1$ personLastName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(personLastName), 2); personAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ personAddition.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(personAddition), 3); // company company = MDEditText.createDefaultEditText(context, ServiceMessages.getString("enterprise"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true, this); //$NON-NLS-1$ company.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(company), 0); companyAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ companyAddition.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(companyAddition), 1); // company title companyTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ companyTitleValue.setTag("COMPANY_TITLE"); //$NON-NLS-1$ companyTitleValue.setOnItemSelectedListener(this); linearLayout.addView(companyTitleValue.getTopParent(), 2); companyName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("name"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true, this); //$NON-NLS-1$ companyName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(companyName), 3); formRelativeLayout.addView(linearLayout); contentLinearLayout.addView(formRelativeLayout); ScrollView scrollView = new ScrollView(context); LinearLayout.LayoutParams scrollViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); scrollView.setLayoutParams(scrollViewParams); relativeLayout.addView(contentLinearLayout); scrollView.addView(relativeLayout); return scrollView; } @Override public void loadData() { if(zantrtypValue == null) { view.addView(createJobDetailNewEditView(context)); } // set dialog's title setFormTitle(ServiceMessages.getString("jobEdit")); //$NON-NLS-1$ personalNumber = app.dbutil.getUser().getPersonalNumber(); // zantrty List driveValueList = new ArrayList(); List driverList = app.dbutil.selectDriveList(); if (!driverList.isEmpty()) { for (int i = 0; i < driverList.size(); i++) { Drive drive = driverList.get(i); driveValueList.add(new CustomSpinnerItem(drive.getCode(), drive.getText(), drive.getLongText())); } } zantrtypValue.setContents(driveValueList); if (StringUtil.isNotEmpty(job.getDriveType()) && !driveValueList.isEmpty()) { zantrtypValue.setSelectionByName(job.getDriveType()); } else { zantrtypValue.setSelection(0); } Drive zantrtyp = app.dbutil.selectDriveByText(job.getDriveType()); if (zantrtyp != null && zantrtyp.isLongText()) { zantrtypDescription.setText(job.getDescription()); } // title List titleValueList = new ArrayList(); @SuppressWarnings("rawtypes") Iterator itr = app.enumUtil.titelEnum.iterator(); while (itr.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) itr.next(); titleValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } personTitleValue.setContents(titleValueList); companyTitleValue.setContents(titleValueList); if (StringUtil.isNotEmpty(objectAddress.getTitle()) && !titleValueList.isEmpty()) { String title = app.enumUtil.titelEnum.get(objectAddress.getTitle()); personTitleValue.setSelectionByName(title); companyTitleValue.setSelectionByName(title); } else { personTitleValue.setSelection(0); companyTitleValue.setSelection(0); } personFirstName.setText(objectAddress.getName1()); personLastName.setText(objectAddress.getName2()); personAddition.setText(objectAddress.getName3()); company.setText(objectAddress.getName1()); companyName.setText(objectAddress.getName2()); companyAddition.setText(objectAddress.getName3()); location.setText(objectAddress.getLocation()); street.setText(objectAddress.getStreet()); zip.setText(objectAddress.getPostalCode()); city.setText(objectAddress.getCity()); tel1.setText(objectAddress.getTelNumber1()); tel2.setText(objectAddress.getTelNumber2()); fax.setText(objectAddress.getFaxNumber()); email.setText(objectAddress.getEmail()); if (objectAddress.isPrivate()) { personRadioButton.setChecked(true); } else { firmaRadioButton.setChecked(true); } } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { clearErrorMessages(); if (firmaRadioButton.isChecked()) { setPersonInfomation(false); setFimaInfomation(true); } else if (personRadioButton.isChecked()) { setPersonInfomation(true); setFimaInfomation(false); } } private void setFimaInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } company.setVisibility(visibility); companyAddition.setVisibility(visibility); companyTitleValue.setRequired(isVisible); companyTitleValue.getTopParent().setVisibility(visibility); companyName.setVisibility(visibility); } private void setPersonInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } personTitleValue.getTopParent().setVisibility(visibility); personFirstName.setVisibility(visibility); personLastName.setVisibility(visibility); personAddition.setVisibility(visibility); } @Override public void onFormReset() { super.onFormReset(); zantrtypValue.setSelection(0); zantrtypDescription.getText().clear(); personTitleValue.setSelection(0); personFirstName.getText().clear(); personLastName.getText().clear(); personAddition.getText().clear(); companyTitleValue.setSelection(0); company.getText().clear(); companyName.getText().clear(); companyAddition.getText().clear(); } @Override protected boolean isValid() { boolean result = super.isValid(); String selectMessage = Messages.getString("pleaseSelectValue"); //$NON-NLS-1$ String provideMessage = Messages.getString("pleaseProvideValue"); //$NON-NLS-1$ if (zantrtypValue.getSelectedItemPosition() == 0) { zantrtypValue.setError(selectMessage); result = false; } if (firmaRadioButton.isChecked()) { if (companyTitleValue.isRequired() && companyTitleValue.getSelectedItemPosition() == 0) { companyTitleValue.setError(selectMessage); result = false; } if ("".equals(company.getText().toString().trim())) { //$NON-NLS-1$ company.setError(provideMessage); result = false; } if ("".equals(companyName.getText().toString().trim())) { //$NON-NLS-1$ companyName.setError(provideMessage); result = false; } } else { if (personTitleValue.isRequired() && personTitleValue.getSelectedItemPosition() == 0) { personTitleValue.setError(selectMessage); result = false; } if ("".equals(personLastName.getText().toString().trim())) { //$NON-NLS-1$ personLastName.setError(provideMessage); result = false; } } return result; } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (objectAddress.isInitial()) { objectAddress.setJobNumber(job.getJobNumber()); objectAddress.setJobType(job.getJobType()); objectAddress.setPartnerNummer("$" + CommonConstants.randomInt(9)); //$NON-NLS-1$ job.setIdObjectAddress(objectAddress); app.dbutil.insertAddress(objectAddress); } if (partnerAddress.isInitial()) { partnerAddress.setJobNumber(job.getJobNumber()); partnerAddress.setJobType(job.getJobType()); partnerAddress.setPartnerNummer("$" + CommonConstants.randomInt(9)); //$NON-NLS-1$ job.setIdByPartnerAddress(partnerAddress); app.dbutil.insertAddress(partnerAddress); } assignToObject(); app.dbutil.updateJob(job); return onBackPressed(); } }; return true; } public void assignToObject() { job.setCommissionNumber(vbeln); job.setDriveType(zantrtypValue.getSelectedName()); job.setDescription(zantrtypDescription.getText().toString()); job.setPersonalNumber(personalNumber); String title = ""; //$NON-NLS-1$ // private address if (personRadioButton.isChecked()) { if (personTitleValue.getSelectedItemPosition() != 0) { title = personTitleValue.getSelectedId(); } partnerAddress.setName1(personFirstName.getText().toString()); partnerAddress.setName2(personLastName.getText().toString()); objectAddress.setName1(personLastName.getText().toString()); partnerAddress.setName3(personAddition.getText().toString()); partnerAddress.setPrivate(true); objectAddress.setPrivate(true); } // enterprise address else if (firmaRadioButton.isChecked()) { if (companyTitleValue.getSelectedItemPosition() != 0) { title = companyTitleValue.getSelectedId(); } objectAddress.setName1(company.getText().toString()); partnerAddress.setName1(company.getText().toString()); partnerAddress.setName2(companyName.getText().toString()); partnerAddress.setName3(companyAddition.getText().toString()); partnerAddress.setPrivate(false); objectAddress.setPrivate(false); } objectAddress.setTitle(title); partnerAddress.setTitle(title); objectAddress.setLocation(location.getText().toString()); objectAddress.setStreet(street.getText().toString()); objectAddress.setCity(city.getText().toString()); objectAddress.setPostalCode(zip.getText().toString()); partnerAddress.setTelNumber1(tel1.getText().toString()); partnerAddress.setTelNumber2(tel2.getText().toString()); partnerAddress.setFaxNumber(fax.getText().toString()); partnerAddress.setEmail(email.getText().toString()); objectAddress.setDIRTYFLG(true); partnerAddress.setDIRTYFLG(true); } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("ZANTRTYP".equals(parent.getTag())) { //$NON-NLS-1$ zantrtypValue.clearError(); CustomSpinnerItem zantrtypCustomSpinner = (CustomSpinnerItem)zantrtypValue.getSelectedItem(); if ("ANDERE".equalsIgnoreCase(zantrtypCustomSpinner.getName())) { //$NON-NLS-1$ zantrtypDescription.setEnabled(true); zantrtypDescription.setText(zantrtypCustomSpinner.getDescription()); zantrtypDescription.requestFocus(zantrtypCustomSpinner.getDescription().length()); zantrtypDescription.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); } else { zantrtypDescription.setEnabled(false); zantrtypDescription.setText(zantrtypCustomSpinner.getDescription()); zantrtypDescription.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); } } else if ("PERSON_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ personTitleValue.clearError(); } else if ("COMPANY_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ companyTitleValue.clearError(); } } @Override public void onNothingSelected(AdapterView arg0) { // Do nothing } public boolean checkDbKeys(String mldnr, String parnrJob, String parnr) { if (mldnr == null || parnrJob == null || parnr == null) { return false; } if (parnrJob.equalsIgnoreCase(parnr)) { return false; } else if (app.dbutil.cntJobid(mldnr) > 0) { return false; } else if (app.dbutil.cntPerNo(parnrJob) > 0) { return false; } else if (app.dbutil.cntPerNo(parnr) > 0) { return false; } return true; } public static class FormArguments { private boolean isNewJob; private String vbeln; private Job job; private Address objectAddress; private Address partnerAddress; protected FormArguments() { } protected FormArguments(Job job) { } public FormArguments(boolean isNewJob, String vbeln, Job job, Address objectAddress, Address partnerAddress) { this.isNewJob = isNewJob; this.vbeln = vbeln; this.job = job; this.objectAddress = objectAddress; this.partnerAddress = partnerAddress; } public boolean isNewJob() { return isNewJob; } public String getVbeln() { return vbeln; } public Job getJob() { return job; } public Address getObjectAddress() { return objectAddress; } public Address getPartnerAddress() { return partnerAddress; } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { super.onTextChanged(s, start, before, count); if (personLastName.hasFocus()) { personLastName.clearError(); } if (company.hasFocus()) { company.clearError(); } if (companyName.hasFocus()) { companyName.clearError(); } } @Override public void clearErrorMessages() { super.clearErrorMessages(); zantrtypValue.clearError(); if (firmaRadioButton.isChecked()) { companyTitleValue.clearError(); } else { personTitleValue.clearError(); } personLastName.clearError(); company.clearError(); companyName.clearError(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.stepstone.stepper.StepperLayout; import com.stepstone.stepper.VerificationError; import com.stepstone.stepper.internal.type.AbstractStepperType; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RadioButton; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReturnReason; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.adapters.StepAdapter; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.RadioButtonListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.RadioButtonListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StepUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Forward a Job with 2 steps form. * * @author cyu (29-08-2019) * * @see "[MIG-463] Forwarding of partly done jobs" */ public class JobForwardForm extends SuperForm { private static Log log = LogFactory.getLog(JobForwardForm.class); private Job job; private MDSpinner reasonValue; private Image backImage; private StepperLayout stepper; private RadioButtonListWidget dialoglistWidget; private RadioButtonListWidgetItem radioButtonListWidgetItemSelected = null; private RadioButton radioButtonSelected = null; @Override public void onFormCall(Object argument) { if (argument instanceof JobForwardFormArgument) { JobForwardFormArgument formArguments = (JobForwardFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobListForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); saveButton.setVisible(false); view.addView(createStepView()); return view; } private View createStepView() { StepUtil jobContentStep = new StepUtil(createForwardReasonStep(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(!reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { return null; } else { reasonValue.setError(Messages.getString("pleaseSelectValue")); return new VerificationError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } @Override public void onSelected() { //update UI when selected } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText } }); StepUtil partnerDialogStepUtil = new StepUtil(createPartnerDialogStep(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(radioButtonListWidgetItemSelected != null) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { job.setStatusEdit(new Date()); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.FORWARDED, JobStatus.SAP_Forwarded, reasonValue.getSelectedId()); return app.leaveToForm(JobListForm.class); } }, false); return null; } else { app.showMessage(ServiceMessages.getString("noEmployeeSelected"), true); //$NON-NLS-1$ return new VerificationError(ServiceMessages.getString("noEmployeeSelected")); //$NON-NLS-1$ } } @Override public void onSelected() { loadPartner(); } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText } }); StepAdapter myStepAdapter = new StepAdapter(context, jobContentStep, partnerDialogStepUtil); // create a mobile stepper with 'dot' progress stepper = new StepperLayout.Builder(context) .setStepperType(AbstractStepperType.DOTS).create(); // link layout to step adapter stepper.setAdapter(myStepAdapter); return stepper; } private View createForwardReasonStep(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout reasonLinearLayout = new LinearLayout(context); reasonLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); reasonLinearLayout.setOrientation(LinearLayout.VERTICAL); // reason reasonValue = MDSpinner.createDefaultSpinner(reasonLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { reasonValue.setError(null); reasonValue.clearError(); } @Override public void onNothingSelected(AdapterView arg0) { } }); contentLinearLayout.addView(reasonLinearLayout); return contentLinearLayout; } private View createPartnerDialogStep(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); dialoglistWidget = new RadioButtonListWidget(context); // Search View SearchView partnerSearchView = new SearchView(context); partnerSearchView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); partnerSearchView.setQueryHint(ServiceMessages.getString("search")); //$NON-NLS-1$ partnerSearchView.setFocusable(true); partnerSearchView.setFocusableInTouchMode(true); partnerSearchView.setBackgroundColor(LayoutUtils.DEFAULT_SEARCH_COLOR); partnerSearchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String queryText) { dialoglistWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { dialoglistWidget.getAdapter().getFilter().filter(queryText); return true; } }); contentLinearLayout.addView(partnerSearchView); contentLinearLayout.addView(dialoglistWidget); return contentLinearLayout; } private void loadPartner() { dialoglistWidget.clean(); final List partnerList = app.dbutil.selectEmployeeList(app.dbutil.getUser(), ""); //$NON-NLS-1$ final ArrayList items = new ArrayList(); for (int i = 0; i < partnerList.size(); i++) { final Employee partner = partnerList.get(i); final RadioButtonListWidgetItem item = new RadioButtonListWidgetItem(); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); item.setLeftRadioButtonTag(String.valueOf(partner.getPersonalNumber())); item.setTitleText(partner.getLastName() + " " + partner.getFirstName()); //$NON-NLS-1$ item.setStringLine1(ServiceMessages.getString("telWColon") + partner.getPhoneNumber()); //$NON-NLS-1$ item.setStringLine2(ServiceMessages.getString("personalNumber") + ":" + partner.getPersonalNumber()); //$NON-NLS-1$ //$NON-NLS-2$ item.setOnClickListener(onPartnerItemClicked(item, partner)); if (radioButtonListWidgetItemSelected != null) { if (radioButtonListWidgetItemSelected.getLeftRadioButtonTag().equalsIgnoreCase(item.getLeftRadioButtonTag())) { item.setCheck(true); } } items.add(item); } dialoglistWidget.addItems(items); } private OnClickListener onPartnerItemClicked(final RadioButtonListWidgetItem item, final Employee partner) { return new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton && partner.getPhoneNumber() != null) { String phoneNumber = partner.getPhoneNumber().replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } if (v instanceof RadioButton) { RadioButton radioButton = (RadioButton) v; if (radioButton.isChecked()) { job.setJobForward(partner.getPersonalNumber()); } //MIG-228 Forward of a job to a partner caused a app crash // remove checked all radioButtonListWidgetItem if(radioButtonListWidgetItemSelected != null) { radioButtonListWidgetItemSelected.setCheck(false); } radioButtonListWidgetItemSelected = item; // remove checked all radioButton if(radioButtonSelected != null) { radioButtonSelected.setChecked(false); } radioButtonSelected = radioButton; radioButtonListWidgetItemSelected.setCheck(true); radioButtonSelected.setChecked(true); } } }; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); radioButtonListWidgetItemSelected = null; // set dialog's title setFormTitle(ServiceMessages.getString("forward")); //$NON-NLS-1$ List reasonValueList = new ArrayList(); List reasonList = app.dbutil.selectJobDeleteReasonList(); for (int i = 0; i < reasonList.size(); i++) { Reason reason = reasonList.get(i); reasonValueList.add(new CustomSpinnerItem(reason.getReasonText(), reason.getText(), reason.getText())); } reasonValue.setContents(reasonValueList); return null; } @Override public void onFormReset() { super.onFormReset(); stepper.setCurrentStepPosition(0); } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return onBackPressed(); } }; return true; } public static class JobForwardFormArgument { private Job job; protected JobForwardFormArgument() { } public JobForwardFormArgument(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.ServerJob; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult.Status; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm.JobSearchFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The Job List Result Form For Job Search. * * @author nop (20-04-2017) * * @see "[MIG-52] implement of "search job"" */ public class JobSearchListForm extends SuperForm{ private static Log log = LogFactory.getLog(JobSearchListForm.class); private String jobType; private CheckBoxListWidget checkBoxListWidget; private List selectedList = new ArrayList(); @Override public void onFormCall(Object argument) { if (argument instanceof JobSearchListFormArguments) { JobSearchListFormArguments formArguments = (JobSearchListFormArguments) argument; this.jobType = formArguments.getJobType(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); saveButton.setVisible(false); // create download Button ActionCtrl downloadButton = addActionCtrl(false, true, 1, "onDownloadPressed"); //$NON-NLS-1$ downloadButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_WHITE, CommonConstants.Images.IMAGE_DPI))); downloadButton.setTitle(ServiceMessages.getString("download")); //$NON-NLS-1$ RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); checkBoxListWidget = new CheckBoxListWidget(context); checkBoxListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); checkBoxListWidget.setDividerHeight(1); checkBoxListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // set empty items ArrayList items = new ArrayList(); checkBoxListWidget.addItems(items); contentLinearLayout.addView(checkBoxListWidget); relativeLayout.addView(contentLinearLayout); view = new LinearLayout(context); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { setFormTitle(jobType + " " + ServiceMessages.getString("download")); //$NON-NLS-1$ //$NON-NLS-2$ app.messageUtil.showContinueMessage(); checkBoxListWidget.clean(); new AsyncTask(this) { private List employeeList; @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { employeeList = app.dbutil.selectEmployeeList(""); return null; } @Override protected void runOnUIThread() { final List jobList = app.dbutil.selectServerJobList(); ArrayList items = new ArrayList(); for (int i = 0; i < jobList.size(); i++) { final ServerJob data = jobList.get(i); final CheckBoxListWidgetItem item = new CheckBoxListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(StringUtil.removeAllLeadingZero(data.getJobNumber()) + ": " + data.getStreet() + " " + data.getPostalCode() + " " + data.getCity()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ item.setStringLine1(JobType.MON.equals(jobType)?data.getcommissionNumberNoLeadingZero():data.getCommissionNumber() + " " + data.getLocation()); //$NON-NLS-1$ item.setCheck(false); if (!new JobType(jobType).isMON() && !data.getPersonalNumber().isEmpty() && !data.getPersonalNumber().equalsIgnoreCase("00000000")) { item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK, CommonConstants.Images.IMAGE_DPI))); String fullname = ""; for (Employee employee : employeeList) { if (employee.getPersonalNumber() == Integer.parseInt(data.getPersonalNumber())) { fullname = employee.getFirstName() + " " + employee.getLastName(); } } item.setStringLine2("Bezogen von.: " + fullname + " / "+ StringUtil.removeAllLeadingZero(data.getPersonalNumber())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { item.isShowLeftCheckBox(true); item.setLeftCheckBoxTag(data.getJobNumber()); item.setStringLine2(jobType + "-Code: " + data.getServiceContractType() + "*/ " + data.getMonthYear() + "**" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { CheckBox checkBox = (CheckBox) v; if (checkBox.isChecked()) { selectedList.add(checkBox.getTag().toString()); } else { selectedList.remove(checkBox.getTag().toString()); } item.setCheck(checkBox.isChecked()); } } }); items.add(item); } checkBoxListWidget.addItems(items); } }; return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobSearchForm.class, new JobSearchFormArguments(null)); } @Override public void onFormReset() { super.onFormReset(); jobType = null; selectedList = new ArrayList(); setFormTitle(null); } protected ApplicationEvent onDownloadPressed() { if (selectedList.isEmpty()) { app.showMessage(ServiceMessages.getString("selectOneOrMoreJobs")); //$NON-NLS-1$ return null; } if (ServiceJobUtil.isMaxDownload(selectedList)) { app.showMessage(ServiceMessages.getString("youCanSelectMaximumOf30Jobs")); //$NON-NLS-1$ return null; } downloadJobs(); return null; } private void downloadJobs() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (ServiceJobUtil.isMaxConfirmDownload(selectedList)) { String message = MessageFormat.format(ServiceMessages.getString("doYouReallyWantToLoadXjobsAtOnce"), new Object[] { selectedList.size()}); //$NON-NLS-1$ if (app.showMessageBox(message, ServiceMessages.getString("confirmation"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ Application.MBOX_ICON_QUESTION) == Application.MBOX_RESULT_NO) { return null; } } Map downloadErrorMap = new HashMap(); for (String mldnr : selectedList) { RemoteTransactionResult result = getOrder(mldnr); if (result.getStatus() == Status.error) { if ("E".equalsIgnoreCase(result.getMessageType()) && !result.getMessage().isEmpty()) { downloadErrorMap.put(mldnr, result.getMessage()); } else { return null; } } } return app.leaveToForm(JobDownloadResultForm.class, new JobDownloadResultForm.FormArguments(jobType, selectedList, downloadErrorMap)); } }; } private RemoteTransactionResult getOrder(String mldnr) { RemoteTransactionResult result = new RemoteTransactionHandler().runGetOrder(mldnr, jobType, app.dbutil.getUser().getPersonalNumber()); if (result.getStatus() == Status.success && result.getMessage().isEmpty()) { Job job = app.dbutil.selectJobByJobIdAndJobType(mldnr, jobType); //MIG-883 Wrong personal number in SAVE_REPORT in a specific use case if (job.getPersonalNumber() != app.dbutil.getUser().getPersonalNumber()) { log.info("pernr " + job.getPersonalNumber() + " received, update to active user."); job.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); } job.calculateActiveDate(); // every job who is downloaded by user have to be set automatically in status RECEIVED (including UPDATE_STATUS to backend). new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } return result; } public static class JobSearchListFormArguments { private String jobType; public JobSearchListFormArguments(String jobType) { this.jobType = jobType; } public JobSearchListFormArguments(String jobType, String commissionNumber) { this.jobType = jobType; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.FormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ui.LayoutInflater; /** * * see "MIG-611 Checklist for MON-jobs" */ public class ReportChecklistForm extends SuperForm { private static Log log = LogFactory.getLog(ReportChecklistForm.class); private Job job; private Person user; private CheckListRadioGroup stateRadioGroup; private CheckListRadioGroup sIARadioGroup; private CheckListRadioGroup readyRadioGroup; private CheckListRadioGroup instructionRadioGroup; private CheckListRadioGroup testCheckListRadioGroup; @Override public ApplicationEvent onBackPressed() { onCancel(); leaveToJobDetailForm(); return null; } @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 0, 16, 16); stateRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(stateRadioGroup); sIARadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(sIARadioGroup); readyRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(readyRadioGroup); instructionRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(instructionRadioGroup); testCheckListRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(testCheckListRadioGroup); saveButton.setTitle(ServiceMessages.getString("save")); view.addView(contentLinearLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); onFormReset(); // set dialog's title this.setFormTitle(ServiceMessages.getString("Checklist")); //$NON-NLS-1$ loadData(); user = app.dbutil.getUser(); stateRadioGroup.setText(getText("ChecklistStateText")); sIARadioGroup.setText(getText("ChecklistSIAText")); readyRadioGroup.setText(getText("ChecklistReadyText")); instructionRadioGroup.setText(getText("ChecklistInstructionText")); testCheckListRadioGroup.setText(getText("ChecklistTestText")); return null; } @Override public void onFormReset() { super.onFormReset(); stateRadioGroup.reset(); sIARadioGroup.reset(); readyRadioGroup.reset(); instructionRadioGroup.reset(); testCheckListRadioGroup.reset(); } /** * Loads data. */ public void loadData() { Report report = this.job.getCurrentReport(); // All radio button groups have to be unselected (both buttons). log.info("checklist " + report.getChecklistState() ); if (!report.isChecklistStateUnselected()) { stateRadioGroup.setChecked(report.isChecklistState()); } if (!report.isChecklistSIAUnselected()) { sIARadioGroup.setChecked(report.isChecklistSIA()); } if (!report.isChecklistReadyUnselected()) { readyRadioGroup.setChecked(report.isChecklistReady()); } if (!report.isChecklistInstructionUnselected()) { instructionRadioGroup.setChecked(report.isChecklistInstruction()); } if (!report.isChecklistTestUnselected()) { testCheckListRadioGroup.setChecked(report.isChecklistTest()); } } @Override protected boolean isValid() { boolean result = super.isValid(); // View focusView = null; // String errorMessage = Messages.getString("pleaseProvideValue"); return result; } @Override protected boolean onSave() { //The user have to click at least at one button of each group (yes or no) //Check if all radio buttons group have at least one selected button //The checklist cannot be saved if at least one radio button group is unselected (in this case, the user can leave the UI only with "x" icon in app bar if (stateRadioGroup.isEmpty() || sIARadioGroup.isEmpty() || readyRadioGroup.isEmpty() || instructionRadioGroup.isEmpty() || testCheckListRadioGroup.isEmpty()) { return false; } Report report = this.job.getLatestReport(); // assign value to object and insert new report assignToReport(report); app.dbutil.insertReplaceReport(report); log.info("Report saved." + report.getGuId()); app.dbutil.updateJob(job); job.loadReports(app.dbutil); leaveToJobDetailForm(); return true; } private void assignToReport(Report rep) { rep.setChecklistState(stateRadioGroup.isChecked()); rep.setChecklistSIA(sIARadioGroup.isChecked()); rep.setChecklistReady(readyRadioGroup.isChecked()); rep.setChecklistInstruction(instructionRadioGroup.isChecked()); rep.setChecklistTest(testCheckListRadioGroup.isChecked()); } private void leaveToJobDetailForm() { app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailForm.JobDetailFormArgument(job, 2)); } public void onCancel() { } @Override public void clearErrorMessages() { super.clearErrorMessages(); } private String getText(String key) { log.info("ProfileText " + user.getProfileText() + " Language " + user.getLanguage()); if (user.getProfileText().equalsIgnoreCase(CommonConstants.CommissionNumber.CH)) { Locale locale = Locale.ENGLISH; if (user.getLanguage().equalsIgnoreCase("D")) { locale = Locale.GERMAN; } else if (user.getLanguage().equalsIgnoreCase("F")) { locale = Locale.FRANCE; } return ServiceMessages.getString(locale, key); } else if (user.getProfileText().equalsIgnoreCase(CommonConstants.CommissionNumber.DE)) { return ServiceMessages.getString(Locale.GERMAN, key); } return ServiceMessages.getString(key); } private class CheckListRadioGroup extends LinearLayout { private MDRadioButton yesRadioButton; private MDRadioButton noRadioButton; private TextView textView; public CheckListRadioGroup(Context context) { super(context); addView(createVKFView()); } private View createVKFView() { GridLayout gridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); gridLayout.setLayoutParams(gridLayoutParams); gridLayout.setColumnCount(3); RelativeLayout yesRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams yesRelativeLayoutParams = new GridLayout.LayoutParams(); yesRelativeLayoutParams.width = 0; yesRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; yesRelativeLayoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.1f); yesRelativeLayoutParams.leftMargin = LayoutUtils.convertDpToPixel(context, 6); yesRelativeLayout.setLayoutParams(yesRelativeLayoutParams); TextView YesTextView = new TextView(context); YesTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); YesTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams yesTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); YesTextView.setLayoutParams(yesTextViewValueParams); YesTextView.setText(ServiceMessages.getString("yes")); YesTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); YesTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); yesRelativeLayout.addView(YesTextView); gridLayout.addView(yesRelativeLayout); RelativeLayout noRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams noRelativeLayoutParams = new GridLayout.LayoutParams(); noRelativeLayoutParams.width = 0; noRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; noRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.1f); noRelativeLayoutParams.leftMargin = LayoutUtils.convertDpToPixel(context, 6); noRelativeLayout.setLayoutParams(noRelativeLayoutParams); TextView noTextView = new TextView(context); noTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); noTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams noTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); noTextView.setLayoutParams(noTextViewValueParams); noTextView.setText(ServiceMessages.getString("no")); noTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); noTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); noRelativeLayout.addView(noTextView); gridLayout.addView(noRelativeLayout); RelativeLayout emptyGridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams emptyGridRelativeLayoutParams = new GridLayout.LayoutParams(); emptyGridRelativeLayoutParams.width = 0; emptyGridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; emptyGridRelativeLayoutParams.columnSpec = GridLayout.spec(2, 1, 0.8f); emptyGridRelativeLayout.setLayoutParams(emptyGridRelativeLayoutParams); gridLayout.addView(emptyGridRelativeLayout); GridLayout.LayoutParams yesRadioButtonGridLayoutParams = new GridLayout.LayoutParams(); yesRadioButtonGridLayoutParams.width = 0; yesRadioButtonGridLayoutParams.height = LayoutParams.WRAP_CONTENT; yesRadioButtonGridLayoutParams.columnSpec = GridLayout.spec(0, 1, 0.1f); yesRadioButton = MDRadioButton.createDefaultRadioButton(gridLayout, ""); ((LinearLayout) yesRadioButton.getParent()).setLayoutParams(yesRadioButtonGridLayoutParams); GridLayout.LayoutParams noRadioButtonGridLayoutParams = new GridLayout.LayoutParams(); noRadioButtonGridLayoutParams.width = 0; noRadioButtonGridLayoutParams.height = LayoutParams.WRAP_CONTENT; noRadioButtonGridLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.1f); noRadioButton = MDRadioButton.createDefaultRadioButton(gridLayout, ""); ((LinearLayout) noRadioButton.getParent()).setLayoutParams(noRadioButtonGridLayoutParams); RelativeLayout textRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams textRelativeLayoutParams = new GridLayout.LayoutParams(); textRelativeLayoutParams.width = 0; textRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; textRelativeLayoutParams.columnSpec = GridLayout.spec(2, 1, 0.8f); textRelativeLayout.setLayoutParams(textRelativeLayoutParams); textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); textView.setLayoutParams(gridTextViewValueParams); textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textRelativeLayout.addView(textView); gridLayout.addView(textRelativeLayout); yesRadioButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (((MDRadioButton) v).isChecked()) { noRadioButton.setChecked(false); } } }); noRadioButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (((MDRadioButton) v).isChecked()) { yesRadioButton.setChecked(false); } } }); textView.setClickable(true); textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!yesRadioButton.isChecked()) { yesRadioButton.setChecked(true); noRadioButton.setChecked(false); } else { yesRadioButton.setChecked(false); noRadioButton.setChecked(true); } } }); return gridLayout; } public void setText(String text) { textView.setText(text); } public boolean isChecked() { return yesRadioButton.isChecked(); } public void setChecked(boolean checklistState) { if (checklistState) { yesRadioButton.setChecked(true); noRadioButton.setChecked(false); } else { yesRadioButton.setChecked(false); noRadioButton.setChecked(true); } } public void reset() { yesRadioButton.setChecked(false); noRadioButton.setChecked(false); } public boolean isEmpty() { return !yesRadioButton.isChecked() && !noRadioButton.isChecked(); } public void setError(CharSequence error) { yesRadioButton.setError(error); noRadioButton.setError(error); } public void clearError() { yesRadioButton.clearError(); noRadioButton.clearError(); } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.forms.ReportDocumentDetailForm.ReportDocumentDetailFormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class ReportDocumentAttachmentsListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportDocumentAttachmentsListForm.class); protected Job job; private Toolbar toolbar; protected DetailListWidget listWidget; private ActionCtrl addButton; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportDocumentAttachmentsListFormArguments) { ReportDocumentAttachmentsListFormArguments formArguments = (ReportDocumentAttachmentsListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new DetailListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, Messages.getString("noDocumentsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(Messages.getString("documents")); //$NON-NLS-1$ loadImageAttachmentsList(); return null; } private void loadImageAttachmentsList() { listWidget.clean(); Map> reportDocumentsList = app.dbutil.selectDocumentListByReport(job.getLatestReport()); view.removeAllViews(); if(reportDocumentsList.isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); Iterator> iterator = reportDocumentsList.values().iterator(); List> docs = new ArrayList>(); while (iterator.hasNext()) { List jobFiles = iterator.next(); final DetailListWidgetItem item = new DetailListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); String title = ""; String line1 = "-"; String line2 = ""; JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(jobFiles.get(0).getFormDesc()); if (jobFormDesc != null && !jobFormDesc.getFormDesc().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { line1 = jobFormDesc.getText(); } String noForm = ""; if (job.getFormDesc1().equalsIgnoreCase(jobFiles.get(0).getFormDesc())) { noForm = job.getLatestReport().getNoForm1(); } else if (job.getFormDesc2().equalsIgnoreCase(jobFiles.get(0).getFormDesc())) { noForm = job.getLatestReport().getNoForm2(); } else if (job.getFormDesc3().equalsIgnoreCase(jobFiles.get(0).getFormDesc())) { noForm = job.getLatestReport().getNoForm3(); } if (jobFiles.get(0).getJobFileId().contains("NO_FORM")) { if (noForm.isEmpty()) noForm = jobFiles.get(0).getJobFileId().substring(jobFiles.get(0).getJobFileId().length()-2, jobFiles.get(0).getJobFileId().length()); title = app.dbutil.selectJobNoFormByNoForm(noForm).getText(); line2 = Messages.getString("noDocumentsRecorded"); } else { title = jobFiles.get(0).getDescription(); line2 = jobFiles.size() + " " + Messages.getString("documents"); } item.setTitleText(title); item.setStringLine1(line1); item.setStringLine2(line2); items.add(item); docs.add(jobFiles); } listWidget.setOnItemClickListener(createOnItemClickListener(docs)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List> docs) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { app.injectAndLeaveToForm(ReportDocumentDetailForm.class, new ReportDocumentDetailForm.ReportDocumentDetailFormArguments(job, docs.get(position))); //$NON-NLS-1$ } }; } protected ApplicationEvent onAddPressed() { return app.leaveToForm(ReportDocumentDetailForm.class, new ReportDocumentDetailFormArguments(job, new ArrayList())); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } public static class ReportDocumentAttachmentsListFormArguments { private Job job; public ReportDocumentAttachmentsListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportDocumentDetailForm.ReportDocumentDetailFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportDocumentAttachmentsNewEditForm extends DialogForm { private static Log log = LogFactory.getLog(ReportDocumentAttachmentsNewEditForm.class); // initialized by the kolibri framework... public static ServiceApplication app; private Job job; private Bitmap bitmap; private JobFile jobFile; private List jobFiles; private ImageView image; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil utilButton; @Override public void onFormCall(Object argument) { if (argument instanceof ReportDocumentAttachmentsNewEditFormArguments) { ReportDocumentAttachmentsNewEditFormArguments formArguments = (ReportDocumentAttachmentsNewEditFormArguments) argument; job = formArguments.getJob(); bitmap = formArguments.getBitmap(); jobFile = formArguments.getJobFile(); jobFiles = formArguments.getJobFiles(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; utilButton = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMaxHeight(800); image.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, null); return false; } }); contentLinearLayout.addView(image); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroup.setPadding(2, 2, 2, 2); radioGroup.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.addView(radioGroup); messages = MDEditText.createDefaultEditText(contentLinearLayout, "description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); Button deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(jobFile == null) { messages.getText().clear(); } else { actionDelete(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(contentLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("Document")); //$NON-NLS-1$ messages.getText().clear(); image.setImageBitmap(null); if (bitmap == null) { bitmap = jobFile.getSignPicBitmap(); } image.setImageBitmap(bitmap); if(!jobFile.getDescription().isEmpty()) messages.setText(jobFile.getDescription()); return null; } @Override protected ApplicationEvent onSavePressed() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (jobFile.getJobFileId().isEmpty()) { Date date = new Date(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); if (jobFile.isValid()) { jobFiles.add(jobFile); app.dbutil.insertJobFile(jobFile); } else { throw new ApplicationException(); } } else { jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); app.dbutil.updateJobFile(jobFile); } return onBackPressed(); } }; return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ReportDocumentDetailForm.class, new ReportDocumentDetailFormArguments(job, jobFiles)); } private void actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { app.dbutil.deleteJobFile(jobFile); jobFiles.remove(jobFile); } finally { db.commit(); } app.showMessage(ServiceMessages.getString("fileDeleted")); //$NON-NLS-1$ return onBackPressed(); } }; } public static class ReportDocumentAttachmentsNewEditFormArguments { private Job job; private Bitmap bitmap; private JobFile jobFile; private List jobFiles; public ReportDocumentAttachmentsNewEditFormArguments(Job zkdmob ,Bitmap bitmap, JobFile jobFile, List jobFiles) { this.job = zkdmob; this.bitmap = bitmap; this.jobFile = jobFile; this.jobFiles = jobFiles; } public Job getJob() { return job; } public Bitmap getBitmap() { return bitmap; } public JobFile getJobFile() { return jobFile; } public List getJobFiles() { return jobFiles; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.util.ServiceFormUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class ReportFormListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportFormListForm.class); protected Job job; private Form formSelected = null; private Toolbar toolbar; protected CheckBoxListWidget listWidget; private ActionCtrl addButton; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportFormListFormArguments) { ReportFormListFormArguments formArguments = (ReportFormListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new CheckBoxListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noFormsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("Forms")); //$NON-NLS-1$ loadFormTable(); return null; } private void loadFormTable() { listWidget.clean(); view.removeAllViews(); if (app.dbutil.selectFormInstanceListByGuid( job.getLatestReport().getGuId()).isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); List formItem = new ArrayList(); for (final Form form : app.dbutil.selectFormList()) { List formItemList = app.dbutil.selectFormItemListByFormIdAndFormVersion(form.getId(), form.getVersion()); if (!formItemList.isEmpty()) { List formInstances = app.dbutil.selectFormInstanceListByGuidAndFormId(job.getLatestReport().getGuId(), form.getId()); if (!formInstances.isEmpty()) { final CheckBoxListWidgetItem item = new CheckBoxListWidgetItem(); item.isShowRightLayout(true); item.setCheck(false); item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ServiceFormUtil.getCheckImageStatus(formItemList, formInstances), CommonConstants.Images.IMAGE_MAX_DPI))); item.setTitleText(form.getName()); item.setStringLine1(form.getDescription()); item.setStringLine2(String.valueOf(form.getVersion())); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EDIT, CommonConstants.Images.IMAGE_MAX_DPI))); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { formSelected = form; leaveToEditForm(); } }); items.add(item); formItem.add(form); } } } listWidget.setClickable(false); // listWidget.setOnItemClickListener(createOnItemClickListener(formItem)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List formList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { formSelected = formList.get(position); leaveToEditForm(); } }; } private void leaveToEditForm() { if (formSelected == null) { return; } app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportFormNewEditForm.class, new ReportFormNewEditForm.FormArguments(job, formSelected)); } }, false); } private void showFormsDialog() { List items = new ArrayList(); formSelected = null; final List forms = app.dbutil.selectValidFormList(); for (Form form : forms) { log.info("Form " + form.getName() + " id " + form.getId() + " status " + form.getStatus() + " valid from " + DateTimeUtil.showDateTime(form.getValidFrom()) + " valid to " + DateTimeUtil.showDateTime(form.getValidTo())); items.add(form.getName()); } MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("ChooseForm"), ServiceMessages.getString("cancel")); alertDialog.setSingleChoiceItems(items.toArray(new String[0]), -1, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { formSelected = forms.get(which); } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { leaveToEditForm(); } }); alertDialog.show(); } protected ApplicationEvent onAddPressed() { showFormsDialog(); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } public static class ReportFormListFormArguments { private Job job; public ReportFormListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.FormValueList; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormItemType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.BitmapLoadUtils; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportFormListForm.ReportFormListFormArguments; import ch.mfiles.kaba.kolibri.service.ui.widgets.FormImageLayout; import ch.mfiles.kaba.kolibri.service.util.SignatureUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.ui.SignatureView; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.LayoutHelper; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ReportFormNewEditForm extends SuperForm { private static Log log = LogFactory.getLog(ReportFormNewEditForm.class); protected Job job; private Form form; private List formItems; private LinearLayout formContentLinearLayout; private ScrollView scrollView; private Toolbar toolbar; private final String CONTENT_VIEW = "CONTENT"; private Map formItemValueMap = new HashMap(); private Map cardMap = new HashMap(); private AppCompatButton deleteButton; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; job = formArguments.getJob(); form = formArguments.getForm(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); // set invisible save button // saveButton.setVisible(false); formContentLinearLayout = new LinearLayout(context); formContentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); formContentLinearLayout.setOrientation(LinearLayout.VERTICAL); formContentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout content = new LinearLayout(context); content.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); content.setOrientation(LinearLayout.VERTICAL); // Button LinearLayout deleteButtonLinearLayout = new LinearLayout(context); // deleteButtonLinearLayout.setLayoutParams(getGridLayoutParams(31, 0, 3)); deleteButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable deleteButtonGradientDrawable = new GradientDrawable(); deleteButtonGradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); deleteButtonGradientDrawable.setCornerRadius(7); deleteButtonGradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); deleteButton = new AppCompatButton(context); LinearLayout.LayoutParams deleteButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); deleteButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; deleteButton.setLayoutParams(deleteButtonParams); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new View.OnClickListener() { private boolean showConfirmDeleteDialog() { return app.showMessageBox(ServiceMessages.getString("areYouSureThatYouWantToDeleteRecord"), ServiceMessages.getString("warning"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK; } @Override public void onClick(View paramView) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (showConfirmDeleteDialog()) { app.dbutil.deleteFormInstanceByGuidAndFormId(job.getCurrentReport().getGuId(), String.valueOf(form.getId())); // delete saved signature. Iterator> itrView = formItemValueMap.entrySet().iterator(); while (itrView.hasNext()) { Entry entry = itrView.next(); FormItemValue formItemValue = (FormItemValue)entry.getValue(); FormInstance formInstance = formItemValue.getFormInstance(); if (formInstance != null && !formInstance.getAttachmentValue().isEmpty()) { if (formItemValue.getView() instanceof SignatureView) { app.deleteFile(formInstance.getAttachmentValue()); } if (formItemValue.getView() instanceof FormImageLayout) { app.deleteFile(formInstance.getAttachmentValue()); } formInstance.setAttachmentValue(""); } } return app.leaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); } return null; } }; } }); deleteButton.setBackgroundDrawable(deleteButtonGradientDrawable); deleteButton.setContentDescription("delete"); deleteButtonLinearLayout.addView(deleteButton); content.addView(formContentLinearLayout); content.addView(deleteButtonLinearLayout); saveButton.setTitle(ServiceMessages.getString("save")); scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(content); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); toolbar.setEnabled(true); setFormTitle(form.getName()); createContent(); scrollView.scrollBy(0, 0); return null; } private void resetAllContents() { formContentLinearLayout.removeAllViews(); cardMap.clear(); formItemValueMap.clear(); } private void createContent() { resetAllContents(); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_MARGIN); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(form.getName()); titleTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(titleTextView); TextView descriptionTextView = new TextView(context); descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); descriptionTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); descriptionTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); descriptionTextView.setText(form.getDescription()); descriptionTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(descriptionTextView); formContentLinearLayout.addView(linearLayout); formItems = app.dbutil.selectFormItemListByFormIdAndFormVersion(form.getId(), form.getVersion()); deleteButton.setEnabled(!formItems.isEmpty()); if (formItems.isEmpty()) { return; } for (FormItem formItem : formItems) { if (cardMap.containsKey(formItem.getCardName())) { } else { CardView cardView = createCardView(formItem.getCardName()); formContentLinearLayout.addView(cardView); cardMap.put(formItem.getCardName(), cardView); } LinearLayout cardContent = (LinearLayout) cardMap.get(formItem.getCardName()).findViewWithTag(CONTENT_VIEW); cardContent.addView(createView(formItem)); } } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); if (toolbar.isEnabled()) { toolbar.setEnabled(false); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("TheFormIsDiscardedContinue"), ServiceMessages.getString("discardForm"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { app.injectAndLeaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); } toolbar.setEnabled(true); return null; } }, false); } return null; } @Override protected boolean isValid() { boolean result = super.isValid(); View focusView = null; String errorMessage = Messages.getString("pleaseProvideValue"); Iterator> itrView = formItemValueMap.entrySet().iterator(); while (itrView.hasNext()) { Entry entry = itrView.next(); FormItemValue formItemValue = (FormItemValue)entry.getValue(); if (formItemValue.getView() instanceof MDSpinner) { final MDSpinner mdSpinner = (MDSpinner)formItemValue.getView(); if (mdSpinner.isRequired() && (mdSpinner.getSelectedId() == CommonConstants.PLEASE_SELECT || mdSpinner.getSelectedId().isEmpty()) ) { result = false; focusView = mdSpinner; mdSpinner.setError(errorMessage); } log.info("combo box " + mdSpinner.getTextView().getText() + " value " + mdSpinner.getSelectedName()+ " --> " + mdSpinner.getSelectedId()); } if (formItemValue.getView() instanceof MDEditText) { final MDEditText editText = (MDEditText)formItemValue.getView(); if (editText.getText().toString().isEmpty() && editText.isRequired()) { result = false; editText.setError(errorMessage); focusView = editText; } } if (formItemValue.getView() instanceof FormImageLayout) { FormImageLayout formImageLayout = (FormImageLayout)formItemValue.getView(); if (formImageLayout.isRequire() && formImageLayout.getImageBitmap() == null) { result = false; app.showMessage(formImageLayout.getErrorMessage(), true); } } } if (!result && focusView != null) { scrollView.scrollTo(0, (int) focusView.getY()); focusView.requestFocus(); } return result; } @Override protected boolean onSave() { List newFormInstances = new ArrayList(); Iterator> itrView = formItemValueMap.entrySet().iterator(); while (itrView.hasNext()) { Entry entry = itrView.next(); FormItemValue formItemValue = (FormItemValue)entry.getValue(); FormInstance formInstance = formItemValue.getFormInstance(); if (formInstance == null) { formInstance = new FormInstance(); formInstance.setGuid(job.getCurrentReport().getGuId()); formInstance.setFormId(form.getId()); formInstance.setFormItemId(String.valueOf(entry.getKey())); formInstance.setFormVersion(formItemValue.getFormItem().getFormVersion()); formInstance.setFormItemType(formItemValue.getFormItem().getFormItemType().getCode()); } newFormInstances.add(assignToFormInstance(formItemValue.getView(), formInstance)); } app.dbutil.insertOrReplaceJobReportFormInstanceList(newFormInstances); app.injectAndLeaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); return false; } private FormInstance assignToFormInstance(View view, FormInstance formInstance) { if (view instanceof RadioButton) { RadioButton radioButton = (RadioButton)view; formInstance.setBooleanValue(radioButton.isChecked()); } if (view instanceof MDSpinner) { final MDSpinner mdSpinner = (MDSpinner)view; formInstance.setValueId(mdSpinner.getSelectedId()); formInstance.setValueListId(String.valueOf(mdSpinner.getTag())); log.info("combo box " + mdSpinner.getTextView().getText() + " value " + mdSpinner.getSelectedName() + " --> " + mdSpinner.getSelectedId()); log.info("ValueId " + formInstance.getValueId() + " ValueListId " + formInstance.getValueListId()); } if (view instanceof AppCompatCheckBox) { AppCompatCheckBox appCompatCheckBox = (AppCompatCheckBox)view; formInstance.setBooleanValue(appCompatCheckBox.isChecked()); } if (view instanceof MDEditText) { final MDEditText editText = (MDEditText)view; if (!editText.getText().toString().isEmpty()) { if (editText.getInputType() == InputType.TYPE_CLASS_NUMBER) { formInstance.setFloatValue(Double.valueOf(editText.getText().toString())); } else { formInstance.setStringValue(editText.getText().toString()); } } } if (view instanceof SignatureView) { SignatureView signatureView = (SignatureView)view; String imagePath; if (!formInstance.getAttachmentValue().isEmpty()) { imagePath = formInstance.getAttachmentValue(); // app.deleteFile(imagePath); } else { // Generate file name and path for the signature file imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, form.getId() + "_" + formInstance.getFormItemId() + "_" + Long.toString(new Date().getTime()) + ".bmp", true); } if (signatureView.isDirty()) { // signature from UI -> save file try { log.info("image path " + imagePath); if (log.isDebugEnabled()) log.debug("Save signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ String originalImagePath = SignatureUtil.getOriginalSignatureFileName(imagePath); signatureView.save(originalImagePath); signatureView.save(imagePath, SignatureUtil.TARGET_WIDTH, SignatureUtil.TARGET_HEIGHT, SignatureUtil.TARGET_DENSITY); log.info("originalImagePath path " + originalImagePath); formInstance.setAttachmentValue(imagePath); } catch (IOException e) { throw new ApplicationException(e); } } } if (view instanceof FormImageLayout) { FormImageLayout formImageLayout = (FormImageLayout)view; String imagePath; if (!formInstance.getAttachmentValue().isEmpty()) { imagePath = formInstance.getAttachmentValue(); } else { // Generate file name and path for the signature file imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, form.getId() + "_" + formInstance.getFormItemId() + "_" + Long.toString(new Date().getTime()) + ".jpg", true); } if (formImageLayout.getImageBitmap() != null) { // image loaded from UI -> save Image File (new/edit) FileUtils.writeBitmapToFile(imagePath, formImageLayout.getImageBitmap()); formInstance.setAttachmentValue(imagePath); } else { app.deleteFile(imagePath); formInstance.setAttachmentValue(""); } } return formInstance; } protected CardView createCardView(String title) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 10, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MIN_MARGIN); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_MARGIN); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(title); titleTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(titleTextView); // --------------- content-------------------- LinearLayout content = new LinearLayout(context); content.setTag(CONTENT_VIEW); content.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); content.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(content); // --------------- content-------------------- cardView.addView(linearLayout); return cardView; } private LinearLayout createView(FormItem formItem) { LinearLayout result = null; log.info("FormItemType " + formItem.getFormItemType().getCode()); switch (formItem.getFormItemType().getCode()) { case FormItemType.RDBT: result = createRadio(formItem); break; case FormItemType.COMB: result = createComboBox(formItem); break; case FormItemType.CHKB: result = createCheckBox(formItem); break; case FormItemType.TEXT: result = createTextInput(formItem); break; case FormItemType.NUMF: result = createTextInput(formItem); break; case FormItemType.SIGN: result = createSignature(formItem); break; case FormItemType.TITL: result = createTitle(formItem); break; case FormItemType.SEPR: result = createSeparator(formItem); break; case FormItemType.IMAG: result = createImage(formItem); break; default: result = new LinearLayout(context); break; } return result; } private LinearLayout createRadio(FormItem formItem) { LinearLayout radioLinearLayout = new LinearLayout(context); radioLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioLinearLayout.setOrientation(LinearLayout.VERTICAL); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setOrientation(LinearLayout.VERTICAL); RadioButton radioButton = new RadioButton(context); radioButton.setTag(formItem.getId()); radioButton.setText(formItem.getLabel()); radioButton.setChecked(false); radioGroup.addView(radioButton); // contentItemMap.put(formItem.getId(), radioButton); // // if (valueItemMap.containsKey(formItem.getId())) { // radioButton.setChecked(Boolean.valueOf(valueItemMap.get(formItem.getId()))); // } FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { radioButton.setChecked(Boolean.valueOf(formInstance.isBooleanValue())); formItemValue.setFormInstance(formInstance); } formItemValue.setView(radioButton); formItemValueMap.put(formItem.getId(), formItemValue); return radioLinearLayout; } private LinearLayout createComboBox(FormItem formItem) { LinearLayout comboBoxLinearLayout = new LinearLayout(context); comboBoxLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); final MDSpinner combo = MDSpinner.createDefaultSpinner(comboBoxLinearLayout, formItem.getLabel(), formItem.isMandatory()); combo.setTag(formItem.getId()); combo.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { combo.clearError(); } }); combo.setTag(formItem.getValueListId()); List formValueLists = app.dbutil.selectValueListsByValueListId(formItem.getValueListId()); List customSpinnerItemList = new ArrayList(); String emptyText = formItem.getEmptyText(); log.info("formItem " + formItem.getLabel() + " EmptyText " + formItem.getEmptyText()); customSpinnerItemList.add(new CustomSpinnerItem("", emptyText)); boolean isDuplicated = false; String defaultValueId = ""; for (FormValueList formValueList : formValueLists) { log.info("formValueList " + formValueList.getValueId() + " value " + formValueList.getValue() + " default " + formValueList.isDefaultValue()); if (formValueList.getValue().equalsIgnoreCase(emptyText)) { isDuplicated = true; defaultValueId = formValueList.getValueId(); } if (formValueList.isDefaultValue()) { defaultValueId = formValueList.getValueId(); } customSpinnerItemList.add(new CustomSpinnerItem(formValueList.getValueId(), formValueList.getValue())); } if (isDuplicated) { customSpinnerItemList.remove(0); } combo.setContents(customSpinnerItemList); if (!defaultValueId.isEmpty()) { combo.setSelectionById(defaultValueId); } FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { combo.setSelectionById(formInstance.getValueId()); formItemValue.setFormInstance(formInstance); } formItemValue.setView(combo); formItemValueMap.put(formItem.getId(), formItemValue); return comboBoxLinearLayout; } private LinearLayout createCheckBox(FormItem formItem) { LinearLayout checkBoxViewLinearLayout = new LinearLayout(context); checkBoxViewLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); AppCompatCheckBox checkBox = CommonUtilForm.getCheckBox(context, formItem.getLabel()); //$NON-NLS-1$ checkBox.setChecked(false); checkBox.setTag(formItem.getId()); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); checkBoxViewLinearLayout.addView(checkBox); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { checkBox.setChecked(formInstance.isBooleanValue()); formItemValue.setFormInstance(formInstance); } formItemValue.setView(checkBox); formItemValueMap.put(formItem.getId(), formItemValue); return checkBoxViewLinearLayout; } private LinearLayout createTextInput(FormItem formItem) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout barcodeLinearLayout = new LinearLayout(context); barcodeLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams barcodeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLinearLayoutParams.gravity = Gravity.CENTER; barcodeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.weight = 1; barcodeLinearLayout.setLayoutParams(barcodeLinearLayoutParams); barcodeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); int type = InputType.TYPE_CLASS_NUMBER; if (formItem.getFormItemType().isTEXT()) { type = InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; } if (formItem.getFormItemType().isNUMF()) { type = InputType.TYPE_CLASS_NUMBER; } final MDEditText barcodeEditText = MDEditText.createDefaultEditText(barcodeLinearLayout, formItem.getLabel(), type, formItem.isMandatory()); LinearLayout.LayoutParams barcodeLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLayoutParams.gravity = Gravity.CENTER; barcodeLayoutParams.width = 0; barcodeLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLayoutParams.weight = formItem.getFormItemType().isTEXT()? 0.9f:1f; barcodeEditText.getParentTextInputLayout().setLayoutParams(barcodeLayoutParams); log.info("text " + formItem.getLabel() + " is Require " + formItem.isMandatory()); barcodeEditText.setTag(formItem.getId()); if (formItem.getMaxStringSize() > 0) { barcodeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(formItem.getMaxStringSize()) }); } barcodeEditText.clearFocus(); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { barcodeEditText.setText(formItem.getFormItemType().isNUMF()? String.valueOf(formInstance.getFloatValue()) : formInstance.getStringValue()); formItemValue.setFormInstance(formInstance); } formItemValue.setView(barcodeEditText); formItemValueMap.put(formItem.getId(), formItemValue); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = formItem.getFormItemType().isTEXT()? 0.1f:0f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { private String barcode = ""; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { if (barcodeEditText.getInputType() == (InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)) { if (!barcode.isEmpty()) { barcodeEditText.requestFocus(); barcodeEditText.getText().clear(); barcodeEditText.append(barcode); } } } }; } }); cameraLinearLayout.addView(gridImageView); barcodeLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(barcodeLinearLayout); return contentLinearLayout; } private LinearLayout createSeparator(FormItem formItem) { LinearLayout separatorLayout = new LinearLayout(context); separatorLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); separatorLayout.setOrientation(LinearLayout.HORIZONTAL); separatorLayout.setPadding(0, 0, 0, LayoutUtils.DEFAULT_MIN_PADDING); DividerView dividerView = new DividerView(context); separatorLayout.addView(dividerView); return separatorLayout; } private LinearLayout createTitle(FormItem formItem) { LinearLayout titleLinearLayout = new LinearLayout(context); titleLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); textView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textView.setPadding(5, 10, 5, 5); textView.setText(formItem.getLabel()); textView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); titleLinearLayout.addView(textView); return titleLinearLayout; } private LinearLayout createSignature(FormItem formItem) { LinearLayout signatureLinearLayout = new LinearLayout(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardViewParams.setMargins(0, 0, 0, 0); int height = LayoutParams.MATCH_PARENT; if (LayoutHelper.getDisplayMetrics().widthPixels > SignatureUtil.TARGET_WIDTH) { height = (int) (LayoutHelper.getDisplayMetrics().widthPixels * SignatureUtil.ASPECT_RATIO); } cardViewParams.width = LayoutParams.MATCH_PARENT; if (height > 0) { cardViewParams.height = height; } signatureLinearLayout.setLayoutParams(cardViewParams); signatureLinearLayout.setPadding(0, 0, 0, 0); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); SignatureView signatureView = new SignatureView(context); linearLayout.addView(signatureView); signatureLinearLayout.addView(linearLayout); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { try { signatureView.load(SignatureUtil.getOriginalSignatureFileName(formInstance.getAttachmentValue())); // signatureView.lock(); } catch (IOException e) { log.error("Found IOException:", e); //$NON-NLS-1$ app.showMessageBox(ServiceMessages.getString("signatureCanNotBeLoadedFromFile"), //$NON-NLS-1$ ServiceMessages.getString("error"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_ERROR); } formItemValue.setFormInstance(formInstance); } formItemValue.setView(signatureView); formItemValueMap.put(formItem.getId(), formItemValue); return signatureLinearLayout; } private LinearLayout createImage(FormItem formItem) { LinearLayout imageViewLinearLayout = new LinearLayout(context); imageViewLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); final FormImageLayout imageLayout = new FormImageLayout(context); imageViewLinearLayout.addView(imageLayout.createFormImageLayout(app, formItem.getLabel(), formItem.isMandatory(), new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Iterator iterator = formItemValueMap.values().iterator(); while (iterator.hasNext()) { FormItemValue formItemValue = iterator.next(); if (formItemValue.getView() instanceof MDEditText) { MDEditText textInput = (MDEditText) formItemValue.getView(); textInput.clearFocus(); } } } })); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { if (!formInstance.getAttachmentValue().isEmpty()) { BitmapLoadUtils.decodeBitmapInBackground(appman.getContext(), Uri.fromFile(new File(formInstance.getAttachmentValue())), new BitmapLoadUtils.BitmapLoadCallback() { @Override public void onFailure(@NonNull Exception bitmapWorkerException) { } public void onBitmapLoaded(Bitmap bitmap, int exifOrientation) { imageLayout.setBitmap(bitmap); } }); formItemValue.setFormInstance(formInstance); } } formItemValue.setView(imageLayout); formItemValueMap.put(formItem.getId(), formItemValue); return imageViewLinearLayout; } public static class FormArguments { private Job job; private Form form; public FormArguments(Job job, Form form) { this.job = job; this.form = form; } public Job getJob() { return job; } public Form getForm() { return form; } public void setForm(Form form) { this.form = form; } } public final class FormItemValue { FormItemValue() { } private String id; private View view; private FormInstance formInstance; private FormItem formItem; public String getId() { return id; } public void setId(String id) { this.id = id; } public View getView() { return view; } public void setView(View view) { this.view = view; } public FormInstance getFormInstance() { return formInstance; } public void setFormInstance(FormInstance formInstance) { this.formInstance = formInstance; } public FormItem getFormItem() { return formItem; } public void setFormItem(FormItem formItem) { this.formItem = formItem; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.FormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * * see "MIG-641 New flag "guarantee" in job" */ public class ReportGuaranteeForm extends SuperForm { private static Log log = LogFactory.getLog(ReportGuaranteeForm.class); private Job job; private RadioButton guaranteeRadioButton; private RadioButton goodwillRadioButton; private RadioButton billingRadioButton; private MDSpinner workTypeValue; @Override public ApplicationEvent onBackPressed() { onCancel(); return app.leaveToForm(ReportEditForm.class, new FormArguments(job, null)); } @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout textViewLinearLayout;textViewLinearLayout = new LinearLayout(context); textViewLinearLayout.setOrientation(LinearLayout.VERTICAL); textViewLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textViewLinearLayout.setPadding(16, 16, 16, 16); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("valid_guarantee_label")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); textViewParams.gravity = Gravity.LEFT; textViewParams.topMargin = 20; textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setLayoutParams(textViewParams); textViewLinearLayout.addView(textView); contentLinearLayout.addView(textViewLinearLayout); LinearLayout radioGroupLinearLayout = new LinearLayout(context); radioGroupLinearLayout.setOrientation(LinearLayout.VERTICAL); radioGroupLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroupLinearLayout.setPadding(16, 16, 16, 16); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setOrientation(LinearLayout.VERTICAL); guaranteeRadioButton = new RadioButton(context); guaranteeRadioButton.setText(ServiceMessages.getString("Guarantee")); radioGroup.addView(guaranteeRadioButton); goodwillRadioButton = new RadioButton(context); goodwillRadioButton.setText(ServiceMessages.getString("Goodwill")); radioGroup.addView(goodwillRadioButton); billingRadioButton = new RadioButton(context); billingRadioButton.setText(Messages.getString("billing")); billingRadioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { workTypeValue.setRequired(isChecked); workTypeValue.setEnabled(isChecked); } }); radioGroup.check(guaranteeRadioButton.getId()); radioGroup.addView(billingRadioButton); radioGroupLinearLayout.addView(radioGroup); contentLinearLayout.addView(radioGroupLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); workTypeValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("typeOfWork"), false); //$NON-NLS-1$ workTypeValue.setEnabled(false); workTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { workTypeValue.clearError(); } }); contentLinearLayout.addView(workTypeLinearLayout); saveButton.setTitle(ServiceMessages.getString("save")); view.addView(contentLinearLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title this.setFormTitle(ServiceMessages.getString("Guarantee")); //$NON-NLS-1$ List typeOfWorkValueList = new ArrayList(); List workTypeList = app.dbutil.selectWorkTypeListByJobType(job.getJobType()); for (WorkType workType : workTypeList) { log.info("WorkType " + workType.getText() + " Guarantee " + workType.isGuarantee()); if (workType.isGuarantee()) { typeOfWorkValueList.add(new CustomSpinnerItem((String) workType.getWorkTypeCode(), (String) workType.getText())); } } workTypeValue.setContents(typeOfWorkValueList); if (!typeOfWorkValueList.isEmpty()) { if (job.getJobType().isSAV()) { workTypeValue.setSelection(5); } } guaranteeRadioButton.setChecked(true); loadData(); return null; } @Override public void onFormReset() { super.onFormReset(); } /** * Loads data. */ public void loadData() { Report report = this.job.getCurrentReport(); } @Override protected boolean isValid() { boolean result = super.isValid(); View focusView = null; String errorMessage = Messages.getString("pleaseProvideValue"); if (workTypeValue.isRequired() && workTypeValue.getSelectedItemPosition() == 0) { workTypeValue.setError(errorMessage); //$NON-NLS-1$ // Überprüfung abbrechen, sonst NPE beim prüfen der SAV monate! result = false; log.info("workTypeValue " + result); if (focusView == null) focusView = workTypeValue; } return result; } @Override protected boolean onSave() { Report report = this.job.getLatestReport(); // assign value to object and insert new report assignToReport(report); if(job.getJobType().isREP() || job.getJobType().isSAV()) { // The change of the type of work in report have to be assumed to all existing timestamps of the report. // This concerns only the job types REP and SAV. if (report.getTimes().size() > 0 && !workTypeValue.getSelectedId().equalsIgnoreCase(report.getTimes().get(0).getWorkTypeCode())) { for (int i = 0; i < report.getTimes().size(); i++) { report.getTimes().get(i).setWorkTypeCode(report.getWorkType());; } report.setTimes(app.dbutil, new ArrayList(job.getCurrentReport().getTimes())); } } app.dbutil.insertReplaceReport(report); log.info("Report saved." + report.getGuId()); leaveToJobDetailForm(); return true; } private void assignToReport(Report rep) { if (guaranteeRadioButton.isChecked()) { rep.setBilling(CommonConstants.Report.BILLING_GUARANTEE); } if (goodwillRadioButton.isChecked()) { rep.setBilling(CommonConstants.Report.BILLING_GOODWILL); } if (billingRadioButton.isChecked()) { rep.setBilling(CommonConstants.PLEASE_SELECT); rep.setWorkType(workTypeValue.getSelectedId()); rep.setTimesWorkType(workTypeValue.getSelectedId(), app.dbutil); } } private void leaveToJobDetailForm() { app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailForm.JobDetailFormArgument(job, 2)); } public void onCancel() { } @Override public void clearErrorMessages() { super.clearErrorMessages(); } private void loadReport(Report report) { } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * New Form. */ public class ReportImageAttachmentsListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportImageAttachmentsListForm.class); protected Job job; private Toolbar toolbar; protected ImageListWidget listWidget; private ActionUtil utilButton; private ActionCtrl addButton; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportImageAttachmentsListFormArguments) { ReportImageAttachmentsListFormArguments formArguments = (ReportImageAttachmentsListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); utilButton = new ActionUtil(app); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new ImageListWidget(context); view.addView(listWidget); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("images")); //$NON-NLS-1$ loadImageAttachmentsList(); return null; } private void loadImageAttachmentsList() { listWidget.clean(); ArrayList items = new ArrayList(); List reportImageAttachmentsList = app.dbutil.selectReportJobFileImageListByReport(job.getLatestReport()); addButton.setEnabled(true); addButton.setImage(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI)); for (int i = 0; i < reportImageAttachmentsList.size(); i++) { final JobFile jobFile = reportImageAttachmentsList.get(i); final ImageListWidgetItem item = new ImageListWidgetItem(); item.setDescription(jobFile.getDescription()); item.setImageBitmap(jobFile.getSignPicBitmap()); log.info("Type " + jobFile.getType()); String type = "Intern"; if("E".equalsIgnoreCase(jobFile.getType())) { type = "z. Hd. Kunden"; } item.setType(type); item.setStatus(ServiceMessages.getString("status") + ": " + ServiceMessages.getString(jobFile.getSentDate().getTime() > 0 ? "sent" : "notSend")); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(reportImageAttachmentsList)); } listWidget.addItems(items); } private OnItemClickListener createOnItemClickListener(final List reportImageAttachmentsList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { JobFile jobFile = reportImageAttachmentsList.get(position); app.injectAndLeaveToForm(ReportImageAttachmentsNewEditForm.class, new ReportImageAttachmentsNewEditForm.ReportImageAttachmentsNewEditFormArguments(job, null, jobFile)); //$NON-NLS-1$ } }; } private void leaveToImageNewEditForm(Bitmap bitmap) { if(bitmap == null) return; app.injectAndLeaveToForm(ReportImageAttachmentsNewEditForm.class, new ReportImageAttachmentsNewEditForm.ReportImageAttachmentsNewEditFormArguments(job, bitmap, null)); } protected ApplicationEvent onAddPressed() { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, null); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } public static class ReportImageAttachmentsListFormArguments { private Job job; public ReportImageAttachmentsListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.support.v7.widget.GridLayout; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Billing; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.MaterialListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.MaterialListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.forms.ReportMaterialNewEditForm.ReportMaterialNewEditFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; /** * New Form. */ public class ReportMaterialListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportMaterialListForm.class); protected Job job; protected MaterialListWidget listWidget; private LinearLayout listLinearLayout; private TextView summayPriceTextView; int materialType; private ReportMaterial selectedReportMaterial; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportMaterialListFormArguments) { ReportMaterialListFormArguments formArguments = (ReportMaterialListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); // GridLayout priceGridLayout = new GridLayout(context); RelativeLayout.LayoutParams priceGridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); priceGridLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, 65), LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 52), LayoutUtils.convertDpToPixel(context, 10)); priceGridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); priceGridLayout.setLayoutParams(priceGridLayoutParams); priceGridLayout.setColumnCount(2); priceGridLayout.setUseDefaultMargins(true); Drawable[] drawables = new Drawable[] { new ColorDrawable(Color.LTGRAY), new ColorDrawable(Color.WHITE)}; LayerDrawable borderDrawable = new LayerDrawable(drawables); // Set padding for background color layer borderDrawable.setLayerInset(1, // Index of the drawable to adjust [background color layer] 0, // Number of pixels to add to the left bound [left border] 0, // Number of pixels to add to the top bound [top border] 0, // Number of pixels to add to the right bound [right border] 4 // Number of pixels to add to the bottom bound [bottom border] ); priceGridLayout.setBackground(borderDrawable); TextView gridTextViewKey = new TextView(priceGridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.5f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(ServiceMessages.getString("summaryTotal")); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); priceGridLayout.addView(gridTextViewKey); RelativeLayout gridRelativeLayout = new RelativeLayout(priceGridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.5f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); summayPriceTextView = new TextView(priceGridLayout.getContext()); summayPriceTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); summayPriceTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); summayPriceTextView.setLayoutParams(gridTextViewValueParams); // summayPriceTextView.setText("value"); // gridTextViewValue.setTextColor(textColor); gridRelativeLayout.addView(summayPriceTextView); priceGridLayout.addView(gridRelativeLayout); contentLinearLayout.addView(priceGridLayout); listLinearLayout = new LinearLayout(context); listLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams listLinearLayoutParams = new LinearLayout.LayoutParams(0,0); listLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; listLinearLayoutParams.height = LayoutParams.FILL_PARENT; listLinearLayoutParams.width = LayoutParams.FILL_PARENT; listLinearLayoutParams.weight = 1f; listLinearLayout.setLayoutParams(listLinearLayoutParams); listWidget = new MaterialListWidget(context); listLinearLayout.addView(listWidget); contentLinearLayout.addView(listLinearLayout); view.addView(contentLinearLayout); // create scan action ActionCtrl scanAction = addActionCtrl(false, true, 1, "onScanPressed"); //$NON-NLS-1$ scanAction.setTitle(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); ActionCtrl actionAdd = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ actionAdd.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("spareParts")); //$NON-NLS-1$ loadMaterialList(); return null; } private void loadMaterialList() { listWidget.clean(); ArrayList items = new ArrayList(); List reportMaterialList = app.dbutil.selectReportMaterialList(job.getCurrentReport().getGuId()); float summayPrice = 0; // Re: MIG-379 Release 2.1.8: No validation for "No material used" // The checkbox should not be activated without user input, even if the user enters the material report overview and leave the form without any input. // if(reportMaterialList.isEmpty()) { // if(!job.getLatestReport().isNoMaterial()) { // job.getLatestReport().setNoMaterial(true); // DatabaseUtil.getInstance().updateReport(job.getLatestReport()); // } // } for (int i = 0; i < reportMaterialList.size(); i++) { final ReportMaterial reportMaterial = reportMaterialList.get(i); final MaterialListWidgetItem item = new MaterialListWidgetItem(); // N = normal material, out of masterdata // P = personal material, self created material // K = K-material, without material number String status = "N"; //$NON-NLS-1$ String price = ""; Billing billing = app.dbutil.selectBillingTypeByJobTypeAndCode(job.getJobType(), reportMaterial.getAccountCode()); if (billing != null) { item.setStringLine2(billing.getText()); } if (reportMaterial.isK14()) { status = "K"; //$NON-NLS-1$ price = reportMaterial.getPrice(); } else { Material selectedMaterial = app.dbutil.selectMaterialByMatNo(reportMaterial.getSparePartNumber()); MaterialPerson materialPerson = app.dbutil.selectMaterialPersonByMatNo(reportMaterial.getSparePartNumber()); if (selectedMaterial != null) { reportMaterial.setSparePartNumber(selectedMaterial.getMaterialNumber()); reportMaterial.setProductName(selectedMaterial.getMaterialShortText()); reportMaterial.setUnit(selectedMaterial.getUnit()); price = (billing != null && billing.getCode().equalsIgnoreCase(ServiceConstants.MATERIAL_BILLING_NEW_PRICE)) ? selectedMaterial.getNewPrice():selectedMaterial.getSubstitutePrice(); } else if (materialPerson != null) { reportMaterial.setSparePartNumber(materialPerson.getMaterialNumber()); reportMaterial.setProductName(materialPerson.getMaterialShortText()); status = "P"; //$NON-NLS-1$ } } item.isShowEllipInTextEnd(true); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); item.setStatusColor(LayoutUtils.DEFAULT_MATERIAL_COLOR); item.setStatusType(status); item.setTitleText(reportMaterial.getProductName()); item.setStringLine1(reportMaterial.getAmount() + " " + reportMaterial.getUnit()); //$NON-NLS-1$ if (price.isEmpty()) { item.setStringPrice("-"); } else { float floatPeice = Float.valueOf(price); float sum = floatPeice * Float.valueOf(reportMaterial.getAmount()); log.info("sum = " + sum); item.setStringPrice(price.isEmpty() ? "-" : formatDecimal(sum)); summayPrice += sum; } item.setStringPrice(price); log.info(price); item.setReplacement(reportMaterial.isDelivery() ? ServiceMessages.getString("additionalDelivery") :""); item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedReportMaterial = reportMaterial; if (v instanceof ImageButton) { onDeletePressed(); } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(reportMaterialList)); } summayPriceTextView.setText(summayPrice > 0? formatDecimal(summayPrice): "-"); listWidget.addItems(items); } private String formatDecimal (float floatValue) { try { log.info("user language " + app.dbutil.getUser().getLanguage()); Locale locale = Locale.ENGLISH; if (app.dbutil.getUser().getLanguage().contains("D")) { //locale = Locale.GERMAN;// outbut = 3.347,20 } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("#,###.00", symbols); format.setMaximumFractionDigits(2); return format.format(floatValue); } catch (NumberFormatException e) { } return ""; } private void onDeletePressed() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { app.dbutil.deleteReportMaterial(selectedReportMaterial); List listParts = app.dbutil.selectReportMaterialList(job.getCurrentReportGuId(app.dbutil)); for (int i = 0; i < listParts.size(); i++) { app.dbutil.updateReportMaterialIdx(listParts.get(i), i); } } finally { db.commit(); } app.showMessage(ServiceMessages.getString("materialWasDeleted")); //$NON-NLS-1$ return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); loadMaterialList(); } }; } private OnItemClickListener createOnItemClickListener(final List reportMatList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { ReportMaterial reportMaterial = reportMatList.get(position); app.injectAndLeaveToForm(ReportMaterialNewEditForm.class, new ReportMaterialNewEditFormArguments(job, reportMaterial, reportMaterial.isK14(), "")); //$NON-NLS-1$ } }; } protected ApplicationEvent onAddPressed() { showMaterialDialog(job); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } protected ApplicationEvent onScanPressed() { new AsyncTask(this) { private String barcode; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(ReportMaterialListForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { app.showMessage(result.toString()); barcode = result.getContents(); log.info("scan result -> " + result.getContents()); //$NON-NLS-1$ return app.leaveToForm(ReportMaterialNewEditForm.class, new ReportMaterialNewEditFormArguments(job, null, false, barcode)); } return null; } }; return null; } private void showMaterialDialog(final Job job) { String[] items = { ServiceMessages.getString("normalMaterial"), ServiceMessages.getString("K14Material") }; //$NON-NLS-1$ //$NON-NLS-2$ MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("typeOfMaterial"),ServiceMessages.getString("cancel")); //$NON-NLS-1$ //$NON-NLS-2$ alertDialog.setSingleChoiceItems(items, materialType, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { materialType = which; } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new OnClickListener() { //$NON-NLS-1$ public void onClick(android.content.DialogInterface dialog, int which) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportMaterialNewEditForm.class, new ReportMaterialNewEditFormArguments(job, null, materialType == 1, "")); //$NON-NLS-1$ } }, false); } }); alertDialog.show(); } public static class ReportMaterialListFormArguments { private Job job; public ReportMaterialListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Typeface; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable.OnCheckedChange; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable.OnEnabledChange; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable.OnItemsChange; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportMeasurementForm extends SuperForm { private static Log log = LogFactory.getLog(ReportMeasurementForm.class); protected Job job; private Toolbar toolbar; private MeasurementTable measurementTable; private MeasurementTable measurementTable2; private MeasurementTable measurementTable3; private CardView cardView1; private CardView cardView2; private CardView cardView3; private boolean isKmgInstalles = true; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportMeasurementFormArguments) { ReportMeasurementFormArguments formArguments = (ReportMeasurementFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); LinearLayout cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); measurementTable = new MeasurementTable(this, app, "01"); measurementTable2 = new MeasurementTable(this, app, "02"); measurementTable3 = new MeasurementTable(this, app, "03"); cardView1 = createCardView(Messages.getString("measurement") + " 1", measurementTable); cardView2 = createCardView(Messages.getString("measurement") + " 2", measurementTable2); cardView3 = createCardView(Messages.getString("measurement") + " 3", measurementTable3); cardLinearLayout.addView(cardView1); cardLinearLayout.addView(cardView2); cardLinearLayout.addView(cardView3); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING , LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); linearLayout.addView(cardLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(linearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // check if KMG-LITE app is present PackageManager pm = appman.getContext().getPackageManager(); PackageInfo pckInfo = null; try { pckInfo = pm.getPackageInfo("de.gte.kmglite.blapp", PackageManager.GET_ACTIVITIES); } catch (NameNotFoundException e) { } if (pckInfo == null) { app.showMessage("KMG-LITE App not installed!"); isKmgInstalles = false; } loadMeasurementTables(); return null; } private void loadMeasurementTables() { measurementTable.loadTable(app.dbutil.selectReportMeasurementListByMeasuringPoint(job.getLatestReport(), "01")); measurementTable2.loadTable(app.dbutil.selectReportMeasurementListByMeasuringPoint(job.getLatestReport(), "02")); measurementTable3.loadTable(app.dbutil.selectReportMeasurementListByMeasuringPoint(job.getLatestReport(), "03")); } protected CardView createCardView(String title, MeasurementTable measurementTable) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 0, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MIN_MARGIN); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_MARGIN); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(title); titleTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(titleTextView); // --------------- content-------------------- linearLayout.addView(measurementTable.getTable()); // --------------- content-------------------- // --------------- button-------------------- linearLayout.addView(createButtonLayout(measurementTable)); // --------------- button-------------------- cardView.addView(linearLayout); return cardView; } private RelativeLayout createButtonLayout(final MeasurementTable measurementTable) { RelativeLayout buttonRelativeLayout = new RelativeLayout(context); RelativeLayout.LayoutParams buttonRelativeLayoutParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); buttonRelativeLayout.setLayoutParams(buttonRelativeLayoutParams); LinearLayout buttonLinearLayout = new LinearLayout(context); RelativeLayout.LayoutParams buttonLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); buttonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); buttonLayoutParams.topMargin = LayoutUtils.convertDpToPixel(context, 5); buttonLayoutParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 5); buttonLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); buttonLinearLayout.setLayoutParams(buttonLayoutParams); buttonLinearLayout.setOrientation(LinearLayout.HORIZONTAL); final ImageView deleteImageView = new ImageView(context); deleteImageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); LinearLayout.LayoutParams deleteImageViewParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 28), LayoutUtils.convertDpToPixel(context, 28)); deleteImageViewParams.rightMargin = 30; deleteImageView.setLayoutParams(deleteImageViewParams); deleteImageView.setEnabled(false); deleteImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); measurementTable.onCheckedChange(new OnCheckedChange() { @Override public void onCheckedChange(List checkedList) { setButtonDeleteEnabled(deleteImageView, !checkedList.isEmpty()); } }); measurementTable.onEnabledChange(new OnEnabledChange() { @Override public void onEnabledChange(boolean enabled) { setButtonDeleteEnabled(deleteImageView, enabled); } }); deleteImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onDeleted(measurementTable.getCheckedList()); } }); final ImageView scanImageView = new ImageView(context); LinearLayout.LayoutParams scanImageViewParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 28), LayoutUtils.convertDpToPixel(context, 28)); scanImageView.setLayoutParams(scanImageViewParams); scanImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onStartMeasurement(measurementTable.getMeasurementPoint(), measurementTable.getList()); } }); measurementTable.onEnabledChange(new OnEnabledChange() { @Override public void onEnabledChange(boolean enabled) { log.info("onEnabledChange " +enabled ); setButtonScanEnabled(scanImageView, enabled); } }); setButtonScanEnabled(scanImageView, isKmgInstalles); LinearLayout iconLinearLayout = new LinearLayout(context); RelativeLayout.LayoutParams iconLinearLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); iconLinearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); iconLinearLayout.setLayoutParams(iconLinearLayoutParams); iconLinearLayout.setOrientation(LinearLayout.HORIZONTAL); iconLinearLayout.addView(deleteImageView); iconLinearLayout.addView(scanImageView); buttonLinearLayout.addView(iconLinearLayout); final LinearLayout messageLinearLayout = new LinearLayout(context); RelativeLayout.LayoutParams messageLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); messageLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); messageLayoutParams.topMargin = LayoutUtils.convertDpToPixel(context, 5); messageLinearLayout.setLayoutParams(messageLayoutParams); messageLinearLayout.setOrientation(LinearLayout.HORIZONTAL); TextView gridTextViewValue = new TextView(context); gridTextViewValue.setText(ServiceJobUtil.getTooMuchMeasurementAreMadeForOnemeasurePointMessage()); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); messageLinearLayout.addView(gridTextViewValue); buttonRelativeLayout.addView(messageLinearLayout); measurementTable.onItemsChange(new OnItemsChange() { @Override public void onItemsChange() { int visibility = View.GONE; if (measurementTable.getList() != null && measurementTable.getList().size() > ServiceConstants.MAX_MEASUREMENT_FOR_ONE_POINT) { visibility = View.VISIBLE; } messageLinearLayout.setVisibility(visibility); } }); buttonRelativeLayout.addView(buttonLinearLayout); return buttonRelativeLayout; } private void setButtonDeleteEnabled(final ImageView deleteImageView, boolean enabled) { if (enabled) { deleteImageView.setEnabled(true); deleteImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { deleteImageView.setEnabled(false); deleteImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } } private void setButtonScanEnabled(final ImageView scanImageView, boolean enabled) { if (enabled) { scanImageView.setEnabled(true); scanImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.REMOTE_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { scanImageView.setEnabled(false); scanImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.REMOTE_BLACK, CommonConstants.Images.IMAGE_DPI))); } } private void setEnabled(boolean enabled) { measurementTable.setEnabled(enabled); measurementTable2.setEnabled(enabled); measurementTable3.setEnabled(enabled); } private void onDeleted(final List measurements) { if (measurements.isEmpty()) { return; } setEnabled(false); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("TheCapturedDataWillBeDeleted"), ServiceMessages.getString("DeleteMeasurement"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { deleteMeasurements(measurements); } return null; } protected void runOnUIThread() { setEnabled(true); loadMeasurementTables(); } }; } private void onStartMeasurement(final String measurementPoint, final List measurements) { setEnabled(false); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { log.warn("Device does not support Bluetooth"); } if (!mBluetoothAdapter.isEnabled()) { app.showWarningMessageBox(ServiceMessages.getString("BluetoothIsNotTurnOn")); setEnabled(true); } else { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { onStartMeasurement(measurementPoint); return null; } protected void runOnUIThread() { setEnabled(true); loadMeasurementTables(); } }; } } private void deleteMeasurements(List measurements) { for (ReportMeasurement reportMeasurement : measurements) { app.dbutil.deleteReportMeasurement(reportMeasurement); } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } private Intent getMeasuredValues() { Intent result = null; if (isKmgInstalles) { Intent message = new Intent("de.gte.kmglite.blapp.measure"); message.setClassName("de.gte.kmglite.blapp", "de.gte.kmglite.blapp.MeasureInterfaceActivity"); result = appman.startActivityForResult(message); } return result; } protected void onStartMeasurement(String measurementPoint) { boolean measuredValues = true; while (measuredValues) { Intent result = getMeasuredValues(); ReportMeasurement reportMeasurement = null; try { if (result != null) { try { reportMeasurement = parseJson(new JSONObject(result.getStringExtra("measurement"))); } catch (JSONException e) { log.error(e.getMessage()); e.printStackTrace(); } } else { // TODO for test only reportMeasurement = readJsonFile(); measuredValues = false; } } catch (Exception e) { log.info("user cancelled measurement"); } if (reportMeasurement != null) { reportMeasurement.setGuid(job.getCurrentReport().getGuId()); reportMeasurement.setCommissionNumber(job.getCommissionNumber()); reportMeasurement.setMeasurementPoint(measurementPoint); reportMeasurement.setPersonalNumber(job.getPersonalNumber()); int nextMeasurement = app.dbutil.selectNextMeasurementFromReportMeasurement(job.getLatestReport(), measurementPoint); reportMeasurement.setMeasurement((nextMeasurement < 10 ? "0" + nextMeasurement:""+nextMeasurement)); app.dbutil.insertReportMeasurement(reportMeasurement); } } } private ReportMeasurement readJsonFile() { int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance() , Manifest.permission.READ_EXTERNAL_STORAGE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance() , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE , Manifest.permission.WRITE_EXTERNAL_STORAGE}, ServiceConstants.PERMISSION_REQUEST_CODE); } File jsonFile = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/ch.mfiles.kolibri/files", "KMG-LITE-20200509-154849.json"); try { FileReader fileReader = new FileReader(jsonFile); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuilder stringBuilder = new StringBuilder(); String line = bufferedReader.readLine(); while (line != null){ stringBuilder.append(line).append("\n"); line = bufferedReader.readLine(); } // This responce will have Json Format String String responce = stringBuilder.toString(); JSONObject jsonObject = new JSONObject(responce); return parseJson(jsonObject); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } catch (JSONException e) { log.error(e); } return null; } private ReportMeasurement parseJson(JSONObject jsonObject) { try { ReportMeasurement reportMeasurement = new ReportMeasurement(); reportMeasurement.setDynamicPowerPeakValue(jsonObject.getString("DynamicPower")); reportMeasurement.setStaticEndPower(jsonObject.getString("EndPower")); reportMeasurement.setDynamicTime(jsonObject.getString("DynamicTime")); reportMeasurement.setSNOfDevice(jsonObject.getString("SerialNumber")); reportMeasurement.setDeviceType(jsonObject.getString("DeviceType")); // "CalibrationDate":"2020-05-08T00:00:00" SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String dateStr = jsonObject.getString("CalibrationDate"); Date calibrationDate = sdf.parse(dateStr); reportMeasurement.setCalibrationDate(calibrationDate); return reportMeasurement; } catch (JSONException e) { log.error(e); e.printStackTrace(); } catch (ParseException e) { log.error(e); e.printStackTrace(); } return null; } public static class ReportMeasurementFormArguments { private Job job; public ReportMeasurementFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.PorterDuff.Mode; import android.graphics.Typeface; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * @author nop (12-05-2017) * * @see "[MIG-53] implement of "report messages"" */ public class ReportMessageNewEditForm extends SuperForm implements OnItemSelectedListener, TextWatcher { private static Log log = LogFactory.getLog(ReportMessageNewEditForm.class); private Job job; private MDSpinner messageType; private MDSpinner messageCode; private MDEditText messages; private TextView messageLengthView; private Map messageMap = new HashMap(); @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); messageType = new MDSpinner(context); messageType.setTag("MESSAGETYPE"); //$NON-NLS-1$ LinearLayout.LayoutParams spinnerLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); spinnerLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), 0, 0, 0); messageType.setLayoutParams(spinnerLayoutParams); messageType.getBackground().setColorFilter(LayoutUtils.DEFAULT_WHITE, Mode.SRC_ATOP); messageType.setOnItemSelectedListener(this); toolbar.addView(messageType); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); messageCode = MDSpinner.createDefaultSpinner(contentLinearLayout, ServiceMessages.getString("template"), false); //$NON-NLS-1$ messageCode.setTag("MESSAGETEMPLATE"); //$NON-NLS-1$ messageCode.setOnItemSelectedListener(this); messages = MDEditText.createDefaultEditText(contentLinearLayout, "", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE_HUNDRED_AND_TEN)}); messages.setSingleLine(false); messages.addTextChangedListener(this); messageLengthView = CommonUtilForm.getTextView(context, "0/" + CommonConstants.MaxLength.FIVE_HUNDRED_AND_TEN.toString()); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); Button deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { messageCode.setSelection(0); messages.getText().clear(); JobMessage jobMessage = messageMap.get(messageType.getSelectedId()); jobMessage.setMessageCode(""); jobMessage.setMessageCodeText(""); jobMessage.setFullText(""); messageMap.put(messageType.getSelectedId(), jobMessage); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(relativeLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); loadData(); return null; } /** * Loads data. */ public void loadData() { fillComboMessageType(); // set select(Customer (Kunde)) for the first time messageType.setSelection(ServiceConstants.Index.ZERO); } private void fillComboMessageType() { // Create a new, empty report object and save it to the database if (job.getLatestReport().getReportStatus().isReceived()) { app.dbutil.insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(app.dbutil), job.getNextReportIdx(app.dbutil), job.isCycleOfInstallationFlag())); job.loadReports(app.dbutil); } Iterator itr = app.enumUtil.messageRecipientEnum.iterator(); Map messageRecipientMap = new HashMap(); while (itr.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) itr.next(); JobMessage jobMessage = app.dbutil.selectJobMessageListByreportAndMsgId(job.getCurrentReport(), (String) entry.getKey()); if (jobMessage == null) { jobMessage = new JobMessage(); jobMessage.setGuId(job.getLatestReport().getGuId()); jobMessage.setMessageId((String) entry.getKey()); } System.out.println("Recipient " + entry.getValue()); messageMap.put((String) entry.getKey(), jobMessage); messageRecipientMap.put((String) entry.getKey(), entry); } List messageTypeValueList = new ArrayList(); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.CUSTOMER, (String) messageRecipientMap.get(CommonConstants.Message.CUSTOMER).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.HEAD_OF_DEPARTMENT, (String) messageRecipientMap.get(CommonConstants.Message.HEAD_OF_DEPARTMENT).getValue())); if (job.getJobType().isMON()) { messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.PROJECT_MANAGER, (String) messageRecipientMap.get(CommonConstants.Message.PROJECT_MANAGER).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.DISPOSITION, (String) messageRecipientMap.get(CommonConstants.Message.DISPOSITION).getValue())); } else { messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.KDZ1, (String) messageRecipientMap.get(CommonConstants.Message.KDZ1).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.KDZ2, (String) messageRecipientMap.get(CommonConstants.Message.KDZ2).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.KDZ3, (String) messageRecipientMap.get(CommonConstants.Message.KDZ3).getValue())); } messageType.setContents(messageTypeValueList); } private void fillComboMessageTemplate(String msgid) { List messageTemplateValueList = new ArrayList(); if(job.getJobType().isMON()) { List jobMonTextMessageList = app.dbutil.selectJobMonMessageByLangu(app.dbutil.getUser().getLanguage()); for (JobMonText jobMonText : jobMonTextMessageList) { messageTemplateValueList.add(new CustomSpinnerItem(jobMonText.getMonText(), jobMonText.getText())); } } else { List reportMessageList = app.dbutil.selectReportMessage(); for (ReportMessage reportMessage : reportMessageList) { if (msgid.equalsIgnoreCase(CommonConstants.Message.CUSTOMER)) { if (reportMessage.isKND()) { messageTemplateValueList.add(new CustomSpinnerItem(reportMessage.getMessageCode(), reportMessage.getMessage())); } } else if (msgid.equalsIgnoreCase(CommonConstants.Message.HEAD_OF_DEPARTMENT)) { if (reportMessage.isABTL()) { messageTemplateValueList.add(new CustomSpinnerItem(reportMessage.getMessageCode(), reportMessage.getMessage())); } } else { if (reportMessage.isKDZ()) { messageTemplateValueList.add(new CustomSpinnerItem(reportMessage.getMessageCode(), reportMessage.getMessage())); } } } } messageCode.setContents(messageTemplateValueList); } @Override public ApplicationEvent onBackPressed() { // Create a new, empty report object and save it to the database if (job.getLatestReport().getReportStatus().isReceived()) { app.dbutil.insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(app.dbutil), job.getNextReportIdx(app.dbutil), job.isCallServiceFlag())); job.loadReports(app.dbutil); } Iterator itr = messageMap.keySet().iterator(); while (itr.hasNext()) { String key = (String) itr.next(); JobMessage jobMessage = messageMap.get(key); if (!app.dbutil.insertJobMessage(jobMessage)){ app.dbutil.updateJobMessage(jobMessage); } } job.loadReports(app.dbutil); return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } @Override public void onFormReset() { super.onFormReset(); messages.setText(""); //$NON-NLS-1$ messageLengthView.setText(""); //$NON-NLS-1$ } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("MESSAGETYPE".equals(parent.getTag())) { //$NON-NLS-1$ fillComboMessageTemplate(messageType.getSelectedId()); ((TextView) parent.getChildAt(0)).setTextColor(LayoutUtils.DEFAULT_WHITE); ((TextView) parent.getChildAt(0)).setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); ((TextView) parent.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); JobMessage jobMessage = messageMap.get(messageType.getSelectedId()); if (jobMessage.getMessageCode().isEmpty()) { messageCode.setSelection(0); } else { messageCode.setSelectionById(jobMessage.getMessageCode()); } if (jobMessage.getFullText().isEmpty()) { messages.getText().clear(); } else { messages.setText(jobMessage.getFullText()); } } else if ("MESSAGETEMPLATE".equals(parent.getTag())) { updateMessage(); } } @Override public void onNothingSelected(AdapterView arg0) { // Auto-generated method stub } public static class FormArguments { private Job job; protected FormArguments() { } public FormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } @Override public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) { // Auto-generated method stub } @Override public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { // Auto-generated method stub } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + CommonConstants.MaxLength.FIVE_HUNDRED_AND_TEN.toString()); //$NON-NLS-1$ updateMessage(); } private void updateMessage() { JobMessage jobMessage = messageMap.get(messageType.getSelectedId()); if (messageCode.getSelectedItemPosition() != 0) { jobMessage.setMessageCode(messageCode.getSelectedId()); jobMessage.setMessageCodeText(messageCode.getSelectedName()); } else { jobMessage.setMessageCode(""); jobMessage.setMessageCodeText(""); } jobMessage.setMessageId(messageType.getSelectedId()); if (StringUtil.isNotEmpty(messages.getText().toString())) { jobMessage.setFullText(messages.getText().toString()); } messageMap.put(messageType.getSelectedId(), jobMessage); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.PorterDuff.Mode; import android.graphics.Typeface; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.ReportContentWidget; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.SignatureForm.Arguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The summary of report. * * @author cyu (23-06-2017) * * @see "[MIG-159] implement of report summary" */ public class ReportSummaryForm extends SuperForm implements OnItemSelectedListener{ private static Log log = LogFactory.getLog(ReportSummaryForm.class); private List jobList; private MDSpinner reportValue; private ReportContentWidget reportContentWidget; @Override public void onFormCall(Object argument) { if (argument instanceof Arguments) { Arguments formArguments = (Arguments) argument; jobList = formArguments.getJobList(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); LinearLayout headerLinearLayout = new LinearLayout(context); headerLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerLinearLayout.setOrientation(LinearLayout.VERTICAL); reportValue = new MDSpinner(context); reportValue.setTag("REPORT"); //$NON-NLS-1$ LinearLayout.LayoutParams spinnerLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); spinnerLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), 0, 0, 0); reportValue.setLayoutParams(spinnerLayoutParams); reportValue.getBackground().setColorFilter(LayoutUtils.DEFAULT_WHITE, Mode.SRC_ATOP); reportValue.setOnItemSelectedListener(this); toolbar.addView(reportValue); RelativeLayout relativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams addressRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); addressRelativeLayoutParams.setMargins(0, 0, 0, LayoutUtils.DEFAULT_MAX_MARGIN); relativeLayout.setLayoutParams(addressRelativeLayoutParams); LinearLayout cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); reportContentWidget = new ReportContentWidget(app, app.dbutil, context); cardLinearLayout.addView(reportContentWidget.createTimesCard()); cardLinearLayout.addView(reportContentWidget.createReportCard()); cardLinearLayout.addView(reportContentWidget.createMaterialCard()); cardLinearLayout.addView(reportContentWidget.createMessageCard()); // cardLinearLayout.addView(reportContentWidget.createImageCard()); ScrollView scrollView = new ScrollView(context); LinearLayout.LayoutParams scrollViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); scrollView.setLayoutParams(scrollViewParams); scrollView.addView(cardLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { List reportValueList = new ArrayList(); if (!jobList.isEmpty()) { for (int i = 0; i < jobList.size(); i++) { Job job = jobList.get(i); String text = ServiceMessages.getString("report") + " " + (i+1) + " " + ServiceMessages.getString("of") + " " + jobList.size(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ reportValueList.add(new CustomSpinnerItem(job.getJobNumber(), text, text)); } } reportValue.setContents(reportValueList); return null; } private void loadReportContents(Job job) { job.loadAddresses(app.dbutil); reportContentWidget.setJob(job); reportContentWidget.loadTimes(false); reportContentWidget.loadReport(); reportContentWidget.loadMaterial(); reportContentWidget.loadMessage(); // reportContentWidget.loadImage(); } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("REPORT".equals(parent.getTag())) { //$NON-NLS-1$ ((TextView) parent.getChildAt(0)).setTextColor(LayoutUtils.DEFAULT_WHITE); ((TextView) parent.getChildAt(0)).setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); ((TextView) parent.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); loadReportContents(jobList.get(reportValue.getSelectedItemPosition())); } } @Override public void onNothingSelected(AdapterView arg0) { // Do nothing } @Override public ApplicationEvent onBackPressed() { // appman.inject(new KolibriRunnable() { // @Override // public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, // Registry reg) { // return appman.getActiveApplication().leaveToForm(SignatureForm.class, new SignatureForm.Arguments(jobList, true)); // } // }, false); return app.closeForm(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.DateUtils; /** * New Form. */ public class ReportTimeListForm extends SuperForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(ReportTimeListForm.class); /** * The dialog's add action. */ protected ActionCtrl addButton; protected Job job; protected JobReportTime selectedTime; protected TimeListWidget listWidget; private TimeUtil timeUtil; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments) { ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments formArguments = (ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments) argument; job = formArguments.getJob(); selectedTime = formArguments.getTime(); if (null != selectedTime) { loadTimeList(); } } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); timeUtil = new TimeUtil(app, app.dbutil, this); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new TimeListWidget(context); view.addView(listWidget); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("jobTime")); //$NON-NLS-1$ loadTimeList(); return null; } private void loadTimeList() { listWidget.clean(); Report report = job.getCurrentReport(); // Time spent (only if available) report.loadTimes(app.dbutil); List reportTimeList = report.getTimes(); ArrayList items = new ArrayList(); for (int i = 0; i < reportTimeList.size(); i++) { final JobReportTime reportTime = reportTimeList.get(i); final TimeListWidgetItem item = new TimeListWidgetItem(); log.info("IDX " + reportTime.getIdx() + " time from " + DateTimeUtil.showDateTime(reportTime.getStartTime()) + " to " + DateTimeUtil.showDateTime(reportTime.getStopTime())); item.setDateTitle(DateTimeUtil.showDayOfMonth(reportTime.getDate())); item.setDateText(DateTimeUtil.showDayOfWeek(reportTime.getStartTime())); WorkType WorkType = app.dbutil.selectWorkTypeByJobTypeAndWorkTypeCode(job.getJobType(), reportTime.getWorkTypeCode()); item.setTitleText(WorkType == null ? "" : WorkType.getText()); String line1 = ServiceMessages.getString("inProgress"); //$NON-NLS-1$ if (DateUtils.getInitialDateTime().equals(reportTime.getStopTime())) { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.STOP_TIME, CommonConstants.Images.IMAGE_DPI))); item.setTextColor(LayoutUtils.DEFAULT_RED); } else { line1 = DateTimeUtil.showTime(reportTime.getStartTime()) + "-" + DateTimeUtil.showTime(reportTime.getStopTime()) + " " + ServiceMessages.getString("clock"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } item.setStringLine1(line1); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton) { selectedTime = reportTime; actionTime(); } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(reportTimeList)); } listWidget.addItems(items); } private OnItemClickListener createOnItemClickListener(final List reportTimeList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { if(((TimeListWidgetItem) listWidget.getItemAtPosition(position)).getTextColor() == LayoutUtils.DEFAULT_TEXT_COLOR) { app.injectAndLeaveToForm(ReportTimeNewEditForm.class, new ReportTimeListFormArguments(job, reportTimeList.get(position))); } } }; } private void actionTime() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (DateUtils.getInitialDateTime().equals(selectedTime.getStopTime())) { timeUtil.stopTime(job, new RunOnUIThread() { @Override public void runOnUIThread() { loadTimeList(); } }); } return null; } }, false); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } protected ApplicationEvent onAddPressed() { app.injectAndLeaveToForm(ReportTimeNewEditForm.class, new ReportTimeListFormArguments(job, null)); return null; } public static class ReportTimeListFormArguments { private Job job; private JobReportTime time; public ReportTimeListFormArguments(Job job, JobReportTime time) { this.job = job; this.time = time; } public Job getJob() { return job; } public JobReportTime getTime() { return time; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class RescheduleJobForm extends SuperForm implements OnItemSelectedListener { private static Log log = LogFactory.getLog(RescheduleJobForm.class); private Job job; private MDSpinner dateValue; private TimeEditText timeText; private Date dateSelected = new Date(); private String defaultTime = "00:00"; private ActionCtrl sendButton; private MDSpinner reasonValue; @Override public void onFormCall(Object argument) { if (null == argument) { // create new time } else { if (argument instanceof RescheduleJobFormArguments) { RescheduleJobFormArguments formArguments = (RescheduleJobFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); sendButton = addActionCtrl(false, true, 1, "onSendPressed"); //$NON-NLS-1$ sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout dateLinearLayout = new LinearLayout(context); dateLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; dateLinearLayout.setLayoutParams(leftIconLinearLayoutParams); final LinearLayout dayLinearLayout = new LinearLayout(context); dayLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams dateValueParams = new LinearLayout.LayoutParams(0, 0); dateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; dateValueParams.width = 0; dateValueParams.height = LayoutParams.MATCH_PARENT; dateValueParams.weight = 0.5f; dayLinearLayout.setLayoutParams(dateValueParams); // date dateValue = MDSpinner.createDefaultSpinner(dayLinearLayout, ServiceMessages.getString("date"), false); //$NON-NLS-1$ dateValue.setTag("DATUM"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) dateValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateValue.getUnderline().setLayoutParams(underlineLinearLayout); dateLinearLayout.addView(dayLinearLayout); dateValue.setFocusable(false); dateValue.setFocusableInTouchMode(false); dateValue.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { DatePickerDialog datePickerDialog = getDatePickerDialog(); datePickerDialog.setButton(android.content.DialogInterface.BUTTON_NEGATIVE, ServiceMessages.getString("cancel"), new android.content.DialogInterface.OnClickListener() { //$NON-NLS-1$ @Override public void onClick(android.content.DialogInterface dialog, int which) { if (which == android.content.DialogInterface.BUTTON_NEGATIVE) { dateValue.setEnabled(true); dialog.dismiss(); } } }); dateValue.setEnabled(false); datePickerDialog.show(); return true; } }); timeText = TimeEditText.createDefaultEditText(dateLinearLayout, ServiceMessages.getString("time"), true); //$NON-NLS-1$ timeText.setTag("BIS"); //$NON-NLS-1$ timeText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus && job.getJobRescheduleTime().getTime() == 0 && timeText.getText().toString().equalsIgnoreCase(defaultTime)) { timeText.getText().clear(); } if(!hasFocus && timeText.getText().toString().isEmpty()) { timeText.setText(defaultTime); //$NON-NLS-1$ } } }); LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; timeText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); contentLinearLayout.addView(dateLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // reason reasonValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(this); contentLinearLayout.addView(workTypeLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } private DatePickerDialog getDatePickerDialog() { Calendar calendar = Calendar.getInstance(); return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDate(year, monthOfYear, dayOfMonth); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } private void setDate(int year, int monthOfYear, int dayOfMonth) { Calendar calendar = DateTimeUtil.getToday(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); dateSelected = calendar.getTime(); List dateTypeValueList = new ArrayList(); String date = DateTimeUtil.showDate(calendar.getTime()); dateTypeValueList.add(new CustomSpinnerItem(date, date)); dateValue.setContents(dateTypeValueList); dateValue.setEnabled(true); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("RescheduleJob")); // set invisible save button saveButton.setVisible(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendButton.setEnabled(false); loadData(); return null; } public void loadData() { List reasonValueList = new ArrayList(); List reasonList = app.dbutil.selectReasonList(); if(reasonList.isEmpty()) { reasonValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, "Bitte w�hlen..")); } for (int i = 0; i < reasonList.size(); i++) { Reason reason = reasonList.get(i); reasonValueList.add(new CustomSpinnerItem(reason.getReasonText(), reason.getText(), reason.getText())); } reasonValue.setContents(reasonValueList); // timeText.clearError(); Calendar calendar = Calendar.getInstance(); if(job.getJobRescheduleDate().getTime() != 0) { calendar.setTime(job.getJobRescheduleDate()); } setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); if(job.getJobRescheduleTime().getTime() != 0) { timeText.setText(DateTimeUtil.showTimeGMT(job.getJobRescheduleTime())); } else { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); timeText.setText(DateTimeUtil.showTimeGMT(calendar.getTime())); } timeText.clearFocus(); } @Override public ApplicationEvent onBackPressed() { // not edited new AsyncTask(this) { private MDEditText errorText = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { return app.leaveToForm(JobListForm.class); } @Override public void runOnUIThread() { if (errorText != null) { errorText.setError(ServiceMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ } } }; return null; } public ApplicationEvent onSendPressed() { if(reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { reasonValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ return null; } Date time = DateTimeUtil.parseDateFromHHmm(timeText.getText().toString(), dateSelected); if(time == null || (time != null && time.before(new Date()))) { dateValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); //$NON-NLS-1$ return null; } job.setJobRescheduleDate(time); job.setJobRescheduleTime(time); job.setAppointmentDate(time); job.calculateActiveDate(); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(new RemoteTransactionHandler().runUpdateEdate(job.getJobNumber(), job.getJobType().getCode() , job.getJobRescheduleDate() , job.getJobRescheduleTime() , reasonValue.getSelectedId())) { app.dbutil.updateJob(job); } return app.leaveToForm(JobListForm.class); } }; return null; } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if ("DATUM".equals(parent.getTag())) { //$NON-NLS-1$ dateValue.setSelected(false); dateValue.clearFocus(); } reasonValue.setError(null); reasonValue.clearError(); if(reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendButton.setEnabled(false); } else { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); sendButton.setEnabled(true); } } @Override public void onNothingSelected(AdapterView parent) { // Auto-generated method stub } public static class RescheduleJobFormArguments { private Job job; public RescheduleJobFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The super class of all forms within this application. Contains common * members, methods and controls. * */ public abstract class ServiceNavigationForm extends NavigationForm { private static Log log = LogFactory.getLog(ServiceNavigationForm.class); // initialized by the kolibri framework... public static ServiceApplication app; protected Context context; NavigationMenuListItem vehicleInventory; private Job job; private JobReportTime selectedJobTime; public Job getSelectedJob() { return job; } public void setSelectedJob(Job job) { this.job = job; this.job.loadAddresses(app.dbutil); this.job.loadReports(app.dbutil); } public void reloadSelectedJob() { this.job = app.dbutil.selectJobByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); this.job.loadReports(app.dbutil); } public JobReportTime getSelectedJobtime() { return selectedJobTime; } public void setSelectedJobTime(JobReportTime jobTime) { selectedJobTime = jobTime; } public ApplicationEvent actionExit() { return appman.exitApplication(); } protected void updateJobStatus(final String localStatus, final String sapStatus) { log.info("updateJobStatus status isNew " + getSelectedJob().getStatus().isNew()); //$NON-NLS-1$ if (new RemoteTransactionHandler().updateStatus(db, getSelectedJob(), localStatus, sapStatus, "")) { //$NON-NLS-1$ log.info("after updateStatus" + getSelectedJob().getStatus().toString()); //$NON-NLS-1$ reloadSelectedJob(); log.info("after reloadSelectedJob" + getSelectedJob().getStatus().toString()); //$NON-NLS-1$ if (JobStatus.RECEIVED.equals(localStatus)) { // remove existing a new job notification new Notifications(app).removeNotification(CommonConstants.Notification.NEW_JOB); } } } @Override public void onMenuItemClickListener(ListView menuView) { menuView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, final View innerView, int position, long id) { onMenuItemClicked(innerView); } }); } private void onMenuItemClicked(final View innerView) { if ("VEHICLE_INVENTORY".equals(innerView.getTag()) && !vehicleInventory.isEnable()) { return; } new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if ("TIMESHEET_APP".equals(innerView.getTag())) { //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.TIMESHEET_APP)) { app.showWarningMessageBox( ServiceMessages.getString("gilgenTimesheetApplicationIsNotInstalled")); //$NON-NLS-1$ return null; } return Runtime.getApplicationManager().leaveToApplication(CommonConstants.Application.TIMESHEET_APP, true); } else if ("MATERIAL_APP".equals(innerView.getTag())) { //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.MATERIAL_APP)) { app.showWarningMessageBox(ServiceMessages.getString("gilgenMaterialApplicationIsNotInstalled")); //$NON-NLS-1$ return null; } return Runtime.getApplicationManager().leaveToApplication(CommonConstants.Application.MATERIAL_APP, true); } else if ("VEHICLE_INVENTORY".equals(innerView.getTag())) { new RemoteTransactionHandler().runGetDeliveryList(app.dbutil.getUser().getPersonalNumber(), monitor); return app.callForm(ArticleListForm.class); } else if ("REFRESH_MASTER_DATA".equals(innerView.getTag())) { //$NON-NLS-1$ app.refreshMasterData(true); } else if ("COLLECTIVE_SIGNATURE".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(SignatureBundleListForm.class); } else if ("SHORT_MESSAGES".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(ShortMessageListForm.class); } else if ("EMPLOYEES".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(EmployeeListForm.class); } else if ("ABSENCE_NOTIFICATION".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(AbsenceNotificationListForm.class); } else if ("RELEASE_DEVICE".equals(innerView.getTag())) { //$NON-NLS-1$ return releaseDevice(); } else if ("EXIT_APP".equals(innerView.getTag())) { //$NON-NLS-1$ return appman.exitApplication(); } return null; } @Override protected void runOnUIThread() { getView().closeDrawers(); if ("REFRESH_MASTER_DATA".equals(innerView.getTag())) { createVehicleInventoryItem(); onMenuItemNotifyDataSetChanged(); } } }; } protected ApplicationEvent releaseDevice() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (DeviceMirrorringHandler.getInstance().releaseDevice( String.valueOf(DatabaseUtil.getInstance().getUser().getPersonalNumber()), app, monitor)) return appman.exitFramework(); return null; } }; return null; } @Override public ApplicationEvent onBackPressed() { return null; } @Override public void onMenuItemLoad(List menuListView) { if (!menuListView.isEmpty()) { menuListView.clear(); } // Timesheet App NavigationMenuListItem timesheetApp = new NavigationMenuListItem(); timesheetApp.setTag("TIMESHEET_APP"); //$NON-NLS-1$ timesheetApp.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.PLAY_WITH_CIRCLE, CommonConstants.Images.IMAGE_DPI))); timesheetApp.setText(ServiceMessages.getString("timesheetApp")); //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.TIMESHEET_APP)) { timesheetApp.setEnable(false); } menuListView.add(timesheetApp); // Material App NavigationMenuListItem materialApp = new NavigationMenuListItem(); materialApp.setTag("MATERIAL_APP"); //$NON-NLS-1$ materialApp.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.SETTING, CommonConstants.Images.IMAGE_DPI))); materialApp.setText(ServiceMessages.getString("materialApp")); //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.MATERIAL_APP)) { materialApp.setEnable(false); } menuListView.add(materialApp); // Vehicle Inventory vehicleInventory = new NavigationMenuListItem(); vehicleInventory.setTag("VEHICLE_INVENTORY"); //$NON-NLS-1$ vehicleInventory.setText(ServiceMessages.getString("vehicleInventory")); createVehicleInventoryItem(); menuListView.add(vehicleInventory); // Refresh Master Data NavigationMenuListItem refreshMasterData = new NavigationMenuListItem(); refreshMasterData.setTag("REFRESH_MASTER_DATA"); //$NON-NLS-1$ refreshMasterData.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.UPDATE, CommonConstants.Images.IMAGE_DPI))); refreshMasterData.setText(ServiceMessages.getString("refreshMasterData")); //$NON-NLS-1$ menuListView.add(refreshMasterData); // Collective Signature NavigationMenuListItem collectiveSignature = new NavigationMenuListItem(); collectiveSignature.setTag("COLLECTIVE_SIGNATURE"); //$NON-NLS-1$ collectiveSignature.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.LIST, CommonConstants.Images.IMAGE_DPI))); collectiveSignature.setText(ServiceMessages.getString("collectiveSignature")); //$NON-NLS-1$ menuListView.add(collectiveSignature); // Short Messages NavigationMenuListItem shortMessages = new NavigationMenuListItem(); shortMessages.setTag("SHORT_MESSAGES"); //$NON-NLS-1$ shortMessages.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EMAIL, CommonConstants.Images.IMAGE_DPI))); shortMessages.setText(ServiceMessages.getString("shortMessages")); //$NON-NLS-1$ menuListView.add(shortMessages); // Employees NavigationMenuListItem userList = new NavigationMenuListItem(); userList.setTag("EMPLOYEES"); //$NON-NLS-1$ userList.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.CONTACT_PHONE, CommonConstants.Images.IMAGE_DPI))); userList.setText(ServiceMessages.getString("employees")); //$NON-NLS-1$ menuListView.add(userList); // Absence notification NavigationMenuListItem AbsenceNotification = new NavigationMenuListItem(); AbsenceNotification.setTag("ABSENCE_NOTIFICATION"); //$NON-NLS-1$ AbsenceNotification.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.ABSENCE_BLACK, CommonConstants.Images.IMAGE_DPI))); AbsenceNotification.setText(ServiceMessages.getString("absences")); //$NON-NLS-1$ menuListView.add(AbsenceNotification); // Release device (device mirroring) NavigationMenuListItem releaseDevice = new NavigationMenuListItem(); releaseDevice.setTag("RELEASE_DEVICE"); //$NON-NLS-1$ releaseDevice.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.OFFLINE_SHARE, CommonConstants.Images.IMAGE_DPI))); releaseDevice.setText(ServiceMessages.getString("releaseDevice")); //$NON-NLS-1$ menuListView.add(releaseDevice); // Exit Service Application NavigationMenuListItem exitServiceApplication = new NavigationMenuListItem(); exitServiceApplication.setTag("EXIT_APP"); //$NON-NLS-1$ exitServiceApplication.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EXIT, CommonConstants.Images.IMAGE_DPI))); exitServiceApplication.setText(ServiceMessages.getString("exitServiceApplication")); //$NON-NLS-1$ menuListView.add(exitServiceApplication); onMenuItemNotifyDataSetChanged(); } private void createVehicleInventoryItem() { if (app.dbutil.getUser().getWarehouseNumber().isEmpty()) { vehicleInventory.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.WRENCH_DISABLED, CommonConstants.Images.IMAGE_DPI))); vehicleInventory.setEnable(false); } else { vehicleInventory.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.WRENCH_BLACK, CommonConstants.Images.IMAGE_DPI))); vehicleInventory.setEnable(true); } } } package ch.mfiles.kaba.kolibri.service.forms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ShortMessageListForm.FormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (12-05-2017) * * @see "[MIG-55] implement of "short messages"" */ public class ShortMessageForm extends SuperForm { private static Log log = LogFactory.getLog(ShortMessageForm.class); private ShortMessage msg; private TextView subject; private TextView longText; private ActionCtrl sendAction; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; msg = formArguments.getShortMessage(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create send action sendAction = addActionCtrl(false, true, 1, "actionSend"); //$NON-NLS-1$ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); subject = new TextView(context); subject.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); subject.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams betreffParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); betreffParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; subject.setLayoutParams(betreffParams); subject.setPadding(0, 30, 0, 30); subject.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); contentLinearLayout.addView(subject); longText = new TextView(context); longText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); longText.setPadding(30, 30, 30, 30); longText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); longText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setStroke(5, LayoutUtils.DEFAULT_DISABLED_COLOR); // longText.setBackground(gradientDrawable); contentLinearLayout.addView(longText); relativeLayout.addView(contentLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(relativeLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("shortMessages")); //$NON-NLS-1$ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(false); if (msg.isConfirmed()/* && !msg.getStatus().equalsIgnoreCase(CommonConstants.ZSHORTMSG.Status.CONFIRMED)*/) { sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(true); } subject.setText(msg.getSubject()); longText.setText(msg.getMessage().trim()); // remove existing a short message notification new Notifications(app).removeNotification(CommonConstants.Notification.SHORT_MESSAGE); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ShortMessageListForm.class); } protected ApplicationEvent actionSend() { hideSoftInputFromWindow(); if (msg.isConfirmed()) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (new RemoteTransactionHandler().runComfirmShortMSG(msg)) { // remove existing a short message notification new Notifications(app).removeNotification(CommonConstants.Notification.SHORT_MESSAGE); return appman.getActiveApplication().leaveToForm(ShortMessageListForm.class); } return null; } }; } return null; } @Override public void onFormReset() { super.onFormReset(); subject.setText(""); //$NON-NLS-1$ longText.setText(""); //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (12-05-2017) * * @see "[MIG-55] implement of "short messages"" */ public class ShortMessageListForm extends SuperForm { private DefaultListWidget listWidget; private LinearLayout emptyMessageView; private List selectedList = new ArrayList(); @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create delete action ActionCtrl deleteAction = addActionCtrl(false, true, 1, "actionDelete"); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); listWidget = new DefaultListWidget(context); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); listWidget.setVisibility(View.GONE); view.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noShortMessageAvailable")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); emptyMessageView.setVisibility(View.GONE); view.addView(emptyMessageView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); if (emptyMessageView.getChildCount() > 0) { emptyMessageView.removeAllViewsInLayout(); } setFormTitle(ServiceMessages.getString("shortMessages")); //$NON-NLS-1$ loadTable(); return null; } private void loadTable() { listWidget.clean(); selectedList.clear(); final List msgList = app.dbutil.selectShortMessageListbyPerNo(app.dbutil.getUser().getPersonalNumber()); if (!msgList.isEmpty()) { ArrayList items = new ArrayList(); for (int i = 0; i < msgList.size(); i++) { final ShortMessage msg = msgList.get(i); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setStatusColor(msg.getStatusColor()); item.setStatusType(msg.getConfirmedMsg()); item.isShowCheckBox(true); item.setTitleText(msg.getSubject()); item.setStringLine1(msg.getReceiveDate()); item.setStringLine2(DateTimeUtil.showTime(msg.getReceiveTime()) + " " + ServiceMessages.getString("clock")); //$NON-NLS-1$ //$NON-NLS-2$ if (msg.isConfirmed() && !msg.getStatus().equalsIgnoreCase(CommonConstants.ShortMessage.Status.CONFIRMED)) { item.isEnabledCheckBox(false); } else { item.isEnabledCheckBox(true); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { CheckBox checkBox = (CheckBox) v; if (checkBox.isChecked()) { if (selectedList == null) { selectedList = new ArrayList(); } selectedList.add(msg); } else { removeShortMessageFromList(msg); } } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(msgList)); } listWidget.addItems(items); listWidget.setVisibility(View.VISIBLE); emptyMessageView.setVisibility(View.GONE); } else { listWidget.setVisibility(View.GONE); emptyMessageView.setVisibility(View.VISIBLE); } } private OnItemClickListener createOnItemClickListener(final List msgList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(ShortMessageForm.class, new FormArguments((ShortMessage) msgList.get(position))); } }, false); } }; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } @Override public void onFormReset() { super.onFormReset(); selectedList = new ArrayList(); setFormTitle(null); } protected ApplicationEvent actionDelete() { hideSoftInputFromWindow(); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (selectedList.isEmpty()) { app.showMessage(ServiceMessages.getString("selectOneOrMoreShortMessages")); //$NON-NLS-1$ return null; } String message = MessageFormat.format(ServiceMessages.getString("doYouReallyWantToDeleteXShortMessagesAtOnce"), //$NON-NLS-1$ new Object[] { selectedList.size() }); if (app.showMessageBox(message, ServiceMessages.getString("confirmation"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ Application.MBOX_ICON_QUESTION) == Application.MBOX_RESULT_YES) { for (ShortMessage shortMessage : selectedList) { app.dbutil.deleteShortMessage(shortMessage); } app.showMessage(ServiceMessages.getString("theSelectedMessageAreDeleted")); //$NON-NLS-1$ } return null; } @Override public void runOnUIThread() { super.runOnUIThread(); loadTable(); } }; return null; } private void removeShortMessageFromList(ShortMessage msg) { if (selectedList != null && !selectedList.isEmpty()) { for (Iterator iter = selectedList.iterator(); iter.hasNext();) { ShortMessage shortMsg = iter.next(); if (shortMsg.getPersonalNumber() == msg.getPersonalNumber() && shortMsg.getMessageKey() == msg.getMessageKey()) { iter.remove(); return; } } } } /** * The Short Message Form Arguments Class. * @author nop */ public static class FormArguments { private ShortMessage shortMessage; public FormArguments(ShortMessage shortMessage) { this.shortMessage = shortMessage; } public ShortMessage getShortMessage() { return shortMessage; } public void setShortMessage(ShortMessage shortMessage) { this.shortMessage = shortMessage; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The Signature List. * * @author cyu (12-06-2017) * * @see "[MIG-40] GUI: collective signature" */ public class SignatureBundleListForm extends SuperForm{ private static Log log = LogFactory.getLog(SignatureBundleListForm.class); private DefaultListWidget listWidget; protected ActionCtrl signButton = null; private List checkedJobList = new ArrayList(); /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create sign action signButton = addActionCtrl(false, true, 1, "onSignPressed"); //$NON-NLS-1$ saveButton.setVisible(false); listWidget = new DefaultListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); //0xAARRGGBB listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.addView(listWidget); return view; } @Override public ApplicationEvent onFormShow() { this.setFormTitle(ServiceMessages.getString("collectiveSignature")); //$NON-NLS-1$ loadTable(); signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_WHITE, CommonConstants.Images.IMAGE_DPI))); boolean validSelection = isJobSelectionValid(); if (validSelection) { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_WHITE, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(true); } else { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(false); } return null; } private void loadTable() { listWidget.clean(); checkedJobList.clear(); List reportList = app.dbutil.selectReportListOfSignBundle(); ArrayList items = new ArrayList(); for (int i = 0; i < reportList.size(); i++) { final Report report = reportList.get(i); final Job job = app.dbutil.selectJobByJobIdAndJobType(report.getJobNumber(), report.getJobType().getCode()); job.loadAddresses(app.dbutil); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setStatusColor(job.getStatusColor()); item.setStatusType(job.getStatusType()); item.setButtonImage(null); Address objAddress = job.getObjectAddress(); item.setTitleText(app.getAddressTitle(objAddress)); String lint1 = objAddress.getStreet(); lint1 += ", " + objAddress.getPostalCode(); //$NON-NLS-1$ lint1 += " " + objAddress.getCity(); //$NON-NLS-1$ item.setStringLine1(lint1); item.setStringLine2(objAddress.getLocation()); if(report.isSignatureFlag()) { // MIG-240 Signed jobs in GUI "collective signature" // item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { item.isShowCheckBox(true); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { item.setCheck(((CheckBox) v).isChecked()); if(((CheckBox) v).isChecked()) { checkedJobList.add(job); } else { checkedJobList.remove(job); } boolean validSelection = isJobSelectionValid(); if (validSelection) { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_WHITE, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(true); } else { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(false); } } } }); items.add(item); } } listWidget.addItems(items); } private boolean isJobSelectionValid() { boolean isValid = true; // --> 19.4.11 bep: Check is no longer a prerequisite to sign reports HashSet vbeln = new HashSet(); // Check if at least one job is selected if (!checkedJobList.isEmpty()) { // Check if all jobs have current report which is not signed yet for (int i = 0; i < checkedJobList.size(); i++) { Job job = checkedJobList.get(i); job.loadReports(app.dbutil); Report report = job.getLatestReport(); if (!report.getReportStatus().isInitial()) { // --> 19.4.11 bep: Check is no longer a prerequisite to sign reports // vbeln.add(report.getCommissionNumber()); log.info("CommissionNumber " +report.getCommissionNumber()); //$NON-NLS-1$ if (report.isSignatureFlag()) { isValid = false; } } else { isValid = false; } } // Check if all jobs belong to the same installation (VBELN) // --> 19.4.11 bep: Check is no longer a prerequisite to sign reports if (vbeln.size() > 1) { isValid = false; } } else { isValid = false; } return isValid; } public ApplicationEvent onSignPressed() { return app.callForm(SignatureForm.class, new SignatureForm.Arguments(checkedJobList, true)); } @Override public ApplicationEvent onBackPressed() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobListForm.class); } }, false); return null; } } package ch.mfiles.kaba.kolibri.service.forms; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public abstract class SuperForm extends DialogForm { // initialized by the kolibri framework... public static ServiceApplication app; protected Context context; protected LinearLayout view; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image clearImage = imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(clearImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_WHITE); return view; } @Override protected ApplicationEvent onSavePressed() { hideSoftInputFromWindow(); if (isValid()) { onSave(); } return null; } protected boolean isValid() { return true; } /** * Closes the keyboard (if open) */ protected void hideSoftInputFromWindow() { KeyboardUtil.closeKeyboard(appman, getView()); } /** * Clears the error messages. */ protected void clearErrorMessages() { } } package ch.mfiles.kaba.kolibri.service.test; import android.content.Context; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm.DialogInterface; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class LongTaskForm extends Form implements OnMenuItemClickListener { public static ServiceApplication app; /** * Derive the dialog's interface from base interface and add dialog specific * content. * * @author joerg * */ public static class SampleDialogInterface extends DialogInterface { private String text; public String getText() { return text; } public SampleDialogInterface(String text) { this.text = text; } } private EditText m_text; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample NavView"); //$NON-NLS-1$ // prepare toolbar getToolbar().setBackgroundColor(Color.BLUE); // don't set a navigation icon since it is provided by // ActionBarDrawerToggle further below automatically // create content including navigation view DrawerLayout drawer = new DrawerLayout(context); drawer.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always // show below toolbar drawer.setBackgroundColor(Color.WHITE); // create the dialog's view hierarchy, one may use inflation instead LinearLayout contentView = new LinearLayout(context); contentView.setOrientation(LinearLayout.VERTICAL); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); m_text = new EditText(context); m_text.setHint(""); //$NON-NLS-1$ m_text.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); m_text.setTextColor(Color.BLACK); m_text.setHintTextColor(Color.GRAY); contentView.addView(m_text); // create NavigationView NavigationView navigationView = new NavigationView(context); navigationView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); navigationView.setBackgroundColor(Color.LTGRAY); // populate menu Menu menu = navigationView.getMenu(); menu.setGroupCheckable(Menu.CATEGORY_CONTAINER, false, true); menu.add(Menu.NONE, 1, 1, "Test Item 1").setOnMenuItemClickListener(this); //$NON-NLS-1$ menu.add(Menu.NONE, 2, 2, "Test Item 2").setChecked(true); //$NON-NLS-1$ menu.add(Menu.NONE, 3, 3, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.NONE, 4, 4, "Test Item 1"); //$NON-NLS-1$ // link toolbar to drawer layout (creationg left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null, drawer, getToolbar(), 0, 0); drawer.addDrawerListener(drawerToggle); drawerToggle.syncState(); // add views to drawer drawer.addView(contentView); drawer.addView(navigationView); return drawer; } private class DialogTask extends AsyncTask { public DialogTask() { super(LongTaskForm.this); } @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { app.showMessageBox("test", "test", Application.MBOX_BUTTON_YES_NO_CANCEL, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ app.inform("weiter geht's..."); //$NON-NLS-1$ return null; } } @Override public boolean onMenuItemClick(MenuItem item) { new DialogTask(); return true; } } package ch.mfiles.kaba.kolibri.service.test; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm.DialogInterface; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.test.SampleDialogForm.SampleDialogInterface; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.Form; /** * A Form calling a dialog. */ public class SampleCallingForm extends Form { public static ServiceApplication app; private DialogInterface m_calledDialogInterface = null; // ... /** Calls SampleDialogForm */ @SuppressWarnings("unused") private ApplicationEvent actionCallDialog() { // example for calling the sample dialog (on AM thread) m_calledDialogInterface = new SampleDialogInterface(""); //$NON-NLS-1$ return app.callForm(SampleDialogForm.class, m_calledDialogInterface); } @Override public ApplicationEvent onFormShow() { // check if we are shown after a dialog was dismissed if (m_calledDialogInterface != null) { DialogInterface dInt = m_calledDialogInterface; m_calledDialogInterface = null; return onReturnFromDialog(dInt); } // normal onFormShow() processing... // ... return null; } private ApplicationEvent onReturnFromDialog(DialogInterface dInt) { if (dInt.isCancelled()) // do nothing if dialog was cancelled return null; if (dInt instanceof SampleDialogInterface) return onReturnFromSampleDialog((SampleDialogInterface) dInt); // dispatch to further dialog returns... // ... throw new ApplicationException("Returning from unknown dialog!?"); //$NON-NLS-1$ } /** Processes return from SampleDialogForm */ private ApplicationEvent onReturnFromSampleDialog(SampleDialogInterface dInt) { // ... return null; } } package ch.mfiles.kaba.kolibri.service.test; import android.content.Context; import android.graphics.Color; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.ui.LayoutInflater; public class SampleDialogForm extends DialogForm { public static ServiceApplication app; /** * Derive the dialog's interface from base interface and add dialog specific * content. * * @author joerg * */ public static class SampleDialogInterface extends DialogInterface { private String text; public String getText() { return text; } public SampleDialogInterface(String text) { this.text = text; } } private EditText m_text; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample Dialog"); //$NON-NLS-1$ // create the dialog's view hierarchy, one may use inflation instead LinearLayout view = new LinearLayout(context); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(Color.WHITE); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); m_text = new EditText(context); m_text.setHint(""); //$NON-NLS-1$ m_text.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); m_text.setTextColor(Color.BLACK); m_text.setHintTextColor(Color.GRAY); view.addView(m_text); return view; } private SampleDialogInterface m_dialogInterface; @Override public void onFormCall(Object parameter) { super.onFormCall(parameter); // retrieve and set the dialog content from the dialog's interface m_dialogInterface = (SampleDialogInterface) parameter; if (m_dialogInterface.text != null) m_text.setText(m_dialogInterface.text); } @Override protected ValidationResult validate() { // implement content validation, exit on first validation error while // checking for validity from top to bottom and left to right... String text = m_text.getText().toString(); if (text.length() == 0) return new ValidationResult(m_text, "Enter a text!"); //$NON-NLS-1$ // success return null; } @Override protected boolean onSave() { // update dialog's interface, return false in case of // errors while saving e.g. to database... but should be better handelt // by the dialog's validation method. Errors could be presented by a // SnackBar or app.showMessageBox() m_dialogInterface.text = m_text.getText().toString(); return super.onSave(); } } package ch.mfiles.kaba.kolibri.service.test; import android.content.Context; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm.DialogInterface; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.LayoutInflater; public class SampleNavigationViewForm extends Form { public static ServiceApplication app; /** * Derive the dialog's interface from base interface and add dialog specific * content. * * @author joerg * */ public static class SampleDialogInterface extends DialogInterface { private String text; public String getText() { return text; } public SampleDialogInterface(String text) { this.text = text; } } private EditText m_text; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample NavView"); //$NON-NLS-1$ // prepare toolbar getToolbar().setBackgroundColor(Color.BLUE); // don't set a navigation icon since it is provided by // ActionBarDrawerToggle further below automatically // create content including navigation view DrawerLayout drawer = new DrawerLayout(context); drawer.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always show below toolbar drawer.setBackgroundColor(Color.WHITE); // create the dialog's view hierarchy, one may use inflation instead LinearLayout contentView = new LinearLayout(context); contentView.setOrientation(LinearLayout.VERTICAL); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); m_text = new EditText(context); m_text.setHint(""); //$NON-NLS-1$ m_text.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); m_text.setTextColor(Color.BLACK); m_text.setHintTextColor(Color.GRAY); contentView.addView(m_text); // create NavigationView NavigationView navigationView = new NavigationView(context); navigationView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); navigationView.setBackgroundColor(Color.LTGRAY); // populate menu Menu menu = navigationView.getMenu(); menu.add(Menu.CATEGORY_CONTAINER, 1, 1, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.CATEGORY_CONTAINER, 2, 2, "Test Item 2").setChecked(true); //$NON-NLS-1$ menu.add(Menu.CATEGORY_CONTAINER, 3, 3, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.CATEGORY_CONTAINER, 4, 4, "Test Item 1"); //$NON-NLS-1$ menu.setGroupCheckable(Menu.CATEGORY_CONTAINER, false, true); // link toolbar to drawer layout (creationg left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null, drawer, getToolbar(), 0, 0); drawer.addDrawerListener(drawerToggle); drawerToggle.syncState(); // add views to drawer drawer.addView(contentView); drawer.addView(navigationView); return drawer; } } package ch.mfiles.kaba.kolibri.service.test; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.CardView; import android.text.InputType; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.LayoutInflater; /** * Sample Form with tabbed content following Material design guidelines. * * @author joerg * */ public class SampleTabForm extends Form { public static ServiceApplication app; /** * A PagerAdapter providing a static number of views. * * @author joerg * */ private static class ViewPageAdapter extends PagerAdapter { private static class Page { String title; View view; Page(String title, View view) { this.view = view; this.title = title; } } private List viewPages = new ArrayList(); public void addPage(String title, View pageView) { viewPages.add(new Page(title, pageView)); notifyDataSetChanged(); } @Override public Object instantiateItem(ViewGroup container, int position) { View pageView = viewPages.get(position).view; container.addView(pageView); return pageView; } @Override public CharSequence getPageTitle(int position) { return viewPages.get(position).title; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return viewPages.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample Tabbed View"); //$NON-NLS-1$ // prepare toolbar getToolbar().setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // create content including navigation view DrawerLayout drawer = new DrawerLayout(context); drawer.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always // show below toolbar drawer.setBackgroundColor(Color.WHITE); // create the dialog's view hierarchy, one may use inflation instead View contentView = createTabContentView(context); // create NavigationView NavigationView navigationView = createNavigationView(context); // link toolbar to drawer layout (creating left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null, drawer, getToolbar(), 0, 0); drawer.addDrawerListener(drawerToggle); drawerToggle.syncState(); // add views to drawer drawer.addView(contentView); drawer.addView(navigationView); return drawer; } private NavigationView createNavigationView(Context context) { NavigationView navigationView = new NavigationView(context); navigationView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); navigationView.setBackgroundColor(Color.LTGRAY); // populate menu Menu menu = navigationView.getMenu(); menu.setGroupCheckable(Menu.CATEGORY_CONTAINER, false, true); menu.add(Menu.NONE, 1, 1, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.NONE, 2, 2, "Test Item 2").setChecked(true); //$NON-NLS-1$ menu.add(Menu.NONE, 3, 3, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.NONE, 4, 4, "Test Item 1"); //$NON-NLS-1$ return navigationView; } private View createTabContentView(Context context) { // create vertical linear view to hold TabLayout and ViewPager LinearLayout contentView = new LinearLayout(context); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentView.setOrientation(LinearLayout.VERTICAL); // create TabLayout TabLayout tabLayout = new TabLayout(context); LinearLayout.LayoutParams tabLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); tabLayout.setLayoutParams(tabLayoutParams); tabLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); tabLayout.setTabTextColors(LayoutUtils.DEFAULT_TAB_TEXT_COLOR, LayoutUtils.DEFAULT_TAB_SELECTED_TEXT_COLOR); contentView.addView(tabLayout); // create 3 simple pages and add them to a page adapter ViewPageAdapter pagerAdapter = new ViewPageAdapter(); LinearLayout viewPage1 = new LinearLayout(context); CardView cardView = new CardView(context); cardView.setRadius(20); cardView.setCardElevation(2); LinearLayout.LayoutParams cardLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardLayoutParams.topMargin = 20; cardView.setLayoutParams(cardLayoutParams); cardView.setUseCompatPadding(true); viewPage1.addView(cardView); EditText text1 = MDEditText.createDefaultEditText(cardView, "Obligatory Text1", InputType.TYPE_CLASS_TEXT, //$NON-NLS-1$ true); pagerAdapter.addPage("Tab1", viewPage1); //$NON-NLS-1$ LinearLayout viewPage2 = new LinearLayout(context); EditText text2 = MDEditText.createDefaultEditText(viewPage2, "Obligatory Text2", InputType.TYPE_CLASS_TEXT, //$NON-NLS-1$ true); pagerAdapter.addPage("Tab2", viewPage2); //$NON-NLS-1$ LinearLayout viewPage3 = new LinearLayout(context); EditText text3 = MDEditText.createDefaultEditText(viewPage3, "Obligatory Text3", InputType.TYPE_CLASS_TEXT, //$NON-NLS-1$ true); pagerAdapter.addPage("Tab3", viewPage3); //$NON-NLS-1$ // ViewPager for PageAdapter ViewPager viewPager = new ViewPager(context); viewPager.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); contentView.addView(viewPager); viewPager.setAdapter(pagerAdapter); // link TabLayout to ViewPager tabLayout.setupWithViewPager(viewPager); // to add images to the pager's tabs (if required): // contentView.getTabAt(0).setIcon(...); return contentView; } } package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.R.color; import android.content.Context; import android.graphics.Bitmap; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; public class FormImageLayout extends LinearLayout { private Context context; private String label; private boolean isRequire; private OnClickListener onClickListener; private Bitmap imageBitmap; private LinearLayout imageTextLayout; private ImageView deleteIcon; private ActionUtil actionUtil; public FormImageLayout(Context context) { super(context); this.context = context; } public FormImageLayout createFormImageLayout(ServiceApplication app, ViewGroup parent, String label, boolean required, OnClickListener onClickListener) { if (parent == null) { return null; } Context context = parent.getContext(); FormImageLayout formImageLayout = createFormImageLayout(app, label, required, onClickListener); LinearLayout textInputLinearLayout = new LinearLayout(context); textInputLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLinearLayout.addView(formImageLayout); parent.addView(textInputLinearLayout); return formImageLayout; } public FormImageLayout createFormImageLayout(ServiceApplication app, String label, boolean required, OnClickListener clickListener) { this.label = label; this.isRequire = required; this.actionUtil = new ActionUtil(app); this.onClickListener = clickListener; LinearLayout contentLayout = new LinearLayout(context); contentLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLayout.setOrientation(LinearLayout.HORIZONTAL); contentLayout.setBackgroundColor(color.white); contentLayout.setPadding(0, 0, 0, 0); TextView formName = new TextView(context); formName.setGravity(Gravity.CENTER_VERTICAL); if (required) { label += "*"; } formName.setText(label); formName.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); LinearLayout.LayoutParams formNameTextParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); formNameTextParams.width = 0; formNameTextParams.weight = 0.25f; formNameTextParams.gravity = Gravity.CENTER_VERTICAL; formName.setLayoutParams(formNameTextParams); contentLayout.addView(formName); imageTextLayout = new LinearLayout(context); imageTextLayout.setOrientation(LinearLayout.HORIZONTAL); imageTextLayout.setPadding(0, 0, 0, 0); LinearLayout.LayoutParams imageTextDescParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); imageTextDescParams.width = 0; imageTextDescParams.weight = 0.45f; imageTextDescParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; imageTextLayout.setLayoutParams(imageTextDescParams); contentLayout.addView(imageTextLayout); LinearLayout buttonLinearLayout = new LinearLayout(context); buttonLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams buttonLinearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); buttonLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; buttonLinearLayoutParams.height = 80; buttonLinearLayoutParams.width = 0; buttonLinearLayoutParams.weight = 0.30f; buttonLinearLayoutParams.topMargin = 20; buttonLinearLayoutParams.bottomMargin = 20; buttonLinearLayout.setLayoutParams(buttonLinearLayoutParams); deleteIcon = new ImageView(context); LinearLayout.LayoutParams deleteIconParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); deleteIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; deleteIconParams.height = 80; deleteIconParams.width = 80; deleteIcon.setLayoutParams(deleteIconParams); deleteIcon.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); deleteIcon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setBitmap(null); } }); buttonLinearLayout.addView(deleteIcon); ImageView galleryIcon = new ImageView(context); LinearLayout.LayoutParams galleryIconParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); galleryIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; galleryIconParams.height = 80; galleryIconParams.width = 80; galleryIconParams.leftMargin = 30; galleryIcon.setLayoutParams(galleryIconParams); galleryIcon.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHOTO_LIBRARY_BLACK, CommonConstants.Images.IMAGE_DPI))); galleryIcon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickListener.onClick(v); actionUtil.actionGallery(new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { setBitmap(bitmap); } }); } }); buttonLinearLayout.addView(galleryIcon); ImageView addPhotoicon = new ImageView(context); LinearLayout.LayoutParams addPhotoIconParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); addPhotoIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; addPhotoIconParams.height = 80; addPhotoIconParams.width = 80; addPhotoIconParams.leftMargin = 30; addPhotoicon.setLayoutParams(addPhotoIconParams); addPhotoicon.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_PHOTO_BLACK, CommonConstants.Images.IMAGE_DPI))); addPhotoicon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickListener.onClick(v); actionUtil.actionCamera(new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { setBitmap(bitmap); } }); } }); buttonLinearLayout.addView(addPhotoicon); contentLayout.addView(buttonLinearLayout); contentLayout.setOnContextClickListener(new OnContextClickListener() { @Override public boolean onContextClick(View v) { // TODO Auto-generated method stub return false; } }); setBitmap(imageBitmap); FormImageLayout formImageLayout = new FormImageLayout(context); formImageLayout.setOrientation(LinearLayout.VERTICAL); formImageLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); formImageLayout.setBackgroundColor(color.white); formImageLayout.setPadding(0, 0, 0, 0); formImageLayout.addView(contentLayout); formImageLayout.addView(new DividerView(context)); return formImageLayout; } public void setRequire(Boolean isRequire) { this.isRequire = isRequire; } public boolean isRequire() { return this.isRequire; } public Bitmap getImageBitmap() { return this.imageBitmap; }; public String getErrorMessage() { return label + " " + ServiceMessages.getString("notAdded"); } public void setBitmap(Bitmap imageBitmap) { this.imageBitmap = imageBitmap; imageTextLayout.removeAllViews(); if (imageBitmap == null) { TextView imageText = new TextView(context); imageText.setText(ServiceMessages.getString("notAdded")); imageText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); if (isRequire) { imageText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); } LinearLayout.LayoutParams imageTextParams = LayoutUtils.DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT(); imageTextParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; imageText.setLayoutParams(imageTextParams); imageTextLayout.addView(imageText); deleteIcon.setVisibility(View.INVISIBLE); } else { int height = 160; int width = 240; FrameLayout imageFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT()); overlayParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; overlayParams.height = height; overlayParams.width = width; overlayParams.topMargin = 20; overlayParams.bottomMargin = 20; imageFrameLayout.setLayoutParams(overlayParams); ImageView image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_START); image.setMinimumHeight(height); image.setMaxHeight(height); image.setMaxWidth(width); image.setImageBitmap(imageBitmap); imageFrameLayout.addView(image); imageTextLayout.addView(imageFrameLayout); deleteIcon.setVisibility(View.VISIBLE); imageTextLayout.requestFocus(); } } } package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.R.color; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnContextClickListener; import android.widget.AbsListView; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; public class FormListItemWidget { private ServiceApplication app; private Context context; private Form form; private OnClickListener clickListener; private boolean checked; public FormListItemWidget(ServiceApplication app, Form form, OnClickListener clickListener) { this.app = app; this.context = app.appman.getContext(); this.form = form; this.clickListener = clickListener; } public View getView() { LinearLayout rootLinearLayout = new LinearLayout(context); rootLinearLayout.setOrientation(LinearLayout.VERTICAL); rootLinearLayout.setClickable(true); LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); contentItemLayout.setBackgroundColor(color.white); contentItemLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); LinearLayout leftIconLinearLayout = new LinearLayout(context); leftIconLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0,0); leftIconLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; leftIconLinearLayoutParams.width = 0; leftIconLinearLayoutParams.height = LayoutParams.FILL_PARENT; leftIconLinearLayoutParams.weight = 0f; leftIconLinearLayout.setLayoutParams(leftIconLinearLayoutParams); // if (leftView != null) { // leftIconLinearLayoutParams.weight = 0.55f; // leftIconLinearLayout.addView(leftView); // } contentItemLayout.addView(leftIconLinearLayout); // if (middleView != null) { // contentItemLayout.addView(middleView); // } else { contentItemLayout.addView(createMiddleLayout()); // } LinearLayout buttonLinearLayout = new LinearLayout(context); buttonLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams buttonLinearLayoutParams = new LinearLayout.LayoutParams(LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); buttonLinearLayoutParams.gravity = Gravity.CENTER | Gravity.RIGHT; buttonLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; buttonLinearLayout.setLayoutParams(buttonLinearLayoutParams); // if (rightView != null) { // buttonLinearLayout.addView(rightView); // } else { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.RIGHT | Gravity.CENTER_HORIZONTAL; endFrameLayout.setLayoutParams(endFrameParams); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EDIT, CommonConstants.Images.IMAGE_DPI))); // imageButton.setId(ID_BUTTON); endFrameLayout.addView(imageButton); buttonLinearLayout.addView(endFrameLayout); // } contentItemLayout.addView(buttonLinearLayout); rootLinearLayout.addView(contentItemLayout); // LinearLayout contentItemLayout = new LinearLayout(context); // contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); // // contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); //// contentItemLayout.setPadding(0 //// , LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING //// , LayoutUtils.DEFAULT_MIN_PADDING); // // // Generate bottom border only // LayerDrawable bottomBorder = getBorders( // Color.WHITE, // Background color // Color.LTGRAY, // Border color // 0, // Left border in pixels // 0, // Top border in pixels // 0, // Right border in pixels // 2 // Bottom border in pixels // ); // contentItemLayout.setBackground(bottomBorder); // // FrameLayout.LayoutParams checkBoxParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); // checkBoxParams.gravity = Gravity.LEFT ; // // CheckBox checkBox = new CheckBox(context); //// checkBox.setId(ID_CHECK); // checkBox.setPadding(0, 0, 8, 0); // checkBox.setLayoutParams(checkBoxParams); // contentItemLayout.addView(checkBox); // // TextView measureTextView = new TextView(context); //// measureTextView.setId(ID_MEASURE); // measureTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // measureTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); // LinearLayout.LayoutParams measureTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // measureTextParams.width = 0; // measureTextParams.weight = 0.42f; // measureTextView.setLayoutParams(measureTextParams); // // contentItemLayout.addView(measureTextView); // // TextView fDymTextView = new TextView(context); //// fDymTextView.setId(ID_FDYM); // fDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // fDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); // // LinearLayout.LayoutParams fDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // fDymTextParams.width = 0; // fDymTextParams.weight = 0.2f; // fDymTextView.setLayoutParams(fDymTextParams); // // contentItemLayout.addView(fDymTextView); // // TextView tDymTextView = new TextView(context); //// tDymTextView.setId(ID_TDYM); // tDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // tDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); // // // LinearLayout.LayoutParams tDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // tDymTextParams.width = 0; // tDymTextParams.weight = 0.20f; // tDymTextView.setLayoutParams(tDymTextParams); // contentItemLayout.addView(tDymTextView); // // TextView fEneTextView = new TextView(context); //// fEneTextView.setId(ID_FEND); // // fEneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // fEneTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); // // LinearLayout.LayoutParams fEneTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // fEneTextParams.width = 0; // fEneTextParams.weight = 0.18f; // fEneTextView.setLayoutParams(fEneTextParams); // contentItemLayout.addView(fEneTextView); // // // checkBox.setOnClickListener(clickListener); // checkBox.setFocusable(false); // checkBox.setChecked(checked); // // System.out.println("getView set checked " + checkBox.isChecked()); //// measureTextView.setText(measurement.getMeasurement()); //// fDymTextView.setText(measurement.getDynamicPowerPeakValue()); //// tDymTextView.setText(measurement.getDynamicTime()); //// fEneTextView.setText(measurement.getStaticEndPower());; // // measureTextView.setEllipsize(TruncateAt.END); rootLinearLayout.setOnContextClickListener(new OnContextClickListener() { @Override public boolean onContextClick(View v) { // TODO Auto-generated method stub return false; } }); rootLinearLayout.addView(new DividerView(context)); return rootLinearLayout; } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 3f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(25, 0, 0, 0); TextView titleTextView = new TextView(context); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(form.getName()); midLinearLayout.addView(titleTextView); TextView textLineOneTextView = new TextView(context); textLineOneTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineOneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineOneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineOneTextView.setEllipsize(TruncateAt.END); textLineOneTextView.setMaxLines(1); textLineOneTextView.setSingleLine(); textLineOneTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textLineOneTextView.setText(form.getDescription()); midLinearLayout.addView(textLineOneTextView); TextView textLineTwoTextView = new TextView(context); textLineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineTwoTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textLineTwoTextView.setText(String.valueOf(form.getVersion())); midLinearLayout.addView(textLineTwoTextView); return midLinearLayout; } protected LayerDrawable getBorders(int bgColor, int borderColor, int left, int top, int right, int bottom){ // Initialize new color drawables ColorDrawable borderColorDrawable = new ColorDrawable(borderColor); ColorDrawable backgroundColorDrawable = new ColorDrawable(bgColor); // Initialize a new array of drawable objects Drawable[] drawables = new Drawable[] { borderColorDrawable, backgroundColorDrawable }; // Initialize a new layer drawable instance from drawables array LayerDrawable layerDrawable = new LayerDrawable(drawables); // Set padding for background color layer layerDrawable.setLayerInset(1, // Index of the drawable to adjust [background color layer] left, // Number of pixels to add to the left bound [left border] top, // Number of pixels to add to the top bound [top border] right, // Number of pixels to add to the right bound [right border] bottom // Number of pixels to add to the bottom bound [bottom border] ); // Finally, return the one or more sided bordered background drawable return layerDrawable; } public Form getForm() { return form; } public void setChecked(Boolean checked) { this.checked = checked; } public boolean isChecked() { return checked; } } package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.CardView; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.forms.JobDetailAddressEditForm; import ch.mfiles.kaba.kolibri.service.forms.JobDetailAddressForm; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; /** * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public abstract class GridLayoutForm extends Form { protected CardView cardView; protected Context context; protected ServiceApplication app; public GridLayoutForm(Context context, ServiceApplication app) { super(); this.app = app; this.context = context; } /** * Creates grid parent layout. * * @param title */ protected GridLayout createGridLayout(String title) { return createGridLayout(title, null, null); } /** * Creates grid parent layout. * * @param title * @param job */ protected GridLayout createGridLayout(String title, final Job job, final Address address) { cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 0, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MAX_PADDING); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); gradientDrawable.setCornerRadius(7f); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_CARD_VIEW_SHADOW_COLOR); cardView.setBackground(gradientDrawable); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); RelativeLayout relativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams relativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); relativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); relativeLayout.setLayoutParams(relativeLayoutParams); TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); textView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textView.setPadding(5, 10, 5, 5); textView.setText(title); textView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); relativeLayout.addView(textView); if (job != null && !job.getStatus().isFinalized()) { ImageView imageView = new ImageView(context); RelativeLayout.LayoutParams imageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); imageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); imageView.setLayoutParams(imageViewParams); imageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EDIT, CommonConstants.Images.IMAGE_DPI))); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobDetailAddressEditForm.class, new JobDetailAddressForm.AddressFormArguments(job, address)); } }, false); } }); relativeLayout.addView(imageView); } GridLayout gridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); gridLayout.setLayoutParams(gridLayoutParams); gridLayout.setColumnCount(2); gridLayout.setUseDefaultMargins(true); linearLayout.addView(relativeLayout); linearLayout.addView(gridLayout); cardView.addView(linearLayout); return gridLayout; } protected View getParrentView() { return getParentView(null); } protected View getParentView(View v) { FrameLayout frameLayout = new FrameLayout(context); frameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); RelativeLayout relativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams relativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); relativeLayout.setLayoutParams(relativeLayoutParams); LinearLayout linearLayout = new LinearLayout(context); LinearLayout.LayoutParams linearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.VERTICAL); if (v == null) { linearLayout.addView(cardView); } else { linearLayout.addView(v); } relativeLayout.addView(linearLayout); frameLayout.addView(relativeLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(frameLayout); return scrollView; } /** * Creates no content available layout. * * @param message */ protected View createNoContentAvailableLayout(String message) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView textView = new TextView(context); textView.setText(message); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); linearLayout.addView(textView); return linearLayout; } } package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.text.TextUtils.TruncateAt; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class MeasurementListItemWidget { private Context context; private ReportMeasurement measurement; private OnClickListener clickListener; private boolean checked; public MeasurementListItemWidget(Context context, ReportMeasurement measurement, OnClickListener clickListener) { this.context = context; this.measurement = measurement; this.clickListener = clickListener; } public View getView() { LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); // contentItemLayout.setPadding(0 // , LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING // , LayoutUtils.DEFAULT_MIN_PADDING); // Generate bottom border only LayerDrawable bottomBorder = getBorders( Color.WHITE, // Background color Color.LTGRAY, // Border color 0, // Left border in pixels 0, // Top border in pixels 0, // Right border in pixels 2 // Bottom border in pixels ); contentItemLayout.setBackground(bottomBorder); FrameLayout.LayoutParams checkBoxParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); checkBoxParams.gravity = Gravity.LEFT ; CheckBox checkBox = new CheckBox(context); // checkBox.setId(ID_CHECK); checkBox.setPadding(0, 0, 8, 0); checkBox.setLayoutParams(checkBoxParams); contentItemLayout.addView(checkBox); TextView measureTextView = new TextView(context); // measureTextView.setId(ID_MEASURE); measureTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); measureTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); LinearLayout.LayoutParams measureTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); measureTextParams.width = 0; measureTextParams.weight = 0.42f; measureTextView.setLayoutParams(measureTextParams); contentItemLayout.addView(measureTextView); TextView fDymTextView = new TextView(context); // fDymTextView.setId(ID_FDYM); fDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout.LayoutParams fDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fDymTextParams.width = 0; fDymTextParams.weight = 0.2f; fDymTextView.setLayoutParams(fDymTextParams); contentItemLayout.addView(fDymTextView); TextView tDymTextView = new TextView(context); // tDymTextView.setId(ID_TDYM); tDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); tDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout.LayoutParams tDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); tDymTextParams.width = 0; tDymTextParams.weight = 0.20f; tDymTextView.setLayoutParams(tDymTextParams); contentItemLayout.addView(tDymTextView); TextView fEneTextView = new TextView(context); // fEneTextView.setId(ID_FEND); fEneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fEneTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout.LayoutParams fEneTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fEneTextParams.width = 0; fEneTextParams.weight = 0.18f; fEneTextView.setLayoutParams(fEneTextParams); contentItemLayout.addView(fEneTextView); checkBox.setOnClickListener(clickListener); checkBox.setFocusable(false); checkBox.setChecked(checked); System.out.println("getView set checked " + checkBox.isChecked()); measureTextView.setText(measurement.getMeasurement()); fDymTextView.setText(measurement.getDynamicPowerPeakValue()); tDymTextView.setText(measurement.getDynamicTime()); fEneTextView.setText(measurement.getStaticEndPower());; measureTextView.setEllipsize(TruncateAt.END); return contentItemLayout; } protected LayerDrawable getBorders(int bgColor, int borderColor, int left, int top, int right, int bottom){ // Initialize new color drawables ColorDrawable borderColorDrawable = new ColorDrawable(borderColor); ColorDrawable backgroundColorDrawable = new ColorDrawable(bgColor); // Initialize a new array of drawable objects Drawable[] drawables = new Drawable[] { borderColorDrawable, backgroundColorDrawable }; // Initialize a new layer drawable instance from drawables array LayerDrawable layerDrawable = new LayerDrawable(drawables); // Set padding for background color layer layerDrawable.setLayerInset(1, // Index of the drawable to adjust [background color layer] left, // Number of pixels to add to the left bound [left border] top, // Number of pixels to add to the top bound [top border] right, // Number of pixels to add to the right bound [right border] bottom // Number of pixels to add to the bottom bound [bottom border] ); // Finally, return the one or more sided bordered background drawable return layerDrawable; } public ReportMeasurement getMeasurement() { return measurement; } public void setChecked(Boolean checked) { this.checked = checked; } public boolean isChecked() { return checked; } } package ch.mfiles.kaba.kolibri.service.ui.widgets; import java.util.ArrayList; import java.util.List; import com.journeyapps.barcodescanner.camera.CenterCropStrategy; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.Image; public class MeasurementTable { private Form form; private ServiceApplication app; private Context context; private LinearLayout table; private LinearLayout emptyMessageView; private LinearLayout headerTable; private LinearLayout tableContent; private ImageView checkImageView; private List measurementList; private List checkedList; private List itemWidgets; private String measurementPoint; public MeasurementTable(Form form, ServiceApplication app, String measurementPoint) { this.form = form; this.app = app; this.context = app.appman.getContext(); this.table = createMeasurementTable(); this.measurementPoint = measurementPoint; } public View getTable() { return table; } public List getCheckedList() { return checkedList; } public List getList() { return measurementList; } public String getMeasurementPoint() { return measurementPoint; } private LinearLayout createMeasurementTable() { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 5, 5); headerTable = createHeader(ServiceMessages.getString("Measurement"), "Fdyn","Tdyn","Fend"); linearLayout.addView(headerTable); tableContent = new LinearLayout(context); tableContent.setOrientation(LinearLayout.HORIZONTAL); tableContent.setPadding(0, LayoutUtils.DEFAULT_MAX_PADDING, 0, LayoutUtils.DEFAULT_MIN_PADDING); linearLayout.addView(tableContent); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.addView(emptyMessageView); checkedList = new ArrayList(); itemWidgets = new ArrayList(); return linearLayout; } public interface ClickedResult { void onClicked(boolean isChecked); } private LinearLayout createHeader(String measure, String fdym, String tdym, String fend) { LinearLayout headerLayout = new LinearLayout(context); headerLayout.setOrientation(LinearLayout.HORIZONTAL); headerLayout.setPadding(0, LayoutUtils.DEFAULT_MAX_PADDING, 0, 0); headerLayout.addView(new DividerView(context)); checkImageView = new ImageView(context); checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_UNCHECKED, CommonConstants.Images.IMAGE_DPI))); LinearLayout.LayoutParams buttonRelativeLayoutParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 26), LayoutUtils.convertDpToPixel(context, 26)); buttonRelativeLayoutParams.gravity = Gravity.CENTER_VERTICAL; buttonRelativeLayoutParams.leftMargin = 8; buttonRelativeLayoutParams.bottomMargin = 10; checkImageView.setLayoutParams(buttonRelativeLayoutParams); checkImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("Check clicked"); boolean checkAll = false; if (checkedList.size() == itemWidgets.size()) { System.out.println("remvoe all cheked"); checkAll = false; checkedList.clear(); for (int i = 0; i < itemWidgets.size(); i++) { itemWidgets.get(i).setChecked(false); } } else { System.out.println("check all"); checkAll = true; checkedList.clear(); checkedList.addAll(measurementList); } for (int i = 0; i < itemWidgets.size(); i++) { itemWidgets.get(i).setChecked(checkAll); } tableContent.removeAllViews(); tableContent.addView(generateTableContent(itemWidgets)); resetHeaderCheckBox(); } }); headerLayout.addView(checkImageView); TextView measureTextView = new TextView(context); measureTextView.setGravity(Gravity.CENTER_VERTICAL); measureTextView.setText(measure); measureTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); measureTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); LinearLayout.LayoutParams measureTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); measureTextParams.width = 0; measureTextParams.weight = 0.42f; measureTextView.setLayoutParams(measureTextParams); headerLayout.addView(measureTextView); TextView fDymTextView = new TextView(context); LinearLayout.LayoutParams fDymTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fDymTextParams.width = 0; fDymTextParams.weight = 0.2f; fDymTextView.setLayoutParams(fDymTextParams); fDymTextView.setText(fdym); fDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fDymTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); headerLayout.addView(fDymTextView); TextView tDymTextView = new TextView(context); LinearLayout.LayoutParams tDymTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); tDymTextParams.width = 0; tDymTextParams.weight = 0.2f; tDymTextView.setLayoutParams(tDymTextParams); tDymTextView.setText(tdym); tDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); tDymTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); tDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END); headerLayout.addView(tDymTextView); TextView fEneTextView = new TextView(context); LinearLayout.LayoutParams fEneTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fEneTextParams.width = 0; fEneTextParams.weight = 0.18f; fEneTextView.setLayoutParams(fEneTextParams); fEneTextView.setText(fend); fEneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fEneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); headerLayout.addView(fEneTextView); return headerLayout; } private Drawable getBitmanDrawable(Image image) { return form.getBitmanDrawable(image); } private void resetHeaderCheckBox() { if (checkedList != null) { if (checkedList.size() == 0) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_UNCHECKED, CommonConstants.Images.IMAGE_DPI))); } else if (checkedList.size() < itemWidgets.size()) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_SOME, CommonConstants.Images.IMAGE_DPI))); } else if (checkedList.size() == itemWidgets.size()) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_CHECKED, CommonConstants.Images.IMAGE_DPI))); } else { throw new RuntimeException("Checked item more than item in the list."); } checkedChange.onCheckedChange(getCheckedList()); } } public void loadTable (List measurements) { checkedList.clear(); this.measurementList = measurements; itemsChange.onItemsChange(); resetHeaderCheckBox(); itemWidgets.clear(); tableContent.removeAllViews(); if (!measurements.isEmpty()) { emptyMessageView.setVisibility(View.GONE); for (int i = 0; i < measurements.size(); i++) { final ReportMeasurement measurement = measurements.get(i); MeasurementListItemWidget listItemWidget = new MeasurementListItemWidget(context, measurement, new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { if(((CheckBox) v).isChecked()) { checkedList.add(measurement); } else { checkedList.remove(measurement); } resetHeaderCheckBox(); } } }); itemWidgets.add(listItemWidget); if(emptyMessageView.getChildCount() > 0) emptyMessageView.removeAllViewsInLayout(); } tableContent.addView(generateTableContent(itemWidgets)); } else { if(emptyMessageView.getChildCount() > 0) emptyMessageView.removeAllViewsInLayout(); emptyMessageView.setVisibility(View.VISIBLE); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); } } private LinearLayout generateTableContent(List itemWidgets) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams contentLinearLayoutParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setLayoutParams(contentLinearLayoutParams); for (int i = 0; i < itemWidgets.size(); i++) { MeasurementListItemWidget listItemWidget = itemWidgets.get(i); contentLinearLayout.addView(listItemWidget.getView()); } return contentLinearLayout; } public interface OnCheckedChange { void onCheckedChange(List checkedList); } private OnCheckedChange checkedChange; public void onCheckedChange(OnCheckedChange checkedChange) { this.checkedChange = checkedChange; checkedChange.onCheckedChange(getCheckedList()); } public interface OnEnabledChange { void onEnabledChange(boolean enabled); } private OnEnabledChange enabledChange; public void onEnabledChange(OnEnabledChange enabledChange) { this.enabledChange = enabledChange; enabledChange.onEnabledChange(enabled); } private boolean enabled = true; public void setEnabled(boolean enabled) { this.enabled = enabled; enabledChange.onEnabledChange(enabled); } public interface OnItemsChange { void onItemsChange(); } private OnItemsChange itemsChange; public void onItemsChange(OnItemsChange itemsChange) { this.itemsChange = itemsChange; itemsChange.onItemsChange(); } } package ch.mfiles.kaba.kolibri.service.util; public class ServiceConstants { ServiceConstants() { } public static final int COMPANY_TITLE_CODE = 0003; public static final int PERMISSION_REQUEST_CODE = 200; public static final int RETENTION_PERIOD_MASTER_REFRESH = 24; // Hours public static final int MAX_DOWNLOAD = 30; public static final int MAX_COMFIRM_DOWNLOAD = 10; public static final String InstallationWorkType = "05"; public static final String ModernisationNecessary = "01"; public static final String OfferModernisation = "02"; public static final String SecurityReport = "06"; public static final int MAX_MEASUREMENT_FOR_ONE_POINT = 1; public static final String MATERIAL_BILLING_NEW_PRICE = "01"; public static final int REQUIRE_IMAGE = 5; public static final class Index { Index() { } public static final Integer NULL = null; public static final Integer ZERO = 0; public static final Integer ONE = 1; public static final Integer TWO = 2; public static final Integer THREE = 3; public static final Integer FOUR = 4; public static final Integer FIVE = 5; public static final Integer SIX = 6; public static final Integer SEVEN = 7; public static final Integer EIGHT = 8; public static final Integer NINE = 9; } public static final class MatUnit { MatUnit() { } public static final String M = "M"; public static final String MM = "MM"; public static final String KG = "KG"; public static final String ST = "ST"; } public static final class KMaterialNumber { KMaterialNumber() { } public static final String K_Material = "K-Material"; public static final String K_11 = "K-11"; public static final String K_12 = "K-12"; public static final String K_13 = "K-13"; public static final String K_14 = "K-14"; } } package ch.mfiles.kaba.kolibri.service.util; import java.util.List; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class ServiceFormUtil { public static boolean isFormEdited(List formInstances) { if (formInstances.isEmpty()) { return false; } return true; } public static boolean isFormInComplete(List formItemLis, List formInstances) { return !isFormDone(formItemLis, formInstances); } public static boolean isFormDone(List formItemLis, List formInstances) { if (formItemLis.size() == formInstances.size()) { return true; } return false; } /** * If a form was edited or done: Check Box * If no form was edited or done: Check Box Outline Blank * If a form has errors or is incomplete: Indeterminate Check Box * @param formItemLis * @param formInstances * @return image as integer */ public static Images getCheckImageStatus(List formItemLis, List formInstances) { Images result = ImagesUtil.Images.CHECK_UNCHECKED; if (isFormEdited(formInstances)) { //If a form was edited or done: "", text black, Icon: Check Box if (isFormDone(formItemLis, formInstances)) { result = ImagesUtil.Images.CHECK_CHECKED; } else { //If a form has errors or is incomplete: "", text red, Icon: Indeterminate Check Box result = ImagesUtil.Images.CHECK_SOME; } } else { //If no form was edited or done: "Kein Formular erfasst." text grey, Icon: Check Box Outline Blank if (isFormDone(formItemLis, formInstances)) { result = ImagesUtil.Images.CHECK_UNCHECKED; } } return result; } /** * If a form was edited or done: text black * If no form was edited or done: text grey * If a form has errors or is incomplete: text red * * @param formItemLis * @param formInstances * @return */ public static int getTextColor(List formItemLis, List formInstances) { int result = LayoutUtils.DEFAULT_TEXT_COLOR; switch (getCheckImageStatus(formItemLis, formInstances)) { case CHECK_UNCHECKED: result = LayoutUtils.DEFAULT_DARK_GRAY; break; case CHECK_CHECKED: result = LayoutUtils.DEFAULT_TEXT_COLOR; break; case CHECK_SOME: result = LayoutUtils.DEFAULT_ERROR_COLOR; break; default: result = LayoutUtils.DEFAULT_TEXT_COLOR; break; } return result; } } package ch.mfiles.kaba.kolibri.service.util; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.CardView; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.ui.SignatureView; import ch.mfiles.kolibri.util.LayoutHelper; public class SignatureUtil { public static final String FILE_PATH = "images"; //$NON-NLS-1$ public static final int TARGET_WIDTH = 240; public static final int TARGET_HEIGHT = 216; public static final int TARGET_DENSITY = 75; public static final float ASPECT_RATIO = 1.11f; public static String getOriginalSignatureFileName(String fileName) { String newFilename = ""; int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { newFilename = fileName.substring(0, i - 1) + "_Original" + fileName.substring(i).toLowerCase(); } return newFilename; } public static View flexibleSignatureView(Context context, SignatureView signatureView) { RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); relativeLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); CardView cardView = new CardView(context); RelativeLayout.LayoutParams cardViewParams = new RelativeLayout.LayoutParams(0, 0); cardViewParams.width = LayoutParams.MATCH_PARENT; if (LayoutHelper.getDisplayMetrics().widthPixels > TARGET_WIDTH) { cardViewParams.height = (int) (LayoutHelper.getDisplayMetrics().widthPixels * ASPECT_RATIO); } else { cardViewParams.height = LayoutParams.MATCH_PARENT; } cardViewParams.addRule(RelativeLayout.CENTER_IN_PARENT); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); gradientDrawable.setCornerRadius(7f); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_CARD_VIEW_SHADOW_COLOR); cardView.setBackgroundDrawable(gradientDrawable); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.addView(signatureView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); cardView.addView(linearLayout); relativeLayout.addView(cardView); return relativeLayout; } } package ch.mfiles.kaba.kolibri.service; //used for testing only public class NotificationTestMessage { public String getContent() { return "AUFTR-12345-REP-BR"; //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.service; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.media.MediaPlayer; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult.Status; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.forms.ArticleDetailForm; import ch.mfiles.kaba.kolibri.service.forms.ArticleDetailForm.ArticleDetailFormArguments; import ch.mfiles.kaba.kolibri.service.forms.JobListForm; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm.JobSearchFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kaba.kolibri.service.util.SignatureUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.NotificationMessage; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.SubProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; /** * Main application class. */ public class ServiceApplication extends Application { public static final Log log = LogFactory.getLog(ServiceApplication.class); public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public EnumUtil enumUtil; public MessageUtil messageUtil; public boolean filterHist; private Notifications notifications; @Override public ApplicationEvent onNotification(NotificationMessage message) { try { if (message.getContent() == null) { // should not happen, not sure if it does log.error("message with no content received"); //$NON-NLS-1$ return null; } // AUFTR-12345-REP-BR if (message.getContent().startsWith(CommonConstants.Prefix.AUFTR)) { // this is a new job -> parse the parameters and fetch it int firstDashPos = message.getContent().indexOf('-', 0); if (firstDashPos <= 0) { return null; } int secondDashPos = message.getContent().indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return null; } int thirdDashPos = message.getContent().indexOf('-', secondDashPos + 1); if (thirdDashPos <= 0) { return null; } final String jobNumber = message.getContent().substring(firstDashPos + 1, secondDashPos); final String orderType = message.getContent().substring(secondDashPos + 1, thirdDashPos); if (dbutil == null) { dbutil = DatabaseUtil.getInstance(); } RemoteTransactionHandler transactionHandler = new RemoteTransactionHandler(); if (transactionHandler.runGetOrder(jobNumber, orderType, dbutil.getUser().getPersonalNumber()).getStatus() == Status.success) { // If this job was already existing in the DB, the // jobStatus has to be // set manually, because the information is not // delivered in the // GET_ORDER transaction String jobNumberLZ = "0000000000".substring(0, 10-jobNumber.length()) + jobNumber; Job newJob = dbutil.selectJobByJobIdAndJobType(jobNumberLZ, orderType); newJob.calculateActiveDate(); if (newJob.getStatus().isForwarded()) { newJob.setStatus(JobStatus.NEW); dbutil.updateJob(newJob); } // Inform user about new job new Notifications(this).newJobNotification(Messages.getString("newJobReceived")); //$NON-NLS-1$ // Inform user about new job (optically) final Form currentForm = this.getCurrentForm(); if (currentForm != null && currentForm instanceof JobListForm) { // update the job list currentForm.runOnUIThread(new Runnable() { @Override public void run() { log.debug("reloading job list"); ((JobListForm) currentForm).loadTable(); } }); } } } if (message.getContent().startsWith(CommonConstants.Prefix.SHORTMSG)) { if (log.isDebugEnabled()) { log.debug("message startsWith SHORTMSG"); //$NON-NLS-1$ } int firstDashPos = message.getContent().indexOf('-', 0); if (firstDashPos <= 0) { return null; } int secondDashPos = message.getContent().indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return null; } final String pernr = message.getContent().substring(firstDashPos + 1, secondDashPos); final String tdName = message.getContent().substring(secondDashPos + 1, message.getContent().length()); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); if (new RemoteTransactionHandler().runGetShortMSG(Integer.parseInt(pernr), tdName)) { // Inform user about new short message new Notifications(this).shortMessageNotification(Messages.getString("newShortMessageReceived")); //$NON-NLS-1$ } } //MBEW-7F000001018E31C62FAAFCFA0D35797F-CONF if (message.getContent().startsWith(CommonConstants.Prefix.MBEW)) { if (log.isDebugEnabled()) { log.debug("message startsWith MBEW"); //$NON-NLS-1$ } log.info(message.getContent()); if (isServiceActive()) { getIncomingArticle(message.getContent()); } else { Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.INCOMING_ARTICLE_NAME, message.getContent()); } } } } catch (Exception e) { log.error("Found Exception: ", e); } return null; } /** * Called by the framework each time the application is started. * * @param obj * An (optional) object supplied by the application that started * this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); enumUtil = EnumUtil.getInstance(this.dbutil); messageUtil = MessageUtil.getInstance(); notifications = new Notifications(this); // make sure the common plugin exists if (null == appman.getApplicationDescriptor(CommonConstants.Application.COMMON_APP)) { showMessageBox(ServiceMessages.getString("gilgenCommonApplicationIsNotInstalled"), ServiceMessages.getString("startGilgenService"), MBOX_BUTTON_OK, MBOX_ICON_ERROR); //$NON-NLS-1$ //$NON-NLS-2$ return appman.exitApplication(); } // register broadcast receiver notifications.registerBroadcastReceiver(); deleteOldJobs(); deleteFormInstancesNotUsed(); setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { try { getIncomingArticle(reg.getProperty(RegistryProperties.INCOMING_ARTICLE_NAME)); } catch (IllegalArgumentException e) { //No IncomingArticle } } return leaveToForm(JobListForm.class); } /** * Refresh app masterdata. * * @param force Set to true to refresh masterdata even if the regular refresh * already took place. */ public void refreshMasterData(boolean force) { Calendar retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.HOUR_OF_DAY, - ServiceConstants.RETENTION_PERIOD_MASTER_REFRESH); Date lastRefresh = new Date(RegistryUtil.getMasterDataRefreshDateProperty(this)); if (lastRefresh.before(retentionPeriodEnd.getTime()) || force) { //showMessage(ServiceMessages.getString("refreshingMasterData")); //$NON-NLS-1$ new AsyncTask(getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { monitor.begin(5); Person currentUser = dbutil.getUser(); // master data refresh monitor.comment(ServiceMessages.getString("refreshMasterData")); boolean refreshMasterdataSuccessful = new RemoteTransactionHandler() .runRefreshMasterdata(currentUser.getPersonalNumber(), "", "X", new SubProgressMonitor(monitor, 3)); //$NON-NLS-1$ //$NON-NLS-2$ if (refreshMasterdataSuccessful) { showMessage(ServiceMessages.getString("masterDataSuccessfullyRefreshed")); //$NON-NLS-1$ } else { showMessage(ServiceMessages.getString("refreshingMasterDataFailed")); //$NON-NLS-1$ } // stock data refresh monitor.comment(ServiceMessages.getString("refreshingStock")); boolean getInventryStockSuccessful = new RemoteTransactionHandler() .runGetInventryStock(currentUser.getPersonalNumber(), currentUser.getWarehouseNumber(), currentUser.getLanguage()); monitor.worked(1); // order synchronization monitor.comment(ServiceMessages.getString("synchronizingOrders")); boolean syncOrderSuccessful = new RemoteTransactionHandler().runSyncOrder(currentUser.getPersonalNumber()); monitor.worked(1); if (refreshMasterdataSuccessful && getInventryStockSuccessful && syncOrderSuccessful) { Calendar nextRefresh = DateTimeUtil.getToday(); nextRefresh.add(Calendar.HOUR_OF_DAY, ServiceConstants.RETENTION_PERIOD_MASTER_REFRESH); RegistryUtil.setMasterDataRefreshDateProperty(ServiceApplication.this, nextRefresh.getTime().getTime()); } // refresh joblist final Form currentForm = getCurrentForm(); if (currentForm != null && currentForm instanceof JobListForm) { // update the job list currentForm.runOnUIThread(new Runnable() { @Override public void run() { log.debug("reloading job list"); ((JobListForm) currentForm).loadTable(); } }); } return null; } }; } } public void deleteOldJobs() { final int retentionPeriodReport = 1; // Month final String infoMsg1 = "Report from {0} for {1}-Job {2} in status {3} found (current retention period is {4} month"; //$NON-NLS-1$ final String infoMsg2 = "Deleted {0}-Job {1} is older than {2} months"; //$NON-NLS-1$ List finalizedJobList = dbutil.selectFinalizedJobList(); if(!finalizedJobList.isEmpty()){ Calendar retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.MONTH, -retentionPeriodReport); log.info("retentionPeriodEnd = " + retentionPeriodEnd.getTime()); for(int i=0; i < finalizedJobList.size(); i++){ Job finalizedJob = finalizedJobList.get(i); finalizedJob.loadReports(dbutil); Report finalizedReport = finalizedJob.getCurrentReport(); log.info("finalizedReport = " + finalizedReport.getCreateDate()); Object[] argumenst = new Object[] { DateTimeUtil.showDateTime(finalizedReport.getCreateDate()), finalizedJob.getJobType(), finalizedJob.getJobNumber(), finalizedJob.getStatus().getCode(), String.valueOf(retentionPeriodReport) }; log.info(MessageFormat.format(infoMsg1, argumenst)); // Criteria for deleting a job oder than the retention period: // 1. there is no report OR // 2. the latest report is older then the retention period if (finalizedReport.getReportStatus().isInitial() || DateTimeUtil.getTime(finalizedReport.getCreateDate()).getTime().before(retentionPeriodEnd.getTime())) { argumenst = new Object[] { finalizedJob.getJobType(), finalizedJob.getCommissionNumber(), String.valueOf(retentionPeriodReport) }; log.info(MessageFormat.format(infoMsg2, argumenst)); dbutil.deleteJob(finalizedJob); } } } deleteSignatureFilesNotUsed(); } public void deleteFormInstancesNotUsed() { log.info("before delete FormInstance not used " + dbutil.selectCountFromTable("FormInstance", "")); dbutil.deleteFormInstancesWithoutReport(); log.info("after delete FormInstance not used " + dbutil.selectCountFromTable("FormInstance", "")); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { // Unregister broadcast receiver and remove the notification notifications.removeNotification(); notifications.unregisterBroadcastReceiver(); return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { deleteExtractedFiles(); } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // make sure the common plugin exists if (null == appman.getApplicationDescriptor(CommonConstants.Application.COMMON_APP)) { throw new ApplicationException(ServiceMessages.getString("installGilgenCommonApplicationFirst")); //$NON-NLS-1$ } } /** * Called by the framework after the application has been upgraded but * before the upgrade is committed to the database. Additional upgrade * post-processing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } private void deleteExtractedFiles(){ deleteExtractedDirAndFiles(new File(Runtime.getInstallationFolder() + File.separator + CommonConstants.Application.SERVICE + File.separator)); } private boolean deleteExtractedDirAndFiles(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i usedSignFilenames = dbutil.selectReportListOfSignFiles(); //read all existing filenames for the file system HashMap signFilesMap = getAllSignatureFiles(); //remove files not used anymore in a report Iterator itr = usedSignFilenames.iterator(); while (itr.hasNext()) { String usedSignFilename = itr.next(); if (signFilesMap.containsKey(usedSignFilename)) signFilesMap.remove(usedSignFilename); if (signFilesMap.containsKey(SignatureUtil.getOriginalSignatureFileName(usedSignFilename))) signFilesMap.remove(SignatureUtil.getOriginalSignatureFileName(usedSignFilename)); } Iterator> itrSignature = signFilesMap.entrySet().iterator(); while (itrSignature.hasNext()) { Map.Entry entry = itrSignature.next(); String filename = (String) entry.getKey(); deleteSignatureFile(filename); } } private HashMap getAllSignatureFiles(){ HashMap signFilesMap = new HashMap(); String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, "", false); //$NON-NLS-1$ File signFileFolder = new File(imagePath); if (signFileFolder.exists()) { File[] signFileArray = signFileFolder.listFiles(new BitmapsOnly()); for (int n=0; n < signFileArray.length; n++) { signFilesMap.put(signFileArray[n].getName(), signFileArray[n]); } } else { log.error("Expected signature file not found: " + imagePath); //$NON-NLS-1$ } return signFilesMap; } public boolean deleteFile(String filePath) { if(log.isDebugEnabled()) log.debug("Delete file: filePath /" + filePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ File fFile = new File(filePath); if (fFile.exists()) { if (fFile.delete()) { log.info("File deleted successfully: "); //$NON-NLS-1$ return true; } else { log.error("Was not able to delete file: " + filePath); //$NON-NLS-1$ return false; } } else { log.error("Expected file not found: " + filePath); //$NON-NLS-1$ return false; } } public boolean deleteSignatureFile(String filename) { String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, filename, true); if(log.isDebugEnabled()) log.debug("Delete signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ File signFile = new File(imagePath); if (signFile.exists()) { if (signFile.delete()) { deleteOriginaSignatureFile(imagePath); log.info("Signature file deleted successfully: " + filename); //$NON-NLS-1$ return true; } else { log.error("Was not able to delete signature file: " + imagePath); //$NON-NLS-1$ return false; } } else { log.error("Expected signature file not found: " + imagePath); //$NON-NLS-1$ return false; } } private void deleteOriginaSignatureFile(String imagePath) { String originalFileName = SignatureUtil.getOriginalSignatureFileName(imagePath); File originaFile = new File(originalFileName); if (originaFile.exists() && originaFile.delete()) { log.info("Signature file deleted successfully: " + originaFile.getName()); } } private class BitmapsOnly implements FilenameFilter { private String suffix; public BitmapsOnly() { this.suffix = ".bmp"; //$NON-NLS-1$ } @Override public boolean accept(File dir, String fileName) { return fileName.endsWith(this.suffix); } } public void injectAndLeaveToForm(final Class formTo, final Object argument) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return leaveToForm(formTo, argument); } }, false); } public void showWarningMessageBox(final String warningMessage){ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { showMessageBox(warningMessage, ServiceMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } public void showMessage(String message) { messageUtil.showMessage(message); } public void showMessage(String message, boolean forceClear) { messageUtil.showMessage(message, forceClear); } public void clearMessage() { messageUtil.clearMessage(); } public String getAddressTitle(Address address) { String title = enumUtil.titelEnum.get(address.getTitle()); String name = ""; if (StringUtil.isNotEmpty(title)) { name = title + " " + address.getName1(); //$NON-NLS-1$ } else { name = address.getName1(); } log.info("Title " + title + " Name1 " + address.getName1() + " Name2 " + address.getName2()); if (address.isPrivate()) { // b) personal address // ZKDMOBADR.TITEL // ZKDMOBADR.NAME1 // ZKDMOBADR.NAME2 return name + " " + address.getName2(); //$NON-NLS-1$ } else { // a) company address // ZKDMOBADR.TITEL // ZKDMOBADR.NAME1 return name; } } public boolean isJobAndReportComplete(Job job) { boolean result = false; Person currentUser = dbutil.getUser(); Report report = job.getCurrentReport(); JobReportTime time = null; if (currentUser != null && !report.getReportStatus().isInitial()) { time = dbutil.selectJobReportTimeByGuid(job.getCurrentReportGuId(dbutil)); if (report.getReportStatus().isNew()){ result = true; if (time != null && time.getStopTime().equals(new Date(0))) { result = false; } } } return result; } public boolean showConfirmDeleteDialog() { return showMessageBox(ServiceMessages.getString("doYouWantToDeleteJob"), ServiceMessages.getString("warning"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES; } public void scanSavJob() { new AsyncTask(getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String jobNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ return null; } else { showMessage(result.toString()); jobNumber = result.getContents(); StringBuilder builder = new StringBuilder(); if(jobNumber.length() < 10) { for (int i = 0; i < 10 - jobNumber.length(); i++) { builder.append("0"); } jobNumber = builder.toString() + jobNumber; } log.info("scan result -> " + jobNumber); //$NON-NLS-1$ } if (!ServiceJobUtil.isValidJobNumber(jobNumber)) { showMessage(ServiceMessages.getString("invalidJobNumber")); //$NON-NLS-1$ return null; } // call SAP if (new RemoteTransactionHandler().runGetOrder(jobNumber, "SAV", dbutil.getUser().getPersonalNumber()).getStatus() == RemoteTransactionResult.Status.success) { Job job = dbutil.selectJobByJobIdAndJobType(jobNumber, "SAV"); job.calculateActiveDate(); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } return leaveToForm(JobListForm.class); } }; } public void scanCommissionNumber() { new AsyncTask(getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String commissionNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ return null; } else { showMessage(result.toString()); commissionNumber = result.getContents(); log.info("scan result -> " + commissionNumber); //$NON-NLS-1$ } return callForm(JobSearchForm.class, new JobSearchFormArguments(null)); } }; } public boolean play(String path) { MediaPlayer mPlayer = new MediaPlayer(); try { log.info("Playing .. " + path); FileInputStream inputStream = new FileInputStream(path); mPlayer.setDataSource(inputStream.getFD()); inputStream.close(); mPlayer.prepare(); mPlayer.start(); } catch (IOException e){ log.error("IOException" + e.getMessage()); return false; } return true; } private boolean isServiceActive() { return Runtime.getApplicationManager().getActiveApplication().getApplicationDescriptor().getApplication().equalsIgnoreCase(CommonConstants.Application.SERVICE_APP); } public void getIncomingArticle(String message) { // Prefix: "MBEW" // Content: // Suffix: "CONF" int firstDashPos = message.indexOf('-', 0); if (firstDashPos <= 0) { return; } int secondDashPos = message.indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return; } final String guid = message.substring(firstDashPos + 1, secondDashPos); final String conf = message.substring(secondDashPos + 1, message.length()); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); int pernr = dbutil.getUser().getPersonalNumber(); if (new RemoteTransactionHandler().runGetMaterialMoveMent(guid, pernr, new Date())) { Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.deleteProperty(RegistryUtil.RegistryProperties.INCOMING_ARTICLE_NAME); } MaterialMovement materialMovement = dbutil.selectMaterialMovement(guid); if (materialMovement != null) { // Inform user about new MBEW new Notifications(this).IncomingArticleNotification(Messages.getString("newVehicleInventoryReceived")); dbutil.deleteMaterialMovement(materialMovement); injectAndLeaveToForm(ArticleDetailForm.class, new ArticleDetailFormArguments(materialMovement)); } } } } /bin/ /build/ gilgenService ch.mfiles.kolibri.plugin.androidResourceBuilder org.eclipse.jdt.core.javabuilder ch.mfiles.kolibri.plugin.kolibriNature org.eclipse.jdt.core.javanature plugins { id("ch.mfiles.kolibri-application") } dependencies { implementation(project(":common")) } # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23
Kontakt Anrufen
Gruppe
Telefon-Nr.
Firma
Name Vorname
Name Vorname
Firma
Gruppe
Telefon-Nr.
cp.android.nanoxml=false cp.android.unrestricted=false eclipse.preferences.version=1 platform=ANDROID #Wed Apr 06 22:48:58 CEST 2011 eclipse.preferences.version=1 encoding//src/ch/mfiles/kaba/kolibri/common/CommonApplication.java=UTF-8 encoding//src/ch/mfiles/kaba/kolibri/common/util/CONSTANTS.java=UTF-8 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.7 #Fri Sep 19 13:25:29 GMT+07:00 2008 eclipse.preferences.version=1 internal.default.compliance=user #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface NoTimeSheet = Es wurde keine Zeit eingegeben. Das Zeiterfassungs-/Spesen-Blatt kann nicht an den Server gesandt werden. ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = Einige der Daten sind ung\u00FCltig. Sind Sie sicher, dass Sie schliessen und die \u00C4nderungen verwerfen wollen? amount = Anzahl Amount = Betrag areYouSureThatYouWantToDeleteAllRecords = Sind Sie sicher, dass Sie alle Datens\u00E4tze l\u00F6schen m\u00F6chten? areYouSureThatYouWantToDeleteRecord = Soll der Eintrag gel\u00F6scht werden? calendar = Kalender cannotTransmissonToServerThereIsUnsavedPersonalTimeData = Einige der Daten sind ung\u00FCltig. Das Zeiterfassungs-/Spesen-Blatt kann nicht an den Server gesandt werden. carMilage = Fz. km changesWillBeLost = \u00C4nderungen gehen verloren, weiterfahren? clear = Reset clock = Uhr compensation = Verg\u00FCtung dailyExpense = Tagesspesen date = Datum day = Tag deduction = Abzug delete = L\u00F6schen employee = Mitarbeiter enteredValueIsInTheFuture = Der eingegebene Wert liegt in der Zukunft. Bitte geben Sie einen g\u00FCltigen Wert ein. enteredValueIsInTheFuturePleaseEnterValidTime = Der eingegebene Wert liegt in der Zukunft. Bitte geben Sie einen g\u00FCltigen Wert ein. exit = Beenden expense = Spesen expenseSheetCouldNotBeSaved = Spesen konnten nicht gespeichert werden. Bitte nochmals probieren. fr = CHF from = Von fromTo = Von - Bis hours = Std ia = IA image = Bild internalTypeOfWork = Interne Arbeitsart internalWorkType = Interne Arbeitsart listIsEmptyNoTimeEntryToDelete = Liste ist leer, Zeit kann nicht gel\u00F6scht werden miscExpense = Div. Spesen newTimeEntryConfictsWithExistingOne = Neuer Eintrag kollidiert mit Bestehendem: {0} - {1} noExpenses = Keine Spesen noExpensesFoundForThisDate = Keine Spesen f\u00FCr dieses Datum erfasst noPresentCannotBeSent = Kein {0} erstellt f\u00FCr {1}, {2} kann nicht \u00FCbermittelt werden. noReportAvailable = Keinen Rapport gefunden noTimeEntrySelected = Keinen Eintrag gew\u00E4hlt non = keine onCall = Pikett opHrs = Betr. Std. p = P payment = Auszahlung personalTime = Zeit personalTimeAndExpensesNotSent = Zeit und Spesen noch nicht \u00FCbertragen! pikett = Pikett pikettExpenses = Pikettspesen pleaseAdjustBeforeSendToServer = Stempelung \u00FCber Mitternacht entdeckt, bitte korrigieren. pleaseEnterTime = Bitte Zeit eingeben pleaseEnterValidTime = Bitte eine g\u00FCltige Zeit eingeben pleaseEnterWorkType = Bitte Arbeitsart angeben removingOldTimesheets = Alte Timesheets l\u00F6schen: save = Speichern send = Senden startTimeAlreadyExists = Es gibt schon einen Eintrag mit identischer Startzeit: {0} startingTime = Startzeit state = Status time = Zeit timeIsRumming = Zeit laufend timeSheet = Zeiterfassung timeSheetNotSentOlderThanThirTyDays = Timesheet vom {0} wurde noch nicht \u00FCbermittelt. timesheet = Zeiterfassung timesheetAlreadySent = Timesheet wurde bereits gesandt. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = Nach der \u00DCbermittlung k\u00F6nnen Sie die Auftragszeiten und das Spesenformular nicht mehr bearbeiten. Fortfahren? timesheetSent = Timesheet gesendet. to = Bis total = Total variousExpenses = Diverse Spesen vehicleKilometers = Fahrzeugkilometer warning = Warnung! wrongFormArgument = Falscher Form\u00FCbergabeparameter #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface NoTimeSheet = Le temps n'a pas \u00E9t\u00E9 entr\u00E9. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre envoy\u00E9e au serveur. ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = Certaines des donn\u00E9es ne sont pas valables. Voulez-vous vraiment fermer et annuler les modifications? amount = Quantit\u00E9 Amount = Montant areYouSureThatYouWantToDeleteAllRecords = \u00CAtes-vous s\u00FBr de vouloir supprimer tous les enregistrements? areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? calendar = Calendrier cannotTransmissonToServerThereIsUnsavedPersonalTimeData = Certaines des donn\u00E9es ne sont pas valables. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre enfoy\u00E9e au serveur. carMilage = Km v\u00E9hic. changesWillBeLost = Les changements seront perdus. Continuer? clear = Remettre clock = Regarder compensation = Remboursement dailyExpense = Frais du jour date = Date day = Jour deduction = D\u00E9duction delete = Effacer employee = Collaborateur enteredValueIsInTheFuture = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. exit = Terminer expense = Frais expenseSheetCouldNotBeSaved = Impossible de m\u00E9moriser les frais. Veuillez r\u00E9essayer. fr = CHF from = De fromTo = de - \u00E0 hours = Heures ia = IA image = Image internalTypeOfWork = Type de travail interne internalWorkType = Type de travail interne listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible de supprimer le temp miscExpense = Div. frais newTimeEntryConfictsWithExistingOne = Nouvelle entr\u00E9e en collision avec l''entr\u00E9e existante: {0} - {1} noExpenses = Pas de frais noExpensesFoundForThisDate = Pas de frais saisies pour cette date noPresentCannotBeSent = Aucun {0} \u00E9tabli pour f\u00FCr {1}, {2} impossible de transmettre. noReportAvailable = Aucun rapport n'est trouv\u00E9 noTimeEntrySelected = Aucun enregistrement n'est saisi non = aucun onCall = Piquet opHrs = Heures de fonct. p = P payment = Versement personalTime = Temps personnel personalTimeAndExpensesNotSent = Temps n\u00E9cessaire et d\u00E9penses n'ont pas \u00E9t\u00E9 transmis! pikett = Piquet pikettExpenses = Frais d'appel pleaseAdjustBeforeSendToServer = Enregistrement d\u00E9t\u00E9ct\u00E9 apr\u00E9s minuit, s.v.p. corriger. pleaseEnterTime = Veuillez saisir le temps pleaseEnterValidTime = Veuillez saisir un temps valide pleaseEnterWorkType = Veuillez introduire le type de travail removingOldTimesheets = Effacer les vieilles fiches horaires : save = Enregistre send = Envoyer startTimeAlreadyExists = Il y a d\u00E9j\u00E0 un enregistrement avec temps de d\u00E9marrage identique: {0} startingTime = Heure de d\u00E9but state = \u00C9tat time = Temps timeIsRumming = Le temps court timeSheet = Saisie du temps timeSheetNotSentOlderThanThirTyDays = Timesheet de {0} n'a pas encore \u00E9t\u00E9 transmis. timesheet = Saisie du temps timesheetAlreadySent = Feuille de saisie des heures a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9e. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = Impossible d'\u00E9diter les temps de commande et le formulaire des frais apr\u00E9s la transmission. Transmettre? timesheetSent = Feuille de temps envoy\u00E9e. to = \u00E0 total = Total variousExpenses = Various Expenses vehicleKilometers = Kilom\u00E9trage du v\u00E9hicule warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface NoTimeSheet = Le temps n'a pas \u00E9t\u00E9 entr\u00E9. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre envoy\u00E9e au serveur. ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = Certaines des donn\u00E9es ne sont pas valables. Voulez-vous vraiment fermer et annuler les modifications? amount = Quantit\u00E9 Amount = Montant areYouSureThatYouWantToDeleteAllRecords = \u00CAtes-vous s\u00FBr de vouloir supprimer tous les enregistrements? areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? calendar = Calendrier cannotTransmissonToServerThereIsUnsavedPersonalTimeData = Certaines des donn\u00E9es ne sont pas valables. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre enfoy\u00E9e au serveur. carMilage = Km v\u00E9hic. changesWillBeLost = Les changements seront perdus. Continuer? clear = Remettre clock = Regarder compensation = Remboursement dailyExpense = Frais du jour date = Date day = Jour deduction = D\u00E9duction delete = Effacer employee = Collaborateur enteredValueIsInTheFuture = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. exit = Terminer expense = Frais expenseSheetCouldNotBeSaved = Impossible de m\u00E9moriser les frais. Veuillez r\u00E9essayer. fr = CHF from = De fromTo = de - \u00E0 hours = Heures ia = IA image = Image internalTypeOfWork = Type de travail interne internalWorkType = Type de travail interne listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible de supprimer le temp miscExpense = Div. frais newTimeEntryConfictsWithExistingOne = Nouvelle entr\u00E9e en collision avec l''entr\u00E9e existante: {0} - {1} noExpenses = Pas de frais noExpensesFoundForThisDate = Pas de frais saisies pour cette date noPresentCannotBeSent = Aucun {0} \u00E9tabli pour f\u00FCr {1}, {2} impossible de transmettre. noReportAvailable = Aucun rapport n'est trouv\u00E9 noTimeEntrySelected = Aucun enregistrement n'est saisi non = aucun onCall = Piquet opHrs = Heures de fonct. p = P payment = Versement personalTime = Temps personnel personalTimeAndExpensesNotSent = Temps n\u00E9cessaire et d\u00E9penses n'ont pas \u00E9t\u00E9 transmis! pikett = Piquet pikettExpenses = Frais d'appel pleaseAdjustBeforeSendToServer = Enregistrement d\u00E9t\u00E9ct\u00E9 apr\u00E9s minuit, s.v.p. corriger. pleaseEnterTime = Veuillez saisir le temps pleaseEnterValidTime = Veuillez saisir un temps valide pleaseEnterWorkType = Veuillez introduire le type de travail removingOldTimesheets = Effacer les vieilles fiches horaires : save = Enregistre send = Envoyer startTimeAlreadyExists = Il y a d\u00E9j\u00E0 un enregistrement avec temps de d\u00E9marrage identique: {0} startingTime = Heure de d\u00E9but state = \u00C9tat time = Temps timeIsRumming = Le temps court timeSheet = Saisie du temps timeSheetNotSentOlderThanThirTyDays = Timesheet de {0} n'a pas encore \u00E9t\u00E9 transmis. timesheet = Saisie du temps timesheetAlreadySent = Feuille de saisie des heures a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9e. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = Impossible d'\u00E9diter les temps de commande et le formulaire des frais apr\u00E9s la transmission. Transmettre? timesheetSent = Feuille de temps envoy\u00E9e. to = \u00E0 total = Total variousExpenses = Various Expenses vehicleKilometers = Kilom\u00E9trage du v\u00E9hicule warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) NoTimeSheet = No time entered. The Timesheet/Expensesheet cannot be sent to the server ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = There are some invalid data. Are you sure you want to close and dismiss the changes? amount = Amount Amount = Amount areYouSureThatYouWantToDeleteAllRecords = Are you sure that you want to delete all records? areYouSureThatYouWantToDeleteRecord = Are you sure that you want to delete this record? calendar = Calendar cannotTransmissonToServerThereIsUnsavedPersonalTimeData = There are some invalid data. The Timesheet/Expensesheet cannot be sent to the server. carMilage = Car milage changesWillBeLost = Changes will be lost, are you sure that you want to continue? clear = Clear clock = O'clock compensation = Compensation dailyExpense = Daily expense date = Date day = Day deduction = Deduction delete = Delete employee = Employee enteredValueIsInTheFuture = The entered value is in the future! Please enter a valid time enteredValueIsInTheFuturePleaseEnterValidTime = The entered value is in the future! Please enter a valid time exit = Exit expense = Expense expenseSheetCouldNotBeSaved = Expense sheet could not be saved. Please try again. fr = CHF from = From fromTo = From - to hours = Hours ia = IA image = Image internalTypeOfWork = Internal type of work internalWorkType = Internal Work type listIsEmptyNoTimeEntryToDelete = List is empty, no time entry to delete miscExpense = Misc. expense newTimeEntryConfictsWithExistingOne = New time entry conficts with existing one: {0} - {1} noExpenses = No expenses noExpensesFoundForThisDate = No expenses found for this date noPresentCannotBeSent = No {0} present for {1}, {2} cannot be sent. noReportAvailable = No report available noTimeEntrySelected = No time entry selected non = non onCall = On-call opHrs = Op.Hrs. p = P payment = Payment personalTime = Personal time personalTimeAndExpensesNotSent = Personal time and expenses aren't sent yet! pikett = Pikett pikettExpenses = Pikett expenses pleaseAdjustBeforeSendToServer = Entry past midnight detected, please adjust it before send to server. pleaseEnterTime = Please enter a time pleaseEnterValidTime = Please enter a valid time pleaseEnterWorkType = Please enter a work type removingOldTimesheets = Removing old time sheets: save = Save send = Send startTimeAlreadyExists = Entry with identical start time {0} already exists. startingTime = Starting time state = State time = Time timeIsRumming = Time is running timeSheet = TimeSheet timeSheetNotSentOlderThanThirTyDays = Timesheet from: {0} refered on the timesheet, that wasn't sent since 30 days. timesheet = Timesheet timesheetAlreadySent = Timesheet already sent. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = The Timesheet/Expensesheet cannot be edited anymore after transmisson to the server.\nAre you sure that you want to transmit the Timesheet together with the Expensesheet? timesheetSent = Timesheet sent. to = To total = Total variousExpenses = Various Expenses vehicleKilometers = Vehicle kilometers warning = Warning! wrongFormArgument = Wrong form argument class found in form package ch.mfiles.kaba.kolibri.timesheet; import java.util.MissingResourceException; import java.util.ResourceBundle; public class TimeSheetMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.timesheet.Messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private TimeSheetMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } package ch.mfiles.kaba.kolibri.timesheet.forms; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class SuperForm extends DialogForm { protected Context context; protected LinearLayout view; // initialized by the kolibri framework... public static TimeSheetApplication app; public static boolean isServiceApp; protected ActionCtrl sendButton; @Override public View onFormLoad(Context context, LayoutInflater inflater) { this.context = context; final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); view.setFocusable(true); view.setFocusableInTouchMode(true); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image clearImage = imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(clearImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create save action Image saveImage = imagesUtil.getImage(ImagesUtil.Images.SAVE_WHITE, CommonConstants.Images.IMAGE_DPI); saveButton = addActionCtrl(false, true, 1, "onSavePressed"); //$NON-NLS-1$ saveButton.setTitle(TimeSheetMessages.getString("save")); //$NON-NLS-1$ saveButton.setImage(saveImage); sendButton = addActionCtrl(false, true, 2, "onSendPressed"); //$NON-NLS-1$ sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); return view; } @Override protected ApplicationEvent onSavePressed() { hideSoftInputFromWindow(); if (isValid()) { onSave(); } return null; } protected boolean isValid() { return true; } /** * Closes the keyboard (if open) */ protected void hideSoftInputFromWindow() { KeyboardUtil.closeKeyboard(appman, getView()); } /** * Clears the error messages. */ protected void clearErrorMessages() { // do nothings } protected ApplicationEvent onSendPressed() { return null; } protected void setSendButtonEnabled(boolean enabled) { sendButton.setEnabled(enabled); if (enabled) { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); } else { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); } } } package ch.mfiles.kaba.kolibri.timesheet.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.InternalWorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class TimeSheetForm extends SuperForm implements OnItemSelectedListener { private static Log log = LogFactory.getLog(TimeSheetForm.class); private CalendarTimeSheet mCalendar; private TimeUtil timeUtil; private TimeSheet time; private RelativeLayout mainView; private MDSpinner internalWorkTypeValue; private TimeEditText fromText; private TimeEditText toText; private AppCompatCheckBox onCallCheckBox; private Button deleteButton; private boolean isEdit = false; public void onFormCall(Object argument) { if (argument instanceof TimeSheetFormArgument) { mCalendar = ((TimeSheetFormArgument) argument).getCALENDAR(); time = ((TimeSheetFormArgument) argument).getTime(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(TimeSheetMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); timeUtil = new TimeUtil(app, app.dbutil, this); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout dateLinearLayout = new LinearLayout(context); dateLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; dateLinearLayout.setLayoutParams(leftIconLinearLayoutParams); fromText = TimeEditText.createDefaultEditText(dateLinearLayout, TimeSheetMessages.getString("from"), true); //$NON-NLS-1$ fromText.setTag("VON"); //$NON-NLS-1$ LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; fromText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); toText = TimeEditText.createDefaultEditText(dateLinearLayout, TimeSheetMessages.getString("to"), true); //$NON-NLS-1$ toText.setTag("BIS"); //$NON-NLS-1$ LinearLayout.LayoutParams toInputLayoutParams = new LinearLayout.LayoutParams(0, 0); toInputLayoutParams.gravity = Gravity.CENTER; toInputLayoutParams.width = 0; toInputLayoutParams.height = LayoutParams.MATCH_PARENT; toInputLayoutParams.weight = 0.5f; toText.getParentTextInputLayout().setLayoutParams(toInputLayoutParams); contentLinearLayout.addView(dateLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // work type internalWorkTypeValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, TimeSheetMessages.getString("internalWorkType"), true); //$NON-NLS-1$ internalWorkTypeValue.setTag("ARBEITSART"); //$NON-NLS-1$ internalWorkTypeValue.setOnItemSelectedListener(this); contentLinearLayout.addView(workTypeLinearLayout); onCallCheckBox = CommonUtilForm.getCheckBox(context, TimeSheetMessages.getString("onCall")); //$NON-NLS-1$ contentLinearLayout.addView(onCallCheckBox); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (time == null) { fromText.getText().clear(); toText.getText().clear(); fromText.clearError(); toText.clearError(); internalWorkTypeValue.clearError(); internalWorkTypeValue.setSelection(0); onCallCheckBox.setChecked(false); } else { deleteTime(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); view.addView(mainView); return view; } /** * This event is received every time the form is shown. This happens if the * form is called by the framework, another form or if reactivated from the * application's form stack. <p/> * * The application developer has to set all member variables (reset the * state of the form) at this point because the framework reuses the forms * (every form is instantiated exactly once during the lifetime of an * application) *

* * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(DateTimeUtil.showDayOfWeek(mCalendar.getDate()) + ", " + DateTimeUtil.showDate(mCalendar.getDate())); //$NON-NLS-1$ if (mainView.getChildCount() > 0) { mainView.removeAllViewsInLayout(); mainView.invalidate(); } setFormTitle(DateTimeUtil.showDate(mCalendar.getDate())); loadData(); fromText.setEnabled(!mCalendar.getStatus().isSENT()); toText.setEnabled(!mCalendar.getStatus().isSENT()); internalWorkTypeValue.setEnabled(!mCalendar.getStatus().isSENT()); onCallCheckBox.setEnabled(!mCalendar.getStatus().isSENT()); deleteButton.setEnabled(!mCalendar.getStatus().isSENT()); mCalendar.getTimeSheets(); setSendButtonEnabled(true); if (time != null && time.getStopTime().equals(DateUtils.getInitialDateTime())) { // time capture started fromText.setRequired(false); fromText.setEnabled(false); toText.setEnabled(false); toText.setRequired(false); } return null; } public void loadData() { List internalWorkTypeValueList = new ArrayList(); List internalWorkTypeList = app.dbutil.selectInternalWorkTypeList(); for (InternalWorkType internalWorkType : internalWorkTypeList) { internalWorkTypeValueList.add(new CustomSpinnerItem((String) internalWorkType.getWorkTypeCode(), (String) internalWorkType.getText())); } fromText.clearError(); toText.clearError(); internalWorkTypeValue.setContents(internalWorkTypeValueList); if (time == null) { isEdit = false; fromText.setText(""); //$NON-NLS-1$ toText.setText(""); //$NON-NLS-1$ fromText.getText().clear(); toText.getText().clear(); internalWorkTypeValue.setSelection(0); deleteButton.setText(TimeSheetMessages.getString("clear")); //$NON-NLS-1$ onCallCheckBox.setChecked(false); } else { isEdit = true; if (!time.getStartTime().equals(DateUtils.getInitialDateTime())) { fromText.setText(DateTimeUtil.showTimeGMT(time.getStartTime())); fromText.clearFocus(); } if (!time.getStopTime().equals(DateUtils.getInitialDateTime())) { toText.setText(DateTimeUtil.showTimeGMT(time.getStopTime())); toText.clearFocus(); } if (!time.getWorkTypeCode().isEmpty()) { internalWorkTypeValue.setSelectionById(time.getWorkTypeCode()); } onCallCheckBox.setChecked(time.isCallFlag()); deleteButton.setText(TimeSheetMessages.getString("delete")); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { // not edited if (time == null && StringUtil.isEmpty(fromText.getText().toString()) && StringUtil.isEmpty(toText.getText().toString())) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } if (time != null && fromText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStartTime())) && toText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStopTime())) && internalWorkTypeValue.getSelectedId().equalsIgnoreCase(time.getWorkTypeCode()) && onCallCheckBox.isChecked() == time.isCallFlag()) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } if(saveTime()) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } }, false); } return null; } private boolean saveTime(){ boolean result = true; if (fromText.getText().length() == 0) { showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } Date startTime = DateTimeUtil.parseDateFromHHmm(fromText.getText().toString(), mCalendar.getDate()); Date stopTime = DateTimeUtil.parseDateFromHHmm(toText.getText().toString(), mCalendar.getDate()); if(time == null && fromText.getText().toString().equalsIgnoreCase(toText.getText().toString())) { // time not captured and same minutes. showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if(startTime == null) { showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; return result; } if (startTime.after(new Date())) { app.showWarningMessageBox(TimeSheetMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if (time != null && time.getStopTime().equals(DateUtils.getInitialDateTime())) { // time capture started stopTime = DateUtils.getInitialDateTime(); } else { if (toText.getText().length() == 0) { showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if(stopTime == null) { showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; return result; } if (startTime.after(stopTime)) { showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if (stopTime.after(new Date())) { app.showWarningMessageBox(TimeSheetMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } } if(!result) { return false; } else { TimeSheet timeSheet = null; if (isEdit) { timeSheet = time; timeSheet.setStartTime(startTime); timeSheet.setStopTime(stopTime); timeSheet.setWorkTypeCode(internalWorkTypeValue.getSelectedId()); timeSheet.setCallFlag(onCallCheckBox.isChecked()); } else { timeSheet = new TimeSheet(app.dbutil.getUser().getPersonalNumber()); timeSheet.setIdx(999); timeSheet.setDate(new Date()); timeSheet.setStartTime(startTime); timeSheet.setStopTime(stopTime); timeSheet.setWorkTypeCode(internalWorkTypeValue.getSelectedId()); timeSheet.setCallFlag(onCallCheckBox.isChecked()); mCalendar.getTimeSheets().add(timeSheet); } log.info("save WorkTypeCode " + timeSheet.getWorkTypeCode()); saveTimeSheet(timeSheet); } return result; } private void showError(final MDEditText textView, final String text) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); textView.setError(text); } }; } /** * Handles on click event for send. * * @return */ @Override public ApplicationEvent onSendPressed() { setSendButtonEnabled(false); if (saveTime() && mCalendar.isValid()) { new AsyncTask(this) { private CalendarTimeSheet sendCalendar; private MDEditText errorText = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(mCalendar.isValid()) { // Reload calendar object from database sendCalendar = app.sendTimeSheet(mCalendar); } return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); if (errorText != null) { errorText.setError(TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ return; } setSendButtonEnabled(true); if (sendCalendar !=null && sendCalendar.getStatus().isSENT()) { app.showMessage(TimeSheetMessages.getString("timesheetSent")); //$NON-NLS-1$ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } }, false); } } }; } else { String errorMessage = TimeSheetMessages.getString("cannotTransmissonToServerThereIsUnsavedPersonalTimeData"); app.showWarningMessageBox(errorMessage, new RunOnUIThread() { @Override public void runOnUIThread() { setSendButtonEnabled(true); } }); } return null; } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (null == time) { // create new time } else { if ("ARBEITSART".equals(parent.getTag())) { //$NON-NLS-1$ if (position != 0) internalWorkTypeValue.clearError(); } } } @Override public void onNothingSelected(AdapterView parent) { // Auto-generated method stub } private void deleteTime() { if (time == null) { return; } new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteRecord"), TimeSheetMessages.getString("warning") //$NON-NLS-1$ //$NON-NLS-2$ , Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } // number the timesheet entries consecutively in chronological // order TreeSet timeSheets = new TreeSet(mCalendar.getTimeSheets()); Iterator itr = timeSheets.iterator(); int idx = 0; while (itr.hasNext()) { TimeSheet temp = itr.next(); if (temp.getPersonalNumber() == time.getPersonalNumber() && temp.getStartTime().compareTo(time.getStartTime()) == 0) { itr.remove(); } else { temp.setIdx(idx); idx++; } } // Save the list of timesheet entries to the current calendar mCalendar.setTimeSheets(timeSheets); // Save hole CALENDAR Object to the database app.dbutil.saveCALENDAR(mCalendar); return null; } @Override protected void runOnUIThread() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } }, false); } }; } /** * Saves all records in the table control to the ZKDMOBREP object and to the database. * ZKDMATIME.IDX attributes will be numbered consecutively according the VON attribute. * @param selectedRecord The currently selected record will be selected again (in the table control). * @return true if the time sheet was saved to the database without problem. false if the time sheet was not saved. */ private boolean saveTimeSheet(TimeSheet selectedRecord) { boolean success = true; TreeSet set = new TreeSet(); Iterator timeSetItr = mCalendar.getTimeSheets().iterator(); while (timeSetItr.hasNext()) { TimeSheet temp = (TimeSheet) timeSetItr.next(); if (!set.add(temp)) { String errorMessage = MessageFormat.format(TimeSheetMessages.getString("startTimeAlreadyExists"), new Object[] { //$NON-NLS-1$ DateTimeUtil.showDateTime(temp.getStartTime()) }); ch.mfiles.kaba.kolibri.common.forms.SuperForm.showWarningMessageBox(app, errorMessage); // reload CALENDAR from db mCalendar = app.dbutil.loadCalendar(mCalendar.getDate(), mCalendar.getPersonalNumber()); success = false; break; } } if (success) { // number the timesheet entries consecutively in chronological order Iterator itr = set.iterator(); int idx = 0; while (itr.hasNext()) { TimeSheet temp = (TimeSheet) itr.next(); temp.setIdx(idx); // Backup the new IDX of the currently edited record if (temp.getStartTime().compareTo(selectedRecord.getStartTime()) == 0) idx++; } // check if there are no overlapping entries int selOverlappingRowIdx = timeUtil.checkWorkTimesheetOverlapping(set); if (selOverlappingRowIdx > -1) { // reload CALENDAR from db mCalendar = app.dbutil.loadCalendar(mCalendar.getDate(), mCalendar.getPersonalNumber()); success = false; } else { // Save the list of timesheet entries to the current calendar mCalendar.setTimeSheets(set); // Save hole CALENDAR Object to the database app.dbutil.saveCALENDAR(mCalendar); success = true; } } return success; } public static class TimeSheetFormArgument { private CalendarTimeSheet calendar; private TimeSheet timeSheet; protected TimeSheetFormArgument() { } public TimeSheetFormArgument(CalendarTimeSheet calendar, TimeSheet timeSheet) { this.calendar = calendar; this.timeSheet = timeSheet; } public CalendarTimeSheet getCALENDAR() { return this.calendar; } public TimeSheet getTime() { return this.timeSheet; } } }
package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenseFile; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenses; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.ExpenseMaskWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class VariousExpensesImageNewEditForm extends SuperForm { private static Log log = LogFactory.getLog(VariousExpensesImageNewEditForm.class); // initialized by the kolibri framework... public static TimeSheetApplication app; private Bitmap bitmap; private VariousExpenses variousExpenses; private ImageView image; private MDSpinner variousExpenseSpinner; private MDEditText amountEditText; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil actionUtil; private Date selectedDate; @Override public void onFormCall(Object argument) { if (argument instanceof VariousExpenseFileNewEditFormArguments) { VariousExpenseFileNewEditFormArguments formArguments = (VariousExpenseFileNewEditFormArguments) argument; selectedDate = formArguments.getDate(); bitmap = formArguments.getBitmap(); variousExpenses = formArguments.getVariousExpense(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(TimeSheetMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; sendButton.setVisible(false); saveButton.setVisible(true); actionUtil = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMaxHeight(800); image.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { actionUtil.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, null); return false; } }); contentLinearLayout.addView(image); LinearLayout variousExpensespinnerLinearLayout = new LinearLayout(context); variousExpensespinnerLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); variousExpensespinnerLinearLayout.setOrientation(LinearLayout.VERTICAL); variousExpenseSpinner = MDSpinner.createDefaultSpinner(variousExpensespinnerLinearLayout, TimeSheetMessages.getString("miscExpense"), true); //$NON-NLS-1$ // variousExpenseSpinner.setEnabled(false); // variousExpenseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { // // @Override // public void onNothingSelected(AdapterView parent) { // // TODO Auto-generated method stub // // } // // @Override // public void onItemSelected(AdapterView parent, View view, int position, long id) { // amountEditText.setEnabled(false); // // Code 00 ("Please Select"): no selection was made so far -> disable // // text for "Diverse Spesen" and value field // if (variousExpenseSpinner.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ // amountEditText.setText(""); // } else if (variousExpenseSpinner.getSelectedId().equalsIgnoreCase("01")) { //$NON-NLS-1$ // // Code 01 ("Diverse.."): -> enable text for "Diverse Spesen" and value field // amountEditText.setEnabled(true); // } else { // // All other codes: -> disable text but enable value filed // amountEditText.setText(""); //$NON-NLS-1$ // } // // } // }); contentLinearLayout.addView(variousExpensespinnerLinearLayout); amountEditText = MDEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("amount"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ amountEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); amountEditText.addTextChangedListener(new ExpenseMaskWatcher(amountEditText)); messages = MDEditText.createDefaultEditText(contentLinearLayout, "description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); Button deleteButton = new Button(context); deleteButton.setText(TimeSheetMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(variousExpenses == null) { messages.getText().clear(); } else { actionDelete(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(contentLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(TimeSheetMessages.getString("image")); //$NON-NLS-1$ messages.getText().clear(); image.setImageBitmap(null); fillExpenseCombo(); amountEditText.setText(""); if (variousExpenses == null) { image.setImageBitmap(bitmap); } else { bitmap = variousExpenses.getVariousExpensesFile().getSignPicBitmap(); image.setImageBitmap(bitmap); // // If SPNSTXT is empty: No 'Diverese Spesen' exist // if (variousExpenses.getAmount().equalsIgnoreCase("")) { //$NON-NLS-1$ // variousExpenseSpinner.setSelection(0); // amountEditText.setText(""); //$NON-NLS-1$ // amountEditText.setText(""); //$NON-NLS-1$ // } // // If SPNSTXT is part of the combobox stings: A value of the // // combobox was selected a no free text was used // else if (app.enumUtil.variousExpensEnum.containsValue(variousExpenses.getExpensesCode())) { // variousExpenseSpinner.setSelectionById(variousExpenses.getExpensesCode()); //// amountEditText.setText(variousExpenses.getAnount()); //// amountEditText.setText(""); //$NON-NLS-1$ // } // // If SPNSTXT is not part of the combobox stings: A free text was // // entered and the combobox contains the entry "01 Diverses.." // else { // variousExpenseSpinner.setSelectionById("01"); //$NON-NLS-1$ // amountEditText.setText(variousExpenses.getAmount()); // } if(!variousExpenses.getVariousExpensesFile().getDescription().isEmpty()) { amountEditText.setText(variousExpenses.getAmount()); messages.setText(variousExpenses.getVariousExpensesFile().getDescription()); variousExpenseSpinner.setSelectionById(variousExpenses.getExpensesCode()); } } return null; } private void fillExpenseCombo() { List miscExpenseValueList = new ArrayList(); Iterator itr = app.enumUtil.variousExpensEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); miscExpenseValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } variousExpenseSpinner.setContents(miscExpenseValueList); } @Override protected ApplicationEvent onSavePressed() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (variousExpenses == null) { int personalNumber = app.dbutil.getUser().getPersonalNumber(); Date date = new Date(); String VariousExpensesFileId = DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"; variousExpenses = new VariousExpenses(selectedDate, personalNumber, VariousExpensesFileId); variousExpenses.setExpensesCode(getVariousExpenseText()); variousExpenses.setAmount(StringUtil.removeLettersAndCountDot(amountEditText.getText().toString(), '.')); variousExpenses.setVariousExpensesId(VariousExpensesFileId); VariousExpenseFile variousExpensesFile = new VariousExpenseFile(); variousExpensesFile.setDate(selectedDate); variousExpensesFile.setPersonalNumber(personalNumber); variousExpensesFile.setVariousExpensesFileId(VariousExpensesFileId); variousExpensesFile.setDescription(messages.getText().toString()); variousExpensesFile.setSignPicBitmap(bitmap); variousExpensesFile.setFormType(new FormType(FormType.JPG)); app.dbutil.insertVariousExpenses(variousExpenses); app.dbutil.insertVariousExpenseFile(variousExpensesFile); } else { variousExpenses.setExpensesCode(getVariousExpenseText()); variousExpenses.setAmount(StringUtil.removeLettersAndCountDot(amountEditText.getText().toString(), '.')); variousExpenses.getVariousExpensesFile().setFormType(new FormType(FormType.JPG)); variousExpenses.getVariousExpensesFile().setDescription(messages.getText().toString()); variousExpenses.getVariousExpensesFile().setSignPicBitmap(bitmap); app.dbutil.updateVariousExpenses(variousExpenses); app.dbutil.updateVariousExpenseFile(variousExpenses.getVariousExpensesFile()); } return onBackPressed(); } }; return null; } private String getVariousExpenseText() { String spnstxt = ""; //$NON-NLS-1$ // Default string 00 "Bitte wählen.." must not be stored if (!variousExpenseSpinner.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ // Only entry 01 "Diverses.." allows to enter an additional // text, otherwise the Combobox string is stored if (variousExpenseSpinner.getSelectedId().equalsIgnoreCase("01")) //$NON-NLS-1$ spnstxt = amountEditText.getText().toString(); else spnstxt = variousExpenseSpinner.getSelectedId(); } return spnstxt; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(selectedDate, 2, isServiceApp)); } private void actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteRecord"), Messages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { app.dbutil.deleteVariousExpense(variousExpenses); } finally { db.commit(); } return onBackPressed(); } }; } public static class VariousExpenseFileNewEditFormArguments { private Date date; private Bitmap bitmap; private VariousExpenses variousExpenses; public VariousExpenseFileNewEditFormArguments(Date date ,Bitmap bitmap, VariousExpenses variousExpenses) { this.date = date; this.bitmap = bitmap; this.variousExpenses = variousExpenses; } public Date getDate() { return date; } public Bitmap getBitmap() { return bitmap; } public VariousExpenses getVariousExpense() { return variousExpenses; } } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** *

A suite of utilities surrounding the use of the * {@link java.util.Calendar} and {@link java.util.Date} object.

* *

TimesheetDateUtils contains a lot of common methods considering manipulations * of Dates or Calendars. Some methods require some extra explanation. * The truncate and round methods could be considered the Math.floor(), * Math.ceil() or Math.round versions for dates * This way date-fields will be ignored in bottom-up order. * As a complement to these methods we've introduced some fragment-methods. * With these methods the Date-fields will be ignored in top-down order. * Since a date without a year is not a valid date, you have to decide in what * kind of date-field you want your result, for instance milliseconds or days. *

* * * * @author Serge Knystautas * @author Stephen Colebourne * @author Janek Bogucki * @author Gary Gregory * @author Phil Steitz * @author Robert Scholte * @since 2.0 * @version $Id: TimesheetDateUtils.java,v 1.2 2011/05/07 08:16:58 bpauli Exp $ */ public class TimesheetDateUtils { /** * The UTC time zone (often referred to as GMT). */ // public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT"); /** * Number of milliseconds in a standard second. * @since 2.1 */ public static final long MILLIS_PER_SECOND = 1000; /** * Number of milliseconds in a standard minute. * @since 2.1 */ public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; /** * Number of milliseconds in a standard hour. * @since 2.1 */ public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; /** * Number of milliseconds in a standard day. * @since 2.1 */ public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; /** * This is half a month, so this represents whether a date is in the top * or bottom half of the month. */ public final static int SEMI_MONTH = 1001; private static final int[][] fields = { {Calendar.MILLISECOND}, {Calendar.SECOND}, {Calendar.MINUTE}, {Calendar.HOUR_OF_DAY, Calendar.HOUR}, {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */ }, {Calendar.MONTH, TimesheetDateUtils.SEMI_MONTH}, {Calendar.YEAR}, {Calendar.ERA}}; /** * A week range, starting on Sunday. */ public final static int RANGE_WEEK_SUNDAY = 1; /** * A week range, starting on Monday. */ public final static int RANGE_WEEK_MONDAY = 2; /** * A week range, starting on the day focused. */ public final static int RANGE_WEEK_RELATIVE = 3; /** * A week range, centered around the day focused. */ public final static int RANGE_WEEK_CENTER = 4; /** * A month range, the week starting on Sunday. */ public final static int RANGE_MONTH_SUNDAY = 5; /** * A month range, the week starting on Monday. */ public final static int RANGE_MONTH_MONDAY = 6; //----------------------------------------------------------------------- /** *

This constructs an Iterator over each day in a date * range defined by a focus date and range style.

* *

For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

* *

This method provides an iterator that returns Calendar objects. * The days are progressed using {@link Calendar#add(int, int)}.

* * @param focus the date to work with, not null * @param rangeStyle the style constant to use. Must be one of * {@link TimesheetDateUtils#RANGE_MONTH_SUNDAY}, * {@link TimesheetDateUtils#RANGE_MONTH_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_SUNDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_RELATIVE}, * {@link TimesheetDateUtils#RANGE_WEEK_CENTER} * @return the date iterator, which always returns Calendar instances * @throws IllegalArgumentException if the date is null * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(Date focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } Calendar gval = Calendar.getInstance(); gval.setTime(focus); return iterator(gval, rangeStyle); } /** *

This constructs an Iterator over each day in a date * range defined by a focus date and range style.

* *

For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

* *

This method provides an iterator that returns Calendar objects. * The days are progressed using {@link Calendar#add(int, int)}.

* * @param focus the date to work with * @param rangeStyle the style constant to use. Must be one of * {@link TimesheetDateUtils#RANGE_MONTH_SUNDAY}, * {@link TimesheetDateUtils#RANGE_MONTH_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_SUNDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_RELATIVE}, * {@link TimesheetDateUtils#RANGE_WEEK_CENTER} * @return the date iterator * @throws IllegalArgumentException if the date is null * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(Calendar focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } Calendar start = null; Calendar end = null; int startCutoff = Calendar.SUNDAY; int endCutoff = Calendar.SATURDAY; switch (rangeStyle) { case RANGE_MONTH_SUNDAY: case RANGE_MONTH_MONDAY: //Set start to the first of the month start = truncate(focus, Calendar.MONTH); //Set end to the last of the month end = (Calendar) start.clone(); end.add(Calendar.MONTH, 1); end.add(Calendar.DATE, -1); //Loop start back to the previous sunday or monday if (rangeStyle == RANGE_MONTH_MONDAY) { startCutoff = Calendar.MONDAY; endCutoff = Calendar.SUNDAY; } break; case RANGE_WEEK_SUNDAY: case RANGE_WEEK_MONDAY: case RANGE_WEEK_RELATIVE: case RANGE_WEEK_CENTER: //Set start and end to the current date start = truncate(focus, Calendar.DATE); end = truncate(focus, Calendar.DATE); switch (rangeStyle) { case RANGE_WEEK_SUNDAY: //already set by default break; case RANGE_WEEK_MONDAY: startCutoff = Calendar.MONDAY; endCutoff = Calendar.SUNDAY; break; case RANGE_WEEK_RELATIVE: startCutoff = focus.get(Calendar.DAY_OF_WEEK); endCutoff = startCutoff - 1; break; case RANGE_WEEK_CENTER: startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3; endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3; break; } break; default: throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid."); //$NON-NLS-1$ //$NON-NLS-2$ } if (startCutoff < Calendar.SUNDAY) { startCutoff += 7; } if (startCutoff > Calendar.SATURDAY) { startCutoff -= 7; } if (endCutoff < Calendar.SUNDAY) { endCutoff += 7; } if (endCutoff > Calendar.SATURDAY) { endCutoff -= 7; } while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) { start.add(Calendar.DATE, -1); } while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) { end.add(Calendar.DATE, 1); } return new DateIterator(start, end); } /** *

This constructs an Iterator over each day in a date * range defined by a focus date and range style.

* *

For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

* * @param focus the date to work with, either * Date or Calendar * @param rangeStyle the style constant to use. Must be one of the range * styles listed for the {@link #iterator(Calendar, int)} method. * @return the date iterator * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is * not a Date or Calendar */ public static Iterator iterator(Object focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } if (focus instanceof Date) { return iterator((Date) focus, rangeStyle); } else if (focus instanceof Calendar) { return iterator((Calendar) focus, rangeStyle); } else { throw new ClassCastException("Could not iterate based on " + focus); //$NON-NLS-1$ } } /** *

Truncate this date, leaving the field specified as the most * significant field.

* *

For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

* * @param date the date to work with, either Date * or Calendar * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is not a * Date or Calendar * @throws ArithmeticException if the year is over 280 million */ public static Date truncate(Object date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } if (date instanceof Date) { return truncate((Date) date, field); } else if (date instanceof Calendar) { return truncate((Calendar) date, field).getTime(); } else { throw new ClassCastException("Could not truncate " + date); //$NON-NLS-1$ } } /** *

Truncate this date, leaving the field specified as the most * significant field.

* *

For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

* * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million */ public static Calendar truncate(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } Calendar truncated = (Calendar) date.clone(); modify(truncated, field, false); return truncated; } //----------------------------------------------------------------------- /** *

Internal calculation method.

* * @param val the calendar * @param field the field constant * @param round true to round, false to truncate * @throws ArithmeticException if the year is over 280 million */ private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); //$NON-NLS-1$ } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == TimesheetDateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case TimesheetDateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); //$NON-NLS-1$ //$NON-NLS-2$ } /** *

Date iterator.

*/ static class DateIterator implements Iterator { private final Calendar endFinal; private final Calendar spot; /** * Constructs a DateIterator that ranges from one date to another. * * @param startFinal start date (inclusive) * @param endFinal end date (not inclusive) */ DateIterator(Calendar startFinal, Calendar endFinal) { super(); this.endFinal = endFinal; spot = startFinal; spot.add(Calendar.DATE, -1); } /** * Has the iterator not reached the end date yet? * * @return true if the iterator has yet to reach the end date */ public boolean hasNext() { return spot.before(endFinal); } /** * Return the next calendar in the iteration * * @return Object calendar for the next date */ public Object next() { if (spot.equals(endFinal)) { throw new RuntimeException(); } spot.add(Calendar.DATE, 1); return spot.clone(); } /** * Always throws UnsupportedOperationException. * * @throws UnsupportedOperationException * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } }
package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.Calendar; import java.util.Date; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import junit.framework.TestCase; public class TimeSheetValidatorTest extends TestCase { private int personalNumber = 99998; private Date today = DateTimeUtil.getToday().getTime(); public TimeSheetValidatorTest(String name) { super(name); } /** * @see "MIG-453 New validation for timesheet" */ @Test public void testValidateSaveTimeSheet() { CalendarTimeSheet calendarTimeSheet = getNewCalendarTimeSheetWithExpenseAndTimesheet(); calendarTimeSheet.getExpense().setNoExpenses(false); calendarTimeSheet.getExpense().setDailyExpenses("56"); calendarTimeSheet.getExpense().setOperatingHoursTotal("191"); calendarTimeSheet.getExpense().setOperatingHoursOf("90"); calendarTimeSheet.getExpense().setOperatingHoursUpTo("101"); assertTrue(calendarTimeSheet.getExpense().validate().isValid()); assertTrue(calendarTimeSheet.isValid()); } @Test public void testValidateTimeSheetWithNoExpenses() { CalendarTimeSheet calendarTimeSheet = getNewCalendarTimeSheetWithExpenseAndTimesheet(); calendarTimeSheet.getExpense().setNoExpenses(true); calendarTimeSheet.getExpense().setOperatingHoursOf("56"); calendarTimeSheet.getExpense().setOperatingHoursUpTo("66"); assertTrue(calendarTimeSheet.isValid()); } private CalendarTimeSheet getNewCalendarTimeSheet() { CalendarTimeSheet calendarTimeSheet = new CalendarTimeSheet(today, personalNumber); assertFalse(calendarTimeSheet.isValid()); return calendarTimeSheet; } private Expenses getNewExpenses(CalendarTimeSheet calendarTimeSheet) { Expenses expenses = new Expenses(calendarTimeSheet.getDate(), calendarTimeSheet.getPersonalNumber()); return expenses; } private TimeSheet getNewTimeSheet(CalendarTimeSheet calendarTimeSheet) { TimeSheet timeSheet = new TimeSheet(calendarTimeSheet.getPersonalNumber()); timeSheet.setDate(calendarTimeSheet.getDate()); timeSheet.setIdx(calendarTimeSheet.getTimeSheets().size() + 1); timeSheet.setWorkTypeCode("01"); return timeSheet; } private CalendarTimeSheet getNewCalendarTimeSheetWithExpenseAndTimesheet() { CalendarTimeSheet calendarTimeSheet = getNewCalendarTimeSheet(); Expenses expenses = getNewExpenses(calendarTimeSheet); assertFalse(calendarTimeSheet.isValid()); calendarTimeSheet.setExpense(expenses); assertFalse(calendarTimeSheet.isValid()); TimeSheet timeSheet = getNewTimeSheet(calendarTimeSheet); timeSheet.setStopTime(DateTimeUtil.getNow().getTime()); Calendar start = DateTimeUtil.getDate(timeSheet.getStopTime()); start.add(Calendar.HOUR, -3); timeSheet.setStartTime(start.getTime()); assertTrue(timeSheet.validate().isValid()); calendarTimeSheet.getTimeSheets().add(timeSheet); return calendarTimeSheet; } } /bin/ /gen/ /build/ gilgenTimeSheet ch.mfiles.kolibri.plugin.androidResourceBuilder org.eclipse.jdt.core.javabuilder ch.mfiles.kolibri.plugin.kolibriNature org.eclipse.jdt.core.javanature plugins { id("ch.mfiles.kolibri-application") } sourceSets { test { java { srcDir("test") } } } repositories { mavenCentral() } val junitConfiguration: Configuration by configurations.creating dependencies { implementation(project(":common")) junitConfiguration("junit:junit:4.12") junitConfiguration("commons-logging:commons-logging:1.2") testImplementation(junitConfiguration) } tasks.named("compileTestJava", JavaCompile::class).configure { classpath = junitConfiguration + classpath } tasks.named("test", Test::class).configure { classpath = junitConfiguration + classpath } # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23 /.idea/ /.gradle/ build/ /buildSrc/.gradle/ default: image: docker.mfiles.ch/repository/public/android-build-23:1.1 # Disable the Gradle daemon for Continuous Integration servers as correctness # is usually a priority over speed in CI environments. Using a fresh # runtime for each build is more reliable since the runtime is completely # isolated from any previous builds. variables: GRADLE_OPTS: "-Dorg.gradle.daemon=false" ORG_GRADLE_PROJECT_signatureKeyPwd: $MFILES_CODE_SIGNING_PWD ORG_GRADLE_PROJECT_publicationJobToken: $CI_JOB_TOKEN before_script: - export GRADLE_USER_HOME=`pwd`/cache # Cache basic gradle data: gradle wrapper download, notification states and # dependency downloads. Create a new cache if the gradle version is changed. cache: &gradle_cache key: files: - gradle/wrapper/gradle-wrapper.properties paths: - cache/caches - cache/notifications - cache/wrapper policy: pull stages: - build - publish # Job to run build and checks not including check for snapshot version number build: stage: build rules: - if: '$CI_COMMIT_TITLE !~ /^new snapshot release/' cache: <<: *gradle_cache policy: pull-push script: - ./gradlew build # Job to run build and checks including check for snapshot version number build-withVersion: stage: build rules: - if: '$CI_COMMIT_TITLE =~ /^new snapshot release/' cache: <<: *gradle_cache policy: pull-push script: - VERSION=`echo $CI_COMMIT_TITLE | sed 's/new snapshot release //'` - echo Kolibri app version extracted from commit message - $VERSION - ./gradlew -PkolibriAppVersion=$VERSION build # Job to publish the build result using gradlew publish if the commit # message title starts with 'new snapshot release'. The app version # is extracted from the remaining title and validated by the Kolibri # app plugin's task checkKolibriAppVersion. publish: stage: publish rules: - if: '$CI_COMMIT_TITLE =~ /^new snapshot release/' script: - VERSION=`echo $CI_COMMIT_TITLE | sed 's/new snapshot release //'` - echo Kolibri app version extracted from commit message - $VERSION - ./gradlew -PkolibriAppVersion=$VERSION publish #!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MSYS* | MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega rootProject.name = "gilgen2020" include("common", "login", "material", "service", "timeSheet", "apk-customizer") package ch.mfiles.kaba.kolibri.common.businessobjects.types; import org.junit.Test; import junit.framework.TestCase; public class JobStatusTest extends TestCase { @Test public void testReportTimeStartedUsesLocalInProgressAndBackend5a() { JobStatus localStatus = new JobStatus("05"); //$NON-NLS-1$ assertTrue(localStatus.isInProgress()); assertEquals("05", JobStatus.IN_PROGRESS); //$NON-NLS-1$ assertEquals("5a", JobStatus.SAP_InProgress); //$NON-NLS-1$ } } package ch.mfiles.kaba.kolibri.common.forms.adapters; import junit.framework.TestCase; public class SpinnerTextStyleTest extends TestCase { public void testNoneDoesNotApplyCustomClosedViewStyle() { assertFalse(SpinnerTextStyle.none().isCustom()); } public void testCustomStyleKeepsValuesForClosedSpinnerView() { SpinnerTextStyle style = SpinnerTextStyle.custom(7, null, 2, 20); assertTrue(style.isCustom()); assertEquals(7, style.getTextColor()); assertNull(style.getTypeface()); assertEquals(2, style.getTextSizeUnit()); assertEquals(20, style.getTextSize()); } } package ch.mfiles.kaba.kolibri.common.util; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import junit.framework.TestCase; public class ReportMaterialInsertPolicyTest extends TestCase { public ReportMaterialInsertPolicyTest(String name) { super(name); } @Test public void testNextIdxDoesNotReuseExistingIdxZero() { ReportMaterial maxReportMaterial = new ReportMaterial(); maxReportMaterial.setIdx(0); assertEquals(1, DatabaseUtil.getNextReportMaterialIdx(0, maxReportMaterial)); } @Test public void testNextIdxKeepsNewIdxWhenNoMaterialExists() { assertEquals(0, DatabaseUtil.getNextReportMaterialIdx(0, null)); } @Test public void testNextIdxKeepsRequestedIdxAboveCurrentMax() { ReportMaterial maxReportMaterial = new ReportMaterial(); maxReportMaterial.setIdx(1); assertEquals(3, DatabaseUtil.getNextReportMaterialIdx(3, maxReportMaterial)); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /** * In the Database -> ZKDMOB * */ public class Job { public static final Log log = LogFactory.getLog(Job.class); private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private int personalNumber = 0; private JobStatus status = new JobStatus(); private String priority = ""; //$NON-NLS-1$ private int jobForward = 0; private String commissionNumber = ""; //$NON-NLS-1$ private String staffName = ""; //$NON-NLS-1$ private String staffPhoneNumber = ""; //$NON-NLS-1$ private String mUPNUM = ""; //$NON-NLS-1$ private Date appointmentDate = new Date(); private int week = 0; private String fix = ""; //$NON-NLS-1$ private String appointment = ""; //$NON-NLS-1$ private String orderNumber = ""; //$NON-NLS-1$ private String partnerOfInstallAddressId = ""; //$NON-NLS-1$ private String kdnServiceAddressId = ""; //$NON-NLS-1$ private String customerAddressId = ""; //$NON-NLS-1$ private String partnerAddressId = ""; //$NON-NLS-1$ private String objectAddressId = ""; //$NON-NLS-1$ private String ownerAddressId = ""; //$NON-NLS-1$ private Date newJobDate = new Date(); private Date activeJobDate = new Date(); private Date jobRescheduleDate = new Date(); private Date jobRescheduleTime = new Date(); private String errorId = ""; //$NON-NLS-1$ private String callServiceFlag = ""; //$NON-NLS-1$ private String maintenanceContractType = ""; //$NON-NLS-1$ private String servicePlanMonth1 = ""; //$NON-NLS-1$ private String servicePlanMonth2 = ""; //$NON-NLS-1$ private String servicePlanMonth3 = ""; //$NON-NLS-1$ private String servicePlanMonth4 = ""; //$NON-NLS-1$ private String servicePlanMonth5 = ""; //$NON-NLS-1$ private String servicePlanMonth6 = ""; //$NON-NLS-1$ private String serviceOpen = ""; //$NON-NLS-1$ // private String contactName = ""; //$NON-NLS-1$ private String contactPhoneNumber = ""; //$NON-NLS-1$ private String technicalName = ""; //$NON-NLS-1$ private String technicalPhoneNumber = ""; //$NON-NLS-1$ private String sellerName = ""; //$NON-NLS-1$ private String sellerPhoneNumber = ""; //$NON-NLS-1$ private String driveType = ""; //$NON-NLS-1$ private String driveTypeUpdated = ""; //$NON-NLS-1$ // private String defaultTime = ""; //$NON-NLS-1$ // private String information = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ private String dirtyFlag = ""; //$NON-NLS-1$ private String communicationStatus = ""; //$NON-NLS-1$ private String communicationStatusNew = ""; //$NON-NLS-1$ private String currentReportGuId = ""; //$NON-NLS-1$ private String cycleOfInstallationFlag = ""; //$NON-NLS-1$ private String formDesc1 = ""; //$NON-NLS-1$ private String formDesc2 = ""; //$NON-NLS-1$ private String formDesc3 = ""; //$NON-NLS-1$ private Date statusEdit = new Date(); private Map addresses = new HashMap(); private List reports = new ArrayList(); private int mCurrentReport = 0; private String serviceRefusedFlag = ""; private String link = ""; private String guarantee = ""; private String moreInformationsFlag = ""; public Job() { } public Job(RecordSet rs) { this.setDriveType(rs.getString(DbConstants.Job.DRIVER_TYPE)); // note: order matters this.setDriveTypeUpdated(rs.getBoolean(DbConstants.Job.DRIVER_TYPE_UPD)); // note: order matters this.setJobType(rs.getString(DbConstants.Job.JOB_TYPE)); this.setCurrentReportGuId(rs.getString(DbConstants.Job.CURRENT_REPORT_GUID)); this.setStaffName(rs.getString(DbConstants.Job.STAFF_NAME)); this.setStaffPhoneNumber(rs.getString(DbConstants.Job.STAFF_PHONE)); this.setAppointmentDate(rs.getDate(DbConstants.Job.APPOINTMENT_DATE)); this.setActiveJobDate(rs.getDate(DbConstants.Job.ACTIVE_DATE)); this.setJobRescheduleDate(rs.getDate(DbConstants.Job.JOB_RESCHEDULE_DATE)); this.setJobRescheduleTime(rs.getDate(DbConstants.Job.JOB_RESCHEDULE_TIME)); this.setNewJobDate(rs.getDate(DbConstants.Job.NEW_JOB_DATE)); this.setErrorId(rs.getString(DbConstants.Job.ERROR_ID)); this.setFix(rs.getString(DbConstants.Job.FIX)); this.setInformation(rs.getString(DbConstants.Job.INFORMATION)); this.setWeek(rs.getInt(DbConstants.Job.WEEK)); this.setDescription(rs.getString(DbConstants.Job.DESCRIPTION)); this.setJobNumber(rs.getString(DbConstants.Job.JOB_NUMBER)); this.setPersonalNumber(rs.getInt(DbConstants.Job.PERSONAL_NUMBER)); this.setPartnerOfInstallAddressId(rs.getString(DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID)); this.setKdnServiceAddressId(rs.getString(DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID)); this.setCustomerAddressId(rs.getString(DbConstants.Job.CUSTOMER_ADDRESS_ID)); this.setPartnerAddressId(rs.getString(DbConstants.Job.PARTNER_ADDRESS_ID)); this.setObjectAddressId(rs.getString(DbConstants.Job.OBJECT_ADDRESS_ID)); this.setOwnerAddressId(rs.getString(DbConstants.Job.OWNER_ADDRESS_ID)); this.setOrderNumber(rs.getString(DbConstants.Job.ORDER_NUMBER)); this.setJobForward(rs.getInt(DbConstants.Job.JOB_FORWARD)); this.setCallServiceFlag(rs.getString(DbConstants.Job.CALL_SERVICE_FLAG)); this.setPriority(rs.getString(DbConstants.Job.PRIORITY)); this.setMaintenanceContractType(rs.getString(DbConstants.Job.MAINTENANCE_CONTRACT_TYPE)); this.setServicePlanMonth1(rs.getString(DbConstants.Job.SERVICE_PLAN_MONTH_1)); this.setServicePlanMonth2(rs.getString(DbConstants.Job.SERVICE_PLAN_MONTH_2)); this.setServicePlanMonth3(rs.getString(DbConstants.Job.SERVICE_PLAN_MONTH_3)); this.setServicePlanMonth4(rs.getString(DbConstants.Job.SERVICE_PLAN_MONTH_4)); this.setServicePlanMonth5(rs.getString(DbConstants.Job.SERVICE_PLAN_MONTH_5)); this.setServicePlanMonth6(rs.getString(DbConstants.Job.SERVICE_PLAN_MONTH_6)); this.setServiceOpen(rs.getString(DbConstants.Job.SERVICE_OPEN)); this.setStatus(new JobStatus(rs.getString(DbConstants.Job.STATUS))); this.setAppointment(rs.getString(DbConstants.Job.APPOINTMENT)); this.setContactName(rs.getString(DbConstants.Job.CONTACT_NAME)); this.setContactPhoneNumber(rs.getString(DbConstants.Job.CONTACT_PHONE)); this.setCommissionNumber(rs.getString(DbConstants.Job.COMMISSION_NUMBER)); this.setDefaultTime(rs.getString(DbConstants.Job.DEFAULT_TIME)); this.setTechnicalName(rs.getString(DbConstants.Job.TECHNICAL_NAME)); this.setTechnicalPhoneNumber(rs.getString(DbConstants.Job.TECHNICAL_PHONE)); this.setSellerName(rs.getString(DbConstants.Job.SELLER_NAME)); this.setSellerPhoneNumber(rs.getString(DbConstants.Job.SELLER_PHONE)); this.setStatusEdit(rs.getDate(DbConstants.Job.STATUS_EDIT)); this.setCycleOfInstallationFlag(rs.getString(DbConstants.Job.CYCLE_OF_INSTALLATIN_FLAG)); this.setFormDesc1(rs.getString(DbConstants.Job.FORM_DESC_1)); this.setFormDesc2(rs.getString(DbConstants.Job.FORM_DESC_2)); this.setFormDesc3(rs.getString(DbConstants.Job.FORM_DESC_3)); this.setServiceRefusedFlag(rs.getString(DbConstants.Job.SERVICE_REFUSED_FLAG)); this.setLink(rs.getString(DbConstants.Job.LINK)); this.setGuarantee(rs.getString(DbConstants.Job.GUARANTEE)); this.setMoreInformationsFlag(rs.getString(DbConstants.Job.MORE_INFORMARION_FLAG)); } public String getDriveType() { return this.driveType; } /** * Sets the drive type and drive type updated if the drive type did change. * @param antrtxt */ public void setDriveType(String antrtxt) { antrtxt = antrtxt == null ? "" : antrtxt; if (this.driveType.equals(antrtxt)) return; setDriveTypeUpdated(true); this.driveType = antrtxt; } public boolean isDriveTypeUpdated() { return "X".equals(this.driveTypeUpdated); } private void setDriveTypeUpdated(boolean driveTypeUpdated) { this.driveTypeUpdated = driveTypeUpdated ? "X" : ""; } public JobType getJobType() { return this.jobType; } public void setJobType(JobType auart) { this.jobType = auart; } public void setJobType(String auart) { this.jobType = new JobType(auart); } public String getCommunicationStatus() { return this.communicationStatus; } public void setCommunicationStatus(String comstat) { this.communicationStatus = comstat; } public String getCommunicationStatusNew() { return this.communicationStatusNew; } public void setCommunicationStatusNew(String comstatn) { this.communicationStatusNew = comstatn; } public String getDirtyFlag() { return this.dirtyFlag; } public void setDirtyFlag(String dyrtyflg) { this.dirtyFlag = dyrtyflg; } public String getStaffName() { return this.staffName; } public void setStaffName(String ernam) { this.staffName = ernam; } public String getErrorId() { return this.errorId; } public void setErrorId(String fc) { this.errorId = fc; } public String getFix() { return this.fix; } public void setFix(String fix) { this.fix = fix; } public boolean isFixed() { return "X".equalsIgnoreCase(this.getFix()); //$NON-NLS-1$ } public void setFixed(boolean fixed) { if (fixed) { this.setFix("X"); //$NON-NLS-1$ } else { this.setFix(""); //$NON-NLS-1$ } } public int getWeek() { return this.week; } public void setWeek(int kw) { this.week = kw; } public String getDescription() { return this.description; } public void setDescription(String ltxt) { this.description = ltxt; } public String getJobNumber() { return this.jobNumber; } public void setJobNumber(String mldnr) { this.jobNumber = mldnr; } /* * OBJNR */ public String getObjectAddressId() { return this.objectAddressId; } /* * OBJNR */ private void setObjectAddressId(String objectAddressId) { this.objectAddressId = objectAddressId; } /* * OBJNR */ public void setIdObjectAddress(Address objectAddress) { this.objectAddressId = objectAddress.getPartnerNummer(); this.addresses.put(objectAddress.getPartnerNummer(), objectAddress); } /* * PARANMNR */ public void setIdByPartnerAddress(Address partnerAddress) { this.partnerAddressId = partnerAddress.getPartnerNummer(); this.addresses.put(partnerAddress.getPartnerNummer(), partnerAddress); } /* * PARAPNR */ public String getPartnerOfInstallAddressId() { return this.partnerOfInstallAddressId; } /* * PARAPNR */ private void setPartnerOfInstallAddressId(String partner) { this.partnerOfInstallAddressId = partner; } /* * PARZANR */ public String getOwnerAddressId() { return this.ownerAddressId; } /* * PARZANR */ private void setOwnerAddressId(String ownerAddress) { this.ownerAddressId = ownerAddress; } // public void setIdByOwnerPARZANRAddress(ZKDMOBADR_Address parzanr) { // this.ownerPARZANRAddressId = parzanr.getPartnerNummer(); // this.addresses.put(parzanr.getPartnerNummer(), parzanr); // } /* * PARZRNR */ public String getKdnServiceAddressId() { return this.kdnServiceAddressId; } /* * PARZRNRA */ private void setKdnServiceAddressId(String kdnServiceAddress) { this.kdnServiceAddressId = kdnServiceAddress; } // public void setIdByKdnServicePARZRNRAddress(ZKDMOBADR_Address parzrnr) { // this.kdnServicePARZRNRAddressId = parzrnr.getPartnerNummer(); // this.addresses.put(parzrnr.getPartnerNummer(), parzrnr); // } // /* // * PARZSNR // */ // public String getCustomerAddressId() { // return this.customerAddressId; // } /* * PARZSNR */ private void setCustomerAddressId(String customerAddress) { this.customerAddressId = customerAddress; } /* * PARZSNR */ public void setIdByCustomerAddress(Address customerAddress) { this.customerAddressId = customerAddress.getPartnerNummer(); this.addresses.put(customerAddress.getPartnerNummer(), customerAddress); } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public int getJobForward() { return this.jobForward; } public void setJobForward(int persno2) { this.jobForward = persno2; } public String getCallServiceFlag() { return this.callServiceFlag; } public void setCallServiceFlag(String pikett) { this.callServiceFlag = pikett; } public void setCallServiceFlag(boolean pikett) { if (pikett) { this.setCallServiceFlag("X"); //$NON-NLS-1$ } else { this.setCallServiceFlag(""); //$NON-NLS-1$ } } public boolean isCallServiceFlag() { return "X".equalsIgnoreCase(this.getCallServiceFlag()); //$NON-NLS-1$ } public String getPriority() { return this.priority; } public void setPriority(String prio) { this.priority = prio; } public String getMaintenanceContractType() { return this.maintenanceContractType; } public void setMaintenanceContractType(String savc) { this.maintenanceContractType = savc; } public String getServicePlanMonth1() { return this.servicePlanMonth1; } public void setServicePlanMonth1(String savlfd1) { this.servicePlanMonth1 = savlfd1; } public String getServicePlanMonth2() { return this.servicePlanMonth2; } public void setServicePlanMonth2(String savlfd2) { this.servicePlanMonth2 = savlfd2; } public String getServicePlanMonth3() { return this.servicePlanMonth3; } public void setServicePlanMonth3(String savlfd3) { this.servicePlanMonth3 = savlfd3; } public String getServicePlanMonth4() { return this.servicePlanMonth4; } public void setServicePlanMonth4(String savlfd4) { this.servicePlanMonth4 = savlfd4; } public String getServicePlanMonth5() { return this.servicePlanMonth5; } public void setServicePlanMonth5(String savlfd5) { this.servicePlanMonth5 = savlfd5; } public String getServicePlanMonth6() { return this.servicePlanMonth6; } public void setServicePlanMonth6(String savlfd6) { this.servicePlanMonth6 = savlfd6; } public String getServiceOpen() { return this.serviceOpen; } public void setServiceOpen(String savoff) { this.serviceOpen = savoff; } public JobStatus getStatus() { return this.status; } public void setStatus(JobStatus status) { this.status = status; } public void setStatus(String status) { this.status.set(status); } public String getAppointment() { return this.appointment; } public boolean isAppointment() { return "X".equalsIgnoreCase(this.getAppointment()); //$NON-NLS-1$ } public void setAppointment(boolean isTVRB) { if (isTVRB) { this.setAppointment("X"); //$NON-NLS-1$ } else { this.setAppointment(""); //$NON-NLS-1$ } } public void setAppointment(String tvrb) { this.appointment = tvrb; } public String getUPNUM() { return this.mUPNUM; } public void setUPNUM(String upnum) { this.mUPNUM = upnum; } public String getCommissionNumber() { return this.commissionNumber; } public String getCommissionNumberNoLeadingZero() { String vbeln = this.commissionNumber; while (vbeln.length() > 0 && vbeln.charAt(0) == '0') { vbeln = vbeln.substring(1); } return vbeln; } public void setCommissionNumber(String vbeln) { this.commissionNumber = vbeln; } public String getDefaultTime() { return this.defaultTime; } public void setDefaultTime(String zkdindzeit) { this.defaultTime = zkdindzeit; } public String getTechnicalName() { return this.technicalName; } public void setTechnicalName(String zmnam) { this.technicalName = zmnam; } public String getTechnicalPhoneNumber() { return this.technicalPhoneNumber; } public void setTechnicalPhoneNumber(String zmtel1) { this.technicalPhoneNumber = zmtel1; } public String getSellerName() { return this.sellerName; } public void setSellerName(String zvnam) { this.sellerName = zvnam; } public String getSellerPhoneNumber() { return this.sellerPhoneNumber; } public void setSellerPhoneNumber(String zvtel1) { this.sellerPhoneNumber = zvtel1; } public String getPartnerAddressId() { return this.partnerAddressId; } public String getCustomerAddressId() { return this.customerAddressId; } private void setPartnerAddressId(String paranmnr) { this.partnerAddressId = paranmnr; } public String getOrderNumber() { return this.orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public Date getAppointmentDate() { return this.appointmentDate; } public Date getStatusEdit() { return this.statusEdit; } public void setAppointmentDate(Date appointmentDate) { this.appointmentDate = appointmentDate; } public String getAppointmentDateAsString() { return DateTimeUtil.tableDate(this.getAppointmentDate()); } public String getHtmlAppointmentDate() { return DateTimeUtil.HtmlDateTime(this.getAppointmentDate()); } public String getAppointmentTime() { return DateTimeUtil.showTime(this.getAppointmentDate()); } public Date getNewJobDate() { return this.newJobDate; } public String getTableNewJobDate() { return DateTimeUtil.tableDate(this.getNewJobDate()); } public String getHtmlDateTimeNewJobDate() { return DateTimeUtil.HtmlDateTime(this.getNewJobDate()); } public void setNewJobDate(Date erdat) { this.newJobDate = erdat; } public Date getActiveJobDate() { return activeJobDate; } public void setActiveJobDate(Date activeJobDate) { this.activeJobDate = activeJobDate; } public Date getJobRescheduleDate() { return jobRescheduleDate; } public void setJobRescheduleDate(Date jobRescheduleDate) { this.jobRescheduleDate = jobRescheduleDate; } public Date getJobRescheduleTime() { return jobRescheduleTime; } public void setJobRescheduleTime(Date jobRescheduleTime) { this.jobRescheduleTime = jobRescheduleTime; } public void setStatusEdit(Date statusEdit) { this.statusEdit = statusEdit; } public String getContactName() { return this.contactName; } public void setContactName(String user_san) { this.contactName = user_san; } public String getInformation() { return this.information; } public void setInformation(String ltxt2) { this.information = ltxt2; } public String getCycleOfInstallationFlag() { return this.cycleOfInstallationFlag; } private void setCycleOfInstallationFlag(String cycleOfInstallationFlag) { this.cycleOfInstallationFlag = cycleOfInstallationFlag; } public void setCycleOfInstallationFlag(boolean cycleOfInstallationFlag) { if (cycleOfInstallationFlag) { this.setCycleOfInstallationFlag("X"); //$NON-NLS-1$ } else { this.setCycleOfInstallationFlag(""); //$NON-NLS-1$ } } public boolean isCycleOfInstallationFlag() { return "X".equalsIgnoreCase(this.getCycleOfInstallationFlag()); //$NON-NLS-1$ } public String getFormDesc1() { return formDesc1; } public void setFormDesc1(String formDesc1) { this.formDesc1 = formDesc1; } public String getFormDesc2() { return formDesc2; } public void setFormDesc2(String formDesc2) { this.formDesc2 = formDesc2; } public String getFormDesc3() { return formDesc3; } public void setFormDesc3(String formDesc3) { this.formDesc3 = formDesc3; } /** * create new GUID if current job has no GUID yet * * @return */ public String getCurrentReportGuId(DatabaseUtil dbutil) throws ApplicationException { if (this.currentReportGuId.length() == 0) { try { GuidGenerator generator = new GuidGenerator(); this.currentReportGuId = generator.generate(); dbutil.updateJob(this); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } } return this.currentReportGuId; } public void setCurrentReportGuId(String currentrapportguid) { this.currentReportGuId = currentrapportguid; } public String getStaffPhoneNumber() { return this.staffPhoneNumber; } public void setStaffPhoneNumber(String ernamtel) { this.staffPhoneNumber = ernamtel; } public String getContactPhoneNumber() { return this.contactPhoneNumber; } public void setContactPhoneNumber(String user_santel) { this.contactPhoneNumber = user_santel; } public List getReports() { return this.reports; } public void setReports(List reports) { this.reports = reports; this.mCurrentReport = 0; } /** * @return the partnerAddress (PARAPNR) */ public Address getPartnerOfInstallAddress() { if (this.addresses.containsKey(this.partnerOfInstallAddressId)) return this.addresses.get(this.partnerOfInstallAddressId); else return new Address(); } /** * @return the kdnServiceAddress (PARZRNR) */ public Address getKdnServiceAddress() { if (this.addresses.containsKey(this.kdnServiceAddressId)) return this.addresses.get(this.kdnServiceAddressId); else return new Address(); } /** * @return the kdnErrorAddress (PARZSNR) */ public Address getCustomerAddress() { if (this.addresses.containsKey(this.customerAddressId)) return this.addresses.get(this.customerAddressId); else return new Address(); } /** * @return the PartnerAddress (PARANMNR) */ public Address getPartnerAddress() { if (this.addresses.containsKey(this.partnerAddressId)) return this.addresses.get(this.partnerAddressId); else return new Address(); } /** * @return the objectAddress (OBJNR) */ public Address getObjectAddress() { if (this.addresses.containsKey(this.objectAddressId)) return this.addresses.get(this.objectAddressId); else return new Address(); } /** * @return the ownerAddress (PARZANR) */ public Address getOwnerAddress() { if (this.addresses.containsKey(this.ownerAddressId)) return this.addresses.get(this.ownerAddressId); else return new Address(); } /** * @return Addresses in a Map */ public Map getAddresses() { return this.addresses; } /** * @param dbutil * @return amount of reports loaded for this job */ public void loadReports(DatabaseUtil dbutil) { this.reports = new ArrayList(); loadReportData(dbutil, reports); this.mCurrentReport = 0; } /** * Load report data from database. * @param dbutil * @param reports Array list to fill with report(s). * @return Returns true if a report */ private boolean loadReportData(DatabaseUtil dbutil, List reports) { reports.addAll(dbutil.selectReportListByJobIdAndJobType(this.jobNumber, this.jobType.getCode())); boolean reportDataExist = !reports.isEmpty(); if (reports.isEmpty()) reports.add(new Report(this.jobNumber, this.jobType, getCurrentReportGuId(dbutil), 1, isCycleOfInstallationFlag())); Report currentReport = reports.get(0); reportDataExist |= currentReport.loadTimes(dbutil) > 0; reportDataExist |= currentReport.loadParts(dbutil) > 0; reportDataExist |= currentReport.loadMessages(dbutil) > 0; reportDataExist |= currentReport.loadImageAttachments(dbutil) > 0; reportDataExist |= currentReport.loadDocumentAttachments(dbutil) > 0; reportDataExist |= currentReport.loadFormInstances(dbutil) > 0; return reportDataExist; } /** * Returns true if the job contains user reported data and thus is 'in progress'. * @return Returns true there are report data. */ public boolean hasReportedData(DatabaseUtil dbutil) { List reports = new ArrayList(); return loadReportData(dbutil, reports); } /** * @return The report currently set in the list */ public Report getCurrentReport() throws IndexOutOfBoundsException { if(reports.isEmpty()) { return null; } return this.reports.get(this.mCurrentReport); } /** * @return Latest (most up to date) report of this job (current report is * set to this one) */ public Report getLatestReport() throws IndexOutOfBoundsException { this.mCurrentReport = 0; return getCurrentReport(); } public boolean hasNextReport() { boolean result = false; if (this.reports.size() > this.mCurrentReport + 1) { result = true; } return result; } /** * @return Next report of this job (in chronological order) * @throws IndexOutOfBoundsException */ public Report getNextReport() throws IndexOutOfBoundsException { int location = this.mCurrentReport + 1; Report report = this.reports.get(location); this.mCurrentReport = location; return report; } public void loadAddresses(DatabaseUtil dbutil) { List
addresses = dbutil.selectAddressListByJobIdAndJobType(this.jobNumber, this.jobType.getCode()); for (int i = 0; i < addresses.size(); i++) { Address adr = addresses.get(i); this.addresses.put(adr.getPartnerNummer(), adr); } } /** * Generates the next report index depending on the highest existing value * in the database. There for the list of reports is loaded from the * database (see loadReports()). * * @param dbutil * @return */ public int getNextReportIdx(DatabaseUtil dbutil) { loadReports(dbutil); if (this.reports.isEmpty() || (getLatestReport().getIdx() == 1 && getLatestReport().getReportStatus().isInitial())) return 1; else return (this.reports.get(0)).getIdx() + 1; } public int getStatusColor() { int result = 0; if (getStatus().isNew()) result = LayoutUtils.DEFAULT_NEW_COLOR; else if (getStatus().isReceived()) result = LayoutUtils.DEFAULT_RECEIVED_COLOR; else if (getStatus().isForwarded()) result = LayoutUtils.DEFAULT_FORWARDED_COLOR; else if (getStatus().isInProgress()) result = LayoutUtils.DEFAULT_INPROGRESS_COLOR; else if (getStatus().isFinalized()) result = LayoutUtils.DEFAULT_FINALIZED_COLOR; else if (getStatus().isPartlyDone()) result = LayoutUtils.DEFAULT_PARTLY_DONE_COLOR; return result; } public String getStatusType() { String result = null; if (getJobType().isSAV()) { result = "SAV"; //$NON-NLS-1$ } else if (getJobType().isREP()) { result = "REP"; //$NON-NLS-1$ } else if (getJobType().isMON()) { result = "MON"; //$NON-NLS-1$ } else if (getJobType().isINITIAL()) { result = "INT"; //$NON-NLS-1$ } return result; } /** * Default working type for repair orders: Non ("Reparatur") because * relevant working type is taken from the report (ZKDMOBREP) record */ protected static final String DEFAULT_REP_ARBA = "01"; //$NON-NLS-1$ /** * Default working type for assambly orders: Non ("Bitte wählen..") because * relevant working type is taken from the report (ZKDMOBREP) record */ protected static final String DEFAULT_MON_ARBA = "00"; //$NON-NLS-1$ /** * Default working type for maintenance orders: "Vertragsservice" */ protected static final String DEFAULT_SAV_ARBA = "05"; //$NON-NLS-1$ /** * Setting ARBA correct: MON: Default value "00 Bitte wählen" REP (1-st * entry): Default value "01 Reparatur" SAV (1-st entry): Default value * "05 Vertragsservice" */ public String getDefaultJobTimeARBA() { String result = ""; //$NON-NLS-1$ if (getJobType().isMON()) { result = DEFAULT_MON_ARBA; } else if (getJobType().isREP()) { result = DEFAULT_REP_ARBA; } else if (getJobType().isSAV()) { result = DEFAULT_SAV_ARBA; } return result; } public boolean isLocalJob() { return getJobNumber().startsWith("$"); //$NON-NLS-1$ } public CommonConstants.CommissionNumber.Type getReportCommissionNumberType() { if(getLatestReport() == null) { return CommonConstants.CommissionNumber.Type.UNKNOWN; } if (CommonConstants.CommissionNumber.DEFAULT.equalsIgnoreCase(getLatestReport().getCommissionNumber())) { return CommonConstants.CommissionNumber.Type.UNKNOWN; } if (getCommissionNumber().equalsIgnoreCase(getLatestReport().getCommissionNumber())) { return CommonConstants.CommissionNumber.Type.CORRECT; } else { return CommonConstants.CommissionNumber.Type.INVALID; } } public void calculateActiveDate() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getJobRescheduleDate()); if(jobType.isREP()) { calendar.add(Calendar.DAY_OF_YEAR, -3); setActiveJobDate(calendar.getTime()); } else if(jobType.isSAV()) { calendar.add(Calendar.DAY_OF_YEAR, -90); setActiveJobDate(calendar.getTime()); } else if(jobType.isMON()) { calendar.add(Calendar.DAY_OF_YEAR, -3); setActiveJobDate(calendar.getTime()); } } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Job.JOB, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Job.JOB, db, folder); } public String getServiceRefusedFlag() { return this.serviceRefusedFlag; } public void setServiceRefusedFlag(String serviceRefusedFlag) { this.serviceRefusedFlag = serviceRefusedFlag; } public void setServiceRefusedFlag(boolean serviceRefusedFlag) { if (serviceRefusedFlag) { this.setServiceRefusedFlag("X"); } else { this.setServiceRefusedFlag(""); } } public boolean isServiceRefusedFlag() { return "X".equalsIgnoreCase(this.getServiceRefusedFlag()); } public String getLink() { return this.link; } public void setLink(String link) { this.link = link; } public String getGuarantee() { return guarantee; } public void setGuarantee(String guarantee) { this.guarantee = guarantee; } public boolean isGuarantee() { return "X".equalsIgnoreCase(this.getGuarantee()); } public void setGuarantee(boolean isGuarantee) { if (isGuarantee) { this.setGuarantee("X"); } else { this.setGuarantee(""); } } public String getMoreInformationsFlag() { return this.moreInformationsFlag; } public void setMoreInformationsFlag(String moreInformationsFlag) { this.moreInformationsFlag = moreInformationsFlag; } public void setMoreInformationsFlag(boolean moreInformationsFlag) { if (moreInformationsFlag) { this.setMoreInformationsFlag("X"); } else { this.setMoreInformationsFlag(""); } } public boolean isMoreInformationsFlag() { return "X".equalsIgnoreCase(this.getMoreInformationsFlag()); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.graphics.Bitmap; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.db.ZKDMOBMV; import ch.mfiles.kaba.kolibri.common.util.BitmapConverterUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMOBMV */ public class JobFile { public static final Log log = LogFactory.getLog(Report.class); private String jobFileId = ""; //$NON-NLS-1$ private String guid = ""; //$NON-NLS-1$ private String jobNumber = ""; //$NON-NLS-1$ private JobType jobType = new JobType(); private String type = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ private boolean signpicAtSet = false; private String signpicAt = ""; //$NON-NLS-1$ private FormType formType = new FormType(); private String formDesc = ""; private Date sentDate = new Date(0); public JobFile() { } public JobFile(RecordSet rs) { this.setJobFileId(rs.getString(DbConstants.JobFile.IDX)); this.setGuid(rs.getString(DbConstants.JobFile.GUID)); this.setJobNumber(rs.getString(DbConstants.JobFile.JOB_NUMBER)); this.setJobType(rs.getString(DbConstants.JobFile.JOB_TYPE)); this.setType(rs.getString(DbConstants.JobFile.TYPE)); this.setDescription(rs.getString(DbConstants.JobFile.DESCRIPTION)); // lazy load file data to reduce memory footprint (MIG-988) //this.setSignPicAt(rs.getString(DbConstants.JobFile.SIGN_PIC_AT)); this.setSignPicAt(null); this.setFormType(new FormType(rs.getString(DbConstants.JobFile.FORM_TYPE))); this.setFormDesc(rs.getString(DbConstants.JobFile.FORM_DESC)); this.setSentDate(rs.getDate(DbConstants.JobFile.SENT_DATE)); } public String getJobFileId() { return jobFileId; } public void setJobFileId(String jobFileId) { this.jobFileId = jobFileId; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public JobType getJobType() { return jobType; } public void setJobType(JobType jobType) { this.jobType = jobType; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSignpicAt() { // lazy load file data from db without keeping it into heap memory (MIG-988) if (signpicAtSet) return signpicAt; DBSession db = Runtime.getApplicationManager().getDBSession(); ZKDMOBMV dbMobmv = ZKDMOBMV.getByPrimaryKey(db, getJobFileId()); return dbMobmv != null ? dbMobmv.getSIGNPIC_AT() : ""; } public void setSignPicAt(String signpicAt) { this.signpicAt = signpicAt; signpicAtSet = signpicAt != null && !signpicAt.isEmpty(); } public void setJobType(String auart) { this.jobType = new JobType(auart); } public Bitmap getSignPicBitmap() { return BitmapConverterUtil.stringToBitMap(getSignpicAt()); } public void setSignPicBitmap(Bitmap bitmap) { setSignPicAt(BitmapConverterUtil.bitMapToString(bitmap)); } public FormType getFormType() { return formType; } public void setFormType(FormType formType) { this.formType = formType; } public String getFormDesc() { return formDesc; } public void setFormDesc(String formDesc) { this.formDesc = formDesc; } public Date getSentDate() { return sentDate; } public void setSentDate(Date sentDate) { this.sentDate = sentDate; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.JobFile.JOB_FILE, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.JobFile.JOB_FILE, db, folder); } public boolean isValid() { boolean result = true; StringBuilder error = new StringBuilder(); error.append("\n"); if(equals(getGuid().trim().isEmpty())) { error.append("Guid required \n"); result = false; } if(getJobNumber().trim().isEmpty()) { error.append("JobNumber required \n" ); result = false; } if(getJobFileId().trim().isEmpty()) { error.append("FileId required \n" ); result = false; } if(getJobType().toString().isEmpty()) { error.append("JobType required \n" ); result = false; } if(getType().trim().isEmpty()) { error.append("Type required \n" ); result = false; } if(getType().trim().equalsIgnoreCase("F") && getFormType().isINITIAL()) { error.append("FormType required \n" ); result = false; } if(getSignpicAt().toString().trim().isEmpty()) { error.append("Signpic required \n" ); result = false; } log.info("is JobFile valid -> " + result + " " + error.toString()); return result; } public String getNoForm() { if (getJobFileId().contains("NO_FORM")) { return getJobFileId().split("NO_FORM")[1]; } return ""; } } package ch.mfiles.kaba.kolibri.common.forms.adapters; import android.graphics.Typeface; import android.widget.TextView; public class SpinnerTextStyle { private static final SpinnerTextStyle NONE = new SpinnerTextStyle(false, 0, null, 0, 0); private final boolean custom; private final int textColor; private final Typeface typeface; private final int textSizeUnit; private final int textSize; private SpinnerTextStyle(boolean custom, int textColor, Typeface typeface, int textSizeUnit, int textSize) { this.custom = custom; this.textColor = textColor; this.typeface = typeface; this.textSizeUnit = textSizeUnit; this.textSize = textSize; } public static SpinnerTextStyle none() { return NONE; } public static SpinnerTextStyle custom(int textColor, Typeface typeface, int textSizeUnit, int textSize) { return new SpinnerTextStyle(true, textColor, typeface, textSizeUnit, textSize); } public boolean isCustom() { return custom; } public int getTextColor() { return textColor; } public Typeface getTypeface() { return typeface; } public int getTextSizeUnit() { return textSizeUnit; } public int getTextSize() { return textSize; } public void applyTo(TextView view) { if (view == null || !custom) { return; } view.setTextColor(textColor); if (typeface != null) { view.setTypeface(typeface); } view.setTextSize(textSizeUnit, textSize); } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class DefaultListWidgetAdapter extends StatusListWidgetAdapter { private static final int ID_CHECK = 1080; protected Context context; public DefaultListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { setRightView(createRightLayout()); return super.getView(position, convertView, parent); } private View createRightLayout() { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; endFrameLayout.setLayoutParams(endFrameParams); endFrameLayout.setBackgroundColor(color.holo_green_light); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setId(ID_BUTTON); imageButton.setContentDescription("Menu"); endFrameLayout.addView(imageButton); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); overlayParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; final CheckBox checkBox = new CheckBox(context); checkBox.setId(ID_CHECK); checkBox.setChecked(false); checkBox.setLayoutParams(overlayParams); endFrameLayout.addView(checkBox); return endFrameLayout; } @Override public void bindView(int position, View view) { super.bindView(position, view); final DefaultListWidgetItem dataSet = (DefaultListWidgetItem)mData.get(position); if (dataSet == null) { return; } ImageButton imageButton = (ImageButton) view .findViewById(ID_BUTTON); CheckBox checkBox = (CheckBox) view .findViewById(ID_CHECK); if (0 != dataSet.getStatusColor()) { GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(dataSet.getStatusColor()); gradientDrawable.setCornerRadius(LayoutUtils.convertDpToPixel(view.getContext(), 50)); gradientDrawable.setStroke(2, dataSet.getStatusColor()); } if (null == imageButton) { return; } if (dataSet.isShowCheckBox()) { checkBox.setVisibility(View.VISIBLE); imageButton.setVisibility(View.INVISIBLE); checkBox.setOnClickListener(dataSet.getOnClickListener()); checkBox.setFocusable(false); checkBox.setChecked(dataSet.isCheck()); checkBox.setEnabled(dataSet.isEnabledCheckBox()); } else { checkBox.setVisibility(View.INVISIBLE); imageButton.setVisibility(View.VISIBLE); if (null != dataSet.getOnClickListener()) { imageButton.setOnClickListener(dataSet.getOnClickListener()); } imageButton.setFocusable(false); } } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import android.graphics.drawable.Drawable; import android.view.View.OnClickListener; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; /** * A item that has an icon on the left, a title, two lines of text and a image * button on the right. * * @author Xin * */ public class DetailListWidgetItem { private String header; private int headerBackgroundColor = LayoutUtils.DEFAULT_LIGHT_GRAY; private Drawable buttonImage = null; private String buttonImageTag; private String titleText; private String stringLine1; private String stringLine2; private String stringLine3; private boolean isShowEllipInTextEnd; private boolean isShowRightLayout = true; private OnClickListener onClickListener = null; private Object data; public String getTitleText() { return titleText; } public void setTitleText(String titleText) { this.titleText = titleText; } public String getStringLine1() { return stringLine1; } public void setStringLine1(String stringLine1) { this.stringLine1 = stringLine1; } public String getStringLine2() { return stringLine2; } public void setStringLine2(String stringLine2) { this.stringLine2 = stringLine2; } public String getStringLine3() { return stringLine3; } public void setStringLine3(String stringLine3) { this.stringLine3 = stringLine3; } public Drawable getButtonImage() { return buttonImage; } public void setButtonImage(Drawable buttonImage) { this.buttonImage = buttonImage; } public String getButtonImageTag() { return buttonImageTag; } public void setButtonImageTag(String buttonImageTag) { this.buttonImageTag = buttonImageTag; } public void isShowEllipInTextEnd(boolean isShowEllipInTextEnd) { this.isShowEllipInTextEnd = isShowEllipInTextEnd; } public boolean isShowEllipInEndOfText() { return isShowEllipInTextEnd; } public boolean isShowRightLayout() { return isShowRightLayout; } public void isShowRightLayout(boolean isShowRightLayout) { this.isShowRightLayout = isShowRightLayout; } public OnClickListener getOnClickListener() { return onClickListener; } public void setOnClickListener(OnClickListener onClickListener) { this.onClickListener = onClickListener; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public int getHeaderBackgroundColor() { return headerBackgroundColor; } public void setHeaderBackgroundColor(int headerBackgroundColor) { this.headerBackgroundColor = headerBackgroundColor; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.InputFilter; import android.text.InputType; import android.util.TypedValue; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.ExpenseMaskWatcher; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class ExpenseMaskEditText extends MDEditText { private static Log log = LogFactory.getLog(ExpenseMaskEditText.class); private static boolean removeDot; private static ExpenseMaskEditText editText = null; public ExpenseMaskEditText(Context context) { super(context); } public static ExpenseMaskEditText createDefaultEditText(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); ExpenseMaskEditText editText = createEditText(context, label, required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private static ExpenseMaskEditText createEditText(Context context, String label, final boolean required) { editText = new ExpenseMaskEditText(context); editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); if (required) { editText.setRequired(required); } if (label != null) { editText.setHint(label); } editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); editText.addTextChangedListener(new ExpenseMaskWatcher(editText)); return editText; } public void setText(String text) { setTextAndSelection(text); } public void setLabel(String label) { super.setHint(label); } public String getValue() { return getText().toString(); } } package ch.mfiles.kaba.kolibri.common.util; import java.util.Random; import android.graphics.Typeface; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kolibri.ApplicationBase; import ch.mfiles.kolibri.ui.Image; public class CommonConstants { CommonConstants(){ } public static final int PERMISSION_REQUEST_CODE = 200; public static final int RETENTION_PERIOD_DAY = 180; public static Random r = new Random(); public static final String PLEASE_SELECT = "00"; public static final String KOLIBRI_ID = "framework.net.kolibriId"; public static final class Local { Local() { } public static final int EN = 0; public static final int GE = 1; public static final int FR = 2; public static final int IT = 3; } public static final class LocalizedTexts { LocalizedTexts() { } public static final String JOB_TYPE = "1"; //$NON-NLS-1$ public static final String JOB_STATUS = "2"; //$NON-NLS-1$ public static final String JOB_PRIORITY = "3"; //$NON-NLS-1$ public static final String ADDRESS_TITLE = "4"; //$NON-NLS-1$ public static final String ADDRESS_TYPE = "5"; //$NON-NLS-1$ public static final String REPORT_SIGNATURE = "6"; //$NON-NLS-1$ public static final String REPORT_CUSTOMER_SUPPORT = "7"; //$NON-NLS-1$ public static final String REPORT_CHCKLISTE = "8"; //$NON-NLS-1$ public static final String MONTH = "9"; //$NON-NLS-1$ public static final String MESSAGE_ID = "10"; //$NON-NLS-1$ public static final String VAREXP = "11"; //$NON-NLS-1$ public static final String INVOICE = "12"; //$NON-NLS-1$ public static final String WORK_TYPE = "13"; //$NON-NLS-1$ public static final String REGISTER_USER = "14"; //$NON-NLS-1$ } public static final class Font { Font() { } public static final int DEFAULT_FONT_SIZE = 13; public static final int DEFAULT_HERDER_FONT_SIZE = 16; public static final int DEFAULT_TITLE_FONT_SIZE = 24; // roboto regular public static Typeface getDefaultRegularFont() { return getDefaultRegularFont(Typeface.NORMAL); } public static Typeface getDefaultRegularFont(int typeface) { return Typeface.create("sans-serif", typeface); //$NON-NLS-1$ } // roboto light public static Typeface getDefaultLightFont() { return getDefaultLightFont(Typeface.NORMAL); } public static Typeface getDefaultLightFont(int typeface) { return Typeface.create("sans-serif-light", typeface); //$NON-NLS-1$ } // roboto condensed public static Typeface getDefaultCondensedFont() { return getDefaultCondensedFont(Typeface.NORMAL); } public static Typeface getDefaultCondensedFont(int typeface) { return Typeface.create("sans-serif-condensed", typeface); //$NON-NLS-1$ } // roboto thin (android 4.2) public static Typeface getDefaultThinFont() { return getDefaultThinFont(Typeface.NORMAL); } public static Typeface getDefaultThinFont(int typeface) { return Typeface.create("sans-serif-thin", typeface); //$NON-NLS-1$ } // roboto medium (android 5.0) public static Typeface getDefaultMediumFont() { return getDefaultMediumFont(Typeface.NORMAL); } public static Typeface getDefaultMediumFont(int typeface) { return Typeface.create("sans-serif-medium", typeface); //$NON-NLS-1$ } } public static class Address { Address() { } /* * * (2009-03-24) * INSERT INTO localizedTexts VALUES ("01","D","Objekt","5") * INSERT INTO localizedTexts VALUES ("02","D","Ansprechperson","5") * INSERT INTO localizedTexts VALUES ("03","D","Auftraggeber","5") * INSERT INTO localizedTexts VALUES ("04","D","Eigentümer","5") * INSERT INTO localizedTexts VALUES ("05","D","Verwaltung","5") * INSERT INTO localizedTexts VALUES ("06","D","Partner","5") * INSERT INTO localizedTexts VALUES ("07","D","Warenempfänger","5") * * OBJNR = 01 - OBJEKT * PARZSNR = 02 - ANSPRECHPERSON * PARANMNR = 03 - AUFTRAGGEBER * PARZANR = 04 - EIGENTUMER * * PARAPNR = 06 - PARTNER * PARZRNR = 07 - WARENEMPFANGER */ public static final String KdnJobNumber = "BSTKD"; //$NON-NLS-1$ /** * OBJEKT */ public static final String OBJECT_ADDRESS = "01"; //$NON-NLS-1$ /** * ANSPRECHPERSON */ public static final String CUSTOMER_ADDRESS = "02"; //$NON-NLS-1$ /** * AUFTRAGGEBER */ public static final String PARTNET_ADDRESS = "03"; //$NON-NLS-1$ /** * EIGENTUMER */ public static final String OWNER_ADDRESS = "04"; //$NON-NLS-1$ // public static final String VERWALTUNG = "05"; /** * PARTNER */ public static final String PARTNER_OF_INSTALLATION_ADDRESS = "06"; //$NON-NLS-1$ /** * WARENEMPFANGER */ public static final String KDN_SERVICE_ADDRESS = "07"; //$NON-NLS-1$ } public static class Report { Report() { } public static final String WORK_TYPE_SERVICE_CONTACT = "05"; //$NON-NLS-1$ public static final String WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA = "98"; public static final String WORK_TYPE_MAINTENANCE_VONOVIA = "99"; public static final String CUSTOMER_SUPPORT_FAX = "01"; //$NON-NLS-1$ public static final String CUSTOMER_SUPPORT_EMAIL = "02"; //$NON-NLS-1$ public static final String CUSTOMER_SUPPORT_FOMULAR = "03"; //$NON-NLS-1$ public static final String CUSTOMER_SUPPORT_WAIVER = "04"; //$NON-NLS-1$ public static final String WORK_TYPE_REPAIR = "01"; public static final String WORK_TYPE_ON_CALL = "02"; public static final String BILLING_GUARANTEE = "04"; public static final String BILLING_GOODWILL = "05"; public static final String WORKTYPE_INSTALLATION = "32"; public static final String FORM_VONOVIA = "VD10"; public static class Month { Month() { } public static final String JAN = "01"; //$NON-NLS-1$ public static final String FEB = "02"; //$NON-NLS-1$ public static final String MAR = "03"; //$NON-NLS-1$ public static final String APR = "04"; //$NON-NLS-1$ public static final String MAY = "05"; //$NON-NLS-1$ public static final String JUN = "06"; //$NON-NLS-1$ public static final String JUL = "07"; //$NON-NLS-1$ public static final String AUG = "08"; //$NON-NLS-1$ public static final String SEP = "09"; //$NON-NLS-1$ public static final String OCT = "10"; //$NON-NLS-1$ public static final String NOV = "11"; //$NON-NLS-1$ public static final String DEC = "12"; //$NON-NLS-1$ } } public static class Message { Message() { } // Abteilungsleiter Kunde KDZ 1 KDZ 2 KDZ 3 public static final String HEAD_OF_DEPARTMENT= "01"; //$NON-NLS-1$ public static final String CUSTOMER = "02"; //$NON-NLS-1$ public static final String KDZ1 = "03"; //$NON-NLS-1$ public static final String KDZ2 = "04"; //$NON-NLS-1$ public static final String KDZ3 = "05"; //$NON-NLS-1$ public static final String PROJECT_MANAGER = "06"; //$NON-NLS-1$ public static final String DISPOSITION = "07"; //$NON-NLS-1$ public static final String SYSTEM_IS_SAVE = "18"; //$NON-NLS-1$ public static final String SYSTEM_WITH_MINOR_DEFECTS = "19"; //$NON-NLS-1$ public static final String SYSTEM_EXHIBITS_DEFECTS = "20"; //$NON-NLS-1$ } // TODOO Replace "Status" with an enum public static class Order { Order() { } public static class Status { Status() { } public static final String NEW_ORDER = "0"; //$NON-NLS-1$ public static final String SENT_ORDER = "1"; //$NON-NLS-1$ } } public static class ShortMessage { ShortMessage() { } public static class Status { Status() { } public static final String RECEIVED = "01"; //$NON-NLS-1$ public static final String READ = "02"; //$NON-NLS-1$ public static final String CONFIRMED = "03"; //$NON-NLS-1$ } } public static class Application { Application() { } // app constants for storing app specific data in the filesystem public static final String COMMON = "CommonApplication"; //$NON-NLS-1$ public static final String SERVICE = "ServiceApplication"; //$NON-NLS-1$ // app constants for access to app classes public static final String COMMON_APP = "ch.mfiles.kaba.kolibri.common.CommonApplication"; //$NON-NLS-1$ public static final String LOGIN_APP = "ch.mfiles.kaba.kolibri.login.LoginApplication"; //$NON-NLS-1$ public static final String MATERIAL_APP = "ch.mfiles.kaba.kolibri.material.MaterialApplication"; //$NON-NLS-1$ public static final String SERVICE_APP = "ch.mfiles.kaba.kolibri.service.ServiceApplication"; //$NON-NLS-1$ public static final String TIMESHEET_APP = "ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication"; //$NON-NLS-1$ } public static class Regex { Regex() { } // eMail validation // public static final String EMAIL_VALIDATOR = "^[^\\s]+@[^\\s]+\\.[^\\s]{2,3}$"; // public static final String EMAIL_VALIDATOR = "^[\\w]+@[\\w]+\\.[\\w]{2,3}$"; // public static final String EMAIL_VALIDATOR = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[\\w]{2,4}$"; public static final String EMAIL_VALIDATOR = "^[\\w\\.\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]+@([\\w\\-]+\\.)+[\\w]{2,7}$"; //$NON-NLS-1$ public static final String EMAIL_VALIDATION_MSG = Messages.getString("FormatMailAddress"); //$NON-NLS-1$ // Tel. and fax number validation public static final String TEL_NR_VALIDATOR = "^[\\d\\s]{1,30}$"; //$NON-NLS-1$ public static final String TEL_NR_VALIDATION_MSG = Messages.getString("onlyNumberAndSpacesAllowedForTelephoneNumber"); //$NON-NLS-1$ // MLDNR number validation public static final String MLDNR_VALIDATOR = "^[\\d]{1,6}$"; //$NON-NLS-1$ public static final String MLDNRR_VALIDATION_MSG = Messages.getString("NumbersUpToSixDigitsAreAllowed"); //$NON-NLS-1$ // Validation of any string with max. length public static String getRegexMaxLength(int length) { return "^.{1," + length + "}$"; //$NON-NLS-1$ //$NON-NLS-2$ } public static String getValidationMsgMaxLength(int length) { return Messages.getString("valueMustNotBeLongerThen") + String.valueOf(length) + Messages.getString("characters"); //$NON-NLS-1$ //$NON-NLS-2$ } } public static class Images { Images() { } public enum Type { BMP, JPG, JPEG, PNG, WEBP } public static final int IMAGE_DPI = 200; public static final int IMAGE_MIN_DPI = 250; public static final int IMAGE_MAX_DPI = 95; public static final String NEW16 = "new16.png"; //$NON-NLS-1$ public static final String INPROGRESS16 = "inProgress16.png"; //$NON-NLS-1$ public static final String FINALIZE16 = "finalize16.png"; //$NON-NLS-1$ public static final String RECEIVE16 = "receive16.png"; //$NON-NLS-1$ public static final String FORWARD16 = "forward16.png"; //$NON-NLS-1$ public static final String MAKING16 = "making16.png"; //$NON-NLS-1$ public static final String CHECK16 = "check16.png"; //$NON-NLS-1$ public static final String REPAIR16 = "repair16.png"; //$NON-NLS-1$ public static final String INSTALL16 = "install16.png"; //$NON-NLS-1$ public static final String CALL = "call.png"; //$NON-NLS-1$ public static final String WARNING = "warning.png"; //$NON-NLS-1$ public static final String IMAGE_PACKAGE = "images"; //$NON-NLS-1$ public static Image getImageByJobType(ApplicationBase app, JobType jobType) { String prefixPath = "images/"; //$NON-NLS-1$ if (jobType.isREP()) { return app.getImage(prefixPath + REPAIR16); } else if (jobType.isSAV()) { return app.getImage(prefixPath + CHECK16); } else if (jobType.isMON()) { return app.getImage(prefixPath + INSTALL16); } else return null; } public static String getImageNameByStatus(JobStatus status) { String result; if (status.isNew()) { result = NEW16; } else if (status.isReceived()) { result = RECEIVE16; } else if (status.isForwarded()) { result = FORWARD16; } else if (status.isInProgress()) { result = INPROGRESS16; } else if (status.isFinalized()) { result = FINALIZE16; } else if (status.isPartlyDone()) { result = MAKING16; } else { result = CHECK16; } return result; } } public static class Prefix { Prefix() { } /* * The prefix for short message * * example: SHORTMSG-78702-0000003990 * * @see "[MIG-53] implement of "report messages"" */ public static final String SHORTMSG = "SHORTMSG"; //$NON-NLS-1$ /* * The prefix for transmit a job from backend to frontend * * example: AUFTR-12345-REP-BR * * @see "[MIG-120] Cannot transmit a job from backend to frontend (GET_ORDER)" */ public static final String AUFTR = "AUFTR"; //$NON-NLS-1$ /* * The prefix for transmit a vehicle inventory from backend to frontend * * example: MBEW-GUID-CONF * * @see "[MIG-818] Implement push message and transaction GET_MBEW for inventory" */ public static final String MBEW = "MBEW"; //$NON-NLS-1$ } public static String randomString(int length) { String tempString = "QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR"; //$NON-NLS-1$ StringBuilder result = new StringBuilder(); Random r = new Random(); int te; for (int i = 1; i <= length; i++) { te = r.nextInt(62); result.append(tempString.charAt(te)); } return result.toString(); } public static String randomInt(int length) { String result = Integer.toString(Math.abs(r.nextInt())); if (result.length() > length) { result = result.substring(0, length); } else if (result.length() < length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length - result.length(); i++) { sb.append("0"); //$NON-NLS-1$ } result = sb.toString() + result; } return result; } public static final class CommissionNumber { CommissionNumber() { } public enum Type { CORRECT, UNKNOWN, INVALID } public static final String DEFAULT = "0459999-99"; //$NON-NLS-1$ public static final int DASH_POSITION = 7; public static final int LETTER_POSITION = 8; //CH -> REP, SAV -> 0xxxxxx-yy -> x: [0-9], y: [0-9][A-Z] public static final String REGX_REP_SAV_CH = "0\\d{6}\\-[A-Za-z0-9]{2}$"; //CH -> MON -> xxxxxx -> x: [0-9] public static final String REGX_MON_CH = "[0-9]{6}$"; //DE -> REP, SAV -> xxxxxxx-yy -> x: [0-9], y: [0-9][A-Z] public static final String REGX_REP_SAV_DE = "\\d{7}\\-[A-Za-z0-9]{2}$"; //DE -> MON -> xxxxxxxxxx -> x: [0-9] public static final String REGX_MON_DE = "[0-9]{10}$"; public static final String CH = "CH"; public static final String DE = "DE"; } public static final class Notification { Notification() { } public static final String BROADCAST_ACTION = "NfAction"; //$NON-NLS-1$ // note: notification id's < 100 are reserved by runtime notifications public static final int NEW_JOB = 100; public static final int SHORT_MESSAGE = 110; public static final int INCOMING_ARTICLE = 120; } public static final class MaxLength { MaxLength() { } public static final Integer ONE = 1; public static final Integer TWO = 2; public static final Integer THREE = 3; public static final Integer FOUR = 4; public static final Integer FIVE = 5; public static final Integer SIX = 6; public static final Integer SEVEN = 7; public static final Integer EIGHT = 8; public static final Integer NINE = 9; public static final Integer TEN = 10; public static final Integer ELEVEN = 11; public static final Integer TWELVE = 12; public static final Integer THIRTEEN = 13; public static final Integer FOURTEEN = 14; public static final Integer FIFTEEN = 15; public static final Integer SIXTEEN = 16; public static final Integer SEVENTEEN = 17; public static final Integer EIGHTTEEN = 18; public static final Integer NINETEEN = 19; public static final Integer TWENTY = 20; public static final Integer TWENTY_FIVE = 25; public static final Integer THIRTY = 30; public static final Integer THIRTY_FIVE = 35; public static final Integer FORTY = 40; public static final Integer FIFTY = 50; public static final Integer SIXTY = 60; public static final Integer SEVENTY = 70; public static final Integer EIGHTY = 80; public static final Integer EIGHTY_TWO = 82; public static final Integer NINETY = 90; public static final Integer ONE_HUNDRED = 100; public static final Integer FIVE_HUNDRED_AND_TEN = 510; public static final Integer ONE_HUNDRED_AND_FIFTY = 150; } public static final class Material { Material() { } public static final String REGEX = "^\\d{2}-\\d{4}-\\d{3}(\\/\\d{2})?$"; //$NON-NLS-1$ public static final String SEARCH_REGEX = "\\d{0,2}(-\\d{0,4})?(-\\d{0,3})?(\\/\\d{0,2})?"; //$NON-NLS-1$ public static final String NUMBER_PREFIX = "45"; //$NON-NLS-1$ } public static final class Mode { Mode() { } public static final String NEW = "NEW"; //$NON-NLS-1$ public static final String EDIT = "EDIT"; //$NON-NLS-1$ public static final String STOP = "STOP"; //$NON-NLS-1$ public static final String PLAYING = "PLAYING"; //$NON-NLS-1$ } public static final class TimeSheet { TimeSheet() { } public static final String REGEX = "^CHF \\d{1,3}\\.\\d{1,2}?$|^CHF \\d{1,3}\\,\\d{1,2}?$"; //$NON-NLS-1$ public static final String EXPENSES_PREFIX = "CHF "; //$NON-NLS-1$ public static final String VEHICLE_REGEX = "\\d{1,9}\\.\\d{1,2}?$"; //$NON-NLS-1$ public static final String TIME_REGEX = "^([0-1][0-9]|2[0-3]):[0-5][0-9]$"; //$NON-NLS-1$ public static final int COLON_POSITION = 2; } public static final class Menu { Menu() { } public static final Integer CAMERA = 1; public static final Integer GALLERY = 2; public static final Integer PDF = 2; } public static final class DeviceType { DeviceType() { } public static final String SMARTPHONE = "s"; public static final String TABLET = "t"; } } package ch.mfiles.kaba.kolibri.common.util; public class DbConstants { DbConstants() { } public static final class From { From() { } public static final String FROM_TEXT = " FROM "; } public static final class DeleteFrom { DeleteFrom() { } public static final String DELETE_FROM = "DELETE " + From.FROM_TEXT; } public static final class Where { Where() { } public static final String WHERE_TEXT = " WHERE "; } public static final class Settings { Settings() { } public static final String T_SETTINGS = "kaba_service_Setting"; } public static final class Job { Job() { } public static final String JOB = "ZKDMOB"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String STATUS = "STATUS"; public static final String PRIORITY = "PRIO"; public static final String JOB_FORWARD = "PERSNO2"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String STAFF_NAME = "ERNAM"; public static final String STAFF_PHONE = "ERNAMTEL"; public static final String APPOINTMENT_DATE = "EDATE"; public static final String ACTIVE_DATE = "ACTIVE_DATE"; public static final String JOB_RESCHEDULE_DATE = "EDATE_DT"; public static final String JOB_RESCHEDULE_TIME = "EDATE_TI"; public static final String WEEK = "KW"; public static final String FIX = "FIX"; public static final String APPOINTMENT = "TVRB"; public static final String OBJECT_ADDRESS_ID = "OBJNR"; public static final String CUSTOMER_ADDRESS_ID = "PARZSNR"; public static final String PARTNER_ADDRESS_ID = "PARANMNR"; public static final String OWNER_ADDRESS_ID = "PARZANR"; public static final String PARTNER_OF_INSTALL_ADDRESS_ID = "PARAPNR"; public static final String CUSTOMER_SERVICE_ADDRESS_ID = "PARZRNR"; public static final String ORDER_NUMBER = "BSTKD"; public static final String NEW_JOB_DATE = "ERDAT"; public static final String ERROR_ID = "FC"; public static final String CALL_SERVICE_FLAG = "PIKETT"; public static final String MAINTENANCE_CONTRACT_TYPE = "SAVC"; public static final String SERVICE_PLAN_MONTH_1 = "SAVLFD1"; public static final String SERVICE_PLAN_MONTH_2 = "SAVLFD2"; public static final String SERVICE_PLAN_MONTH_3 = "SAVLFD3"; public static final String SERVICE_PLAN_MONTH_4 = "SAVLFD4"; public static final String SERVICE_PLAN_MONTH_5 = "SAVLFD5"; public static final String SERVICE_PLAN_MONTH_6 = "SAVLFD6"; public static final String SERVICE_OPEN = "SAVOFF"; public static final String CONTACT_NAME = "USER_SAV"; public static final String CONTACT_PHONE = "USER_SAVTEL"; public static final String TECHNICAL_NAME = "ZMNAM"; public static final String TECHNICAL_PHONE = "ZMTEL1"; public static final String SELLER_NAME = "ZVNAM"; public static final String SELLER_PHONE = "ZVTEL1"; public static final String DRIVER_TYPE = "ANTRTXT"; public static final String DRIVER_TYPE_UPD = "ANTRTXT_UPD"; public static final String DEFAULT_TIME = "ZKDINDZEIT"; public static final String INFORMATION = "LTXT2"; public static final String DESCRIPTION = "LTXT1"; public static final String CURRENT_REPORT_GUID = "CURRENTRAPPORTGUID"; public static final String STATUS_EDIT = "STEDTDATE"; public static final String CYCLE_OF_INSTALLATIN_FLAG = "ZYKFLG"; public static final String FORM_DESC_1 = "FORMDESC1"; public static final String FORM_DESC_2 = "FORMDESC2"; public static final String FORM_DESC_3 = "FORMDESC3"; public static final String SERVICE_REFUSED_FLAG = "KNZSAVPFL"; public static final String LINK = "LINK"; public static final String GUARANTEE = "KNZGARANT"; public static final String MORE_INFORMARION_FLAG = "KNZERWKOM"; } public static final class Address { Address() { } public static final String ADDRESS = "ZKDMOBADR"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String TYPE = "TYPE"; public static final String PARTNER_NUMBER = "PARNR"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String CUSTOMER_NUMBER = "KUNNR"; public static final String TITLE = "TITLE"; public static final String NAME1 = "NAME1"; public static final String NAME2 = "NAME2"; public static final String NAME3 = "NAME3"; public static final String LOCATION = "NAME4"; public static final String STREET = "STREET"; public static final String CITY = "CITY1"; public static final String PASTAL_CODE = "POST_CODE1"; public static final String PHONE_1 = "TEL_NUMBER1"; public static final String PHONE_2 = "TEL_NUMBER2"; public static final String FAX = "FAX_NUMBER1"; public static final String EMAIL = "EMAIL"; public static final String CHANGE_FLAG = "UPD"; public static final String DIRTY_FLAG = "DIRTYFLG"; } public static final class History { History() { } public static final String HISTORY = "ZKDHIST"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String IDX = "IDX"; public static final String Text = "TEXT"; } public static final class Report { Report() { } public static final String REPORT = "ZKDMOBREP"; public static final String IDX = "IDX"; public static final String GUID = "GUID"; public static final String CREATE_DATE = "ERDAT"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String COMMISSION_NUMBER = "ANLNR"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String PARTICAL_REPAIR = "TEILREP"; public static final String FINAL_REPAIR = "ENDREP"; public static final String REASONING = "FOLGEREP"; public static final String INCIDENT_AB = "STORC"; public static final String BILLING = "VERRC"; public static final String SAFETY_REPORT = "SECRAP"; public static final String CUSTOMER_SUPPORT = "RAPSEND"; public static final String CUSTOMRE_SUPPORT_TEXT = "RAPSENDCOM"; public static final String REPORT_STATUS = "REPORTSTATUS"; public static final String CHECK_LIST = "CHCKLISTE"; public static final String ERROR_ID_1 = "FMC1"; public static final String ERROR_H_1 = "FMH1"; public static final String ERROR_FLAG_1 = "FM1"; public static final String ERROR_ID_2 = "FMC2"; public static final String ERROR_H_2 = "FMH2"; public static final String ERROR_FLAG_2 = "FM2"; public static final String ERROR_ID_3 = "FMC3"; public static final String ERROR_H_3 = "FMH3"; public static final String ERROR_FLAG_3 = "FM3"; public static final String SYSTEM_ERROR = "FMB"; public static final String DISTANCE = "KM"; public static final String EXPENSES = "SPESEN"; public static final String SERVICE_PLAN_MENTH_1 = "SAVLFD1"; public static final String SERVICE_PLAN_MENTH_2 = "SAVLFD2"; public static final String SERVICE_PLAN_MENTH_3 = "SAVLFD3"; public static final String SERVICE_PLAN_MENTH_4 = "SAVLFD4"; public static final String SERVICE_PLAN_MENTH_5 = "SAVLFD5"; public static final String SERVICE_PLAN_MENTH_6 = "SAVLFD6"; public static final String MONTH_YEAR = "SAVERL"; public static final String ORDER_NUMBER = "BSTKD"; public static final String SIGNATURE_GUID = "SIGNGUID"; public static final String SIGNATURE_FLAG = "SIGNFLG"; public static final String SIGNATURE = "SIGNPIC"; public static final String SIGNATURE_INFO = "SIGNINFO"; public static final String WORK_TYPE = "ARBA"; public static final String COLLECTIVELY = "SIGNBUNDLE"; public static final String NO_MATERIAL = "NOMATUSED"; public static final String CYCLE_OF_INSTALLATION = "ZYKINT"; public static final String NO_FORM1 = "NO_FORM1"; public static final String NO_FORM2 = "NO_FORM2"; public static final String NO_FORM3 = "NO_FORM3"; public static final String SERVICE_REFUSED = "BGRSAV"; public static final String OPEN_PENDING = "PEND"; public static final String GOVERNMENT_REPORT = "REGIE"; public static final String CHECKLIST_STATE = "IBSSTATE"; public static final String CHECKLIST_SIA = "IBSSIA"; public static final String CHECKLIST_READY = "IBSREADY"; public static final String CHECKLIST_INSTRUCTION = "IBSINSTR"; public static final String CHECKLIST_VKF = "IBSVKF"; public static final String CHECKLIST_TEST = "IBSTEST"; public static final String SIGNATURE_NAME = "SIGNNAME"; public static final String MON_STK = "MONSTK"; public static final String NEXT_INTERVENTION_DATE = "EDATE"; public static final String STATE_OF_INSTALLATION = "BTRBZUST"; public static final String NEXT_INTERVENTION_CODE = "FLGVRG"; } public static final class JobMessage { JobMessage() { } public static final String JOB_MESSAGE = "ZKDMOBMSG"; public static final String GUID = "GUID"; public static final String MESSAGE_ID = "MSGID"; public static final String MESSAGE_CODE = "MSGC"; public static final String TEXT_1 = "TXT1"; public static final String TEXT_2 = "TXT2"; public static final String MoreText = "TXT3"; } public static final class ReportMaterial { ReportMaterial() { } public static final String REPORT_MATERIAL = "ZKDMATORD"; public static final String IDX = "IDX"; public static final String GUID = "GUID"; public static final String NUMBER = "MATNR"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String AMOUNT = "STCK"; public static final String DELIVERY = "MLIF"; public static final String EXPRESS_DELIVERY = "EXPR"; public static final String ACCOUNT_CODE = "VERRC"; public static final String UNIT = "MAUNIT"; public static final String NAME = "MAKTX"; public static final String PRICE = "PRICE"; public static final String BARCODE = "BARC"; public static final String K14 = "K14"; public static final String EXPLANATION_TEXT = "BARCTXT"; public static final String OTHER_TYPE_FLAG = "BARCFLG"; } public static final class JobReportTime { JobReportTime() { } public static final String JOB_REPORT_TIME = "ZKDMOBRTIM"; public static final String GUID = "GUID"; public static final String IDX = "IDX"; public static final String DATE = "DATUM"; public static final String START_TIME = "VON"; public static final String STOP_TIME = "BIS"; public static final String WORK_TYPE_CODE = "ARBA"; } public static final class CalendarTimeSheet { CalendarTimeSheet() { } public static final String CALENDAR_TIME_SHEET = "CALENDAR"; public static final String DATE = "DATUM"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String STATUS = "STATUS"; public static final String DATE_STRING = "DATUM_TXT"; } public static final class TimeSheet { TimeSheet() { } public static final String TIME_SHEET = "ZKDMATIME"; public static final String IDX = "IDX"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String START_TIME = "VON"; public static final String STOP_TIME = "BIS"; // public static final String C_VBELN = "VBELN"; public static final String COST_CENTER = "KOSTL"; public static final String WORK_TYPE_CODE = "ARBA"; public static final String CALL_FLAG = "PIKETT"; } public static final class Expenses { Expenses() { } public static final String EXPENSES = "ZKDMAEXPNS"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String NO_EXPENSES = "KEINESPSSEN"; public static final String EXPENSES_DATE = "SPSNDAT"; public static final String DAILY_EXPENSES = "TGSPSN"; public static final String VARIOUS_EXPENSES = "DIVSPNS"; public static final String DECUCTION = "ABZG"; public static final String EXPENSES_KEY = "SPNSKEY"; public static final String PIKETT_EXPENSES = "PIKETT"; public static final String EXPENSES_DESCRIPTION = "SPNSTXT"; public static final String OPERATING_HOURS_OF = "BVON"; public static final String OPERATION_HOURS_UP_TO = "BBIS"; public static final String OPERATION_HOURS_TOTAL = "BTOT"; public static final String DEDUCTION_DESCRIPTION = "ABZGTXT"; public static final String COMPENSTION = "VERG"; } public static final class OrderMaterial { OrderMaterial() { } public static final String ORDER_MATERIAL = "ZKDMAMAT"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String AMOUNT = "STCK"; public static final String NUMBER = "MATNR"; public static final String EXPRESS_FLAG = "EXPR"; public static final String VARIOUS_MATERIAL = "MAKTX"; public static final String UNIT = "MAUNIT"; public static final String ORDER_DATE = "BESTDAT"; } public static final class ShortMessage { ShortMessage() { } public static final String SHORT_MESSAGE = "ZSHORTMSG"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String MESSAGE_KEY = "TDNAME"; public static final String SUBJECT = "BETREFF"; public static final String CONFIRM = "BESTAETIGT"; public static final String MESSAGE = "LTEXT"; public static final String STATUS = "STATUS"; public static final String RECEIVED_DATE = "ERHALTEN"; public static final String RECEIVED_TIME = "EINGANG"; } // public static final class ZSHORTMSGREC { // public static final String T_ZSHORTMSGREC = "ZSHORTMSGREC"; // public static final String C_PERNR = "PERNR"; // public static final String C_TDNAME = "TDNAME"; // public static final String C_ERHALTEN = "ERHALTEN"; // } public static final class ServerJob { ServerJob() { } public static final String SERVER_JOB = "ZKDMOBMC"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String STREET = "STREET"; public static final String CITY = "CITY1"; public static final String PASTAL_CODE = "POST_CODE1"; public static final String LOCATION = "NAME4"; public static final String SERVICE_CONTRACT_TYPE = "SAVC"; public static final String MONTH_YEAR = "SAVOFF"; public static final String PERSONAL_NUMBER = "LKDPERNR"; } // public static final class Incident { // Incident() { // } // public static final String Incident = "ZKDCSTORC"; // public static final String ErrorCode = "STORC"; // public static final String ZIFF = "ZIFF"; // public static final String Language = "LANGU"; // public static final String Description = "TEXT"; // } public static final class WorkType { WorkType() { } public static final String WORK_TYPE = "ZARBEITSART"; public static final String CODE = "ARBA"; public static final String GROUP = "FRM"; public static final String TEXT = "TEXT"; public static final String REFRESH_FLAG = "REFRESHED"; public static final String GUARANTEE = "KNZGARENT"; } public static final class ErrorCode { ErrorCode() { } public static final String ERROR_CODE = "ZFCODE"; public static final String CODE = "FC"; public static final String TEXT = "TEXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ReportMessage { ReportMessage() { } public static final String REPORT_MESSAGE = "ZKDMOBMSGC"; public static final String CODE = "MSGC"; public static final String TEXT = "TXT"; public static final String KND = "KND"; public static final String KDZ = "KDZ"; public static final String ABTL = "ABTL"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Material { Material() { } public static final String MATERIAL = "ZKDMOBMAT"; public static final String NUMBER = "MATNR"; public static final String TEXT = "MAKTX"; public static final String CUSTOMER_SERVICE_FLAG = "KDMAT"; public static final String MOUNTING_FLAG = "MONMAT"; public static final String UNIT = "MAUNIT"; public static final String SIZE = "VPME"; public static final String NEW_PRICE = "KBETR_NP"; public static final String SUBSTITUE_PRICE = "KBETR_AP"; public static final String CALCULATION_NEW_PRICE = "KPEIN_NP"; public static final String CALCULATION_SUBSTITUE_PRICE = "KPEIN_AP"; public static final String UNIT_NEW_PRICE = "KMEIN_NP"; public static final String UNIT_SUBSTITUE_PRICE = "KMEIN_AP"; public static final String CURRENCY_NEW_PRICE = "WAERK_NP"; public static final String CURRENCY_SUBSTITUE_PRICE = "WAERK_AP"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class MaterialPerson { MaterialPerson() { } public static final String MATERIAL_PERSON = "ZKDMOBMATPERS"; public static final String NUMBER = "MATNR"; public static final String TEXT = "MAKTX"; public static final String CUSTOMER_SERVICE_FLAG = "KDMAT"; public static final String MOUNTING_FLAG = "MONMAT"; } public static final class Person { Person() { } public static final String PERSON = "ZKDMOBMA"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String LAST_NAME = "NACHN"; public static final String FIRST_NAME = "VORNA"; public static final String INITIAL = "INITS"; public static final String PERSONAL_NUMBER_DEPUTY = "STVPERNR"; public static final String PHONE = "TELNR"; public static final String NUM01 = "NUM01"; public static final String SALES_OFFICE = "VKBUR"; public static final String ABSENT_FROM = "ABWVON"; public static final String ABSENT_TO = "ABWBIS"; public static final String LANGUAGE = "COMLANGU"; public static final String DEVICE_ID = "GID"; public static final String PASSWORD = "PWD"; public static final String REFRESH_FLAG = "REFRESHED"; public static final String WAREHOUSE_NUMBER = "LGORT"; public static final String COMMISSION_NUMBER_FORMAT = "ANLFORMAT"; public static final String EXPENSES_ACTIVE = "SPESENERF"; public static final String PROFILE_TEXT = "IBSTEXT"; } public static final class Employee { Employee() { } public static final String EMPLOYEE = "ZKDSMOBMA"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String LAST_NAME = "NACHN"; public static final String FIRST_NAME = "VORNA"; public static final String INITIAL = "INITS"; public static final String PERSONAL_NUMBER_DEPUTY = "STVPERNR"; public static final String PHONE = "TELNR"; public static final String COMMUNICATION_NUMBER = "NUM01"; public static final String SALES_OFFICE = "VKBUR"; public static final String ABSENT_FROM = "ABWVON"; public static final String ABSENT_TO = "ABWBIS"; public static final String LANGUAGE = "COMLANGU"; public static final String DEVICE_ID = "GID"; public static final String PASSOWRD = "PWD"; public static final String SPECIFIC_FUNCTION = "FKT"; public static final String WAREHOUSE_NUMBER = "LGORT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Drive { Drive() { } public static final String DRIVE = "ZKDMOBANTRTYP"; public static final String CODE = "ANTRC"; public static final String TEXT = "TXT"; public static final String LONG_TEXT = "LTEXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Billing { Billing() { } public static final String BILLING = "ZKDMOBVRCINT"; public static final String CODE = "VRCD"; public static final String TEXT = "TXT"; public static final String JOB_TYPE = "AUART"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Order { Order() { } public static final String ORDER = "ZKSMABEST"; public static final String IDX = "IDX"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String STATUS = "STATUS"; public static final String ANZ = "ANZ"; public static final String CREATED_DATE = "ERFASST"; public static final String SENT_DATE = "GESENDET"; } public static final class JobFile { JobFile() { } public static final String JOB_FILE = "ZKDMOBMV"; public static final String IDX = "IDX"; public static final String GUID = "GUID"; public static final String JOB_NUMBER = "MDLNR"; public static final String JOB_TYPE = "AUART"; public static final String TYPE = "ATTCLAS"; public static final String DESCRIPTION = "DESC"; public static final String SIGN_PIC_AT = "SIGNPIC_AT"; public static final String FORM_TYPE = "FORMTYPE"; public static final String FORM_DESC = "FORMDESC"; public static final String SENT_DATE = "SENTDATE"; } public static final class Reason { Reason() { } public static final String REASON = "ZKDMOBMVCASE"; public static final String CODE = "MVCASETXT"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobReturnReason { JobReturnReason() { } public static final String JOB_RETURN_REASON= "ZKDMOBRETURN"; public static final String CODE = "RETTXT"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobMonText { JobMonText() { } public static final String JOB_MON_TEXT = "ZKDMOBMONTXT"; public static final String CODE = "MONTXT"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobFormDesc { JobFormDesc() { } public static final String JOB_FORM_DESC = "ZKDMOBFORMDESC"; public static final String CODE = "FORMDESC"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class JobNoForm{ JobNoForm() { } public static final String JOB_NO_FORM = "ZKDMOBNOFORM"; public static final String CODE = "NO_FORM"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Incident{ Incident() { } public static final String INCIDENT = "ZKDMOBSTORC"; public static final String CODE = "STORC"; public static final String TEXT = "TXT"; public static final String FCT = "FCT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Email { Email() { } public static final String EMAIL = "ZKDSMOBEMAIL"; public static final String JOB_NUMBER = "MLDNR"; public static final String JOB_TYPE = "AUART"; public static final String PARTNER_NUMBER = "PARNR"; public static final String TEXT = "EMAIL"; } public static final class Invoice{ Invoice() { } public static final String INVOICE = "ZKDMOBVERRC"; public static final String CODE = "VERRC"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class InternalWorkType { InternalWorkType() { } public static final String INTERNAL_WORK_TYPE = "ZKDMOBARBA"; public static final String CODE = "ARBA"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ReportMeasurement { ReportMeasurement() { } public static final String REPORT_MEASUREMENT = "ZKDMOBMEAS"; public static final String GUID = "GUID"; public static final String MEASURING_POINT = "PNT"; public static final String COMMISSION_NUMBER = "VBELN"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String MEASUREMENT = "MEAS"; public static final String DYNAMIC_POWER_PEAK_VALUE = "FDYN"; public static final String DYNAMIC_TIME = "TDYN"; public static final String STATIC_END_POWER = "FEND"; public static final String DEVICE_TYPE = "DEVTYPE"; public static final String SN_OF_DEVICE = "SNUMBER"; public static final String CALIBRATION_DATE = "CALDAT"; } public static final class VariousExpenses { VariousExpenses() { } public static final String VARIOUS_EXPENSES = "ZKDMAEXPNSDIV"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String IDX = "IDX"; public static final String AMOUNT = "DIVSPNS"; public static final String EXPENSES_CODE = "SPNSTXT"; } public static final class VariousExpenseFile { VariousExpenseFile() { } public static final String VARIOUS_EXPENSE_FILE = "ZKDMAESPNSPICS"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String DATE = "DATUM"; public static final String IDX = "IDX"; public static final String DESCRIPTION = "DESC"; public static final String FORM_TYPE = "FORMTYP"; public static final String SIGN_PIC_AT = "SIGNPIC_AT"; } public static final class AbsenceNotification { AbsenceNotification() { } public static final String ABSENCE_NOTIFICATION = "ZKDMAABSENCE"; public static final String GUID = "GUID"; public static final String DATE = "ERFDT"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String ABSENCE_TYPE = "ABWGRND"; public static final String DATE_FROM = "DATUMVON"; public static final String DATE_TO = "DATUMBIS"; public static final String TIME_FROM = "ZEITVON"; public static final String TIME_TO = "ZEITBIS"; public static final String TEXT = "TEXT"; } public static final class AbsenceType { AbsenceType() { } public static final String ABSENCE_TYPE = "ZKDMOBABSC"; public static final String ABWGRND = "ABWGRND"; public static final String LANGUAGE = "LANGU"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ServiceRefused { ServiceRefused() { } public static final String SERVICE_REFUSED = "ZKDMOBBEGRSAV"; public static final String SAVRET = "SAVRET"; public static final String LANGUAGE = "SPRAS"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Checklist { Checklist() { } public static final String CHECK_LIST = "ZKDMOBCHKLIST"; public static final String CODE = "CHCKLISTE"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Progress { Progress() { } public static final String PROGRESS = "ZKDMOBMONSTK"; public static final String CODE = "MONSTK"; public static final String SPRAS = "SPRAS"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class Form { Form() { } public static final String FORM = "FORM"; public static final String ID = "Id"; public static final String VERSION = "Version"; public static final String STATUS = "Status"; public static final String VALID_FROM = "ValidFrom"; public static final String VALID_TO = "ValidTo"; public static final String NAME = "Name"; public static final String DESCRIPTION = "Description"; } public static final class FormItem { FormItem() { } public static final String FORMITEM = "FORMITEM"; public static final String FORM_ID = "FormId"; public static final String FORM_VERSION = "FormVersion"; public static final String ID = "Id"; public static final String FORM_ITEM_TYPE = "FormItemType"; public static final String SEQUENCE = "Sequence"; public static final String LABEL = "Label"; public static final String MANDATORY = "Mandatory"; public static final String CARD_NAME = "CardName"; public static final String OBSOLETE = "Obsolete"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String EMPTY_TEXT = "EmptyText"; public static final String GROUP_NAME = "GroupName"; public static final String MAX_STRING_SIZE = "MaxStringSize"; public static final String VALIDATION_REGEX = "ValidationRegex"; public static final String MULTILINE = "Multiline"; public static final String FORMAT = "Format"; public static final String MIN_VALUE = "MinValue"; public static final String MAX_VALUE = "MaxValue"; } public static final class FormDependency { FormDependency() { } public static final String FORMDEPENDENCY = "FORMDEPENDENCY"; public static final String FORM_ID = "FormId"; public static final String FORM_VERSION = "FormVersion"; public static final String FORM_ITEM_ID = "FormItemId"; public static final String DEPENDENCY = "Dependency"; public static final String CHECKBOX_FORM_ITEM_ID = "CheckboxFormItemId"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String VALUE_ID = "ValueId"; } public static final class FormValueList { FormValueList() { } public static final String FORMVALUELIST = "FORMVALUELIST"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String VALUE_ID = "ValueId"; // public static final String NAME = "Name"; public static final String SEQUENCE = "Sequence"; public static final String DEFAULT_VALUE = "DefaultValue"; public static final String VALUE = "Value"; } public static final class FormInstance { FormInstance() { } public static final String FORMINSTANCE = "FORMINSTANCE"; public static final String GUID = "GUID"; public static final String FORM_ID = "FormId"; public static final String FORM_VERSION = "FormVersion"; public static final String FORM_ITEM_ID = "FormItemId"; public static final String VALUE_LIST_ID = "ValueListId"; public static final String VALUE_ID = "ValueId"; public static final String FORM_ITEM_TYPE = "FormItemType"; public static final String STRING_VALUE = "StringValue"; public static final String BOOLEAN_VALUE = "BooleanValue"; public static final String FLOAT_VALUE = "FloatValue"; public static final String ATTACHMENT_VALUE = "AttachmentValue"; } public static final class StateOfInstallation { StateOfInstallation() { } public static final String STATE_OF_INSTALLATION = "ZKDMOBBTRBZUST"; public static final String CODE = "BTRBZUST"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class NextIntervention { NextIntervention() { } public static final String NEXT_INVENTION = "ZKDMOBFLGVRG"; public static final String CODE = "FLGVRG"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class VehicleInventory { VehicleInventory() { } public static final String VEHICLE_INVENTORY = "ZKDMOBFZLGSYNC"; public static final String STORAGE_LOCATION = "LGORT"; public static final String MATERIAL_NUMBER = "MATNR"; public static final String MATERIAL_NAME = "MAKTX"; public static final String STOCK_OF_MATERIAL = "LABST"; public static final String UNIT = "MEINS"; } public static final class Inventory { Inventory() { } public static final String INVENTORY = "ZKDMOBFZLG"; public static final String WAREHOUSE_NUMBER = "LGORT"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String NAME = "NAME_TEXT"; public static final String WAREHOUSE = "LGKNZ"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class ReceiptOfGoods { ReceiptOfGoods() { } public static final String RECEIPT_OF_GOODS = "ZKDMOBWERET"; public static final String CODE = "WEGRND"; public static final String TEXT = "TXT"; public static final String REFRESH_FLAG = "REFRESHED"; } public static final class MaterialMovement { MaterialMovement() { } public static final String MATRIAL_MOVEMENT = "ZKDMOBFZGMBEW"; public static final String GUID = "GUID"; public static final String ORDER_NUMBER = "EBELN"; public static final String ORDER_POSITION = "EBELP"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String MATERIAL_NUMBER = "MATNR"; public static final String FROM = "LGORT_FROM"; public static final String TO = "LGORT_TO"; public static final String ENTRY_COUNT = "ENTRY_QNT"; public static final String ENTRY_UNIT = "ENTRY_UOM"; public static final String RECEIPT_OF_GOODS = "WEGRND"; public static final String BARCODE = "BARC"; public static final String BARCODE_TEXT = "BARCTXT"; public static final String PERSONAL_NUMBER_CONFIRMED = "CONF_PERNR"; } public static final class DeliveryList { DeliveryList() { } public static final String DELIVERY_LIST = "ZKDMOBDELVRYLIST"; public static final String GUID = "GUID"; public static final String PERSONAL_NUMBER = "PERNR"; public static final String ORDER_NUMBER = "EBELN"; public static final String ORDER_POSITION = "EBELP"; public static final String MATERIAL_NUMBER = "MATNR"; public static final String MATERIAL_NAME = "MAKTX"; public static final String FROM = "LGORT_FROM"; public static final String TO = "LGORT_TO"; public static final String WAREHOUSE = "LGKNZ"; public static final String ENTRY_COUNT = "ENTRY_QNT"; public static final String ENTRY_UNIT = "ENTRY_UOM"; public static final String DATE = "WADAK"; public static final String STATUS = "KNZDLVRY"; } } package ch.mfiles.kaba.kolibri.common.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ui.Image; public class ImagesUtil { public static final Log log = LogFactory.getLog(ImagesUtil.class); private static ImagesUtil instance = null; private Application app; private ImagesUtil() { } public static final ImagesUtil getInstance(Application application) { if (instance == null) { instance = new ImagesUtil(); } instance.app = application; return instance; } public ImagesUtil(Application application) { app = application; } public static enum Images { ADD_BLACK , START_TIME_DISABLED , START_TIME , STOP_TIME , SEND_DISABLED_BLACK , SEND_BLACK , SEND_WHITE , DELETE_DISABLED_BLACK , DELETE_BLACK , EDIT , PHONE_DISABLED , PHONE , EMAIL_DISABLED , EMAIL , EXIT_DISABLED , EXIT , CONTACT_PHONE_DISABLED , CONTACT_PHONE , LIST_DISABLED , LIST , SETTING_DISABLED , SETTING , UPDATE_DISABLED , UPDATE , HELP_DISABLED , HELP , INFO_DISABLED , INFO , INFO_WHITH , SUPERVISOR_ACCOUNT_DISABLED , SUPERVISOR_ACCOUNT , SETTING_APP_DISABLED , SETTING_APP , SYSTEM_UPDATE_DISABLED , SYSTEM_UPDATE , INFORMATION_DISABLED , INFORMATION , SAVE_WHITE , SAVE_WHITE_DISABLED , BACK_WHITE , BACK_WHITE_DISABLED , DOWNLOAD_DISABLED_BLACK , DOWNLOAD_BLACK , DOWNLOAD_WHITE , CLOSE_WHITE , SEARCH_WHITE , ASSIGNMENT_IND_DISABLED , ASSIGNMENT_IND , ASSIGNMENT_TURNED_IN_DISABLED , ASSIGNMENT_TURNED_IN , SIGNATURE_DISABLED_BLACK , SIGNATURE_BLACK , SIGNATURE_WHITE , RESTORE_BLACK , RESTORE_WHITE , YOUTUBE_SEARCHED_BLACK , YOUTUBE_SEARCHED_WHITE , ADD_WHITE , DELETE_WHITE , CAMERA_BLACK , CAMERA_WHITE , SEND_DISABLED_WHITE , PLAY_WITH_CIRCLE , PAGE_VIEW_DISABLED_BLACK , PAGE_VIEW_BLACK , PAGE_VIEW_WHITE , INFO_OUTLINE_BLACK , INFO_OUTLINE_DISABLED_BLACK , INFO_OUTLINE_WHITE , MENU , MENU_WHITE , ADD_DISABLED_WHITE , DELETE_DISABLED_WHITE , CAMERA_DISABLED_WHITE , ALARM_BLACK , ALARM_RED , PHOTO_LIBRARY_BLACK , PICTURE_AS_PDF_BLACK , SCHEDULE_BLACK , SCHEDULE_DISABLED_BLACK , CHECK_SOME , CHECK_CHECKED , CHECK_UNCHECKED , CHECK , CHECK_WHITE , DOWNLOAD_SUCCESS , DOWNLOAD_ERROR , DONE_BLACK , DONE_WHITE , REMOTE_BLACK , ABSENCE_BLACK , OFFLINE_SHARE , SEARCH_FILE_BLACK , SEARCH_FILE_DISABLED , ADD_PHOTO_BLACK , WRENCH_BLACK , WRENCH_DISABLED , UPDATE_WHITE , SHOPPING_CART_BLACK , SHOPPING_CART_DISABLED , SHOPPING_CART_WHITE , TRUCK_BLACK , TRUCK_WHITE , SHOPPING_CART_ADD_BLACK , SHOPPING_CART_ADD_DISABLED , SHOPPING_CART_ADD_WHITE , CAMERA_DISABLED_BLACK } public Image getImage(Images image) { return getImage(image, null); } public Image getImage(Images image, Integer dpi){ Image result = null; switch (image) { case ADD_BLACK: return setImageDpi("images/ic_add_black_24dp.png", dpi); //$NON-NLS-1$ case BACK_WHITE: return setImageDpi("images/ic_arrow_back_white_48dp.png", dpi); //$NON-NLS-1$ case BACK_WHITE_DISABLED: return setImageDpi("images/ic_arrow_back_white_disabled_48dp.png", dpi); //$NON-NLS-1$ case START_TIME_DISABLED: return setImageDpi("images/ic_play_arrow_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case START_TIME: return setImageDpi("images/ic_play_arrow_black_24dp.png", dpi); //$NON-NLS-1$ case STOP_TIME: return setImageDpi("images/ic_stop_black_24dp.png", dpi); //$NON-NLS-1$ case CLOSE_WHITE: return setImageDpi("images/ic_clear_white_48dp.png", dpi); //$NON-NLS-1$ case SAVE_WHITE: return setImageDpi("images/ic_save_white_48dp.png", dpi); //$NON-NLS-1$ case SAVE_WHITE_DISABLED: return setImageDpi("images/ic_save_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case SEND_DISABLED_BLACK: return setImageDpi("images/ic_send_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SEND_BLACK: return setImageDpi("images/ic_send_black_24dp.png", dpi); //$NON-NLS-1$ case SEND_WHITE: return setImageDpi("images/ic_send_white_24dp.png", dpi); //$NON-NLS-1$ case SEND_DISABLED_WHITE: return setImageDpi("images/ic_send_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case DELETE_DISABLED_BLACK: return setImageDpi("images/ic_delete_forever_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case DELETE_BLACK: return setImageDpi("images/ic_delete_forever_black_24dp.png", dpi); //$NON-NLS-1$ case EDIT: return setImageDpi("images/ic_mode_edit_black_24dp.png", dpi); //$NON-NLS-1$ case SEARCH_WHITE: return setImageDpi("images/ic_search_white_24dp.png", dpi); //$NON-NLS-1$ case PHONE_DISABLED: return setImageDpi("images/ic_phone_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case PHONE: return setImageDpi("images/ic_phone_black_24dp.png", dpi); //$NON-NLS-1$ case CONTACT_PHONE_DISABLED: return setImageDpi("images/ic_contact_phone_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case CONTACT_PHONE: return setImageDpi("images/ic_contact_phone_black_24dp.png", dpi); //$NON-NLS-1$ case EMAIL_DISABLED: return setImageDpi("images/ic_email_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case EMAIL: return setImageDpi("images/ic_email_black_24dp.png", dpi); //$NON-NLS-1$ case EXIT_DISABLED: return setImageDpi("images/ic_exit_to_app_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case EXIT: return setImageDpi("images/ic_exit_to_app_black_24dp.png", dpi); //$NON-NLS-1$ case LIST_DISABLED: return setImageDpi("images/ic_list_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case LIST: return setImageDpi("images/ic_list_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING_DISABLED: return setImageDpi("images/ic_settings_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING: return setImageDpi("images/ic_settings_black_24dp.png", dpi); //$NON-NLS-1$ case UPDATE_DISABLED: return setImageDpi("images/ic_update_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case UPDATE: return setImageDpi("images/ic_update_black_24dp.png", dpi); //$NON-NLS-1$ case HELP_DISABLED: return setImageDpi("images/ic_help_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case HELP: return setImageDpi("images/ic_help_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_DISABLED: return setImageDpi("images/ic_info_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case INFO: return setImageDpi("images/ic_info_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_WHITH: return setImageDpi("images/ic_info_white_24dp.png", dpi); //$NON-NLS-1$ case SUPERVISOR_ACCOUNT_DISABLED: return setImageDpi("images/ic_supervisor_account_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SUPERVISOR_ACCOUNT: return setImageDpi("images/ic_supervisor_account_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING_APP_DISABLED: return setImageDpi("images/ic_settings_applications_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SETTING_APP: return setImageDpi("images/ic_settings_applications_black_24dp.png", dpi); //$NON-NLS-1$ case SYSTEM_UPDATE_DISABLED: return setImageDpi("images/ic_system_update_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SYSTEM_UPDATE: return setImageDpi("images/ic_system_update_black_24dp.png", dpi); //$NON-NLS-1$ case INFORMATION_DISABLED: return setImageDpi("images/ic_perm_device_information_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case INFORMATION: return setImageDpi("images/ic_perm_device_information_black_24dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_DISABLED_BLACK: return setImageDpi("images/ic_file_download_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_BLACK: return setImageDpi("images/ic_file_download_black_24dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_WHITE: return setImageDpi("images/ic_file_download_white_48dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_IND_DISABLED: return setImageDpi("images/ic_assignment_ind_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_IND: return setImageDpi("images/ic_assignment_ind_black_24dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_TURNED_IN_DISABLED: return setImageDpi("images/ic_assignment_turned_in_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case ASSIGNMENT_TURNED_IN: return setImageDpi("images/ic_assignment_turned_in_black_24dp.png", dpi); //$NON-NLS-1$ case SIGNATURE_DISABLED_BLACK: return setImageDpi("images/ic_gesture_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case SIGNATURE_BLACK: return setImageDpi("images/ic_gesture_black_24dp.png", dpi); //$NON-NLS-1$ case SIGNATURE_WHITE: return setImageDpi("images/ic_gesture_white_24dp.png", dpi); //$NON-NLS-1$ case RESTORE_BLACK: return setImageDpi("images/ic_restore_page_black_24dp.png", dpi); //$NON-NLS-1$ case RESTORE_WHITE: return setImageDpi("images/ic_restore_page_white_24dp.png", dpi); //$NON-NLS-1$ case YOUTUBE_SEARCHED_BLACK: return setImageDpi("images/ic_youtube_searched_for_black_24dp.png", dpi); //$NON-NLS-1$ case YOUTUBE_SEARCHED_WHITE: return setImageDpi("images/ic_youtube_searched_for_white_24dp.png", dpi); //$NON-NLS-1$ case ADD_WHITE: return setImageDpi("images/ic_add_white_24dp.png", dpi); //$NON-NLS-1$ case DELETE_WHITE: return setImageDpi("images/ic_delete_forever_white_24dp.png", dpi); //$NON-NLS-1$ case CAMERA_BLACK: return setImageDpi("images/ic_camera_black_24dp.png", dpi); //$NON-NLS-1$ case CAMERA_WHITE: return setImageDpi("images/ic_camera_white_24dp.png", dpi); //$NON-NLS-1$ case PLAY_WITH_CIRCLE: return setImageDpi("images/ic_play_circle_outline_black_24dp.png", dpi); //$NON-NLS-1$ case PAGE_VIEW_DISABLED_BLACK: return setImageDpi("images/ic_pageview_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case PAGE_VIEW_BLACK: return setImageDpi("images/ic_pageview_black_24dp.png", dpi); //$NON-NLS-1$ case PAGE_VIEW_WHITE: return setImageDpi("images/ic_pageview_white_24dp.png", dpi); //$NON-NLS-1$ case INFO_OUTLINE_BLACK: return setImageDpi("images/ic_info_outline_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_OUTLINE_DISABLED_BLACK: return setImageDpi("images/ic_info_outline_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case INFO_OUTLINE_WHITE: return setImageDpi("images/ic_info_outline_white_24dp.png", dpi); //$NON-NLS-1$ case MENU: return setImageDpi("images/menu.png", dpi); //$NON-NLS-1$ case MENU_WHITE: return setImageDpi("images/menu_white.png", dpi); //$NON-NLS-1$ case ADD_DISABLED_WHITE: return setImageDpi("images/ic_add_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case DELETE_DISABLED_WHITE: return setImageDpi("images/ic_delete_forever_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case CAMERA_DISABLED_WHITE: return setImageDpi("images/ic_camera_disabled_white_24dp.png", dpi); //$NON-NLS-1$ case ALARM_BLACK: return setImageDpi("images/ic_alarm_black_24dp.png", dpi); //$NON-NLS-1$ case ALARM_RED: return setImageDpi("images/ic_alarm_red_24dp.png", dpi); //$NON-NLS-1$ case PHOTO_LIBRARY_BLACK: return setImageDpi("images/ic_photo_library_black_24dp.png", dpi); //$NON-NLS-1$ case PICTURE_AS_PDF_BLACK: return setImageDpi("images/ic_picture_as_pdf_black_24dp.png", dpi); //$NON-NLS-1$ case SCHEDULE_BLACK: return setImageDpi("images/ic_schedule_black_24dp.png", dpi); //$NON-NLS-1$ case SCHEDULE_DISABLED_BLACK: return setImageDpi("images/ic_schedule_disabled_black_24dp.png", dpi); //$NON-NLS-1$ case CHECK_SOME: return setImageDpi("images/ic_checkbox_some_60dp.png", dpi); //$NON-NLS-1$ case CHECK_CHECKED: return setImageDpi("images/ic_checkbox_checked_60dp.png", dpi); //$NON-NLS-1$ case CHECK_UNCHECKED: return setImageDpi("images/ic_checkbox_unchecked_60dp.png", dpi); //$NON-NLS-1$ case CHECK: return setImageDpi("images/ic_check_512dp.png", dpi); //$NON-NLS-1$ case CHECK_WHITE: return setImageDpi("images/ic_check_white_512dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_SUCCESS: return setImageDpi("images/ic_download_success_512dp.png", dpi); //$NON-NLS-1$ case DOWNLOAD_ERROR: return setImageDpi("images/ic_download_error_512dp.png", dpi); //$NON-NLS-1$ case DONE_BLACK: return setImageDpi("images/ic_done_black_24db.png", dpi); //$NON-NLS-1$ case DONE_WHITE: return setImageDpi("images/ic_done_white_24db.png", dpi); //$NON-NLS-1$ case REMOTE_BLACK: return setImageDpi("images/ic_remote_black_24dp.png", dpi); //$NON-NLS-1$ case ABSENCE_BLACK: return setImageDpi("images/ic_absence_black_24dp.png", dpi); //$NON-NLS-1$ case OFFLINE_SHARE: return setImageDpi("images/ic_offline_share_black_24dp.png", dpi); //$NON-NLS-1$) case SEARCH_FILE_BLACK: return setImageDpi("images/ic_search_file_black_72dp.png", dpi); //$NON-NLS-1$) case SEARCH_FILE_DISABLED: return setImageDpi("images/ic_search_file_disabled_72dp.png", dpi); //$NON-NLS-1$) case ADD_PHOTO_BLACK: return setImageDpi("images/ic_add_photo_black_32dp.png", dpi); //$NON-NLS-1$) case WRENCH_BLACK: return setImageDpi("images/ic_wrench_black_72dp.png", dpi); //$NON-NLS-1$) case WRENCH_DISABLED: return setImageDpi("images/ic_wrench_disabled_black_72dp.png", dpi); //$NON-NLS-1$) case UPDATE_WHITE: return setImageDpi("images/ic_update_white_24dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_BLACK: return setImageDpi("images/ic_shopping_cart_black_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_DISABLED: return setImageDpi("images/ic_shopping_cart_disabled_white_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_WHITE: return setImageDpi("images/ic_shopping_cart_white_128dp.png", dpi); //$NON-NLS-1$ case TRUCK_BLACK: return setImageDpi("images/ic_truck_black_128dp.png", dpi); //$NON-NLS-1$ case TRUCK_WHITE: return setImageDpi("images/ic_truck_white_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_ADD_BLACK: return setImageDpi("images/ic_shopping_cart_add_black_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_ADD_DISABLED: return setImageDpi("images/ic_shopping_cart_add_disabled_white_128dp.png", dpi); //$NON-NLS-1$ case SHOPPING_CART_ADD_WHITE: return setImageDpi("images/ic_shopping_cart_add_white_128dp", dpi); //$NON-NLS-1$ case CAMERA_DISABLED_BLACK: return setImageDpi("images/ic_camera_disabled_black_24dp.png", dpi); //$NON-NLS-1$ default: break; } return result; } private Image setImageDpi(String imageUrl, Integer dpi) { if (dpi != null) { return app.getImage(imageUrl, dpi); } else { return app.getImage(imageUrl); } } } #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface # ä=\u00E4, Ä=\u00C4, ö=\u00F6, ü=\u00FC, AppointmentDate = Einsatz: AtLeastXImagesNecessary = Mindestens {0} Bilder erforderlich BluetoothIsNotTurnOn = Bluetooth ist nicht eingeschaltet. CHF = CHF CannotCreateOrder = Bestellung kann nicht erstellt werden. CannotSaveDocAlreadyExist = Kann nicht gespeichert werden, {0} existiert bereits. Checklist = Checkliste IBS ChecklistInstructionText = Die Anlage wurde dem Betreiber \u00FCbergeben, Instruktion durchgef\u00FChrt und ein Betreiberhandbuch abgegeben. ChecklistReadyText = Die Anlage ist gem\u00E4ss Auftrag komplett und betriebsbereit. ChecklistSIAText = Die Anlage entspricht in allen Teilen SIA 343 (DIN 18650) sowie Tornorm-Nr. SN 12453. ChecklistStateText = Alle montierten Elemente der Anlage sind in einwandfreiem Zustand und weisen keine Sch\u00E4den auf (Farbe, Glas usw.). ChecklistTestText = Brand- und Wertschutzfunktionen angeschlossen und getestet. ChecklistVKFText = Instruktion an den Betreiber erfolgt. Wenn nein, Betreiberhandbuch auf Anlage. Die Dokumentation VKF wird dem Auftraggeber zugestellt. ChooseForm = Formularauswahl Client = Kunde ClientNumber = Kundennummer Contact = Ansprechperson Customer = Auftraggeber DeleteMeasurement = Messung L\u00F6schen? DeleteReport = Rapport l\u00F6schen? DiscardMeasurement = Messung verwerfen? DoYouReallyWantToDeleteTheCompleteReport = Wollen Sie wirklich den vollst\u00E4ndigen Rapport l\u00F6schen?\nErfasste Rapportzeiten, Material, Unterschrift usw. werden ebenfalls gel\u00F6scht. Document = Dokument DocumentReqired = Dokument {0} verlangt. DocumentsWillBeLost = Dokumente werden gel\u00F6scht, wollen Sie fortfahren? Done = Erledigt E = E EstateManagement = Verwaltung FormReqired = Formulare {0} verlangt. Forms = Formulare GoodsIssue = Warenausgang GoodsReceipt = Wareneingang Goodwill = Kulanz Guarantee = Garantie GuaranteeMaterial = Materialr\u00FCcklieferung GuaranteeTitle = Garantie ImageReqired = Bild {0} verlangt. Important = Wichtiges JobFinishedSendReport = Ist der Auftrag abgeschlossen? Rapport senden? K14Material = K-Material Measurement = Messung MeasurementComplete = Messung: Erfasst. MeasurementInComplete = Messung unvollst\u00E4ndig MeasurementMaximum = Max. {0} Messungen m\u00F6glich NoPhoneNumber = Keine Tel. Nummer Object = Objekt Odered = Bestellt OrderNo = Auftr. Nr. OverwriteAnExistingMeasurement = Die erfassten Daten werden gel\u00F6scht. Fortfahren? Owner = Eigent\u00FCmer Partner = Partner Planed = Geplant PleaseEnterATime = Bitte Zeit eingeben Receiver = Warenempf\u00E4nger ReleaseDevice = Ger\u00E4t freigeben RescheduleJob = Auftrag neu planen SAV = SAV SAVResponsible = SAV Verantwortlicher Service = Service Signature = Unterschrift TheCapturedDataWillBeDeleted = Die erfassten Daten werden gel\u00F6scht. Fortfahren? TheFormIsDiscardedContinue = Das Formular wird verworfen. Fortfahren? TheSelectedArticleIsNotInMasterdata = Der gew\u00E4hlte Artikel ist in den Stammdaten nicht vorhanden. Bitte Support kontaktieren. TheSelectedItemIsNotInStockContinue = Der gew\u00E4hlte Artikel ist nicht im Lagerbestand vorhanden. Fortfahren? UserName = MA-Name VC = VC WrongFormatXX-XXXX-XXX/XX = Falsches Format (XX-XXXX-XXX/XX). YouAreSingingNReport = Sie unterzeichnen {0} Rapporte. aborted = abgebrochen\u2026 absenceList = Abwesenheitsmeldung absenceNotification = Abwesenheit erfassen absenceType = Abwesenheitsart absences = Abwesenheiten accept = Annehmen active = Aktiv add = Hinzuf\u00FCgen addition = Zusatz additionalDelivery = Nachlieferung address = Adresse addressDoesNotExist = {0}-Adresse nicht gefunden. addresses = Adressen agregatedSignature = Sammelunterschrift allowedTime = Vorgabezeit amount = Anzahl appointment = Termin appointmentDefined = Fixtermin areYouSureThatYouWantToDeleteRecord = Soll der Eintrag gel\u00F6scht werden? areYouSureWantToDeleteRecord = Eintrag l\u00F6schen? artNo = Artikelnummer articleName = Artikelbezeichnung articleNotINInventory = Artikel nicht in Bestand vorhanden! articleNumber = Artikelnummer articleScan = Artikel Scan back = Zur\u00FCck backOffice = Innendienst bemHistory = Bem. / History billing = Verrechnung camera = Kamera cancel = Abbrechen captured = Erfasst caseHandler = Sachbearbeiter change = \u00C4ndern changeAddress = Adresse \u00E4ndern changesWillBeLost = \u00C4nderungen werden verworfen, wollen Sie weiterfahren? charging = Verrechnung checkCycles = Zyklen erf. checkList = Checkliste IBS city = Ort clear = Reset clock = Uhr codeReturnDelivery = Code R\u00FCcklieferung collectiveSignature = Sammelunterschrift commNo = Komm.-Nr. commNoCheck = Komm.Nr.-Check commNotCorrect = Komm.-Nr. falsch? commissionNumber = Kommissionsnummer commissionNumberNotCorrectWillSaveEmptyString = Kommissionsnummer falsch (0XXXXXX-XX) completed = Erledigt configurations = Einstellungen confirm = Best\u00E4tigen confirmation = Best\u00E4tigung consequentialRepair = Folgereparatur coordinateAppointment = Termin absprechen! correct = Korrekt correctCommissionNumber = Korrekte Kommissionsnummer eingeben. costumerRemark = Kunden Bem. costumerReport = Kundenrapport costumerService = Kundendienst createJob = Auftrag erstellen createREPJob = REP Job erstellen customizeYourInfo = Infos anpassen. cycleOfInstallation = Zykluszahl date = Datum dateFrom = Datum von dateTo = Datum bis delete = L\u00F6schen deleteCompleteReport = GESAMTEN RAPPORT L\u00D6SCHEN deliverDate = Lieferdatum delivered = Geliefert deliveredArticles = Ausgeliefert department = Abteilung description = Beschreibung designation = Artikelbezeichnung deviceMirroring = Ger\u00E4t freigeben discardForm = Formular verwerfen? distance = Distanz distancesBetween0To999kmAreAppropriate = Es sind Distanzen zwischen 0 und 999km zugelassen. doYouReallyWantToDeleteXShortMessagesAtOnce = M\u00F6chten Sie wirklich {0} Kurznachrichten sofort l\u00F6schen? doYouReallyWantToLoadXjobsAtOnce = Wollen Sie wirklich {0} Auftr\u00E4ge gleichzeitig laden? doYouWantToDeleteJob = Auftrag l\u00F6schen? doYouWantToDeleteThisSignature = M\u00F6chten Sie die Unterschrift wirklich l\u00F6schen? doYouWantToGetOrder = Auftrag runterladen (MLDNR :{0})? done = Erledigt download = Runterladen downloadOrder = Auftrag runterladen downloadOrder(SAP) = Auftrag runterladen (SAP) drive = Antriebstyp duplicatedMaterialNumber = Artikel {0} schon verhanden {1} kann nicht hinzugef\u00FCgt werden. duration = Bestand editReport = Rapport editieren email = E-Mail employee = Mitarbeitende employees = Mitarbeitende endRepair = Erledigt enteredValueIsInTheFuturePleaseEnterValidTime = Der eingegebene Wert liegt in der Zukunft. Bitte geben Sie einen g\u00FCltigen Wert ein. enterprise = Firma erase = L\u00F6schen error = Fehler errorCode = FM errorMessages = Fehlermeldungen: ers = Nachlieferung existingEntriesFromCannotAddEntryOn = Bestehende Eintr\u00E4ge vom {0}, kann {1} nicht hinzuf\u00FCgen exists = Vorhanden exit = Beenden exitServiceApplication = Beenden expenses = Spesen explanationForReturn = Grund R\u00FCcklieferung external = z. Hd. Kunde failure = St\u00F6rung fax = Fax fileDeleted = Datei gel\u00F6scht. finalRepair = Endreparatur finalized = Erledigt finished = Erledigte firstName = Vorname followup = Folgereparatur forward = Weiterleiten from = Von fromImventory = Aus Lager gilgenCommonApplicationIsNotInstalled = Die Common-Applikation ist nicht installiert. Die Service-Applikation kann darum nicht gestartet werden. gilgenMaterialApplicationIsNotInstalled = Die Material-Applikation ist nicht installiert! gilgenTimesheetApplicationIsNotInstalled = Die Timesheet-Applikation ist nicht installiert! governmentReport = Regierapport history = Historie hours = Std. hrs = Std. image = Bild images = Bilder inProgress = laufend incidentA = St\u00F6rung A incidentB = St\u00F6rung B incomingArticle = Wareneingang incomingArticleTitle = Warenbewegung incomingArticleWithoutListEntry = Eingang buchen info = Info information = Information insertFixedMasterDataFile = Stammdaten laden(File) insertingMasterData = Stammdaten einf\u00FCgen ... installGilgenCommonApplicationFirst = Bitte zuerst die Common-Applikation installieren. Danach die Installation fortsetzen und Kolibri neu starten. installationError = Anlagefehler installationState = Betriebszustand internal = Intern interventionType = Folgevorgang invalid = Falsch invalidBarcodeGuarantee = Ung\u00FCltiger Barcode invalidCommissionNumber = Ung\u00FCltige Kommissionsnummer invalidJobNumber = Ung\u00FCltige Auftragsnummer invalidKomNo = Falsche Komm.-Nr. inventoryInformations = Lagerinfos inventoryName = Lagername inventoryNumber = Lagernummer inventoryStock = Lagerbestand job = Auftrag job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = Der gew\u00E4hlte Auftrag konnte nicht gel\u00F6scht werden. Bitte \u00FCbertragen Sie offene Rapporte und Zeiten. jobDeleted = Auftrag gel\u00F6scht jobDetails = Jobdetails jobEdit = Rapportbearbeitung jobInfo = Job-Info jobList = Jobliste jobNumber = Auftragsnummer jobState = Auftragsstatus jobTime = Auftragszeit jobsSelected = {0} / {1} Auftr\u00E4gen selektiert lastName = Nachname link = Link listIsEmptyNoTimeEntryToDelete = Liste ist leer, Zeit kann nicht gel\u00F6scht werden listOfEmployees = Mitarbeiterliste location = Anlage maintenance = Service maintenanceCode = SAV Code maintenanceDone = Service ausgef\u00FChrt maintenanceMonths = Service-Monate maintenancePlanned = SAV geplant masterDataSuccessfullyRefreshed = Stammdaten erfolgreich aktualisiert material = Material materialApp = Material App materialName = Artikelbezeichnung materialNumber = Artikelnummer materialWasDeleted = Artikel wurde gel\u00F6scht. materialWithThisNameAlreadyExists = Material mit diesem Namen existiert bereits. materialWithThisNumberAlreadyExists = Material mit dieser Nummer existiert bereits. maximumOfCheckdBoxesIs6 = Maximale Auswahl: 6 messageToChef = Mitteilung Vorgesetzter messageToCostumer = Mitteilung Kunde messageToKDZ = Mitteilung KDZ messages = Mitteilungen month = Monat moreInformations = Erw. Komm. mtDone = SAV erledigt mtPlanned = SAV geplant name = Bezeichung nameOfInventory = Lager new = Neu newInventory = Neues Lager newJob = Neuer Auftrag newReport = Neuer Rapport newTimeEntryConfictsWithExistingOne = Neuer Eintrag kollidiert mit Bestehendem: {0} - {1} next = Weiter nextReport = N\u00E4chster Rapport no = Nein noAbsencesRecorded = Keine Abwesenheiten erfasst noAppointmentKnown = Kein Abwesenheiten bekannt noArticleFound = Kein Artikel gefunden. noChecklistPresent = Checklist fehlt, Rapport kann nicht \u00FCbermittelt werden. noDataAvailable = Keine Daten verf\u00FCgbar noDataForOrderTypePleaseRefreshMasterdata = Keine Daten f\u00FCr Auftragsart, bitte Stammdaten aktualisieren. noDocumentPresent = Kein Dokument vorhanden, Rapport kann nicht gesendet werden. noEmployeeSelected = Kein Mitarbeitender ausgew\u00E4hlt. noFormDescImagePresent = Dokument/Bild {0} nicht vorhanden. noFormDescPresent = Dokument {0} nicht vorhanden. noFormsRecorded = Keine Formulare vorhanden noImagesEntriesReportCannotBeSent = Keine Bilder erfasst, Rapport kann nicht \u00FCbermittelt werden. noImagesRecorded = Keine Bilder vorhanden noJobAvailable = Keine Auftr\u00E4ge vorhanden. noJobSelected = Kein Auftrag ausgew\u00E4hlt! noMaterialPresent = Material fehlt, Rapport kann nicht \u00FCbermittelt werden. noMaterialRecorded = Noch kein Material erfasst. noMaterialused = Kein Material verwendet noMessagesRecorded = Noch keine Mitteilungen erfasst. noNumberToDialPleaseSelectJob. = Es kann nicht gew\u00E4hlt werden. Bitte w\u00E4hlen Sie ein noReasonSelected = Keine Begr\u00FCndung gew\u00E4hlt noRecordsAvailable = Keine Zeiten vorhanden noReport = Kein Rapport noReportAvailable = Noch kein Rapport erfasst noReportRecorded = Noch kein Rapport erstellt. noShortMessageAvailable = Keine Kurznachrichten vorhanden. noSignature = Keine Unterschrift noSignatureCaptured = Keine Unterschrift erfasst noSignaturePresent = Signatur fehlt, Rapport kann nicht \u00FCbermittelt werden. noSignatureReasonSaved = Keine Signatur: Grund erfasst. noTimeEntrySelected = Kein Eintrag gew\u00E4hlt noTimesRecorded = Noch keine Zeiten erfasst. noTimesheetEntriesReportCannotBeSent = Keine Zeiten erfasst, Rapport kann nicht \u00FCbermittelt werden. noVonoviaFormPresent = Vonovia Formulare fehlt, Rapport kann nicht \u00FCbermittelt werden. normalMaterial = Normales Material notAdded = nicht erfasst notEdit = Nicht bearbeitet notImplementedYet = Noch nicht implementiert. notPossible = Nicht m\u00F6glich notRecorded = Nicht erfasst notSend = Nicht gesendet number = Anzahl of = von ok = OK onCall = Pikett open = Offen openMaintenance = SAV offen openPending = Offene Pendenz orderDate = Auftragsdatum orderNo = Auftragsnummer orderPosition = Bestellposition orderType = Auftragsart orderedArticles = Ausstehend otherTypeOfMaterial = Material ungleich\u0009\u0009 outgoingArticle = Warenausgang\u0009\u0009 outgoingArticles = Warenausg\u00E4nge outgoingArticlesList = Warenausg\u00E4nge partialRepair = Teilerledigt partiallySend = Teilweise gesendet pdfFiles = PDF person = Person personalNumber = Pers\u00F6nliche Nummer phone = Telefon planned = Geplant plannedJob = Geplanter Auftrag pleaseCompleteTheReport = Bitte Rapport vervollst\u00E4ndigen pleaseEnterValidDate = Bitte geben Sie ein g\u00FCltiges Datum ein pleaseEnterValidTime = Bitte eine g\u00FCltige Zeit eingeben pleaseSelectValidTime = Bitte g\u00FCltige Uhrzeit w\u00E4hlen previous = Vorheriger previousReport = Vorheriger Rapport price = Preis priority = Priorit\u00E4t progress = Fortschritt projectLeader = Projektleiter reason = Begr\u00FCndung reasonForDelete = L\u00F6schgrund reasonReturnDelivery = Grund R\u00FCcklieferung reasongIncomingArticle = Begr\u00FCndung Wareneingang receipt = Eingang receive = Runterladen receivedFrom = Bezogen von refreshMasterData = Stammdaten aktualisieren refreshMasterData(SAP) = Stammdaten aktualisieren refreshingMasterData = Stammdaten aktualisieren ... refreshingMasterDataFailed = Stammdaten aktualisieren fehlgeschlagen! refreshingStock = Lager aktualisieren releaseDevice = Ger\u00E4t freigeben remarks = Bemerkungen report = Rapport report(s) = Arbeitsrapport(e) reportAbsence = Abwesenheit melden reportCannotBeSent = Rapport kann nicht \u00FCbermittelt werden. reportData = Rapportdaten reportMessageToCustomer = {0}-Auftr\u00E4ge m\u00FCssen eine Rapportnachricht an Kunde enthalten. reportView = Rapportansicht reports = Rapporte reschedule = Neu planen rideToSideNotCharged = Es wird keine Anfahrt verrechnet. salesPerson = Verk\u00E4ufer savc = SAV-Code save = Speichern savingNotPossible = Speichern nicht m\u00F6glich scan = Scan search = Suchen searchJob = Job suchen searchOrder(SAP) = Auftrag suchen (SAP) secondVisitNeeded = Es ist ein 2. Einsatz n\u00F6tig. securityReport = Sicherheitsrapport securityReportCreated = Sicherheitsrapport erstellt securityReportFilledIn = Sicherheitsrapport erstellt selectOneOrMoreJobs = W\u00E4hlen Sie einen oder mehrere Auftr\u00E4ge aus. selectOneOrMoreShortMessages = W\u00E4hlen Sie eine oder mehrere Kurznachrichten aus. send = Senden sendAbsenceNotification = Wollen Sie diese Abwesenheit melden? Meldungen k\u00F6nnen nach dem Senden nicht mehr bearbeitet werden. sendReport = Rapport senden? sendReportTo = Rapport senden an: sendingReport = Rapport senden sent = gesendet sentDate = Gesendet servicePerformed = Ausgef\u00FChrt serviceRefused = Abgelehnt shortMessage = Kurznachricht shortMessages = Kurznachrichten showPlannedJobDialogText = Der Auftrag hat ein geplantes Einsatzdatum und wird nach dem Best\u00E4tigen im Filter "Geplant" angezeigt. signatureAlreadySaved = Unterschrift ist bereits gespeichert signatureBelongsToJobsDoYouWanToDeleteIt = Die Sammelunterschrift geh\u00F6rt zu {0} Auftr\u00E4gen. Soll sie gel\u00F6scht werden? signatureBundle = Sammelunterschrift signatureCanNotBeLoadedFromFile = Unterschrift kann nicht von der Datei geladen werden. signatureCannotBeChanged = Die Sammelunterschrift kann nicht mehr ge\u00E4ndert werden, weil mind. ein Rapport aus der Gruppe bereits gesendet wurde. signatureDeleted = Unterschrift gel\u00F6scht. signatureSaved = Unterschrift gespeichert spareParts = Ersatzteile spareparts = Ersatzteile start = Start startGilgenService = Start Gilgen Service state = Status status = Status stock = Anzahl stop = Stop street = Strasse streetOrNumber = Strasse / Nummer summaryTotal = Gesamtsumme synchronizingOrders = Auftr\u00E4ge synchronisieren tel1 = Tel. 1 tel2 = Tel. 2 telWColon = Tel.: template = Vorlage theSelectedMessageAreDeleted = Die ausgew\u00E4hlten Nachrichten werden gel\u00F6scht. thereAreTimeStampsWithoutWorkType = Es gibt noch Zeiten ohne Arbeitsart. Bitte korrigieren. time = Zeit timeFrom = Zeit von timeNotStopped = Zeit nicht gestoppt timeSheet = Zeiterfassung timeStopped = Zeit gestoppt timeTo = Zeit bis times = Zeiten timesBelongToDifferentDays = Zeiten geh\u00F6ren zu unterschiedlichen Tagen. timesheetApp = Timesheet App title = Anrede to = Bis tooManyMeasurements = Zu viele Messungen bei einem Messpunkt vorhanden. total = Total transit = Transit typeOfJob = Auftragsart typeOfMaterial = Materialart typeOfWork = Arbeitssart unit = Einheit unknown = Unbekannt userList = Mitarbeiterliste valid = Korrekt valid_guarantee_label = Diese Anlage besitzt ein g\u00FCltiges Garantiekennzeichen. Bitte treffen Sie einen Fallentscheid. vehicleInventory = Fahrzeuglager warning = Warnung! way = Weg week = Woche workType = Arbeitsart wrongComm = Falsche Komm.-Nr. wrongFormArgument = Falscher Form\u00FCbergabeparameter year = Jahr yes = Ja youAreSigning = Sie unterschreiben youCanSelectMaximumOf30Jobs = Es k\u00F6nnen maximal 30 Auftr\u00E4ge ausgew\u00E4hlt werden. zip = PLZ zipCity = PLZ / Ort #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AppointmentDate = D\u00E9lai: AtLeastXImagesNecessary = Au moins {0} images n\u00E9cessaires BluetoothIsNotTurnOn = Bluetooth n'est pas activ\u00E9. CHF = CHF CannotCreateOrder = Commande ne peut pas \u00EAtre cr\u00E9\u00E9e. CannotSaveDocAlreadyExist = Ne peut pas \u00EAtre sauvegard\u00E9, {0} existe d\u00E9j\u00E0 Checklist = Checklist IBS ChecklistInstructionText = L\u2019instruction de l\u2019exploitant a \u00E8t\u00E8 effectu\u00E8e / Si non, le manuel d\u2019exploitation est d\u00E8pos\u00E8 sur l\u2019installation. La documentation AEAI sera envoy\u00E8e au client. ChecklistReadyText = L\u2019installation est compl\u00E8te et op\u00E8rationnelle conform\u00E8ment au contrat ChecklistSIAText = L'installation avec tous les \u00E8l\u00E8ments correspond aux directives de la SIA 343/214, SN EN16005:2012. .ainsi que les normes de porte No. SN EN 12453:2017. ChecklistStateText = Tous les \u00E9l\u00E9ments de l'installation sont en parfait \u00E9tat et n'ont pas de dommage (couleur, verre, etc.). ChecklistTestText = Fonctions coupe-feu et de protection de la valeur raccord\u00Ees et test\u00E8es. ChecklistVKFText = L\u2019exploitant a \u00E9t\u00E9 instruit. Sinon: manuel pour l\u2019op\u00E9rateur sur l\u2019installation. La documentation AEAI sera envoy\u00E9e au commettant. ChooseForm = Formularauswahl Client = Client ClientNumber = No. de Client Contact = Contact Customer = Entrepreneur DeleteMeasurement = Efface le mesure? DeleteReport = Effacer rapport? DiscardMeasurement = Annuler le mesure? DoYouReallyWantToDeleteTheCompleteReport = Voulez-vous vraiment effacer le rapport complet?\nTemps de rapport saisis, mat\u00E9riel, signature etc. seront \u00E9galement effac\u00E9s. Document = Document DocumentReqired = Document {0} requis. DocumentsWillBeLost = Des documents sont supprim\u00E9s, voulez-vous continuer? Done = Achev\u00E9 E = E EstateManagement = Administration FormReqired = Formulare {0} requis. Forms = Formulare GoodsIssue = Sortie de marchandises GoodsReceipt = La r\u00E9ception des marchandises Goodwill = \u00C0 bien plaire Guarantee = Livraison retour GuaranteeMaterial = Livraison retour GuaranteeTitle = Livraison retour ImageReqired = Image {0} requis. Important = Important JobFinishedSendReport = La commande est termin\u00E9e? Envoyer le rapport? K14Material = Mat\u00E9riel K Measurement = Mesure MeasurementComplete = Mesure: Saisie. MeasurementInComplete = Mesure incompl\u00E8te MeasurementMaximum = Au maximum {0} mesures possible. NoPhoneNumber = Pas de no. de t\u00E9l\u00E9phone Object = Objet Odered = Command\u00E9 OrderNo = No. de commande OverwriteAnExistingMeasurement = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es et une nouvelle mesure est lanc\u00E9e. Continuer? Owner = Propri\u00E9taire Partner = Partner Planed = Planifi\u00E9 PleaseEnterATime = Veuillez enregistrer le temps Receiver = Destinataire de marchandise ReleaseDevice = Partager un appareil RescheduleJob = Replanifier l'ordre SAV = SAV SAVResponsible = Responsable SAV Service = Service Signature = Signature TheCapturedDataWillBeDeleted = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es. Continuer? TheFormIsDiscardedContinue = Das Formular wird verworfen. Fortfahren? TheSelectedArticleIsNotInMasterdata = L'article s\u00E9lectionn\u00E9 n'est pas dans les donn\u00EEs de base. Veuillez contacter l'assistance. TheSelectedItemIsNotInStockContinue = L'article s\u00E9lectionn\u00E9 n'est pas en stock. Continuer? UserName = MA-Name VC = VC WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). YouAreSingingNReport = Vous signez {0} rapports. aborted = annul\u00E9\u2026 absenceList = Message d'absence absenceNotification = Saisire l'absence absenceType = D\u00E9but de l'absence absences = Absences accept = Accepter active = Active add = Ajouter addition = Compl\u00E9ment additionalDelivery = Livraison ult\u00E9rieure address = Adresse addressDoesNotExist = Pas trouv\u00E9 l'adresse {0}. addresses = Adresses agregatedSignature = Signature collective allowedTime = Temps pr\u00E9vu amount = Quantit\u00E9 appointment = D\u00E9lai appointmentDefined = D\u00E9lai fixe areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? areYouSureWantToDeleteRecord = Effacer l'enregistrement? artNo = No. d'article articleName = Artikelbezeichnung articleNotINInventory = Article pas en stock ! articleNumber = num\u00E9ro d'article articleScan = Nom de l'article back = Retour backOffice = Vente interne bemHistory = Remarque / Historique billing = Facturation camera = Camera cancel = Annuler captured = Saisie caseHandler = Responsable de projet change = Changement changeAddress = Changement d'adresse changesWillBeLost = Les changements sont rejett\u00E9s, continuer? charging = Facturation checkCycles = Cycles checkList = Check-list IBS city = Lieu clear = Remettre clock = Regarder codeReturnDelivery = Livraison de retour de code collectiveSignature = Signature collective commNo = No. de comm. commNoCheck = V\u00E9rifiez No. de Commission commNotCorrect = No. de commission pas correcte? commissionNumber = No. de commission commissionNumberNotCorrectWillSaveEmptyString = Num\u00E9ro de commission incorrect (0XXXXXX-XX) completed = Compl\u00E9t\u00E9 configurations = Configurations confirm = Confirmer confirmation = Confirmation consequentialRepair = R\u00E9paration successive coordinateAppointment = Convenir le d\u00E9lai! correct = Correct correctCommissionNumber = Corrigez le num\u00E9ro de commission. costumerRemark = Remarque clients costumerReport = Rapport clients costumerService = SAV createJob = Cr\u00E9er un ordre createREPJob = Cr\u00E9er job REP customizeYourInfo = Personnalisez votre informations. cycleOfInstallation = Num\u00E9ro de cycle date = Date dateFrom = Date de dateTo = Date \u00E0 delete = Effacer deleteCompleteReport = EFFACER RAPPORT ENTIER deliverDate = la date de livraison delivered = Position livr\u00E9e deliveredArticles = Livr\u00E9 department = D\u00E9pt. description = Description designation = Designation deviceMirroring = Appareil lib\u00E9r\u00E9 discardForm = Formular verwerfen? distance = Distance distancesBetween0To999kmAreAppropriate = Les distances entre 0 e 999km sont permises. doYouReallyWantToDeleteXShortMessagesAtOnce = Voulez-vous vraiment supprimer {0} Flashes d'informations \u00E0 la fois? doYouReallyWantToLoadXjobsAtOnce = Voulez-vous vraiment charger {0} emplois \u00E0 la fois? doYouWantToDeleteJob = Effacer la commande? doYouWantToDeleteThisSignature = Voulez-vous vraiment effacer la signature? doYouWantToGetOrder = T\u00E9l\u00E9charger la commande (MLDNR :{0})? done = Termin\u00E9 download = T\u00E9l\u00E9charger downloadOrder = T\u00E9l\u00E9charger la commande downloadOrder(SAP) = T\u00E9l\u00E9charger la commande (SAP) drive = Type entrainment duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. duration = Dur\u00E9e editReport = Editer le rapport email = Email employee = Employ\u00E9(e) employees = Employ\u00E9s endRepair = R\u00E9paration finale enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enterprise = Entreprise erase = Effacer error = Erreur errorCode = Code erreur errorMessages = Rapports de non-conformit\u00E9: ers = Rechange existingEntriesFromCannotAddEntryOn = Impossible pour {1} d''ajouter les enregistrements existants de {0} exists = Existant exit = Quitter exitServiceApplication = Quitter expenses = Frais explanationForReturn = Raison pour le renvoi (de mat\u00E9riel) external = Au client failure = D\u00E9faillance fax = Fax fileDeleted = Fichier supprim\u00E9. finalRepair = Raison du retour de livraison finalized = Fini finished = Termin\u00E9 firstName = Pr\u00E9nom followup = R\u00E9p. suivant forward = Transf\u00E9rer from = De fromImventory = En stock gilgenCommonApplicationIsNotInstalled = L'application commune n'est pas install\u00E9e. C'est la raison pourquoi l'application service ne peut pas \u00E9tre d\u00E9marr\u00E9e. gilgenMaterialApplicationIsNotInstalled = L'application mat\u00E9riel n'est pas install\u00E9e! gilgenTimesheetApplicationIsNotInstalled = L'application Timesheet n'est pas install\u00E9e! governmentReport = Rapport des travaux en r\u00E9gie history = Historique hours = Heures hrs = Hrs. image = Image images = Images inProgress = En courant incidentA = D\u00E9faillance A incidentB = D\u00E9faillance B incomingArticle = La r\u00E9ception des marchandises incomingArticleTitle = La r\u00E9ception des marchandises incomingArticleWithoutListEntry = R\u00E9server l'entr\u00E9e info = Info information = Information insertFixedMasterDataFile = Charger les donn\u00E9es de base (fichier) insertingMasterData = Ins\u00E9rer les donn\u00E9es de base ... installGilgenCommonApplicationFirst = S.v.p. installer premi\u00E9rement l'application commune de suite continuer l'installation et red\u00E9marrer Kolibri. installationError = Erreur d'installation installationState = \u00E9tat de fonctionnement internal = Interne interventionType = processus de suivi invalid = Incorrect invalidBarcodeGuarantee = Code-barre invalide invalidCommissionNumber = No. de commission invalide invalidJobNumber = No. de commande invalide invalidKomNo = No. de commission incorrect inventoryInformations = Informations boursi\u00E9res inventoryName = Nom du camp inventoryNumber = Num\u00E9ro d'entrep\u00F4t inventoryStock = Action job = Commande job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = Impossible d'effacer la commande s\u00E9lectionn\u00E9e. S.v.p. transmettre les rapports ouverts et temps. jobDeleted = Commande effac\u00E9e jobDetails = D\u00E9tails d'ordre jobEdit = Modification de rapport jobInfo = Info Job jobList = Liste Job jobNumber = Num\u00E9ro de commande jobState = \u00C9tat de commande jobTime = Temps de commande jobsSelected = {0} / {1} jobs s\u00E9lectionn\u00E9 lastName = Nom de famille link = Link listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible d'effacer le temps listOfEmployees = Liste des employ\u00E9s location = Installation maintenance = Service maintenanceCode = Code SAV maintenanceDone = Service ex\u00E9cut\u00E9 maintenanceMonths = Mois de service maintenancePlanned = SAV pr\u00E9vu masterDataSuccessfullyRefreshed = Donn\u00E9es de base actualis\u00E9es avec succ\u00E9s material = Mat\u00E9riel materialApp = App. Mat\u00E9riel materialName = D\u00E9signation d'article materialNumber = Num\u00E9ro d'article materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. maximumOfCheckdBoxesIs6 = Maximum de choix: 6 messageToChef = Message sup\u00E9rieur messageToCostumer = Message client messageToKDZ = Message KDZ messages = Communications month = Mois moreInformations = Erw. Komm. mtDone = SAV fini mtPlanned = SAV pr\u00E9vu name = D\u00E9signation nameOfInventory = Camp new = Nouveau newInventory = Nouvel entrep\u00F4t newJob = Nouvel ordre newReport = Nouveau rapport newTimeEntryConfictsWithExistingOne = Nouveau enregistrement en collision avec l''enregistrement existant: {0} - {1} next = Continuer nextReport = Prochain rapport no = No noAbsencesRecorded = Aucune absences enregistr\u00E9e noAppointmentKnown = Pas de d\u00E9lai noArticleFound = Aucun article trouv\u00E9. noChecklistPresent = Manque la checklist, impossible de transmettre le rapport. noDataAvailable = Pas de donn\u00E9es disponibles noDataForOrderTypePleaseRefreshMasterdata = Pas de donn\u00E9es pour le type de commande, s.v.p. actualiser les donn\u00E9es de base. noDocumentPresent = Aucun document disponible, le rapport ne peut \u00EAtre envoy\u00E9 noEmployeeSelected = Aucun employ\u00E9 s\u00E9lectionn\u00E9. noFormDescImagePresent = document/image {0} n'existe pas. noFormDescPresent = Document {0} n'existe pas. noFormsRecorded = Aucun formulare enregistr\u00E9 noImagesEntriesReportCannotBeSent = Aucun image saisis, impossible de transmettre le rapport. noImagesRecorded = Aucun image enregistr\u00E9 noJobAvailable = Aucun travail disponible. noJobSelected = Aucune commande s\u00E9lectionn\u00E9! noMaterialPresent = Manque la mat\u00E9riel , impossible de transmettre le rapport. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMaterialused = Aucun mat\u00E9riel utilis\u00E9. noMessagesRecorded = Aucun message enregistr\u00E9 noNumberToDialPleaseSelectJob. = Impossible de choisir. Veuillez s\u00E9lectionner une c noReasonSelected = Aucune justification n'est choisie noRecordsAvailable = Aucun temps saisie noReport = Aucun rapport noReportAvailable = Aucun rapport saisie noReportRecorded = Aucun rapport enregistr\u00E9 noShortMessageAvailable = Aucun message court disponible. noSignature = Aucune signature noSignatureCaptured = Aucune signature n'est saisie noSignaturePresent = Manque la signature, impossible de transmettre le rapport. noSignatureReasonSaved = Pas de signature: Basic d\u00E9tect\u00E9. noTimeEntrySelected = Aucun enregistrement n'est saisi noTimesRecorded = Aucune heure enregistr\u00E9e noTimesheetEntriesReportCannotBeSent = Aucun temps saisis, impossible de transmettre le rapport. noVonoviaFormPresent = Manque la Vonovia formulare, impossible de transmettre le rapport. normalMaterial = Mat\u00E9riel standard notAdded = no registrado notEdit = Pas \u00E9dit\u00E9 notImplementedYet = Pas encore impl\u00E9ment\u00E9. notPossible = Impossible notRecorded = Non enregistr\u00E9 notSend = Pas envoy\u00E9(e) number = Nombre of = de ok = OK onCall = Piquet open = Ouvert openMaintenance = SAV ouvert openPending = Affaire en suspens orderDate = Date de commande orderNo = No de commande orderPosition = Article de commande orderType = Type de commande orderedArticles = En attente otherTypeOfMaterial = Mat\u00E9riau diff\u00E9rent\u0009\u0009 outgoingArticle = Sortie de marchandises\u0009\u0009 outgoingArticles = Sortie de marchandises outgoingArticlesList = Action partialRepair = R\u00E9paration partielle partiallySend = Partiellement envoy\u00E9(e) pdfFiles = PDF person = Responsable personalNumber = Num\u00E9ro personnel phone = T\u00E9l\u00E9phone planned = Pr\u00E9vu plannedJob = Travail pr\u00E9vu pleaseCompleteTheReport = Remplissez le rapport, s.v.p. pleaseEnterValidDate = Veuillez enregistrer un temps date pleaseEnterValidTime = Veuillez enregistrer un temps valide pleaseSelectValidTime = Veuillez s\u00E9lectionner une heure valide previous = Pr\u00E9c\u00E9dente previousReport = Rapport pr\u00E9c\u00E9dent price = Prix priority = Priorit\u00E9 progress = Progress projectLeader = Chef de projet reason = Raison reasonForDelete = Raison d'effacer reasonReturnDelivery = Raison du retour de livraison reasongIncomingArticle = Justification de la r\u00E9ception des marchandises receipt = Entr\u00E9e receive = T\u00E9l\u00E9charger receivedFrom = Re\u00E7u de refreshMasterData = Actualiser les donn\u00E9es de base refreshMasterData(SAP) = Actualiser les donn\u00E9es de base refreshingMasterData = Actualiser les donn\u00E9es de base ... refreshingMasterDataFailed = Actualisation des donn\u00E9es de base \u00E9chou\u00E9e! refreshingStock = Mise \u00E0 jour du stock releaseDevice = Partager un appareil remarks = Remarques report = Rapport report(s) = Rapport(s) de travai reportAbsence = D\u00E9poser l'absence reportCannotBeSent = Impossible de transmettre le rapport. reportData = Donn\u00E9es du rapport reportMessageToCustomer = Les commandes {0} doivent contenir un message du rapport destin\u00E9 au client. reportView = Vue du rapport reports = Rapports reschedule = Reprogrammer rideToSideNotCharged = Aucun d\u00E9placement ne sera factur\u00E9. salesPerson = Technico-commercial savc = Code de SAV save = Sauvegarder savingNotPossible = Impossible de m\u00E9moriser scan = Balayage search = Recherche searchJob = Recherche Job searchOrder(SAP) = Chercher la commande (SAP) secondVisitNeeded = 2\u00E8me utilisation n\u00E9cessaire. securityReport = Rapport de s\u00E9curit\u00E9 securityReportCreated = Rapport de s\u00E9curit\u00E9 \u00E9tabli securityReportFilledIn = Rapport de s\u00E9curit\u00E9 \u00E9tabli selectOneOrMoreJobs = S\u00E9lectionnez un ou plusieurs ordres. selectOneOrMoreShortMessages = S\u00E9lectionnez un ou plusieurs messages courts. send = Envoy\u00E9(e) sendAbsenceNotification = D\u00E9sirez-vous annoncer cette absence? Apr\u00E8s avoir envoy\u00E9 les messages, il n'est plus possible de les \u00E9diter. sendReport = Envoyer le rapport? sendReportTo = Envoyer le rapport \u00E0 sendingReport = Envoyer le rappor sent = envoy\u00E9 sentDate = Envoy\u00E9(e) servicePerformed = Accompli serviceRefused = Refus\u00E9 shortMessage = Flash d'information shortMessages = Flash d'informations showPlannedJobDialogText = L'ordre a une date d\u2019intervention planifi\u00E9e et est affich\u00E9 dans le filtre "Planifi\u00E9" apr\u00E8s confirmation. signatureAlreadySaved = Signature d\u00E9j\u00E0 m\u00E9moris\u00E9e signatureBelongsToJobsDoYouWanToDeleteIt = La signature collective appartient \u00E0 des commandes {0}. Effacer ? signatureBundle = Signature collective signatureCanNotBeLoadedFromFile = Impossible de charger la signature par le fichier. signatureCannotBeChanged = Impossible de modifier la signature collective, car au min. un rapport de la groupe a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9. signatureDeleted = Signature supprim\u00E9. signatureSaved = Signature m\u00E9moris\u00E9e spareParts = Pi\u00E8ces de rechange spareparts = Pi\u00E8ces de rechange start = D\u00E9marrage startGilgenService = D\u00E9marrage Gilgen Service state = \u00C9tat status = \u00C9tat stock = Nombre stop = Arr\u00E9t street = Rue streetOrNumber = Rue/No. summaryTotal = Somme totale synchronizingOrders = Synchroniser les ordres tel1 = T\u00E9l. 1 tel2 = T\u00E9l. 2 telWColon = T\u00E9l.: template = Soumission theSelectedMessageAreDeleted = Les messages s\u00E9lectionn\u00E9s sont supprim\u00E9s. thereAreTimeStampsWithoutWorkType = Il y a encore de temps sans mode de travail, s.v.p corriger. time = Temps timeFrom = \u00E0 timeNotStopped = Le temps n'est pas arr\u00E9t\u00E9 timeSheet = Saisie du temps timeStopped = Le temps est arr\u00E9t\u00E9 timeTo = jusqu'\u00E0 times = Temps timesBelongToDifferentDays = Les temps font partie de diff\u00E9rents jours. timesheetApp = Timesheet App title = Titre to = de tooManyMeasurements = Trop de mesurages disponibles en un seuil point de mesurage. total = Total transit = Transit typeOfJob = Type de commande typeOfMaterial = Type de mat\u00E9riel typeOfWork = Type de travail unit = Unit\u00E9 unknown = Inconnu userList = Liste d'employ\u00E9s valid = Correct valid_guarantee_label = Cette installation poss\u00E8de une identification de garantie valable. Veuillez s.v.p. prendre une d\u00E9cision. vehicleInventory = Entrep\u00F4t de v\u00E8hicules warning = Avertissement! way = Mani\u00E8re week = Semaine workType = Mode de travail wrongComm = Mauvais no. de comm. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect year = Ann\u00E9e yes = Oui youAreSigning = Vous signez youCanSelectMaximumOf30Jobs = Vous pouvez s\u00E9lectionner un maximum de 30 emplois. zip = NPA zipCity = NPA / Lieu #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AppointmentDate = D\u00E9lai: AtLeastXImagesNecessary = Sono necessarie almeno {0} immagini BluetoothIsNotTurnOn = Bluetooth n'est pas activ\u00E9. CHF = CHF CannotCreateOrder = Commande ne peut pas \u00EAtre cr\u00E9\u00E9e. CannotSaveDocAlreadyExist = Ne peut pas \u00EAtre sauvegard\u00E9, {0} existe d\u00E9j\u00E0 Checklist = Checklist IBS ChecklistInstructionText = Le syst\u00E8me a \u00E9t\u00E9 remis \u00E0 l\u2019exploitant qui a re\u00E7u les instructions ainsi qu\u2019un manuel pour l\u2019op\u00E9rateur. ChecklistReadyText = Le syst\u00E8me est complet selon la commande et pr\u00EAt au fonctionnement. ChecklistSIAText = L'installation est conforme \u00E0 la norme SIA 343 (DIN 18650) ainsi que la norme de portes et portails No SN 12453. ChecklistStateText = Tous les \u00E9l\u00E9ments mont\u00E9s de l'installation sont en parfait \u00E9tat et ne repr\u00E9senten aucun dommage (couleur, verre, etc.). ChecklistTestText = L\u2019exploitant a \u00E9t\u00E9 instruit. Sinon: manuel pour l\u2019op\u00E9rateur sur l\u2019installation. La documentation AEAI sera envoy\u00E9e au commettant. ChecklistVKFText = L\u2019exploitant a \u00E9t\u00E9 instruit. Sinon: manuel pour l\u2019op\u00E9rateur sur l\u2019installation. La documentation AEAI sera envoy\u00E9e au commettant. ChooseForm = Formularauswahl Client = Client ClientNumber = no. de Client Contact = Contact Customer = Entrepreneur DeleteMeasurement = Efface le mesure? DeleteReport = Effacer rapport? DiscardMeasurement = Annuler le mesure? DoYouReallyWantToDeleteTheCompleteReport = Voulez-vous vraiment effacer le rapport complet?\nTemps de rapport saisis, mat\u00E9riel, signature etc. seront \u00E9galement effac\u00E9s. Document = Document DocumentReqired = Document {0} requis. DocumentsWillBeLost = Des documents sont supprim\u00E9s, voulez-vous continuer? Done = Achev\u00E9 E = E EstateManagement = Administration FormReqired = Formular {0} requis. Forms = Formulare GoodsIssue = Uscita merci GoodsReceipt = Ricevuta Merci Goodwill = \u00C0 bien plaire Guarantee = Livraison retour GuaranteeMaterial = Livraison Mat\u00E9riel GuaranteeTitle = Livraison retour ImageReqired = Image {0} requis. Important = Important JobFinishedSendReport = La commande est termin\u00E9e? Envoyer le rapport? K14Material = Mat\u00E9riel K Measurement = Mesure MeasurementComplete = Mesure: Saisie. MeasurementInComplete = Mesure incompl\u00E8te MeasurementMaximum = Au maximum 3 mesures possible. NoPhoneNumber = Pas de no. de t\u00E9l\u00E9phone Object = Objet Odered = Ordinato OrderNo = No. de commande OverwriteAnExistingMeasurement = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es et une nouvelle mesure est lanc\u00E9e. Continuer? Owner = Propri\u00E9taire Partner = Partner Planed = Planifi\u00E9 PleaseEnterATime = Veuillez enregistrer le temps Receiver = Destinataire de marchandise ReleaseDevice = Partager un appareil RescheduleJob = Replanifier l'ordre SAV = SAV SAVResponsible = Responsable SAV Service = Service Signature = Signature TheCapturedDataWillBeDeleted = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es. Continuer? TheFormIsDiscardedContinue = Das Formular wird verworfen. Fortfahren? TheSelectedArticleIsNotInMasterdata = L'articolo s\u00E9lectionn\u00E9s non esiste nei dati anagrafici. Si prega di contattare l'assistenza. TheSelectedItemIsNotInStockContinue = L'articolo s\u00E9lectionn\u00E9s non \u00E9 disponibile. Continua? UserName = MA-Name VC = VC WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). YouAreSingingNReport = Vous signez {0} rapports. aborted = annul\u00E9\u2026 absenceList = Message d'absence absenceNotification = Saisire l'absence absenceType = D\u00E9but de l'absence absences = Absences accept = Accepter active = Active add = Ajouter addition = Compl\u00E9ment additionalDelivery = Retour address = Adresse addressDoesNotExist = Pas trouv\u00E9 l'adresse {0}. addresses = Adresses agregatedSignature = Signature collective allowedTime = Temps pr\u00E9vu amount = Quantit\u00E9 appointment = D\u00E9lai appointmentDefined = D\u00E9lai fixe areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? areYouSureWantToDeleteRecord = Effacer l'enregistrement? artNo = No. d'article articleName = Nome dell'elemento articleNotINInventory = Articolo non in stock! articleNumber = codice articolo articleScan = Scansione dell'article back = Retour backOffice = Vente interne bemHistory = Remarque / Historique billing = Facturation camera = Camera cancel = Annuler captured = Saisie caseHandler = Responsable de projet change = Changement changeAddress = Changement d'adresse changesWillBeLost = Les changements sont rejett\u00E9s, continuer? charging = Facturation checkCycles = Cycles checkList = Check-list IBS city = Lieu clear = Remettre clock = Regarder codeReturnDelivery = Consegna del reso con codice collectiveSignature = Signature collective commNo = No. de comm. commNoCheck = V\u00E9rifiez No. de Commission commNotCorrect = No. de commission pas correcte? commissionNumber = No. de commission commissionNumberNotCorrectWillSaveEmptyString = Num\u00E9ro de commission incorrect (0XXXXXX-XX) completed = Compl\u00E9t\u00E9 configurations = Configurations confirm = Confirmer confirmation = Confirmation consequentialRepair = R\u00E9paration successive coordinateAppointment = Convenir le d\u00E9lai! correct = Correct correctCommissionNumber = Corrigez le num\u00E9ro de commission. costumerRemark = Remarque clients costumerReport = Rapport clients costumerService = SAV createJob = Cr\u00E9er un ordre createREPJob = Cr\u00E9er job REP customizeYourInfo = Personnalisez votre informations. cycleOfInstallation = Num\u00E9ro de cycle date = Date dateFrom = Date de dateTo = Date \u00E0 delete = Effacer deleteCompleteReport = EFFACER RAPPORT ENTIER deliverDate = data di consegna delivered = Posizione consegnata deliveredArticles = Consegnato department = D\u00E9pt. description = Description designation = Designation deviceMirroring = Appareil lib\u00E9r\u00E9 discardForm = Formular verwerfen? distance = Distance distancesBetween0To999kmAreAppropriate = Les distances entre 0 e 999km sont permises. doYouReallyWantToDeleteXShortMessagesAtOnce = Voulez-vous vraiment supprimer {0} Flashes d'informations \u00E0 la fois? doYouReallyWantToLoadXjobsAtOnce = Voulez-vous vraiment charger {0} emplois \u00E0 la fois? doYouWantToDeleteJob = Effacer la commande? doYouWantToDeleteThisSignature = Voulez-vous vraiment effacer la signature? doYouWantToGetOrder = T\u00E9l\u00E9charger la commande (MLDNR :{0})? done = Termin\u00E9 download = T\u00E9l\u00E9charger downloadOrder = T\u00E9l\u00E9charger la commande downloadOrder(SAP) = T\u00E9l\u00E9charger la commande (SAP) drive = Type entrainment duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. duration = Durata editReport = Editer le rapport email = Email employee = Employ\u00E9(e) employees = Employ\u00E9s endRepair = R\u00E9paration finale enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enterprise = Entreprise erase = Effacer error = Erreur errorCode = Code erreur errorMessages = Rapports de non-conformit\u00E9: ers = Rechange existingEntriesFromCannotAddEntryOn = Impossible pour {1} d''ajouter les enregistrements existants de {0} exists = Existant exit = Quitter exitServiceApplication = Quitter expenses = Frais explanationForReturn = Grund R\u00FCcklieferung external = Au client failure = D\u00E9faillance fax = Fax fileDeleted = Fichier supprim\u00E9. finalRepair = Raison du retour de livraison finalized = Fini finished = Termin\u00E9 firstName = Pr\u00E9nom followup = R\u00E9p. suivant forward = Transf\u00E9rer from = De fromImventory = Da magazzino gilgenCommonApplicationIsNotInstalled = L'application commune n'est pas install\u00E9e. C'est la raison pourquoi l'application service ne peut pas \u00E9tre d\u00E9marr\u00E9e. gilgenMaterialApplicationIsNotInstalled = L'application mat\u00E9riel n'est pas install\u00E9e! gilgenTimesheetApplicationIsNotInstalled = L'application Timesheet n'est pas install\u00E9e! governmentReport = Rapport des travaux en r\u00E9gie history = Historique hours = Heures hrs = Hrs. image = Image images = Images inProgress = En courant incidentA = D\u00E9faillance A incidentB = D\u00E9faillance B incomingArticle = Ricevuta Merci incomingArticleTitle = Ricevuta Merci incomingArticleWithoutListEntry = Prenota l'ingresso info = Info information = Information insertFixedMasterDataFile = Charger les donn\u00E9es de base (fichier) insertingMasterData = Ins\u00E9rer les donn\u00E9es de base ... installGilgenCommonApplicationFirst = S.v.p. installer premi\u00E9rement l'application commune de suite continuer l'installation et red\u00E9marrer Kolibri. installationError = Erreur d'installation installationState = condizione operativa internal = Interne interventionType = processo di follow-up invalid = Incorrect invalidBarcodeGuarantee = Code-barre invalide invalidCommissionNumber = No. de commission invalide invalidJobNumber = No. de commande invalide invalidKomNo = No. de commission incorrect inventoryInformations = Informazioni sulle scorte inventoryName = Nome del campo inventoryNumber = Numero di magazzino inventoryStock = Azione job = Commande job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = Impossible d'effacer la commande s\u00E9lectionn\u00E9e. S.v.p. transmettre les rapports ouverts et temps. jobDeleted = Commande effac\u00E9e jobDetails = D\u00E9tails d'ordre jobEdit = Modification de rapport jobInfo = Info Job jobList = Liste Job jobNumber = Num\u00E9ro de commande jobState = \u00C9tat de commande jobTime = Temps de commande jobsSelected = {0} / {1} jobs s\u00E9lectionn\u00E9 lastName = Nom de famille link = Link listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible d'effacer le temps listOfEmployees = Liste des employ\u00E9s location = Installation maintenance = Service maintenanceCode = Code SAV maintenanceDone = Service ex\u00E9cut\u00E9 maintenanceMonths = Mois de service maintenancePlanned = SAV pr\u00E9vu masterDataSuccessfullyRefreshed = Donn\u00E9es de base actualis\u00E9es avec succ\u00E9s material = Mat\u00E9riel materialApp = App. Mat\u00E9riel materialName = D\u00E9signation d'article materialNumber = Num\u00E9ro d'article materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. maximumOfCheckdBoxesIs6 = Maximum de choix: 6 messageToChef = Message sup\u00E9rieur messageToCostumer = Message client messageToKDZ = Message KDZ messages = Communications month = Mois moreInformations = Erw. Komm. mtDone = SAV fini mtPlanned = SAV pr\u00E9vu name = D\u00E9signation nameOfInventory = Campo new = Nouveau newInventory = Nuovo magazzino newJob = Nouvel ordre newReport = Nouveau rapport newTimeEntryConfictsWithExistingOne = Nouveau enregistrement en collision avec l''enregistrement existant: {0} - {1} next = Continuer nextReport = Prochain rapport no = Nombre noAbsencesRecorded = Aucune absences enregistr\u00E9e noAppointmentKnown = Pas de d\u00E9lai noArticleFound = Nessun articolo trovato. noChecklistPresent = Manque la checklist, impossible de transmettre le rapport. noDataAvailable = Pas de donn\u00E9es disponibles noDataForOrderTypePleaseRefreshMasterdata = Pas de donn\u00E9es pour le type de commande, s.v.p. actualiser les donn\u00E9es de base. noDocumentPresent = Aucun document disponible, le rapport ne peut \u00EAtre envoy\u00E9 noEmployeeSelected = Aucun employ\u00E9 s\u00E9lectionn\u00E9. noFormDescImagePresent = document/image {0} n'existe pas. noFormDescPresent = Document {0} n'existe pas. noFormsRecorded = Aucune formulare enregistr\u00E9 noImagesEntriesReportCannotBeSent = Aucun image saisis, impossible de transmettre le rapport. noImagesRecorded = Aucun image enregistr\u00E9 noJobAvailable = Aucun travail disponible. noJobSelected = Aucune commande s\u00E9lectionn\u00E9! noMaterialPresent = Manque la mat\u00E9riel , impossible de transmettre le rapport. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMaterialused = Aucun mat\u00E9riel utilis\u00E9. noMessagesRecorded = Aucun message enregistr\u00E9 noNumberToDialPleaseSelectJob. = Impossible de choisir. Veuillez s\u00E9lectionner une c noReasonSelected = Aucune justification n'est choisie noRecordsAvailable = Aucun temps saisie noReport = Aucun rapport noReportAvailable = Aucun rapport saisie noReportRecorded = Aucun rapport enregistr\u00E9 noShortMessageAvailable = Aucun message court disponible. noSignature = Aucune signature noSignatureCaptured = Aucune signature n'est saisie noSignaturePresent = Manque la signature, impossible de transmettre le rapport. noSignatureReasonSaved = Pas de signature: Basic d\u00E9tect\u00E9. noTimeEntrySelected = Aucun enregistrement n'est saisi noTimesRecorded = Aucune heure enregistr\u00E9e noTimesheetEntriesReportCannotBeSent = Aucun temps saisis, impossible de transmettre le rapport. noVonoviaFormPresent = Manque la formulare Vonovia, impossible de transmettre le rapport. normalMaterial = Mat\u00E9riel standard notAdded = non registrato notEdit = Pas \u00E9dit\u00E9 notImplementedYet = Pas encore impl\u00E9ment\u00E9. notPossible = Impossible notRecorded = Non enregistr\u00E9 notSend = Pas envoy\u00E9(e) number = Nombre of = de ok = OK onCall = Piquet open = Ouvert openMaintenance = SAV ouvert openPending = Affaire en suspens orderDate = Date de commande orderNo = No de commande orderPosition = Articolo dell'ordine orderType = Type de commande orderedArticles = In attesa di otherTypeOfMaterial = Material ungleich\u0009\u0009\u0009 outgoingArticle = Uscita merci\u0009\u0009 outgoingArticles = Uscita merci outgoingArticlesList = Azione partialRepair = R\u00E9paration partielle partiallySend = Partiellement envoy\u00E9(e) pdfFiles = PDF person = Responsable personalNumber = Num\u00E9ro personnel phone = T\u00E9l\u00E9phone planned = Pr\u00E9vu plannedJob = Travail pr\u00E9vu pleaseCompleteTheReport = Remplissez le rapport, s.v.p. pleaseEnterValidDate = Veuillez enregistrer un temps date pleaseEnterValidTime = Veuillez enregistrer un temps valide pleaseSelectValidTime = Veuillez s\u00E9lectionner une heure valide previous = Pr\u00E9c\u00E9dente previousReport = Rapport pr\u00E9c\u00E9dent price = Prix priority = Priorit\u00E9 progress = Progress projectLeader = Chef de projet reason = Raison reasonForDelete = Raison d'effacer reasonReturnDelivery = Motivo della restituzione reasongIncomingArticle = Giustificazione del ricevimento della merce receipt = Entr\u00E9e receive = T\u00E9l\u00E9charger receivedFrom = Re\u00E7u de refreshMasterData = Actualiser les donn\u00E9es de base refreshMasterData(SAP) = Actualiser les donn\u00E9es de base refreshingMasterData = Actualiser les donn\u00E9es de base ... refreshingMasterDataFailed = Actualisation des donn\u00E9es de base \u00E9chou\u00E9e! refreshingStock = Mise \u00E0 jour du stock releaseDevice = Partager un appareil remarks = Remarques report = Rapport report(s) = Rapport(s) de travai reportAbsence = D\u00E9poser l'absence reportCannotBeSent = Impossible de transmettre le rapport. reportData = Donn\u00E9es du rapport reportMessageToCustomer = Les commandes {0} doivent contenir un message du rapport destin\u00E9 au client. reportView = Vue du rapport reports = Rapports reschedule = Reprogrammer rideToSideNotCharged = Aucun d\u00E9placement ne sera factur\u00E9. salesPerson = Technico-commercial savc = Code de SAV save = Sauvegarder savingNotPossible = Impossible de m\u00E9moriser scan = Balayage search = Recherche searchJob = Recherche Job searchOrder(SAP) = Chercher la commande (SAP) secondVisitNeeded = 2\u00E8me utilisation n\u00E9cessaire. securityReport = Rapport de s\u00E9curit\u00E9 securityReportCreated = Rapport de s\u00E9curit\u00E9 \u00E9tabli securityReportFilledIn = Rapport de s\u00E9curit\u00E9 \u00E9tabli selectOneOrMoreJobs = S\u00E9lectionnez un ou plusieurs ordres. selectOneOrMoreShortMessages = S\u00E9lectionnez un ou plusieurs messages courts. send = Envoy\u00E9(e) sendAbsenceNotification = D\u00E9sirez-vous annoncer cette absence? Apr\u00E8s avoir envoy\u00E9 les messages, il n'est plus possible de les \u00E9diter. sendReport = Envoyer le rapport? sendReportTo = Envoyer le rapport \u00E0 sendingReport = Envoyer le rappor sent = envoy\u00E9 sentDate = Envoy\u00E9(e) servicePerformed = Accompli serviceRefused = Refus\u00E9 shortMessage = Flash d'information shortMessages = Flash d'informations showPlannedJobDialogText = L'ordre a une date d\u2019intervention planifi\u00E9e et est affich\u00E9 dans le filtre "Planifi\u00E9" apr\u00E8s confirmation. signatureAlreadySaved = Signature d\u00E9j\u00E0 m\u00E9moris\u00E9e signatureBelongsToJobsDoYouWanToDeleteIt = La signature collective appartient \u00E0 des commandes {0}. Effacer ? signatureBundle = Signature collective signatureCanNotBeLoadedFromFile = Impossible de charger la signature par le fichier. signatureCannotBeChanged = Impossible de modifier la signature collective, car au min. un rapport de la groupe a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9. signatureDeleted = Signature supprim\u00E9. signatureSaved = Signature m\u00E9moris\u00E9e spareParts = Pi\u00E8ces de rechange spareparts = Pi\u00E8ces de rechange start = D\u00E9marrage startGilgenService = D\u00E9marrage Gilgen Service state = \u00C9tat status = \u00C9tat stock = Nombre stop = Arr\u00E9t street = Rue streetOrNumber = Rue/No. summaryTotal = Totale synchronizingOrders = Synchroniser les ordres tel1 = T\u00E9l. 1 tel2 = T\u00E9l. 2 telWColon = T\u00E9l.: template = Soumission theSelectedMessageAreDeleted = Les messages s\u00E9lectionn\u00E9s sont supprim\u00E9s. thereAreTimeStampsWithoutWorkType = Il y a encore de temps sans mode de travail, s.v.p corriger. time = Temps timeFrom = \u00E0 timeNotStopped = Le temps n'est pas arr\u00E9t\u00E9 timeSheet = Saisie du temps timeStopped = Le temps est arr\u00E9t\u00E9 timeTo = jusqu'\u00E0 times = Temps timesBelongToDifferentDays = Les temps font partie de diff\u00E9rents jours. timesheetApp = Timesheet App title = Titre to = de tooManyMeasurements = Trop de mesurages disponibles en un seuil point de mesurage. total = Total transit = Transit typeOfJob = Type de commande typeOfMaterial = Type de mat\u00E9riel typeOfWork = Type de travail unit = Unit\u00E9 unknown = Inconnu userList = Liste d'employ\u00E9s valid = Correct valid_guarantee_label = Cette installation poss\u00E8de une identification de garantie valable. Veuillez s.v.p. prendre une d\u00E9cision. vehicleInventory = Magazzino veicoli warning = Avertissement! way = Mani\u00E8re week = Semaine workType = Mode de travail wrongComm = Mauvais no. de comm. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect year = Ann\u00E9e yes = Oui youAreSigning = Vous signez youCanSelectMaximumOf30Jobs = Vous pouvez s\u00E9lectionner un maximum de 30 emplois. zip = NPA zipCity = NPA / Lieu #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) AtLeastXImagesNecessary = At least {0} images necessary BluetoothIsNotTurnOn = Bluetooth isn't turned on CHF = CHF CannotCreateOrder = Cannot create order. CannotSaveDocAlreadyExist = Cannot save, {0} already exist. Checklist = Checklist IBS ChecklistInstructionText = The installation was handed over to the operator, instructions were given and an operator manual was handed over. ChecklistReadyText = According to the order, the installation is complete and ready for operation. ChecklistSIAText = The installation corresponds in all parts to SIA 343 (DIN 18650) and Tornorm no. SN 12453. ChecklistStateText = All assembled elements of the installation are in perfect condition and show no signs of damage (paint, glass, etc.). ChecklistTestText = Fire and security functions connected and tested. ChecklistVKFText = Instruction is given to the operator. If not, the operator manual on the installation. The VKF documentation is sent to the client. Client = Client ClientNumber = Client No. Contact = Contact Customer = Customer DeleteMeasurement = Delete measurement? DeleteReport = Delete report? DiscardMeasurement = Discard measurement? DoYouReallyWantToDeleteTheCompleteReport = Do you really want to delete the complete report? \nReport time, material, signature et cetera will be deleted too. Document = Document DocumentReqired = Document {0} required. DocumentsWillBeLost = Documents will be lost, are you sure that you want to continue? Done = Done E = E EstateManagement = Estate Management GoodsReceipt = Goods Receipt GoodsIssue = Goods issue Goodwill = Goodwill Guarantee = Guarantee GuaranteeTitle = Guarantee GuaranteeMaterial = Guarantee ImageReqired = Image {0} required. Important = Important JobFinishedSendReport = Job finished? Send Report? K14Material = K-Material MeasurementComplete = Measurement: Complete. MeasurementInComplete = Measurement incomplete MeasurementMaximum = At maximum {0} measurements possible NoPhoneNumber = No phone number Object = Object Odered = Odered OrderNo = Order No. OverwriteAnExistingMeasurement = The recorded data are discarded and a new measurement is started. Continue? Owner = Owner Partner = Partner Planed = Planed PleaseEnterATime = Please enter a time Receiver = Receiver ReleaseDevice = Release device RescheduleJob = Reschedule job SAVResponsible = SAV responsible SAV = SAV Service = Service Signature = Signature TheCapturedDataWillBeDeleted = The captured data will be deleted. Continue? VC = VC WrongFormatXX-XXXX-XXX/XX = Wrong format(XX-XXXX-XXX/XX) YouAreSingingNReport = You are signing {0} reports. aborted = aborted... absenceList = Absence Notification absenceNotification = Absence Notification absenceType = Absence type absences = Absences accept = Accept active = Active add = Add addition = Addition additionalDelivery = Additional delivery address = Address addressDoesNotExist = {0}-address does not exist addresses = Addresses agregatedSignature = Agregated signature allowedTime = Allowed time amount = Amount appointment = Appointment AppointmentDate = AppointmentDate: appointmentDefined = Appointment defined areYouSureThatYouWantToDeleteRecord = Are you sure that you want to delete this record? areYouSureWantToDeleteRecord = Are you sure that you want to delete this record? articleScan = Article Scan articleName = Article name articleNotINInventory = Artikel not in Inventory! articleNumber = Article number artNo = Art. No. back = Back backOffice = Back office bemHistory = Bem. / History billing = Billing camera = Camera cancel = Cancel captured = Captured caseHandler = Case handler change = Change changeAddress = Change address changesWillBeLost = Changes will be lost, are you sure that you want to continue? charging = Charging checkCycles = Check cycles checkList = Checklist IBS ChooseForm = Choose Form city = City clear = Clear clock = O'clock collectiveSignature = Collective Signature codeReturnDelivery = Code return delivery commNo = Comm. No. commNoCheck = Comm. No.-Check commNotCorrect = Comm. not correct? commissionNumber = Commission number commissionNumberNotCorrectWillSaveEmptyString = Commission number not correct (0XXXXXX-XX)\nand will save empty String. completed = Completed configurations = Configurations confirm = Confirm confirmation = Confirmation consequentialRepair = Consequential repair coordinateAppointment = Coordinate appointment! correct = Correct correctCommissionNumber = Correct commission number costumerRemark = Costumer remark costumerReport = Costumer report costumerService = Costumer service createJob = Create job createREPJob = Create REP-Job customizeYourInfo = Customize your info cycleOfInstallation = Number of cycles date = Date dateFrom = Date from dateTo = Date to delete = Delete deleteCompleteReport = DELETE COMPLETE REPORT deliverDate = Deliver date delivered = Delivered deliveredArticles = Delivered articles department = Department description = Description designation = Designation deviceMirroring = Device mirroring discardForm = Discard form? distance = Distance distancesBetween0To999kmAreAppropriate = Distances between 0 to 999km are appropriate doYouReallyWantToDeleteXShortMessagesAtOnce = Do you really want to delete {0} short messages at once? doYouReallyWantToLoadXjobsAtOnce = Do you really want to load {0} jobs at once? doYouWantToDeleteJob = Do you want to delete job? doYouWantToDeleteThisSignature = Do you want to delete this signature? doYouWantToGetOrder = Do you want to get Order (MLDNR :{0}) done = Done download = Download downloadOrder = Download order downloadOrder(SAP) = Download order(SAP) drive = Drive duplicatedMaterialNumber = There is MaterialNumber {0} duplicated {1} can not insert. duration = Stock editReport = Edit report email = Email employee = Employee employees = Employees endRepair = End Repair enteredValueIsInTheFuturePleaseEnterValidTime = The entered value is in the future! Please enter a valid time. enterprise = Enterprise erase = Erase error = Error errorCode = Error code errorMessages = Error messages: ers = Ers existingEntriesFromCannotAddEntryOn = Existing entries from {0}, can not add entry on {1} exists = Exists exit = Exit exitServiceApplication = Exit service application expenses = Expenses explanationForReturn = Explanation for return external = External failure = Failure fax = Fax fileDeleted = File Deleted. finalRepair = Final repair finalized = Finalized finished = Finished firstName = First name followup = Follow-up forward = Forward from = From FormReqired = From {0} required. Forms = Forms fromImventory = From Inventory gilgenCommonApplicationIsNotInstalled = The Gilgen Common application is not installed! The Gilgen Service cannot run. gilgenMaterialApplicationIsNotInstalled = The Material application is not installed! gilgenTimesheetApplicationIsNotInstalled = The Timesheet application is not installed! governmentReport = report callout charged at cost history = History hours = Hours hrs = Hrs. image = Image images = Images inProgress = In progress incidentA = Incident A incidentB = Incident B incomingArticle = Incoming Article incomingArticleTitle = Incoming Article incomingArticleWithoutListEntry = Post incoming article info = Info information = Information insertFixedMasterDataFile = Insert fixed-master-data(File) insertingMasterData = Inserting MasterData... installGilgenCommonApplicationFirst = Install the Gilgen Common application first. Continue installation and restart Kolibri. installationError = Installation error installationState = State of installation internal = Internal interventionType = Type of next intervention invalid = Invalid invalidBarcodeGuarantee = Invalid Barcode guarantee invalidCommissionNumber = Invalid commission number invalidJobNumber = Invalid job number invalidKomNo = Invalid KomNo inventoryInformations = Inventory informations inventoryName = Inventory name inventoryNumber = Inventory number inventoryStock = Inventory Stock job = Job job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = The selected Job couldn't be deleted. Please send back open reports or working time jobDeleted = Job deleted jobDetails = Job details jobEdit = Job edit jobInfo = Job info jobList = Job list jobNumber = Job number jobState = job state jobTime = Job Time jobsSelected = {0} / {1} jobs selected lastName = Last name link = Link listIsEmptyNoTimeEntryToDelete = List is empty, no time entry to delete listOfEmployees = List of employees location = Location maintenance = Maintenance maintenanceCode = Maintenance code maintenanceDone = Maintenance done maintenanceMonths = Maintenance months maintenancePlanned = Maintenance planned masterDataSuccessfullyRefreshed = Master data successfully refreshed material = Material materialApp = Material App materialName = Material name materialNumber = Material number materialWasDeleted = Material was deleted. materialWithThisNameAlreadyExists = Material with this name already exists materialWithThisNumberAlreadyExists = Material with this number already exists. maximumOfCheckdBoxesIs6 = Maximum of checked boxes is 6 Measurement = Measurement messageToChef = Message to chef messageToCostumer = Message to costumer messageToKDZ = Message to KDZ messages = Messages month = Month moreInformations = More Informations mtDone = Mt. done mtPlanned = Mt. planned name = Name nameOfInventory = Inventory new = New newInventory = New inventory newJob = New job newReport = New report newTimeEntryConfictsWithExistingOne = New time entry conficts with existing one: {0} - {1} next = Next nextReport = Next report no = No noAbsencesRecorded = No Absences recorded noAppointmentKnown = No appointment known noArticleFound = No article found. noChecklistPresent = No checklist present, report cannot be sent. noDataAvailable = No data available noDataForOrderTypePleaseRefreshMasterdata = No data for order type, please refresh masterdata. noDocumentPresent = No document present, report cannot be sent: noEmployeeSelected = No employee selected. noFormDescImagePresent = No document/image {0} present noFormDescPresent = No document {0} present noImagesEntriesReportCannotBeSent = No images entries, report cannot be sent. noFormsRecorded = No forms recorded noImagesRecorded = No images recorded noJobAvailable = No job available. noJobSelected = No job selected! noMaterialPresent = No Material present, report cannot be sent. noMaterialRecorded = No material recorded noMaterialused = No material used. noMessagesRecorded = No messages recorded noNumberToDialPleaseSelectJob. = No number to dial. Please select a job. noReasonSelected = No reason selected noRecordsAvailable = No records available noReport = no report noReportAvailable = No report available noReportRecorded = No report recorded noShortMessageAvailable = No short message available. noSignature = No signature noSignatureCaptured = No signature captured noSignaturePresent = No signature present, report cannot be sent. noSignatureReasonSaved = No signature: Reason saved. notAdded = not added noTimeEntrySelected = No time entry selected noTimesRecorded = No times recorded noTimesheetEntriesReportCannotBeSent = No timesheet entries, report cannot be sent. normalMaterial = Normal material notEdit = Not edited notImplementedYet = Not implemented yet. notPossible = Not possible notRecorded = Not recorded notSend = Not send noVonoviaFormPresent = No Vonovia Form present, report cannot be sent. number = Number of = of ok = OK onCall = On-call open = Open openMaintenance = Open maintenance openPending = Open pending orderDate = Order date orderedArticles = Ordered Articles orderNo = Order number orderPosition = Order position orderType = Order type otherTypeOfMaterial = Other type of material outgoingArticle = Outgoing article outgoingArticles = Outgoing articles outgoingArticlesList = List of outgoing articles partialRepair = Partial repair partiallySend = Partially sent pdfFiles = PDF files person = Person personalNumber = Personal number phone = Phone planned = Planned plannedJob = Planned Job pleaseCompleteTheReport = Please complete the report pleaseEnterValidDate = Please enter a valid date pleaseEnterValidTime = Please enter a valid time pleaseSelectValidTime = Please select a valid time previous = Previous previousReport = Previous report price = Price priority = Priority progress = Fortschritt projectLeader = Project leader reason = Reason reasonForDelete = Reason for delete reasongIncomingArticle = Reasong incoming article reasonReturnDelivery = Reason return delivery receipt = Receipt receive = Receive receivedFrom = Received from refreshMasterData = Refresh master data refreshMasterData(SAP) = Refresh master data refreshingMasterData = Refreshing MasterData... refreshingMasterDataFailed = Refreshing Master data failed! refreshingStock = Refreshing stock releaseDevice = Release device remarks = Remarks report = Report report(s) = report(s) reportAbsence = Report absence reportCannotBeSent = Report cannot be sent. reportData = Report data reportMessageToCustomer = Job type {0} must have a report message to client. reportView = Report view reports = Reports reschedule = Reschedule rideToSideNotCharged = Ride to side not charged salesPerson = Sales person savc = SAVC save = Save savingNotPossible = Saving not possible scan = Scan search = Search searchJob = Search job searchOrder(SAP) = Search order (SAP) secondVisitNeeded = Second visit needed securityReport = Security report securityReportCreated = Security report created securityReportFilledIn = Security report filled in selectOneOrMoreJobs = Select one or more jobs. selectOneOrMoreShortMessages = Select one or more short messages. send = Sent sendAbsenceNotification = Do you want to report this absence? Messages cannot be processed after they have been sent. sendReport = Send report? sendReportTo = Send report to sendingReport = Sending report sent = sent sentDate = Sent servicePerformed = Service performed serviceRefused = Service refused shortMessage = Short message shortMessages = Short messages showPlannedJobDialogText = The job is planned in future and will be displayed in filter "planned" after confirming. signatureAlreadySaved = Signature already saved signatureBelongsToJobsDoYouWanToDeleteIt = The signature belongs to {0} jobs. Do you want to delete it? signatureBundle = Signature bundle signatureCanNotBeLoadedFromFile = Signature can not be loaded from file signatureCannotBeChanged = Signature can not be changed anymore because at least on report from the group has been already sent signatureDeleted = Signature deleted. signatureSaved = Signature saved spareParts = Spare parts spareparts = Spare parts start = Start startGilgenService = Start Gilgen Service state = State status = Status stock = Stock stop = Stop street = Street streetOrNumber = Street/Number summaryTotal = Gesamtsumme synchronizingOrders = Synchronizing orders tel1 = Tel. 1 tel2 = Tel. 2 telWColon = Tel.: template = template TheFormIsDiscardedContinue = The form is discarded. Continue? theSelectedMessageAreDeleted = The selected message(s) are deleted. TheSelectedItemIsNotInStockContinue = The selected item is not in stock. Continue? TheSelectedArticleIsNotInMasterdata = The selected article isn't available in masterdata. Please contact support. thereAreTimeStampsWithoutWorkType = There are time stamps without work type. Please change. time = Time timeFrom = Time from timeNotStopped = Time not stopped timeSheet = TimeSheet timeStopped = Time stopped timeTo = Time to times = Times timesBelongToDifferentDays = Times belong to different days. timesheetApp = Timesheet App title = Title to = To tooManyMeasurements = Too many measurements available at one measuring point total = Total transit = Transit typeOfJob = Type of job typeOfMaterial = Type of material typeOfWork = Type of work unit = Unit unknown = Unknown userList = User list UserName = User-Name valid = Valid valid_guarantee_label = This system has a valid guarantee label. Please make a case decision. vehicleInventory = Vehicle Inventory warning = Warning! way = Way week = Week workType = Work type wrongComm = Wrong commission number wrongFormArgument = Wrong form argument class found in form year = Year yes = Yes youAreSigning = You are signing youCanSelectMaximumOf30Jobs = You can select a maximum of 30 jobs. zip = ZIP zipCity = ZIP / City package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.res.ColorStateList; import android.support.v7.widget.AppCompatRadioButton; import android.text.InputType; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The edit address form for job details. * * @author nop (23-02-2017) * * @see "[MIG-44] implement of "Adressen editieren"" */ public class JobDetailAddressEditForm extends AddressEditSuperForm implements OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(JobDetailAddressEditForm.class); protected Address address; private AppCompatRadioButton firmaRadioButton; private AppCompatRadioButton personRadioButton; private MDSpinner personTitleValue; private MDEditText personFirstName; private MDEditText personLastName; private MDEditText personAddition; private MDSpinner companyTitleValue; private MDEditText company; private MDEditText companyName; private MDEditText companyAddition; private List emailList; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailAddressForm.AddressFormArguments) { JobDetailAddressForm.AddressFormArguments formArguments = (JobDetailAddressForm.AddressFormArguments) argument; job = formArguments.getJob(); address = formArguments.getAddress(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroup.setPadding(10, 0, 10, 10); radioGroup.setOnCheckedChangeListener(this); radioGroup.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.addView(radioGroup); ColorStateList colorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_enabled } }, new int[] { LayoutUtils.DEFAULT_TEXT_COLOR }); firmaRadioButton = new AppCompatRadioButton(context); firmaRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 3f)); firmaRadioButton.setText(ServiceMessages.getString("enterprise")); //$NON-NLS-1$ firmaRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); firmaRadioButton.setSupportButtonTintList(colorStateList); firmaRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); firmaRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(firmaRadioButton); personRadioButton = new AppCompatRadioButton(context); personRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); personRadioButton.setText(ServiceMessages.getString("person")); //$NON-NLS-1$ personRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); personRadioButton.setSupportButtonTintList(colorStateList); personRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); personRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(personRadioButton); RelativeLayout formRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams formRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); formRelativeLayoutParams.topMargin = 10; formRelativeLayout.setLayoutParams(formRelativeLayoutParams); formRelativeLayout.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); // Title personTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ personTitleValue.setTag("PERSON_TITLE"); //$NON-NLS-1$ personTitleValue.setOnItemSelectedListener(this); linearLayout.addView(personTitleValue.getTopParent(), 0); personFirstName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("firstName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(personFirstName), 1); personLastName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("lastName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(personLastName), 2); personAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(personAddition), 3); // company company = MDEditText.createDefaultEditText(context, ServiceMessages.getString("enterprise"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(company), 0); companyAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(companyAddition), 1); // company title companyTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ companyTitleValue.setTag("COMPANY_TITLE"); //$NON-NLS-1$ companyTitleValue.setOnItemSelectedListener(this); linearLayout.addView(companyTitleValue.getTopParent(), 2); companyName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("name"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(companyName), 3); ScrollView scrollView = new ScrollView(context); LinearLayout.LayoutParams scrollViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); scrollView.setLayoutParams(scrollViewParams); formRelativeLayout.addView(linearLayout); contentLinearLayout.addView(formRelativeLayout); scrollView.addView(contentLinearLayout); relativeLayout.addView(scrollView); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("changeAddress")); //$NON-NLS-1$ return null; } @Override public void loadData() { // title List valueList = new ArrayList<>(); Iterator itr = app.enumUtil.titelEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); valueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } emailList = app.dbutil.selectEmailListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); generateEmailContete(emailList.size()); personTitleValue.setContents(valueList); companyTitleValue.setContents(valueList); if (StringUtil.isNotEmpty(address.getTitle()) && !valueList.isEmpty()) { String title = app.enumUtil.titelEnum.get(address.getTitle()); personTitleValue.setSelectionByName(title); companyTitleValue.setSelectionByName(title); } else { personTitleValue.setSelection(0); companyTitleValue.setSelection(0); } personFirstName.setText(address.getName1()); personLastName.setText(address.getName2()); personAddition.setText(address.getName3()); company.setText(address.getName1()); companyName.setText(address.getName2()); companyAddition.setText(address.getName3()); location.setText(address.getLocation()); street.setText(address.getStreet()); zip.setText(address.getPostalCode()); city.setText(address.getCity()); tel1.setText(address.getTelNumber1()); tel2.setText(address.getTelNumber2()); fax.setText(address.getFaxNumber()); email.setText(address.getEmail()); for (int i = 0; i < emailTextList.size(); i++) { MDEditText emailEditText = emailTextList.get(i); emailEditText.setText(emailList.get(i).getEmail()); } if (address.isPrivate()) { personRadioButton.setChecked(true); } else { firmaRadioButton.setChecked(true); } } @Override public void onCheckedChanged(RadioGroup paramRadioGroup, int paramInt) { clearErrorMessages(); if (firmaRadioButton.isChecked()) { setPersonInfomation(false); setFimaInfomation(true); } else if (personRadioButton.isChecked()) { setPersonInfomation(true); setFimaInfomation(false); } } private void setFimaInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } company.setVisibility(visibility); companyAddition.setVisibility(visibility); companyTitleValue.getTopParent().setVisibility(visibility); companyName.setVisibility(visibility); } private void setPersonInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } personTitleValue.setRequired(isVisible); personTitleValue.getTopParent().setVisibility(visibility); personFirstName.setVisibility(visibility); personLastName.setVisibility(visibility); personAddition.setVisibility(visibility); } @Override protected boolean isValid() { boolean result = super.isValid(); String selectMessage = Messages.getString("pleaseSelectValue"); //$NON-NLS-1$ String provideMessage = Messages.getString("pleaseProvideValue"); //$NON-NLS-1$ if (firmaRadioButton.isChecked()) { if (companyTitleValue.isRequired() && companyTitleValue.getSelectedItemPosition() == 0) { companyTitleValue.setError(selectMessage); result = false; } if (company.isRequired() && "".equals(company.getText().toString().trim())) { //$NON-NLS-1$ company.setError(provideMessage); result = false; } if (companyName.isRequired() && "".equals(companyName.getText().toString().trim())) { //$NON-NLS-1$ companyName.setError(provideMessage); result = false; } } else { if (personTitleValue.isRequired() && personTitleValue.getSelectedItemPosition() == 0) { personTitleValue.setError(selectMessage); result = false; } if (personLastName.isRequired() && "".equals(personLastName.getText().toString().trim())) { //$NON-NLS-1$ personLastName.setError(provideMessage); result = false; } } return result; } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { String title = ""; //$NON-NLS-1$ // private address if (personRadioButton.isChecked()) { if (personTitleValue.getSelectedItemPosition() != 0) { title = personTitleValue.getSelectedId(); } address.setName1(personFirstName.getText().toString()); address.setName2(personLastName.getText().toString()); address.setName3(personAddition.getText().toString()); } else if (firmaRadioButton.isChecked()) { if (companyTitleValue.getSelectedItemPosition() != 0) { title = companyTitleValue.getSelectedId(); } address.setName1(company.getText().toString()); address.setName2(companyName.getText().toString()); address.setName3(companyAddition.getText().toString()); } address.setTitle(title); address.setLocation(location.getText().toString()); address.setStreet(street.getText().toString()); address.setPostalCode(zip.getText().toString()); address.setCity(city.getText().toString()); address.setTelNumber1(tel1.getText().toString()); address.setTelNumber2(tel2.getText().toString()); address.setFaxNumber(fax.getText().toString()); address.setEmail(email.getText().toString()); // address.setEmail2(email2.getText().toString()); // address.setEmail3(email3.getText().toString()); if (firmaRadioButton.isChecked()) { address.setPrivate(false); } else { address.setPrivate(true); } app.dbutil.updateAddress(address); new RemoteTransactionHandler().runSaveOrder(job, address); job.loadAddresses(app.dbutil); return onBackPressed(); } }; return true; } @Override public void onFormReset() { super.onFormReset(); personTitleValue.setSelection(0); personFirstName.getText().clear(); personLastName.getText().clear(); personAddition.getText().clear(); companyTitleValue.setSelection(0); company.getText().clear(); companyName.getText().clear(); companyAddition.getText().clear(); } @Override public void onNothingSelected(AdapterView arg0) { //Do nothing } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("PERSON_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ personTitleValue.clearError(); } else if ("COMPANY_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ companyTitleValue.clearError(); } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { super.onTextChanged(s, start, before, count); if (personLastName.hasFocus()) { personLastName.clearError(); } if (company.hasFocus()) { company.clearError(); } if (companyName.hasFocus()) { companyName.clearError(); } } @Override public void clearErrorMessages() { super.clearErrorMessages(); personTitleValue.clearError(); companyTitleValue.clearError(); personLastName.clearError(); company.clearError(); companyName.clearError(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.DialogInterface; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportFormListForm.ReportFormListFormArguments; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceFormUtil; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The report form for job detail. * * @author nop (21-03-2017) * @see "[MIG-51] implement of report overview" */ public class JobDetailReportForm extends GridLayoutForm { private static Log log = LogFactory.getLog(JobDetailReportForm.class); private RelativeLayout reportRelativeLayout; private LinearLayout cardLinearLayout; private CommonConstants.CommissionNumber.Type commissionType = CommonConstants.CommissionNumber.Type.CORRECT; private GridLayout timeGridLayout; private Job job; private int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; JobDetailReportForm detailReportForm; /** * Default working type for repair orders: Non ("Bitte w�hlen..") because * relevant working type is taken from the report (ZKDMOBREP) record */ protected static final String DEFAULT_REP_ARBA = "00"; //$NON-NLS-1$ /** * Default working type for assambly orders: Non ("Bitte w�hlen..") because * relevant working type is taken from the report (ZKDMOBREP) record */ protected static final String DEFAULT_MON_ARBA = "00"; //$NON-NLS-1$ /** * Default working type for maintenance orders: "Vertragsservice" */ protected static final String DEFAULT_SAV_ARBA = "05"; //$NON-NLS-1$ private enum CardType { TIME, REPORT_DATA, CHECKLIST, MATERIAL, MESSAGE, IMAGE, DOCUMENT, MEASUREMENT, FORM } TimeUtil timeUtil = null; public JobDetailReportForm(Context context, ServiceApplication app) { super(context, app); timeUtil = new TimeUtil(app, app.dbutil, this); } /** * Gets view. * * @param job */ public View getView(Job job) { this.job = job; job.loadAddresses(app.dbutil); job.loadReports(app.dbutil); if (job.getStatus().isFinalized()) { textColor = LayoutUtils.DEFAULT_LABEL_COLOR; } else { textColor = LayoutUtils.DEFAULT_TEXT_COLOR; } createLayoutAndContents(); detailReportForm = this; return getParentView(reportRelativeLayout); } /** * Creates layout and contents. */ public void createLayoutAndContents() { reportRelativeLayout = new RelativeLayout(context); reportRelativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); createReportLayoutAndContents(job); reportRelativeLayout.addView(cardLinearLayout); } /** * Creates REP report layout and contents. * * @param job * @param targetLinearLayout * @param title */ private void createReportLayoutAndContents(Job job) { appendTime(); appendReportData(); if (job.getJobType().isMON()) { appendChecklist(); } appendMaterials(); appendMessages(); appendImages(); appendDocuments(); appendMeasurements(); appendForms(); } /** * Creates report text view. * * @param gridLayout * @param text */ private void createReportTextView(GridLayout gridLayout, String text) { createReportTextView(gridLayout, text, textColor); } private void createReportTextView(GridLayout gridLayout, String text, int color) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(text); gridTextViewKey.setTextColor(color); gridLayout.addView(gridTextViewKey); } private void createReportTextView(GridLayout gridLayout, String key, String value) { createReportTextView(gridLayout, key, value, false); } private void createReportTextView(GridLayout gridLayout, String key, String value , boolean isBold) { TextView gridTextViewKey = new TextView(gridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.4f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout gridRelativeLayout = new RelativeLayout(gridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.6f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(gridLayout.getContext()); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(value); gridTextViewValue.setTextColor(textColor); gridRelativeLayout.addView(gridTextViewValue); gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } private void createReportTextViewWithIcon( GridLayout gridLayout, final String timeInfo, final CardType cardType) { createReportTextViewWithIcon(gridLayout, timeInfo, cardType, CommonConstants.Mode.EDIT); } private void createReportTextViewWithIcon(final GridLayout gridLayout, final String timeInfo, final CardType cardType, final String mode) { if (job.getStatus().isFinalized()) { return; } RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, gridLayout.getColumnCount(), 1f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(context); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(""); //$NON-NLS-1$ gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridRelativeLayout.addView(gridTextViewValue); LinearLayout linearLayout = new LinearLayout(context); RelativeLayout.LayoutParams linearLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); linearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.HORIZONTAL); createTimeContents(timeInfo, linearLayout); linearLayout.addView(createAddEditImageView(cardType, mode)); gridRelativeLayout.addView(linearLayout); gridLayout.addView(gridRelativeLayout); } private void createReportViewWithIcon(final GridLayout gridLayout, final String timeInfo, final CardType cardType, final String mode, View view, ImageView image) { RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, gridLayout.getColumnCount(), 1f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(context); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(""); //$NON-NLS-1$ gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridRelativeLayout.addView(gridTextViewValue); LinearLayout linearLayout = new LinearLayout(context); RelativeLayout.LayoutParams linearLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); linearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.HORIZONTAL); if(view != null) { gridRelativeLayout.addView(view); } if(image != null) { linearLayout.addView(image); } else { linearLayout.addView(createAddEditImageView(cardType, mode)); } gridRelativeLayout.addView(linearLayout); gridLayout.addView(gridRelativeLayout); } private ImageView createAddEditImageView(final CardType cardType, final String mode) { ImageView editImageView = new ImageView(context); editImageView.setContentDescription(mode); editImageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); Images editImage = ImagesUtil.Images.EDIT; if (mode.equalsIgnoreCase(CommonConstants.Mode.NEW)) { editImage = ImagesUtil.Images.ADD_BLACK; } editImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(editImage, CommonConstants.Images.IMAGE_DPI))); editImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (CardType.REPORT_DATA == cardType) { if (mode.equalsIgnoreCase(CommonConstants.Mode.NEW)) { showCommissionNumberDialog(); } else { app.injectAndLeaveToForm(ReportEditForm.class, new FormArguments(job, null)); } } else if (CardType.TIME == cardType) { app.injectAndLeaveToForm(ReportTimeListForm.class, new ReportTimeListForm.ReportTimeListFormArguments(job, null)); } else if (CardType.CHECKLIST == cardType) { app.injectAndLeaveToForm(ReportChecklistForm.class, new FormArguments(job, null)); } else if (CardType.MATERIAL == cardType) { app.injectAndLeaveToForm(ReportMaterialListForm.class, new ReportMaterialListForm.ReportMaterialListFormArguments(job)); } else if (CardType.MESSAGE == cardType) { app.injectAndLeaveToForm(ReportMessageNewEditForm.class, new ReportMessageNewEditForm.FormArguments(job)); } else if (CardType.IMAGE == cardType) { app.injectAndLeaveToForm(ReportImageAttachmentsListForm.class, new ReportImageAttachmentsListForm.ReportImageAttachmentsListFormArguments(job)); } else if (CardType.DOCUMENT == cardType) { app.injectAndLeaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); } else if (CardType.MEASUREMENT == cardType) { app.injectAndLeaveToForm(ReportMeasurementForm.class, new ReportMeasurementForm.ReportMeasurementFormArguments(job)); } else if (CardType.FORM == cardType) { app.injectAndLeaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); } } }); return editImageView; } private void createTimeContents(final String timeInfo, LinearLayout linearLayout) { if (timeInfo != null) { ImageView timeInfoImageView = new ImageView(context); LinearLayout.LayoutParams editImageViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); editImageViewParams.rightMargin = 30; timeInfoImageView.setLayoutParams(editImageViewParams); createStartStopTimeImage(job, timeInfoImageView); if (CommonConstants.Mode.STOP.equals(timeInfo)) { timeInfoImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean result = timeUtil.startJobTimeCapturing(job); if (result) { timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, job, new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { appendTimeContent(); onTimeAction.runOnTimeAction(); } }); } } }); } else { timeInfoImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timeUtil.stopTime(job, new RunOnUIThread() { @Override public void runOnUIThread() { appendTimeContent(); onTimeAction.runOnTimeAction(); } }); } }); } linearLayout.addView(timeInfoImageView); } } private void createStartStopTimeImage(final Job job, ImageView timeInfoImageView) { Images timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; timeInfoImageView.setEnabled(false); if (ServiceJobUtil.isJobStartTimeable(job)) { if (app.dbutil.selectPlayingJobReportTimeByReport(job.getCurrentReport()) != null) { timeStatusImage = ImagesUtil.Images.STOP_TIME; timeInfoImageView.setEnabled(true); } else { List jobWithOpenTimesheetList = app.dbutil.selectJobWithOpenTimesheet(); if(jobWithOpenTimesheetList.isEmpty()) { timeStatusImage = ImagesUtil.Images.START_TIME; timeInfoImageView.setEnabled(true); } else { timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; timeInfoImageView.setEnabled(false); for (Job jobWithOpenTimesheet : jobWithOpenTimesheetList) { if (jobWithOpenTimesheet.getPersonalNumber() == job.getPersonalNumber() && jobWithOpenTimesheet.getCommissionNumber().equalsIgnoreCase(job.getCommissionNumber()) && jobWithOpenTimesheet.getJobType() == job.getJobType()) { timeStatusImage = ImagesUtil.Images.START_TIME; timeInfoImageView.setEnabled(true); } } } } } timeInfoImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(timeStatusImage, CommonConstants.Images.IMAGE_DPI))); } private void appendReportData() { Address address = job.getObjectAddress(); GridLayout gridLayout = createGridLayout(ServiceMessages.getString("reportData")); //$NON-NLS-1$ gridLayout.setColumnCount(1); gridLayout.setContentDescription("reportData"); if (job.getCurrentReport().getReportStatus().isNew() || job.getStatus().isFinalized()) { String comNo = job.getCommissionNumber(); if (StringUtil.isNotEmpty(job.getCurrentReport().getCommissionNumber()) && job.getCurrentReport().getCommissionNumber().length() > 1) { comNo = job.getCurrentReport().getCommissionNumber(); } // Anlagen-Nummer if (StringUtil.isNotEmpty(comNo)) createReportTextView(gridLayout, comNo, textColor); // Standort if (StringUtil.isNotEmpty(address.getLocation())) { createReportTextView(gridLayout, address.getLocation(), textColor); } // Strasse / PLZ / Anlage-Ort if (StringUtil.isNotEmpty(address.getStreet()) || StringUtil.isNotEmpty(address.getPostalCode()) || StringUtil.isNotEmpty(address.getCity())) createReportTextView(gridLayout, address.getStreet() + " " + address.getPostalCode() + " " + address.getCity(), textColor); //$NON-NLS-1$ //$NON-NLS-2$ if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.REPORT_DATA); } } else { createReportTextView(gridLayout, Messages.getString("noReportRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ if ((job.getStatus().isReceived() || job.getStatus().isPartlyDone() || job.getStatus().isInProgress()) && !job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.REPORT_DATA, CommonConstants.Mode.NEW); } } cardLinearLayout.addView(cardView); } private void appendTime() { timeGridLayout = createGridLayout(Messages.getString("times")); //$NON-NLS-1$ timeGridLayout.setColumnCount(1); appendTimeContent(); ((LayoutParams) cardView.getLayoutParams()).topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; cardLinearLayout.addView(cardView); } private void appendTimeContent() { Report report = job.getCurrentReport(); log.info("report status " + report.getReportStatus().toString()); log.info("report guid " + report.getGuId() + " has times -> " + report.getTimes().size()); timeGridLayout.removeAllViews(); String timeInfo = CommonConstants.Mode.STOP; // Aufgewendete Zeit (nur wenn vorhanden) report.loadTimes(app.dbutil); List reportTimeList = report.getTimes(); if (reportTimeList.isEmpty()) { createReportTextView(timeGridLayout, Messages.getString("noTimesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ createReportTextViewWithIcon(timeGridLayout, timeInfo, CardType.TIME, CommonConstants.Mode.NEW); } else { long diffTime = 0; for (int i = 0; i < reportTimeList.size(); i++) { JobReportTime reportTime = reportTimeList.get(i); WorkType WorkType = app.dbutil.selectWorkTypeByJobTypeAndWorkTypeCode(job.getJobType(), reportTime.getWorkTypeCode()); String workType = (WorkType == null ? "" : WorkType.getText()); if (!DateUtils.getInitialDateTime().equals(reportTime.getStopTime())) { timeInfo = CommonConstants.Mode.STOP; createReportTextView(timeGridLayout, DateTimeUtil.showDate(reportTime.getDate()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(reportTime.getStartTime()) + "-" //$NON-NLS-1$ + DateTimeUtil.showTime(reportTime.getStopTime()) + " " //$NON-NLS-1$ + workType); } else { timeInfo = CommonConstants.Mode.PLAYING; createReportTextView(timeGridLayout, DateTimeUtil.showDate(reportTime.getDate()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(reportTime.getStartTime()) + "-", LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } diffTime += DateTimeUtil.getTimeDifference(reportTime.getStopTime(), reportTime.getStartTime()); } // total label createReportTextView(timeGridLayout, ServiceMessages.getString("total") //$NON-NLS-1$ , textColor); // time createReportTextView(timeGridLayout, DateTimeUtil.showTime(diffTime)); createReportTextViewWithIcon(timeGridLayout, timeInfo, CardType.TIME); } } private ImageView materialEditImageView; private void appendMaterials() { materialEditImageView = new ImageView(context); materialEditImageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); Images editImage = ImagesUtil.Images.EDIT; // if (mode.equalsIgnoreCase(CommonConstants.Mode.NEW)) { // editImage = ImagesUtil.Images.ADD_BLACK; // } materialEditImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(editImage, CommonConstants.Images.IMAGE_DPI))); materialEditImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { app.injectAndLeaveToForm(ReportMaterialListForm.class, new ReportMaterialListForm.ReportMaterialListFormArguments(job)); } }); GridLayout gridLayout = createGridLayout(Messages.getString("material")); //$NON-NLS-1$ gridLayout.setColumnCount(1); // Verwendetes Material (nur wenn vorhanden) List reportMatList = app.dbutil.selectReportMaterialListByLimit(job.getLatestReport().getGuId(), 3); if (!reportMatList.isEmpty()) { for (int i = 0; i < reportMatList.size(); i++) { ReportMaterial reportMat = reportMatList.get(i); Material part = app.dbutil.selectMaterialByMatNo(reportMat.getSparePartNumber()); String material = reportMat.getAmount() + " " + reportMat.getUnit(); //$NON-NLS-1$ if (part == null) { material += " " + reportMat.getProductName(); //$NON-NLS-1$ } else { material += " " + part.getMaterialShortText(); //$NON-NLS-1$ } createReportTextView(gridLayout, material, textColor); } if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.MATERIAL); } } else { createReportTextView(gridLayout, Messages.getString("noMaterialRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ if (!job.getStatus().isNew() && !job.getStatus().isForwarded() && !job.getStatus().isFinalized()) { AppCompatCheckBox noMaterial = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("noMaterialused")); //$NON-NLS-1$ RelativeLayout.LayoutParams gridCheckBoxViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridCheckBoxViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); noMaterial.setLayoutParams(gridCheckBoxViewValueParams); log.info("isNoMaterial " + job.getLatestReport().isNoMaterial()); noMaterial.setChecked(job.getLatestReport().isNoMaterial()); materialEditImageView.setVisibility(View.VISIBLE); noMaterial.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton paramCompoundButton, final boolean checked) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { job.getLatestReport().setNoMaterial(checked); log.info("report " + job.getLatestReport().getGuId() + " status " + job.getLatestReport().getReportStatus().toString() + " isNoMaterial " + job.getLatestReport().isNoMaterial()); app.dbutil.insertReplaceReport(job.getLatestReport()); // app.dbutil.updateReport(report); app.dbutil.updateJob(job); job.loadReports(app.dbutil); log.info("report " + app.dbutil.selectCountFromTable(DbConstants.Report.REPORT, " WHERE " + DbConstants.Report.GUID + "='" + job.getLatestReport().getGuId()+ "'")); Report report = job.getLatestReport(); log.info("report " + report.getGuId() + " status " + report.getReportStatus().toString() + " isNoMaterial " + report.isNoMaterial()); return null; } @Override protected void runOnUIThread() { if(checked) { materialEditImageView.setVisibility(View.INVISIBLE); } else { materialEditImageView.setVisibility(View.VISIBLE); } } }; } }); createReportViewWithIcon(gridLayout, null, CardType.MATERIAL, CommonConstants.Mode.NEW, noMaterial, materialEditImageView); } } cardLinearLayout.addView(cardView); } private void appendMessages() { Report report = job.getCurrentReport(); GridLayout gridLayout = createGridLayout(Messages.getString("messages")); //$NON-NLS-1$ String messageId = ""; //$NON-NLS-1$ List reportTextList = app.dbutil.selectJobMessageListByReport(report); boolean isEmptyMessage = true; for (int i = 0; i < reportTextList.size(); i++) { JobMessage zkdmobmsg = reportTextList.get(i); String messageIdTemp = zkdmobmsg.getMessageId(); String key = ""; //$NON-NLS-1$ if (!messageId.equals(messageIdTemp)) { key = app.enumUtil.messageRecipientEnum.get(zkdmobmsg.getMessageId()); } String message = ""; log.info("zkdmobmsg " + zkdmobmsg.getMessageCode()); if(job.getJobType().isMON()) { JobMonText jobMonText = app.dbutil.selectReportMONMessageByMsgcAndLangu(zkdmobmsg.getMessageCode(), ""); if(jobMonText != null) { message = jobMonText.getText(); } } else { ReportMessage reportMessage = app.dbutil.selectReportMessageByMsgc(zkdmobmsg.getMessageCode()); if(reportMessage != null) { message = reportMessage.getMessage(); } } if(!message.isEmpty() || !zkdmobmsg.getFullText().isEmpty()) { isEmptyMessage = false; createReportTextView(gridLayout, key, message, true); createReportTextView(gridLayout, "", zkdmobmsg.getFullText()); //$NON-NLS-1$ } } if (isEmptyMessage) { createReportTextView(gridLayout, Messages.getString("noMessagesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ createReportTextViewWithIcon(gridLayout, null, CardType.MESSAGE, CommonConstants.Mode.NEW); } else { if (!job.getStatus().isFinalized()) { createReportTextView(gridLayout, ""); //$NON-NLS-1$ createReportTextViewWithIcon(gridLayout, null, CardType.MESSAGE); } } cardLinearLayout.addView(cardView); } private void appendImages() { GridLayout gridLayout = createGridLayout(Messages.getString("images")); //$NON-NLS-1$ gridLayout.setColumnCount(1); List reportImageAttachmentsList = app.dbutil.selectReportJobFileImageListByReport(job.getLatestReport()); // If no data available: "No report images captured"; text red // // If a document was added: "At least 5 images necessary", text red // if image(s) added: text black, status of report images if (!reportImageAttachmentsList.isEmpty()) { createReportTextView(gridLayout, reportImageAttachmentsList.size() + " " + Messages.getString("images"), textColor); int sentCount = 0; for (JobFile jobFile : reportImageAttachmentsList) { if (jobFile.getSentDate().getTime() > 0) { sentCount++; } } String status = ServiceMessages.getString("status") + ": "; if (sentCount == 0) { // "Not send" when no image was send to backend yet status += ServiceMessages.getString("notSend"); } else if (sentCount < reportImageAttachmentsList.size()) { // "Partially send" when some (but not all) images are send status += ServiceMessages.getString("partiallySend"); } else if (sentCount == reportImageAttachmentsList.size()) { // "Send" when all images are send to backend already status += ServiceMessages.getString("sent"); } createReportTextView(gridLayout, status, textColor); if (!ServiceJobUtil.isInstallationWorkTypeComplete(job)) { createReportTextView(gridLayout, MessageFormat.format(ServiceMessages.getString("AtLeastXImagesNecessary") , new Object[] { ServiceConstants.REQUIRE_IMAGE}), LayoutUtils.DEFAULT_ERROR_COLOR); } if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.IMAGE); } } else { String text = Messages.getString("noImagesRecorded"); int imageRequire = 0; if (!ServiceJobUtil.isReportImageComplete(job)) { imageRequire = 1; } if (!ServiceJobUtil.isInstallationWorkTypeComplete(job)) { imageRequire = ServiceConstants.REQUIRE_IMAGE; } if (imageRequire > 0) { text = MessageFormat.format(ServiceMessages.getString("AtLeastXImagesNecessary") , new Object[] { imageRequire}); } createReportTextView(gridLayout, text, LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ createReportTextViewWithIcon(gridLayout, null, CardType.IMAGE, CommonConstants.Mode.NEW); } cardLinearLayout.addView(cardView); } private void appendDocuments() { GridLayout gridLayout = createGridLayout(Messages.getString("documents")); //$NON-NLS-1$ gridLayout.setColumnCount(1); List documentRequires = ServiceJobUtil.isReportDocsComplete(job); if (!job.getCurrentReport().getDocumentAttachments().isEmpty()) { Iterator> iterator = job.getLatestReport().getDocumentFormDescMap().values().iterator(); while (iterator.hasNext()) { List jobFiles = iterator.next(); JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(jobFiles.get(0).getFormDesc()); String docText = jobFiles.size() + " " + jobFormDesc.getText(); if (jobFiles.get(0).getNoForm().isEmpty()) { docText = jobFiles.size() + " " + jobFormDesc.getText(); } else { // noForm docText = jobFormDesc == null ? "":jobFormDesc.getText() + " :" + app.dbutil.selectJobNoFormByNoForm(jobFiles.get(0).getNoForm()).getText(); } documentRequires.remove(jobFiles.get(0).getFormDesc()); createReportTextView(gridLayout, docText, textColor); } showRequire(gridLayout, documentRequires); if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.DOCUMENT); } } else { if (!ServiceJobUtil.isReportDocsComplete(job).isEmpty()) { showRequire(gridLayout, documentRequires); } else { createReportTextView(gridLayout, Messages.getString("noDocumentsRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); } createReportTextViewWithIcon(gridLayout, null, CardType.DOCUMENT, CommonConstants.Mode.NEW); } cardLinearLayout.addView(cardView); } private void showRequire(GridLayout gridLayout, List documentRequires) { documentRequires = ServiceJobUtil.isReportDocsComplete(job); if (!documentRequires.isEmpty()) { for (String formDocRequire : documentRequires) { JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(formDocRequire); if (jobFormDesc != null) { createReportTextView(gridLayout, getDocumentRequireMessage(jobFormDesc.getText()), textColor); } } } } private String getDocumentRequireMessage(String jobFormDesc) { return MessageFormat.format(ServiceMessages.getString("DocumentReqired"), new Object[] { jobFormDesc}); } private void appendMeasurements() { GridLayout gridLayout = createGridLayout(Messages.getString("measurement")); //$NON-NLS-1$ gridLayout.setColumnCount(1); job.getLatestReport().loadMeasurements(app.dbutil); if (!job.getLatestReport().getMeasurements().isEmpty()) { // If no measurement done: "No measurement available"; text red // If a measurement is done: "Measurement: Complete"; text black // If a measurement has errors or is not complete: "Measurement incomplete", text red // TODO how to know that measurement is error if (!job.getStatus().isNew() && !job.getStatus().isForwarded() && !job.getStatus().isFinalized()) { if (ServiceJobUtil.isTooMuchMeasurementAreMadeForOnemeasurePoint(job.getLatestReport().getMeasurements())) { createReportTextView(gridLayout, ServiceJobUtil.getTooMuchMeasurementAreMadeForOnemeasurePointMessage(), LayoutUtils.DEFAULT_ERROR_COLOR); } else { createReportTextView(gridLayout, ServiceMessages.getString("MeasurementComplete"), textColor); } if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.MEASUREMENT); } } } else { createReportTextView(gridLayout, Messages.getString("noMeasurementsRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); createReportTextViewWithIcon(gridLayout, null, CardType.MEASUREMENT, CommonConstants.Mode.NEW); } // TODO If a measurement has errors or is not complete: "Measurement incomplete", text red cardLinearLayout.addView(cardView); } private void appendChecklist() { GridLayout gridLayout = createGridLayout(ServiceMessages.getString("Checklist")); //$NON-NLS-1$ gridLayout.setColumnCount(1); if (job.getLatestReport().isChedklistEdited()) { createReportTextView(gridLayout, ServiceMessages.getString("completed"), textColor); if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.CHECKLIST); } } else { createReportTextView(gridLayout, ServiceMessages.getString("notEdit"), LayoutUtils.DEFAULT_ERROR_COLOR); createReportTextViewWithIcon(gridLayout, null, CardType.CHECKLIST, CommonConstants.Mode.NEW); } cardLinearLayout.addView(cardView); } private void appendForms() { GridLayout gridLayout = createGridLayout(ServiceMessages.getString("Forms")); //$NON-NLS-1$ gridLayout.setColumnCount(2); String mode = CommonConstants.Mode.NEW; // If no form edited or done: // Icon: + (add) // Active: Always, until report was send // // If a form is edited or done: // Icon: (Edit) // Active: Until report was send // ZKDMOB.FORMDESC1 = 01 (document required as mandatory for user to add an attachment or a generic form to report) // Now check FORM.ID (CHAR4) the 2nd and 3rd digit // -> If those digits of FORM.ID (for example F010)are the same as in ZKKDMOB.FORMDESC1 (in this case 01), the user has to add this generic form // -> If those digits of FORM.ID (for example F020) aren't the same (in this case 01), the user has to add a document as a picture (as already implemented actually) if (app.dbutil.selectFormInstanceListByGuid( job.getLatestReport().getGuId()).isEmpty()) { gridLayout.setColumnCount(1); List documentRequires = ServiceJobUtil.isReportDocsComplete(job); if (!documentRequires.isEmpty()) { for (String formDocRequire : documentRequires) { JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(formDocRequire); String text = MessageFormat.format(ServiceMessages.getString("FormReqired"), new Object[] { jobFormDesc.getText()}); createReportTextView(gridLayout, text, LayoutUtils.DEFAULT_ERROR_COLOR); } } else { createReportTextView(gridLayout, ServiceMessages.getString("noFormsRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); } } else { gridLayout.setColumnCount(2); for (Form form : app.dbutil.selectFormList()) { List formItemList = app.dbutil.selectFormItemListByFormIdAndFormVersion(form.getId(), form.getVersion()); if (!formItemList.isEmpty()) { List formInstances = app.dbutil.selectFormInstanceListByGuidAndFormId(job.getLatestReport().getGuId(), form.getId()); if (!formInstances.isEmpty()) { gridLayout.addView(createFormGridLayout(form, formInstances, formItemList)); if (ServiceFormUtil.isFormEdited(formInstances) || ServiceFormUtil.isFormDone(formItemList, formInstances)) { mode = CommonConstants.Mode.EDIT; } } } } } createReportTextViewWithIcon(gridLayout, null, CardType.FORM, mode); cardLinearLayout.addView(cardView); } private GridLayout createFormGridLayout(Form form, List formInstances, List formItemList) { GridLayout formGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); formGridLayout.setLayoutParams(gridLayoutParams); formGridLayout.setColumnCount(2); formGridLayout.setUseDefaultMargins(true); formGridLayout.setColumnCount(2); LinearLayout formCheckedLayout = new LinearLayout(context); formCheckedLayout.setOrientation(LinearLayout.HORIZONTAL); formCheckedLayout.setPadding(0, 0, 0, 0); ImageView checkImageView = new ImageView(context); LinearLayout.LayoutParams checkImageRelativeLayoutParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 26), LayoutUtils.convertDpToPixel(context, 26)); checkImageRelativeLayoutParams.gravity = Gravity.CENTER_VERTICAL; checkImageRelativeLayoutParams.weight = 0.20f; checkImageRelativeLayoutParams.leftMargin = 0; checkImageView.setLayoutParams(checkImageRelativeLayoutParams); checkImageView.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage( ServiceFormUtil.getCheckImageStatus( formItemList, formInstances) , CommonConstants.Images.IMAGE_DPI))); formCheckedLayout.addView(checkImageView); LinearLayout formNameLayout = new LinearLayout(context); formNameLayout.setOrientation(LinearLayout.HORIZONTAL); formNameLayout.setPadding(0, 0, 0, 0); TextView formName = new TextView(context); formName.setGravity(Gravity.CENTER_VERTICAL); formName.setText(form.getName()); formName.setTextColor(job.getStatus().isFinalized()? textColor:ServiceFormUtil.getTextColor(formItemList, formInstances)); LinearLayout.LayoutParams formNameTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); formNameTextParams.width = 0; formNameTextParams.weight = 0.80f; formNameTextParams.gravity = Gravity.CENTER_VERTICAL; formNameTextParams.topMargin = 6; formName.setLayoutParams(formNameTextParams); formNameLayout.addView(formName); formGridLayout.addView(formCheckedLayout); formGridLayout.addView(formNameLayout); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = 0; params.height = LayoutParams.WRAP_CONTENT; params.columnSpec = GridLayout.spec(0, 2, 1f); formGridLayout.setLayoutParams(params); return formGridLayout; } private void showCommissionNumberDialog() { List items = new ArrayList(); items.add(ServiceMessages.getString("correct") + " " + job.getCommissionNumber()); //$NON-NLS-1$ if(!job.getJobType().isMON()) { items.add(ServiceMessages.getString("unknown")); //$NON-NLS-1$ } items.add(ServiceMessages.getString("invalid")); //$NON-NLS-1$ MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("commNoCheck"),ServiceMessages.getString("cancel")); //$NON-NLS-1$ //$NON-NLS-2$ if((job.getJobType().isMON() || job.getJobType().isSAV() || job.getJobType().isREP()) && !job.getCommissionNumber().isEmpty()) { commissionType = CommonConstants.CommissionNumber.Type.CORRECT; } else { commissionType = CommonConstants.CommissionNumber.Type.UNKNOWN; } alertDialog.setSingleChoiceItems(items.toArray(new String[0]), commissionType.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(!job.getJobType().isMON()) { switch (which) { case 0: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; break; case 1: commissionType = CommonConstants.CommissionNumber.Type.UNKNOWN; break; case 2: commissionType = CommonConstants.CommissionNumber.Type.INVALID; break; default: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; } } else { switch (which) { case 0: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; break; case 1: commissionType = CommonConstants.CommissionNumber.Type.INVALID; break; default: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; } } } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new DialogInterface.OnClickListener() { //$NON-NLS-1$ @Override public void onClick(DialogInterface dialog, int which) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportEditForm.class, new FormArguments(job, commissionType)); } }, false); } }); alertDialog.show(); } public static class FormArguments { private Job job; private CommonConstants.CommissionNumber.Type commissionType; protected FormArguments() { } public FormArguments(Job job, CommonConstants.CommissionNumber.Type commissionType) { this.job = job; this.commissionType = commissionType; } public Job getJob() { return job; } public CommonConstants.CommissionNumber.Type getCommissionType() { return commissionType; } } private OnTimeAction onTimeAction; public interface OnTimeAction { void runOnTimeAction(); } public void setOnTimeActionListener(OnTimeAction onTimeAction) { this.onTimeAction = onTimeAction; } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.businessobjects.JobNoForm; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportDocumentDetailForm extends SuperForm { private static Log log = LogFactory.getLog(ReportDocumentDetailForm.class); private Toolbar toolbar; protected ImageListWidget listWidget; private ActionUtil utilButton; private ActionCtrl addButton; private Button deleteButton; private LinearLayout emptyMessageView; private LinearLayout listLinearLayout; private MDSpinner documentSpinner; private AppCompatCheckBox notRecordedCheckBox; private MDSpinner reasonSpinner; private Job job; private JobFile doc; private List jobFiles; private boolean noForm1; private boolean noForm2; private boolean noForm3; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportDocumentDetailFormArguments) { ReportDocumentDetailFormArguments formArguments = (ReportDocumentDetailFormArguments) argument; jobFiles = formArguments.getJobFiles(); job = formArguments.getJob(); doc = jobFiles.isEmpty() ? null:jobFiles.get(0); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); utilButton = new ActionUtil(app); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); // create add button Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout documentLinearLayout = new LinearLayout(context); documentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); documentLinearLayout.setOrientation(LinearLayout.VERTICAL); documentSpinner = MDSpinner.createDefaultSpinner(documentLinearLayout, ServiceMessages.getString("Document"), true); //$NON-NLS-1$ documentSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { documentSpinner.clearError(); notRecordedCheckBox.setEnabled(false); if (position == 0) { return; } seteEnabledNotRecordedCheckBox(documentSpinner.getSelectedId()); } }); contentLinearLayout.addView(documentLinearLayout); notRecordedCheckBox = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("notRecorded")); //$NON-NLS-1$ notRecordedCheckBox.setChecked(false); notRecordedCheckBox.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { if(((AppCompatCheckBox)v).isChecked()){ reasonSpinner.setEnabled(true); } else { notRecordedCheckBox.setChecked(false); reasonSpinner.setEnabled(false); } reasonSpinner.clearError(); } }); contentLinearLayout.addView(notRecordedCheckBox); LinearLayout reasonLinearLayout = new LinearLayout(context); reasonLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); reasonLinearLayout.setOrientation(LinearLayout.VERTICAL); reasonSpinner = MDSpinner.createDefaultSpinner(reasonLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonSpinner.setTag("REASON"); //$NON-NLS-1$ reasonSpinner.setEnabled(false); // reasonSpinner.setOnItemSelectedListener(this); contentLinearLayout.addView(reasonLinearLayout); listLinearLayout = new LinearLayout(context); listLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams listLinearLayoutParams = new LinearLayout.LayoutParams(0,0); listLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; listLinearLayoutParams.height = LayoutParams.FILL_PARENT; listLinearLayoutParams.width = LayoutParams.FILL_PARENT; listLinearLayoutParams.weight = 1f; listLinearLayout.setLayoutParams(listLinearLayoutParams); listWidget = new ImageListWidget(context); listLinearLayout.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, Messages.getString("noDocumentsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); contentLinearLayout.addView(listLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (doc == null) { documentSpinner.clearError(); documentSpinner.setSelection(0); notRecordedCheckBox.setChecked(false); reasonSpinner.clearError(); reasonSpinner.setEnabled(false); } else { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("areYouSureThatYouWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } if (noForm1) { job.getLatestReport().setNoForm1(""); } else if (noForm2) { job.getLatestReport().setNoForm2(""); } else if (noForm3) { job.getLatestReport().setNoForm3(""); } app.dbutil.insertReplaceReport(job.getLatestReport()); for (JobFile jobFile : jobFiles) { app.dbutil.deleteJobFile(jobFile); } jobFiles.clear(); return app.leaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); } }, false); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(Messages.getString("documents")); //$NON-NLS-1$ loadData(); return null; } public void loadData() { List jobFormDescValueList = new ArrayList(); List jobFormDescs = app.dbutil.selectJobFormDescList(); for (JobFormDesc jobFormDesc : jobFormDescs) { log.info("FormDesc " + jobFormDesc.getFormDesc() + " Text " + jobFormDesc.getText()); jobFormDescValueList.add(new CustomSpinnerItem((String) jobFormDesc.getFormDesc(), (String) jobFormDesc.getText())); } documentSpinner.setContents(jobFormDescValueList); List jobNoFormValueList = new ArrayList(); List jobNoForms = app.dbutil.selectJobNoFormList(); for (JobNoForm jobNoForm : jobNoForms) { log.info("NoForm " + jobNoForm.getNoForm() + " Text " + jobNoForm.getText()); jobNoFormValueList.add(new CustomSpinnerItem((String) jobNoForm.getNoForm(), (String) jobNoForm.getText())); } reasonSpinner.setContents(jobNoFormValueList); notRecordedCheckBox.setEnabled(false); notRecordedCheckBox.setChecked(false); reasonSpinner.setEnabled(false); if (doc == null) { deleteButton.setText(ServiceMessages.getString("clear")); } else { deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ documentSpinner.setSelectionById(doc.getFormDesc()); loadNoForm(); } documentSpinner.setRequired(ServiceJobUtil.isJobRequireFormDesc(job)); loadImageAttachmentsList(); } private void seteEnabledNotRecordedCheckBox(String formDesc) { noForm1 = false; noForm2 = false; noForm3 = false; if (formDesc.equalsIgnoreCase(job.getFormDesc1())) { noForm1 = true; } if (formDesc.equalsIgnoreCase(job.getFormDesc2())) { noForm2 = true; } if (formDesc.equalsIgnoreCase(job.getFormDesc3())) { noForm3 = true; } notRecordedCheckBox.setEnabled(noForm1 || noForm2 || noForm3 || (ServiceJobUtil.isMandatoryByReportMessage(job) && formDesc.equalsIgnoreCase(ServiceConstants.ModernisationNecessary))); if (!notRecordedCheckBox.isEnabled()) { notRecordedCheckBox.setChecked(false); reasonSpinner.setEnabled(false); reasonSpinner.setSelection(0); } } private void loadNoForm() { seteEnabledNotRecordedCheckBox(doc.getFormDesc()); if (notRecordedCheckBox.isEnabled()) { reasonSpinner.setSelectionById(doc.getNoForm()); notRecordedCheckBox.setChecked(!doc.getNoForm().isEmpty()); } reasonSpinner.setEnabled(notRecordedCheckBox.isEnabled() && notRecordedCheckBox.isChecked()); } private void loadImageAttachmentsList() { listWidget.clean(); ArrayList items = new ArrayList(); listLinearLayout.removeAllViews(); if(!jobFiles.isEmpty() && !jobFiles.get(0).getJobFileId().contains("NO_FORM")) { for (int i = 0; i < jobFiles.size(); i++) { final JobFile jobFile = jobFiles.get(i); if (!jobFiles.get(0).getJobFileId().contains("NO_FORM")) { final ImageListWidgetItem item = new ImageListWidgetItem(); item.setDescription(jobFile.getDescription()); item.setImageBitmap(jobFile.getSignPicBitmap()); item.setType(jobFile.getJobFileId()); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(jobFiles)); } } listWidget.addItems(items); listLinearLayout.addView(listWidget); } else { listLinearLayout.addView(emptyMessageView); } } private OnItemClickListener createOnItemClickListener(final List reportImageAttachmentsList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { JobFile jobFile = reportImageAttachmentsList.get(position); app.injectAndLeaveToForm(ReportDocumentAttachmentsNewEditForm.class, new ReportDocumentAttachmentsNewEditForm.ReportDocumentAttachmentsNewEditFormArguments(job, null, jobFile, jobFiles)); //$NON-NLS-1$ } }; } private void leaveToImageNewEditForm(Bitmap bitmap) { if(bitmap == null) return; if(!jobFiles.isEmpty() && jobFiles.get(0).getJobFileId().contains("NO_FORM")) { app.dbutil.deleteJobFile(jobFiles.get(0)); jobFiles.remove(jobFiles.get(0)); if (noForm1) { job.getLatestReport().setNoForm1(""); } else if (noForm2) { job.getLatestReport().setNoForm2(""); } else if (noForm3) { job.getLatestReport().setNoForm3(""); } app.dbutil.insertReplaceReport(job.getLatestReport()); } JobFile jobFile = new JobFile(); jobFile.setGuid(job.getLatestReport().getGuId()); jobFile.setJobNumber(job.getJobNumber()); jobFile.setJobType(job.getJobType()); jobFile.setType("F"); jobFile.setFormType(new FormType(FormType.JPG)); app.injectAndLeaveToForm(ReportDocumentAttachmentsNewEditForm.class, new ReportDocumentAttachmentsNewEditForm.ReportDocumentAttachmentsNewEditFormArguments(job, bitmap, assignToJobFile(jobFile), jobFiles)); } protected ApplicationEvent onAddPressed() { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, null); return null; } @Override public ApplicationEvent onBackPressed() { if (isCancelEdited()) { return app.leaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); } new AsyncTask(this) { private Object errorView = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (doc != null && doc.getNoForm().isEmpty() && notRecordedCheckBox.isChecked() && !isEmptyDocument()) { // change doc attachment to noForm if (app.showMessageBox(ServiceMessages.getString("DocumentsWillBeLost"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } } errorView = saveDocuments(); return null; } @Override public void runOnUIThread() { if (errorView != null) { if(errorView instanceof MDSpinner) { ((MDSpinner) errorView).setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } } }; return null; } private boolean isCancelEdited() { if (doc == null && documentSpinner.getSelectedItemPosition() == 0 && !notRecordedCheckBox.isChecked()) { // cancel create new return true; } if (doc != null && doc.getFormDesc().equalsIgnoreCase(documentSpinner.getSelectedId()) && !doc.getNoForm().isEmpty() && notRecordedCheckBox.isChecked() && doc.getNoForm().equalsIgnoreCase(reasonSpinner.getSelectedId())) { return true; } return false; } private boolean isEmptyDocument() { return (jobFiles.isEmpty() || (!jobFiles.isEmpty() && jobFiles.get(0).getJobFileId().contains("NO_FORM"))); } private Object saveDocuments() { log.info("no form " + reasonSpinner.getSelectedId() + " form desc " + documentSpinner.getSelectedId()); if (documentSpinner.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) && !notRecordedCheckBox.isChecked()) { return documentSpinner; } if (notRecordedCheckBox.isEnabled() && !notRecordedCheckBox.isChecked() && isEmptyDocument()) { app.showMessage("Cannot save document, Please add a file."); return null; } if (!notRecordedCheckBox.isEnabled() && isEmptyDocument()) { app.showMessage("Cannot save document, Please add a file."); return null; } if (notRecordedCheckBox.isEnabled() && notRecordedCheckBox.isChecked() && reasonSpinner.getSelectedId().contentEquals(CommonConstants.PLEASE_SELECT)) { return reasonSpinner; } if ((doc == null) || (doc != null && !doc.getFormDesc().equalsIgnoreCase(documentSpinner.getSelectedId()))) { List documentFileList = app.dbutil.selectDocumentFileListByReport(job.getLatestReport(), documentSpinner.getSelectedId()); List documentFileNoFormList = app.dbutil.selectDocumentFileNoFormListByReportAndDormDesc(job.getLatestReport(), documentSpinner.getSelectedId()); if (!documentFileList.isEmpty()) { // NoForm - > doc already attach some file. showDocAlreadyExisDialog(documentFileList.get(0).getFormDesc()); return null; } else if (!documentFileNoFormList.isEmpty()) { // doc -> NoForm showDocAlreadyExisDialog(documentFileNoFormList.get(0).getFormDesc()); return null; } } if (doc != null && doc.getNoForm().isEmpty() && notRecordedCheckBox.isChecked() && !isEmptyDocument()) { // if (doc != null && notRecordedCheckBox.isChecked() && (!jobFiles.isEmpty() && !jobFiles.get(0).getFormDesc().contains("NO_FORM"))) { for (JobFile jobFile : jobFiles) { app.dbutil.deleteJobFile(jobFile); } jobFiles.clear(); } if (notRecordedCheckBox.isEnabled() && notRecordedCheckBox.isChecked() && !reasonSpinner.getSelectedId().contentEquals(CommonConstants.PLEASE_SELECT)) { if (doc != null) { app.dbutil.deleteJobFile(doc); } doc = new JobFile(); Date date = new Date(); doc.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + reasonSpinner.getSelectedId()); doc.setGuid(job.getLatestReport().getGuId()); doc.setJobNumber(job.getJobNumber()); doc.setJobType(job.getJobType()); doc.setType("F"); app.dbutil.insertJobFile(assignToJobFile(doc)); assignNoFormToReport(notRecordedCheckBox.isChecked() ? reasonSpinner.getSelectedId():""); } // todo case noform chage doc to not empty doc add 1 docimage -> remove all docimage in that doc? for (JobFile jobFile : jobFiles) { app.dbutil.updateJobFile(assignToJobFile(jobFile)); } app.injectAndLeaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); return null; } private void showDocAlreadyExisDialog(final String formDesc) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { app.showMessageBox(MessageFormat.format(ServiceMessages.getString("CannotSaveDocAlreadyExist"), new Object[] { app.dbutil.selectJobFormDescByFormDesc(formDesc).getText()}), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING); return null; } @Override public void runOnUIThread() { if (doc != null) { documentSpinner.setSelectionById(doc.getFormDesc()); } } }; } private void assignNoFormToReport(String noForm) { if (noForm.isEmpty()) { return; } if (noForm1) { job.getLatestReport().setNoForm1(noForm); } else if (noForm2) { job.getLatestReport().setNoForm2(noForm); } else if (noForm3) { job.getLatestReport().setNoForm3(noForm); } app.dbutil.insertReplaceReport(job.getLatestReport()); } private JobFile assignToJobFile(JobFile jobFile) { jobFile.setFormDesc(documentSpinner.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) ? "":documentSpinner.getSelectedId()); return jobFile; } public static class ReportDocumentDetailFormArguments { private List jobFiles; private Job job; public ReportDocumentDetailFormArguments(Job job, List jobFiles) { this.job = job; this.jobFiles = jobFiles; } public Job getJob() { return job; } public List getJobFiles() { return jobFiles; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.support.v7.widget.AppCompatRadioButton; import android.support.v7.widget.GridLayout; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportImageAttachmentsListForm.ReportImageAttachmentsListFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportImageAttachmentsNewEditForm extends DialogForm { private static Log log = LogFactory.getLog(ReportImageAttachmentsNewEditForm.class); // initialized by the kolibri framework... public static ServiceApplication app; private Job job; private Bitmap bitmap; private JobFile jobFile; private ImageView image; private ActionCtrl sendAction; private AppCompatRadioButton internalRadioButton; private AppCompatRadioButton externalRadioButton; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil actionUtil; private LinearLayout sentDateLinearLayout; private TextView sentDateText; private Button deleteButton; private boolean isSent = false; @Override public void onFormCall(Object argument) { if (argument instanceof ReportImageAttachmentsNewEditFormArguments) { ReportImageAttachmentsNewEditFormArguments formArguments = (ReportImageAttachmentsNewEditFormArguments) argument; job = formArguments.getJob(); bitmap = formArguments.getBitmap(); jobFile = formArguments.getJobFile(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; actionUtil = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); sendAction = addActionCtrl(false, true, 1, "onSendingReportImage"); //$NON-NLS-1$ // set invisible save button saveButton.setVisible(false); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMaxHeight(800); image.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { actionUtil.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, null); return false; } }); contentLinearLayout.addView(image); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroup.setPadding(2, 2, 2, 2); radioGroup.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.addView(radioGroup); ColorStateList colorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_enabled } }, new int[] { LayoutUtils.DEFAULT_TEXT_COLOR }); internalRadioButton = new AppCompatRadioButton(context); internalRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 3f)); internalRadioButton.setText(ServiceMessages.getString("internal")); //$NON-NLS-1$ internalRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); internalRadioButton.setSupportButtonTintList(colorStateList); internalRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); internalRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(internalRadioButton); externalRadioButton = new AppCompatRadioButton(context); externalRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); externalRadioButton.setText(ServiceMessages.getString("external")); //$NON-NLS-1$ externalRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); externalRadioButton.setSupportButtonTintList(colorStateList); externalRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); externalRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(externalRadioButton); messages = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("description"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); sentDateLinearLayout = new LinearLayout(context); sentDateLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); sentDateLinearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); sentDateLinearLayout.setOrientation(LinearLayout.VERTICAL); GridLayout sentTimeGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); sentTimeGridLayout.setLayoutParams(gridLayoutParams); sentTimeGridLayout.setColumnCount(2); sentTimeGridLayout.setUseDefaultMargins(true); TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.2f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(ServiceMessages.getString("sentDate")); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); sentTimeGridLayout.addView(gridTextViewKey); RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.8f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); sentDateText = new TextView(context); sentDateText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); sentDateText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_LEFT, RelativeLayout.TRUE); sentDateText.setLayoutParams(gridTextViewValueParams); sentDateText.setText("-"); sentDateText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(sentDateText); sentTimeGridLayout.addView(gridRelativeLayout); sentDateLinearLayout.addView(sentTimeGridLayout); contentLinearLayout.addView(sentDateLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { actionDelete(); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(contentLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("image")); //$NON-NLS-1$ messages.getText().clear(); image.setImageBitmap(null); sentDateText.setText(""); isSent = false; if (jobFile == null) { image.setImageBitmap(bitmap); if(!internalRadioButton.isChecked() && !externalRadioButton.isChecked()) { internalRadioButton.setChecked(true); } } else { bitmap = jobFile.getSignPicBitmap(); image.setImageBitmap(bitmap); if("I".equalsIgnoreCase(jobFile.getType())) { internalRadioButton.setChecked(true); externalRadioButton.setChecked(false); } else { internalRadioButton.setChecked(false); externalRadioButton.setChecked(true); } if(!jobFile.getDescription().isEmpty()) messages.setText(jobFile.getDescription()); if (jobFile.getSentDate().getTime() > 0) { isSent = true; sentDateText.setText(DateTimeUtil.HtmlDateTime(jobFile.getSentDate())); } } setControlsEnabled(); return null; } private String getType() { if(internalRadioButton.isChecked()) { return "I"; } return "E"; } @Override public ApplicationEvent onBackPressed() { saveImage(); return app.leaveToForm(ReportImageAttachmentsListForm.class, new ReportImageAttachmentsListFormArguments(job)); } private void saveImage() { if (jobFile == null) { jobFile = new JobFile(); Date date = new Date(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setGuid(job.getLatestReport().getGuId()); jobFile.setJobNumber(job.getJobNumber()); jobFile.setJobType(job.getJobType()); jobFile.setType(getType()); jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); app.dbutil.insertJobFile(jobFile); } else { jobFile.setType(getType()); jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); app.dbutil.updateJobFile(jobFile); } } private void actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } app.showMessage(ServiceMessages.getString("fileDeleted")); if(jobFile != null) { db.startTransaction(); try { app.dbutil.deleteJobFile(jobFile); } finally { db.commit(); } return onBackPressed(); } return app.leaveToForm(ReportImageAttachmentsListForm.class, new ReportImageAttachmentsListFormArguments(job)); } }; } public ApplicationEvent onSendingReportImage() { sendAction.setEnabled(false); saveImage(); if (new RemoteTransactionHandler().runSavePicture(jobFile)) { jobFile.setSentDate(new Date()); isSent = true; sentDateText.setText(DateTimeUtil.HtmlDateTime(jobFile.getSentDate())); app.dbutil.updateJobFile(jobFile); } setControlsEnabled(); return null; } private void setControlsEnabled() { if (isSent) { sendAction.setEnabled(false); sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { sendAction.setEnabled(true); sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); } image.setEnabled(!isSent); internalRadioButton.setClickable(!isSent); externalRadioButton.setClickable(!isSent); internalRadioButton.setTextColor(isSent? LayoutUtils.DEFAULT_LABEL_COLOR:LayoutUtils.DEFAULT_TEXT_COLOR); externalRadioButton.setTextColor(isSent? LayoutUtils.DEFAULT_LABEL_COLOR:LayoutUtils.DEFAULT_TEXT_COLOR); messages.setEnabled(!isSent); deleteButton.setEnabled(!isSent); sentDateLinearLayout.setVisibility(isSent ? View.VISIBLE:View.GONE); sentDateText.setVisibility(isSent ? View.VISIBLE:View.GONE); } public static class ReportImageAttachmentsNewEditFormArguments { private Job job; private Bitmap bitmap; private JobFile jobFile; public ReportImageAttachmentsNewEditFormArguments(Job zkdmob ,Bitmap bitmap, JobFile jobFile) { this.job = zkdmob; this.bitmap = bitmap; this.jobFile = jobFile; } public Job getJob() { return job; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public JobFile getJobFile() { return jobFile; } public void setJobFile(JobFile jobFile) { this.jobFile = jobFile; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDCalendar; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportTimeNewEditForm extends SuperForm implements OnItemSelectedListener { private static Log log = LogFactory.getLog(ReportTimeNewEditForm.class); private Job job; private JobReportTime time; private MDSpinner workTypeValue; private MDCalendar dateValue; private TimeEditText fromText; private TimeEditText toText; private Button deleteButton; private boolean isExistTime; private String defaultTime = "00:00"; @Override public void onFormCall(Object argument) { if (null == argument) { // create new time } else { if (argument instanceof ReportTimeListFormArguments) { ReportTimeListFormArguments formArguments = (ReportTimeListFormArguments) argument; time = formArguments.getTime(); job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout dateLinearLayout = new LinearLayout(context); dateLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; dateLinearLayout.setLayoutParams(leftIconLinearLayoutParams); final LinearLayout dayLinearLayout = new LinearLayout(context); dayLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams dateValueParams = new LinearLayout.LayoutParams(0, 0); dateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; dateValueParams.width = 0; dateValueParams.height = LayoutParams.MATCH_PARENT; dateValueParams.weight = 0.5f; dayLinearLayout.setLayoutParams(dateValueParams); // date dateValue = MDCalendar.createDefaultCalendar(dayLinearLayout, ServiceMessages.getString("date"), false); //$NON-NLS-1$ dateValue.setTag("DATUM"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) dateValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateValue.getUnderline().setLayoutParams(underlineLinearLayout); dateValue.setSimpleDateFormat(new SimpleDateFormat("dd.MM")); dateLinearLayout.addView(dayLinearLayout); fromText = TimeEditText.createDefaultEditText(dateLinearLayout,ServiceMessages.getString("from"), true); //$NON-NLS-1$ fromText.setTag("VON"); //$NON-NLS-1$ LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; fromText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); toText = TimeEditText.createDefaultEditText(dateLinearLayout, ServiceMessages.getString("to"), true); //$NON-NLS-1$ toText.setTag("BIS"); //$NON-NLS-1$ toText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); LinearLayout.LayoutParams toInputLayoutParams = new LinearLayout.LayoutParams(0, 0); toInputLayoutParams.gravity = Gravity.CENTER; toInputLayoutParams.width = 0; toInputLayoutParams.height = LayoutParams.MATCH_PARENT; toInputLayoutParams.weight = 0.5f; toText.getParentTextInputLayout().setLayoutParams(toInputLayoutParams); contentLinearLayout.addView(dateLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // work type workTypeValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("workType"), true); //$NON-NLS-1$ workTypeValue.setTag("ARBEITSART"); //$NON-NLS-1$ workTypeValue.setOnItemSelectedListener(this); contentLinearLayout.addView(workTypeLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (time == null) { resetTime(); workTypeValue.setSelectionById(job.getDefaultJobTimeARBA()); if (!isExistTime) { Calendar calendar = Calendar.getInstance(); dateValue.setSelectedDate(calendar.getTime()); dateValue.setEnabled(true); } } else { deleteTime(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } private void resetTime() { fromText.setText(defaultTime); fromText.clearFocus(); toText.setText(defaultTime); toText.clearFocus(); fromText.clearFocus(); toText.clearFocus(); fromText.getText().clear(); toText.getText().clear(); fromText.clearError(); toText.clearError(); } // private DatePickerDialog getDatePickerDialog() { // Calendar calendar = Calendar.getInstance(); // return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { // // @Override // public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // setDate(year, monthOfYear, dayOfMonth); // } // // }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); // } // private void setDate(int year, int monthOfYear, int dayOfMonth) { // Calendar calendar = DateTimeUtil.getToday(); // calendar.set(Calendar.YEAR, year); // calendar.set(Calendar.MONTH, monthOfYear); // calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); // // dateSelected = calendar.getTime(); // List dateTypeValueList = new ArrayList(); // dateValue.setSelectedDate(calendar.getTime()); // // String date = DateTimeUtil.showDayMonth(calendar.getTime()); // dateTypeValueList.add(new CustomSpinnerItem(date, date)); // dateValue.setContents(dateTypeValueList); // if (!isExistTime || job.getCurrentReport().getTimes().size() == 1) { // dateValue.setEnabled(true); // } // } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set invisible save button saveButton.setVisible(false); if(job.getJobType().isMON()) { workTypeValue.setRequired(true); workTypeValue.setEnabled(true); } else { workTypeValue.setRequired(false); workTypeValue.setEnabled(false); } loadData(); return null; } public void loadData() { resetTime(); isExistTime = !job.getCurrentReport().getTimes().isEmpty(); List workTypeValueList = new ArrayList(); List workTypeList = app.dbutil.selectWorkTypeListByJobType(job.getJobType()); for (WorkType workType : workTypeList) { log.info("WorkType " + workType.getWorkTypeCode() + " text " + workType.getText() + " Guarantee " + workType.isGuarantee()); workTypeValueList.add(new CustomSpinnerItem((String) workType.getWorkTypeCode(), (String) workType.getText())); } workTypeValue.setContents(workTypeValueList); //$NON-NLS-1$ Calendar calendar = Calendar.getInstance(); if (time == null) { if (isExistTime) { JobReportTime selectedTime = job.getCurrentReport().getTimes().get(0); calendar.setTime(selectedTime.getDate()); } dateValue.setSelectedDate(calendar.getTime()); setFormTitle(DateTimeUtil.showDate(job.getCurrentReport().getCreateDate())); if (job.getLatestReport().getTimes().isEmpty()) workTypeValue.setSelectionById(job.getDefaultJobTimeARBA()); else workTypeValue.setSelectionById((job.getLatestReport().getTimes().get(0)).getWorkTypeCode()); deleteButton.setText(ServiceMessages.getString("clear")); //$NON-NLS-1$ if (isExistTime) { dateValue.setEnabled(false); } else { dateValue.setEnabled(true); } } else { loadTime(calendar); } } private void loadTime(Calendar calendar) { if (isExistTime && job.getCurrentReport().getTimes().size() == 1) { dateValue.setEnabled(true); } else { dateValue.setEnabled(false); } calendar.setTime(time.getDate()); dateValue.setSelectedDate(calendar.getTime()); setFormTitle(DateTimeUtil.showDate(time.getDate())); if (!time.getStartTime().equals(DateUtils.getInitialDateTime())) { fromText.setText(DateTimeUtil.showTimeGMT(time.getStartTime())); fromText.clearFocus(); } if (!time.getStopTime().equals(DateUtils.getInitialDateTime())) { toText.setText(DateTimeUtil.showTimeGMT(time.getStopTime())); toText.clearFocus(); } if (!time.getWorkTypeCode().isEmpty()) { workTypeValue.setSelectionById(time.getWorkTypeCode()); } deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ } @Override public ApplicationEvent onBackPressed() { // not edited if (time == null && fromText.getText().toString().isEmpty() && toText.getText().toString().isEmpty()) { return app.leaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); } if (time != null && fromText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStartTime())) && toText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStopTime())) && (!job.getJobType().isMON() || (job.getJobType().isMON() && time.getWorkTypeCode().equalsIgnoreCase(workTypeValue.getSelectedId())))) { return app.leaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); } new AsyncTask(this) { private Object errorView = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { errorView = saveTime(db); return null; } @Override public void runOnUIThread() { if (errorView != null) { if(errorView instanceof MDEditText) { ((MDEditText) errorView).setError(ServiceMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ } else if(errorView instanceof MDSpinner) { ((MDSpinner) errorView).setError(ServiceMessages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } } }; return null; } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (null == time) { // create new time } else { if ("ARBEITSART".equals(parent.getTag())) { //$NON-NLS-1$ if (position != 0) workTypeValue.clearError(); } else if ("DATUM".equals(parent.getTag())) { //$NON-NLS-1$ dateValue.setSelected(false); dateValue.clearFocus(); } } } @Override public void onNothingSelected(AdapterView parent) { // Auto-generated method stub } private void deleteTime() { if (time == null) { return; } appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("areYouSureThatYouWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } // If the row to delete is a running time capturing, the job status will change to "angenommen" if (time.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) { job.setStatus(new JobStatus(JobStatus.RECEIVED)); } job.getCurrentReport().getTimes().remove(time); // Save the list of timesheet entries to the current report job.getLatestReport().setTimes(app.dbutil, new ArrayList(job.getCurrentReport().getTimes())); job.getLatestReport().loadTimes(app.dbutil); app.dbutil.updateJob(job); time = null; app.injectAndLeaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); return null; } }, false); } /** * Saves the time entries in the table to the DB by the following steps: *
- Validate the values in the fields on the GUI *
- Fill the zkdmobrtim objects into a list *
- Sort the list by "VON" attribute *
- Number the IDX attribute consecutively *
- Open a DB transaction *
- Delete the existing zkdmobrtim belonging to this report *
- Insert the current list of zkdmobrtim records *
- Commit the transaction *
- Refresh the table with the newly ordered list * @return ApplicationEvent */ public Object saveTime(DBSession db) { JobReportTime jobReportTime; if (fromText.getText().length() == 0) { return fromText; } if (toText.getText().length() == 0) { return toText; } Date startTime = DateTimeUtil.parseDateFromHHmm(fromText.getText().toString(), dateValue.getSelectedDate()); Date stopTime = DateTimeUtil.parseDateFromHHmm(toText.getText().toString(), dateValue.getSelectedDate()); if(startTime == null) { return fromText; } if(stopTime == null) { return toText; } if(fromText.getText().toString().equalsIgnoreCase(toText.getText().toString())) { log.info("the same time "); return toText; } log.info("startTime " + DateTimeUtil.showDateTime(startTime)); log.info("stopTime " + DateTimeUtil.showDateTime(stopTime)); if (startTime.after(stopTime)) { return fromText; } if (startTime.after(new Date())) { app.showWarningMessageBox(ServiceMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ return fromText; } if (stopTime.after(new Date())) { app.showWarningMessageBox(ServiceMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ return toText; } if(workTypeValue.isRequired() && workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { return workTypeValue; } if (time != null) { jobReportTime = time; jobReportTime.setDate(dateValue.getSelectedDate()); jobReportTime.setStartTime(startTime); jobReportTime.setStopTime(stopTime); jobReportTime.setWorkTypeCode(workTypeValue.getSelectedId()); } else { jobReportTime = new JobReportTime(); // jobReportTime.setGuid(job.getLatestReport().getGuId()); // jobReportTime.setIdx(app.dbutil.selectNextIDXFromJobReportTimeByGUID(job.getCurrentReport().getGuId())); jobReportTime.setDate(dateValue.getSelectedDate()); jobReportTime.setStartTime(startTime); jobReportTime.setStopTime(stopTime); jobReportTime.setWorkTypeCode(workTypeValue.getSelectedId()); } saveTimeSheet(jobReportTime, db); return null; } /** * Saves all records in the table control to the ZKDMOBREP object an to the database. * ZKDMOBRTIM.IDX attributes will be numbered consecutively according the VON attribute. * * @param selectedRecord The currently selected record will be selected again (in the table control). */ private void saveTimeSheet(JobReportTime selectedRecord, DBSession db) { // check if there are no overlapping entries List overlappingJobReportTimeList = ServiceJobUtil.isJobTimesheetOverlapping(job.getLatestReport().getTimes(), selectedRecord); JobReportTime overlappingJobReportTime = null; if(overlappingJobReportTimeList.size() > 0) { Iterator iterator = overlappingJobReportTimeList.iterator(); while (iterator.hasNext()){ JobReportTime jobReportTime = (JobReportTime) iterator.next(); if(jobReportTime.getStartTime().getTime() == selectedRecord.getStartTime().getTime() || jobReportTime.getStopTime().getTime() == selectedRecord.getStopTime().getTime()) { overlappingJobReportTime = jobReportTime; break; } Object[] arguments = new Object[] { DateTimeUtil.showTime(selectedRecord.getStartTime()) + " - " + DateTimeUtil.showTime(selectedRecord.getStopTime()) , DateTimeUtil.showTime(jobReportTime.getStartTime()) + " - " + DateTimeUtil.showTime(jobReportTime.getStopTime())}; String errorMessage = MessageFormat.format(Messages.getString("overlapping"), arguments); app.showWarningMessageBox(errorMessage); return; } } boolean newReportTimeAdded = false; if(overlappingJobReportTime != null) { // update for (int i = 0; i < job.getLatestReport().getTimes().size(); i++) { if(job.getLatestReport().getTimes().get(i).getIdx() == overlappingJobReportTime.getIdx() && job.getLatestReport().getTimes().get(i).getGuId().equalsIgnoreCase(overlappingJobReportTime.getGuId()) && job.getLatestReport().getTimes().get(i).getDate().getTime() == overlappingJobReportTime.getDate().getTime()) { job.getLatestReport().getTimes().get(i).setStartTime(selectedRecord.getStartTime()); job.getLatestReport().getTimes().get(i).setStopTime(selectedRecord.getStopTime()); } } } else { // add new selectedRecord.setGuid(job.getLatestReport().getGuId()); selectedRecord.setIdx(app.dbutil.selectNextIDXFromJobReportTimeByGUID(job.getCurrentReport().getGuId())); job.getLatestReport().getTimes().add(selectedRecord); newReportTimeAdded = true; } // Save the list of timesheet entries to the current report job.getLatestReport().setTimes(app.dbutil, new ArrayList(job.getLatestReport().getTimes())); job.getLatestReport().loadTimes(app.dbutil); app.dbutil.updateJob(job); if (newReportTimeAdded) { new RemoteTransactionHandler().updateStatus(db, job, JobStatus.IN_PROGRESS, JobStatus.SAP_InProgress, ""); //$NON-NLS-1$ } app.injectAndLeaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); } }
package ch.mfiles.kaba.kolibri.service.util; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobListForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; public class ReportUtil { private static Log log = LogFactory.getLog(ReportUtil.class); private Form form; private ServiceApplication app; public ReportUtil(Form form, ServiceApplication app) { this.form = form; this.app = app; } /** * Handles on click event for sending report. * * @return */ public ApplicationEvent onSendingReport(final Job job) { job.loadReports(app.dbutil); final Report report = job.getLatestReport(); // Load stamping report.loadTimes(app.dbutil); List jobReportTimeList = report.getTimes(); // Check if there are times if (jobReportTimeList.isEmpty()) { app.showMessage(ServiceMessages.getString("noTimesheetEntriesReportCannotBeSent")); //$NON-NLS-1$ return null; } // Determine whether a type of work is specified for all stamps (MON order only) else if (job.getJobType().isMON() && !checkArba(jobReportTimeList)) { app.showMessage(ServiceMessages.getString("thereAreTimeStampsWithoutWorkType")); //$NON-NLS-1$ return null; } else { report.setCreateDate((jobReportTimeList.get(0)).getStartTime()); app.dbutil.updateReport(report); } if(!report.isNoMaterial() && report.getParts().isEmpty()) { app.showMessage(ServiceMessages.getString("noMaterialPresent")); //$NON-NLS-1$ return null; } List formDescList = ServiceJobUtil.isReportDocsComplete(job); String warningMessage = ""; for (String formDesc : formDescList) { if (!warningMessage.isEmpty()) { warningMessage += "\n"; } if (formDesc.equalsIgnoreCase(ServiceConstants.ModernisationNecessary)) { warningMessage += MessageFormat.format(ServiceMessages.getString("noFormDescImagePresent"), new Object[] { app.dbutil.selectJobFormDescByFormDesc(formDesc).getText()}); } else { warningMessage += MessageFormat.format(ServiceMessages.getString("noFormDescPresent"), new Object[] { app.dbutil.selectJobFormDescByFormDesc(formDesc).getText()}); } } if (!warningMessage.isEmpty()) { warningMessage = warningMessage + "\n" + ServiceMessages.getString("reportCannotBeSent"); app.showWarningMessageBox(warningMessage); return null; } if (ServiceJobUtil.isJobRequireReportMessageToCustomer(job)) { String message = MessageFormat.format(ServiceMessages.getString("reportMessageToCustomer"), //$NON-NLS-1$ new Object[] { job.getJobType().getCode() }); app.showMessage(message); //$NON-NLS-1$ return null; } if (!ServiceJobUtil.isReportImageComplete(job) ) { app.showMessage(ServiceMessages.getString("noImagesEntriesReportCannotBeSent")); return null; } if (!ServiceJobUtil.isInstallationWorkTypeComplete(job) ) { app.showMessage(MessageFormat.format(ServiceMessages.getString("AtLeastXImagesNecessary") , new Object[] { ServiceConstants.REQUIRE_IMAGE})); return null; } job.getLatestReport().loadMeasurements(app.dbutil); if (ServiceJobUtil.isTooMuchMeasurementAreMadeForOnemeasurePoint(report.getMeasurements())) { app.showMessage(ServiceMessages.getString("tooManyMeasurements")); //$NON-NLS-1$ return null; } if (!report.isSignatureFlag()) { app.showMessage(ServiceMessages.getString("noSignaturePresent")); //$NON-NLS-1$ //For jobs with type MON, the user only have to let sign the report, if the report time has work type "Installation" (ZARBEITSART = 32). if (job.getJobType().isMON() && ServiceJobUtil.isMandatoryByReportTime(job)) { return null; } return null; } //IBS checklist have to be mandatory when working type is code 32 if (!ServiceJobUtil.isChecklistComplete(job)) { app.showMessage(ServiceMessages.getString("noChecklistPresent")); return null; } //If working type "98" (ZKDMOBREP.ARBA = 98) is selected in report, a specific form is mandatory //If ZKDMOBREP.ARBA = 98, FORM.ID = VD10 is mandatory and have to be saved and added to report. if (!ServiceJobUtil.isReportFormVonoviaComplete(job)) { app.showMessage(ServiceMessages.getString("noVonoviaFormPresent")); return null; } runSaveReport(job, report); return null; } private void runSaveReport(final Job job, final Report report) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (report.isPartialRepair() && !report.isFinalRepair()) { confirmSendingReport(job, ServiceMessages.getString("sendReport"), true); //$NON-NLS-1$ } else { if (log.isDebugEnabled()) { log.debug("last report, no new GUID generated"); //$NON-NLS-1$ } confirmSendingReport(job, ServiceMessages.getString("JobFinishedSendReport"), false); //$NON-NLS-1$ } return null; } }, false); } private ApplicationEvent confirmSendingReport(Job job, String label, boolean isPartialRepair) { GuidGenerator generator = new GuidGenerator(); try { if (app.showMessageBox(label, ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_QUESTION) == Application.MBOX_RESULT_NO) { //$NON-NLS-1$ return null; } else { if (isPartialRepair) { job.setCurrentReportGuId(generator.generate()); } if (new RemoteTransactionHandler().saveReport(form.db, job, SignatureUtil.FILE_PATH)) { if (isPartialRepair) { app.dbutil.insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(app.dbutil), job.getNextReportIdx(app.dbutil), job.isCycleOfInstallationFlag())); job.loadReports(app.dbutil); app.dbutil.updateJob(job); } app.injectAndLeaveToForm(JobListForm.class, null); } else { return null; } } } catch (UnknownHostException | NoSuchAlgorithmException e) { throw new ApplicationException(e); } return null; } /** * @param jobReportTimeList List with time elements * @return true if check is successful, false if problems have been found */ private boolean checkArba(List jobReportTimeList) { boolean result = true; for (int i = 0; i < jobReportTimeList.size(); i++) { String arba = jobReportTimeList.get(i).getWorkTypeCode(); if (arba == null || StringUtil.isEmpty(arba) || CommonConstants.PLEASE_SELECT.equalsIgnoreCase(arba)) { //$NON-NLS-1$ result = false; } } return result; } } package ch.mfiles.kaba.kolibri.service.forms.util; import java.util.Arrays; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import junit.framework.TestCase; public class ReportDeletionStateTest extends TestCase { /** * @see "MIG-998 Job resp. Report is sometimes in an invalid state after deleting the report" */ @Test public void testRestorePartlyDoneAfterDeletingNewerReport() { Job job = new Job(); job.setJobNumber("0000434704"); job.setJobType(JobType.SAV); Report sentPartialReport = new Report(job.getJobNumber(), job.getJobType(), "first-report-guid", 1, false); sentPartialReport.setReportStatus(ReportStatus.RECEIVED); sentPartialReport.setPartialRepair(true); Report reportToDelete = new Report(job.getJobNumber(), job.getJobType(), "second-report-guid", 2, false); reportToDelete.setReportStatus(ReportStatus.NEW); reportToDelete.setFinalRepair(true); job.setReports(Arrays.asList(reportToDelete, sentPartialReport)); assertFalse(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); job.setReports(Arrays.asList(sentPartialReport)); assertTrue(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); assertFalse(sentPartialReport.getGuId().equals(reportToDelete.getGuId())); } @Test public void testDoNotRestorePartlyDoneWithoutReceivedPartialReport() { Job job = new Job(); job.setJobNumber("0000434704"); job.setJobType(JobType.SAV); Report report = new Report(job.getJobNumber(), job.getJobType(), "report-guid", 1, false); job.setReports(Arrays.asList(report)); report.setReportStatus(ReportStatus.RECEIVED); report.setPartialRepair(false); assertFalse(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); report.setPartialRepair(true); report.setReportStatus(ReportStatus.NEW); assertFalse(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); } } package ch.mfiles.kaba.kolibri.service.forms.util; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.util.DateUtils; import junit.framework.TestCase; public class ReportTest extends TestCase { public ReportTest(String name) { super(name); } /** * @see "(MIG-415) Incomplete report can be saved" */ @Test public void testSaveReport() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(""); // empty assertTrue(report.getCustomerSupportText().isEmpty()); //$NON-NLS-1$ // fax report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_FAX); report.setCustomerSupportText("012345678"); assertFalse(report.getCustomerSupportText().isEmpty()); // eMail report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL); report.setCustomerSupportText("abc@a.ch"); assertFalse(report.getCustomerSupportText().isEmpty()); // formula report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_FOMULAR); report.setCustomerSupportText(report.getJobNumber()); assertFalse(report.getCustomerSupportText().isEmpty()); // waiver report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); report.setCustomerSupportText(""); assertTrue(report.isValid()); //$NON-NLS-1$ } /** * @see "MIG-419 Report cannot be saved if "Verzicht" (waiver) in "Send report to:" is selected" */ @Test public void testSaveReport2() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ } /** * @see "MIG-459 CHANGE: New flag for cycles of an installation" */ @Test public void testSaveReport3() { Job job = getJobObjectByStatus(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ report.setIdx(1); report.setPersonalNumber(job.getPersonalNumber()); report.setCommissionNumber(job.getCommissionNumber()); report.setReportStatus(ReportStatus.INITIAL); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ job.setCycleOfInstallationFlag(true); report = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 2, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ report.setIdx(2); report.setPersonalNumber(job.getPersonalNumber()); report.setCommissionNumber(job.getCommissionNumber()); report.setReportStatus(ReportStatus.INITIAL); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertFalse(report.isValid()); //$NON-NLS-1$ report.setCycleOfInstallation("24"); assertTrue(report.isValid()); //$NON-NLS-1$ } private Job getJobObjectByStatusWithReport(String JobStatus) { Job job = new Job(); job.setJobNumber("0000434704"); //$NON-NLS-1$ job.setJobType(JobType.REP); job.setPersonalNumber(9998); job.setStatus(JobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); Report report = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ report.setIdx(1); report.setPersonalNumber(job.getPersonalNumber()); report.setCommissionNumber(job.getCommissionNumber()); report.setReportStatus(ReportStatus.INITIAL); ArrayList reports = new ArrayList(); reports.add(report); job.setReports(reports); return job; } private Job getJobObjectByStatus(String JobStatus) { Job job = new Job(); job.setJobNumber("0000434704"); //$NON-NLS-1$ job.setJobType(JobType.REP); job.setPersonalNumber(9998); job.setStatus(JobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); return job; } /** * @see "MIG-454 Documents as attachment" */ @Test public void testSaveImageJobFile() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("I"); jobFile.setSignPicAt("test"); assertTrue(jobFile.isValid()); } /** * @see "MIG-454 Documents as attachment" */ @Test public void testSaveDocJobFile() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormType(new FormType(FormType.JPG)); assertTrue(jobFile.isValid()); } /** * @see "MIG-461 Required documents in ZKDMOB for documents as attachment" */ @Test public void testValidateReportDocFromJob() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.setJobType(JobType.MON); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); newJobTime.setWorkTypeCode(CommonConstants.Report.WORKTYPE_INSTALLATION); job.getCurrentReport().getTimes().add(newJobTime); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setSafetyReport(true); assertEquals(2, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("02"); job.setFormDesc2("03"); job.setFormDesc3("04"); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals(5, ServiceJobUtil.isReportDocsComplete(job).size()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("05"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertEquals(4, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm2("03"); JobFile NoForm2 = new JobFile(); date = new Date(); NoForm2.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm2()); NoForm2.setGuid(job.getLatestReport().getGuId()); NoForm2.setJobNumber(job.getJobNumber()); NoForm2.setJobType(job.getJobType()); NoForm2.setType("F"); NoForm2.setFormDesc("03"); job.getLatestReport().getDocumentAttachments().add(NoForm2); assertEquals(3, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm3("04"); JobFile NoForm3 = new JobFile(); date = new Date(); NoForm3.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm3()); NoForm3.setGuid(job.getLatestReport().getGuId()); NoForm3.setJobNumber(job.getJobNumber()); NoForm3.setJobType(job.getJobType()); NoForm3.setType("F"); NoForm3.setFormDesc("04"); job.getLatestReport().getDocumentAttachments().add(NoForm3); assertEquals(2, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm1("02"); JobFile NoForm1 = new JobFile(); date = new Date(); NoForm1.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm1()); NoForm1.setGuid(job.getLatestReport().getGuId()); NoForm1.setJobNumber(job.getJobNumber()); NoForm1.setJobType(job.getJobType()); NoForm1.setType("F"); NoForm1.setFormDesc("02"); job.getLatestReport().getDocumentAttachments().add(NoForm1); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setSafetyReport(false); assertEquals(0, ServiceJobUtil.isReportDocsComplete(job).size()); } /** * @see "MIG-484 CHANGE: Mandatory of document, if specific report messages are chosen" * */ @Test public void testReportMessageMandatoryOfDocument() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode(ServiceConstants.ModernisationNecessary); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setFormType(new FormType(FormType.JPG)); job.getCurrentReport().getDocumentAttachments().add(jobFile); JobFile jobImage = new JobFile(); job.getCurrentReport().getImageAttachments().add(jobImage); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); } /** * @see "MIG-511 Mandatories doesn't work if the user stamps 2 times at one report" * */ @Test public void testReportTimeMandatoryOfDocument() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.MON); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateTimeUtil.getNow().getTime()); newJobTime.setWorkTypeCode("30"); job.getCurrentReport().getTimes().add(newJobTime); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(1); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateTimeUtil.getNow().getTime()); newJobTime.setWorkTypeCode(CommonConstants.Report.WORKTYPE_INSTALLATION); job.getCurrentReport().getTimes().add(newJobTime); // job.getCurrentReport().setSafetyReport(false); // assertFalse(ServiceJobUtil.isReportDocsComplete(job, jobImages, jobFiles).isEmpty()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setJobNumber(job.getJobNumber()); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); JobFile jobFile2 = new JobFile(); jobFile2.setJobNumber(job.getJobNumber()); Date date2 = DateTimeUtil.getNow().getTime(); jobFile2.setJobFileId(DateTimeUtil.fileNameDate(date2) + "_" + DateTimeUtil.fileNameTime(date2) + ".jpg"); jobFile2.setType("F"); jobFile2.setSignPicAt("test"); jobFile2.setFormDesc("05"); jobFile2.setJobNumber(job.getJobNumber()); jobFile2.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile2); assertEquals(0, ServiceJobUtil.isReportDocsComplete(job).size()); } /** * @see "MIG-540 Required documents aren't checked by app" * */ @Test public void testRequireOfDocument() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.setFormDesc1("00"); job.setFormDesc2("00"); job.setFormDesc3("00"); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.setFormDesc1("00"); job.setFormDesc2("03"); job.setFormDesc3("04"); assertEquals(2, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("02"); job.setFormDesc2("00"); job.setFormDesc3("00"); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("00"); job.setFormDesc2("00"); job.setFormDesc3("04"); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("00"); job.setFormDesc2("03"); job.setFormDesc3("00"); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("05"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm2("03"); JobFile NoForm2 = new JobFile(); date = new Date(); NoForm2.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm2()); NoForm2.setGuid(job.getLatestReport().getGuId()); NoForm2.setJobNumber(job.getJobNumber()); NoForm2.setJobType(job.getJobType()); NoForm2.setType("F"); NoForm2.setFormDesc("03"); job.getLatestReport().getDocumentAttachments().add(NoForm2); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); } /** * @see "MIG-549 Report can be send without report image if user chooses report message "Modernisation"" * */ @Test public void testRequireOfImage() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode(ServiceConstants.ModernisationNecessary); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertFalse(ServiceJobUtil.isReportImageComplete(job)); JobFile imageFile = new JobFile(); assertFalse(imageFile.isValid()); imageFile.setJobNumber(job.getJobNumber()); date = DateTimeUtil.getNow().getTime(); imageFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); imageFile.setType("I"); imageFile.setSignPicAt("test"); imageFile.setDescription("desc"); imageFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getImageAttachments().add(imageFile); assertTrue(ServiceJobUtil.isReportImageComplete(job)); } /** * @see "MIG-999 Wrong mandatories for report document in job type MON" * * ZKMDOB.AUART = 'MON' ZKDMONMONTXT = '01' or ZKDMONMONTXT = '02' * no document or generic form is required as mandatory. */ @Test public void testJobMonRequireOfImage() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.MON); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode("01"); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.getLatestReport().getMessages().get(0).setMessageCode("02"); assertFalse(ServiceJobUtil.isReportImageComplete(job)); } /** * @see "MIG-751 Check for document doesn't work" * "MIG-745 New check for report document" * "MIG-735 When a document is required with job, we have to check if there's a generic form" * */ @Test public void testRequireOfForm() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // Document is required with job // When a document is required with the job (ZKDMOB.FORDMESC1, ZKDMOB.FORMDESC2, ZKDMOB.FORMDESC3), we should check: // 1. // ZKDMOB.FORMDESC1 = 01 (document required as mandatory for user to add an attachment or a generic form to report) job.setFormDesc1("01"); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // 2. // Now check FORM.ID (CHAR4) the 2nd and 3rd digit // -> If those digits of FORM.ID (for example F010) are the same as in ZKKDMOB.FORMDESC1 (in this case 01), // the user has to add this generic form or has to add an document attachment (ZKDMOBMV.FORMTYPE = 01 // add generic form FormInstance formInstance = new FormInstance(); formInstance.setFormId("F010"); job.getLatestReport().getFormInstances().add(formInstance); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // clear generic form job.getLatestReport().getFormInstances().clear(); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // add document JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // clear document job.getLatestReport().getDocumentAttachments().clear(); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // or can choose to ad no form to report (ZKDMOBREP.NO_FORM) jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + "01"); job.getLatestReport().getDocumentAttachments().add(jobFile); job.getLatestReport().setNoForm1("01"); ServiceJobUtil.isReportDocsComplete(job); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // remove no form job.getLatestReport().setNoForm1(""); // clear no form job.getLatestReport().getDocumentAttachments().clear(); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // clear FormDesc job.setFormDesc1(""); // 3. // One of these points must be added to report, otherwise the user can't send the report assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // Document is required according to report message // In a 2nd case, a document is required when the user adds a report message to report: // If any of the report messages is ZKDMOBMSGC.MSGC = 01 and/or 02, then a modernisation document (ZKDMOBMV.FORMDESC = 01) is necessary. // In this case, the same logic as above have to be implemented JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode(ServiceConstants.ModernisationNecessary); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // remove message job.getLatestReport().getMessages().clear(); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); jobMessage.setMessageCode(ServiceConstants.OfferModernisation); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarDateRange { private static final int MONTH_EDGE_BUFFER_DAYS = 5; private static final int LOAD_MORE_DAYS = 31; public static Range initialMonth(Date focusDate) { Calendar start = firstDayOfMonth(focusDate); start.add(Calendar.DATE, -MONTH_EDGE_BUFFER_DAYS); Calendar end = firstDayOfMonth(focusDate); end.add(Calendar.MONTH, 1); end.add(Calendar.DATE, MONTH_EDGE_BUFFER_DAYS - 1); return new Range(start.getTime(), end.getTime()); } public static Range nextAfter(Date currentLastDate) { Calendar start = startOfDay(currentLastDate); start.add(Calendar.DATE, 1); Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, LOAD_MORE_DAYS - 1); return new Range(start.getTime(), end.getTime()); } public static Range previousBefore(Date currentFirstDate) { Calendar end = startOfDay(currentFirstDate); end.add(Calendar.DATE, -1); Calendar start = (Calendar) end.clone(); start.add(Calendar.DATE, -(LOAD_MORE_DAYS - 1)); return new Range(start.getTime(), end.getTime()); } private static Calendar firstDayOfMonth(Date date) { Calendar calendar = startOfDay(date); calendar.set(Calendar.DAY_OF_MONTH, 1); return calendar; } private static Calendar startOfDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } public static class Range { private final Date startDate; private final Date endDate; private Range(Date startDate, Date endDate) { this.startDate = new Date(startDate.getTime()); this.endDate = new Date(endDate.getTime()); } public Date getStartDate() { return new Date(startDate.getTime()); } public Date getEndDate() { return new Date(endDate.getTime()); } } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarMonthHeaderPolicy { public static boolean shouldShowHeader(Date currentDate, Date previousDate, int position) { if (currentDate == null) { return false; } if (position <= 0 || previousDate == null) { return true; } Calendar current = Calendar.getInstance(); current.setTime(currentDate); Calendar previous = Calendar.getInstance(); previous.setTime(previousDate); return current.get(Calendar.MONTH) != previous.get(Calendar.MONTH) || current.get(Calendar.YEAR) != previous.get(Calendar.YEAR); } private CalendarMonthHeaderPolicy() { } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarMonthTitleState { private int visibleYear = -1; private int visibleMonth = -1; public boolean updateVisibleMonth(Date date) { if (date == null) { return false; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); if (year == visibleYear && month == visibleMonth) { return false; } visibleYear = year; visibleMonth = month; return true; } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; public class CalendarTimeSheetCache { public interface Loader { CalendarTimeSheet loadCalendar(Date date, int personalNumber); } private final Loader loader; private final int personalNumber; private final Map calendarsByDate = new HashMap(); public CalendarTimeSheetCache(Loader loader, int personalNumber) { this.loader = loader; this.personalNumber = personalNumber; } public synchronized CalendarTimeSheet getCalendar(Date date) { Long key = getDateKey(date); CalendarTimeSheet calendar = calendarsByDate.get(key); if (calendar == null) { calendar = loader.loadCalendar(date, personalNumber); calendarsByDate.put(key, calendar); } return calendar; } public synchronized List getMonthItems(Date focusDate) { CalendarDateRange.Range range = CalendarDateRange.initialMonth(focusDate); return getRangeItems(range.getStartDate(), range.getEndDate()); } public synchronized List getRangeItems(Date startDate, Date endDate) { List result = new ArrayList(); Calendar date = startOfDay(startDate); Calendar end = startOfDay(endDate); while (!date.after(end)) { result.add(getCalendar(date.getTime())); date.add(Calendar.DATE, 1); } return result; } public synchronized void preloadAdjacentMonths(Date focusDate) { Calendar previous = Calendar.getInstance(); previous.setTime(focusDate); previous.add(Calendar.MONTH, -1); Calendar next = Calendar.getInstance(); next.setTime(focusDate); next.add(Calendar.MONTH, 1); getMonthItems(previous.getTime()); getMonthItems(focusDate); getMonthItems(next.getTime()); } public synchronized void invalidate(Date date) { calendarsByDate.remove(getDateKey(date)); } public synchronized void clear() { calendarsByDate.clear(); } private static Long getDateKey(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return Long.valueOf(calendar.getTimeInMillis()); } private static Calendar startOfDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } } package ch.mfiles.kaba.kolibri.timesheet.forms; import junit.framework.TestCase; public class ExpenseCurrencyValueTest extends TestCase { public ExpenseCurrencyValueTest(String name) { super(name); } public void testRemovesSecondDecimalSeparatorBeforeSavingExpenseCurrency() { assertEquals("26.00", TimeSheetDetailForm.getExpenseCurrencyValue("26..00")); } public void testKeepsValidExpenseCurrencyValuesUnchanged() { assertEquals("56", TimeSheetDetailForm.getExpenseCurrencyValue("56")); assertEquals("12.50", TimeSheetDetailForm.getExpenseCurrencyValue("12.50")); } public void testClearsExpenseCurrencyWithoutNumbers() { assertEquals("", TimeSheetDetailForm.getExpenseCurrencyValue("..")); assertEquals("", TimeSheetDetailForm.getExpenseCurrencyValue("abc")); } } package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.Date; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import junit.framework.TestCase; public class ExpensesCompensationTest extends TestCase { public void testLegacyTimeSelectionIsSavedAsExpenseCompensation() { Expenses expenses = new Expenses(new Date(0), 99998); expenses.setCompensation(false); assertEquals("A", expenses.getCompensation()); } } package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.ArrayList; import java.util.Date; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Ignore; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBManager; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.impl.FrameworkController; import ch.mfiles.kolibri.net.ConnectionManager; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.net.impl.TransactionHandlerImpl; import ch.mfiles.kolibri.ui.ProgressDlg; @Ignore("Legacy database date checks are disabled.") public class TestDateCorrectness extends TestCase { private static Log log = LogFactory.getLog(TestDateCorrectness.class); public TestDateCorrectness(String name) { super(name); } /* public void testCorrectCALENDARDate() throws Exception { boolean testResult = true; ArrayList calendarDates = selectAllCalendarDates(); for (int i=0; i < calendarDates.size(); i++) { Date date = (Date)calendarDates.get(i); if (!DateTimeUtil.isDate(date)) { testResult = false; log.error("No Date value in CALENDAR (tested with Calendar Obj): " + date + " (" + date.getTime() + ")"); } } assertTrue(testResult); } public void testCorrectZKDMAEXPNSDate() throws Exception { boolean testResult = true; ArrayList calendarDates = selectAllZKDMAEXPNSDates(); for (int i=0; i < calendarDates.size(); i++) { Date date = (Date)calendarDates.get(i); if (!DateTimeUtil.isDate(date)) { testResult = false; log.error("No Date value in ZKDMAEXPNS (tested with Calendar Obj): " + date + " (" + date.getTime() + ")"); } } assertTrue(testResult); } public ArrayList selectAllCalendarDates() { ArrayList result = new ArrayList(); RecordSet rs = m_dbSession.getRecordSet(); String sql = "SELECT " + DbConstants.CALENDAR.C_DATUM + " FROM " + DbConstants.CALENDAR.T_CALENDAR + " ORDER BY " + DbConstants.CALENDAR.C_DATUM + " ASC" ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(rs.getDate(DbConstants.CALENDAR.C_DATUM)); } } finally { rs.dispose(); } return result; } public ArrayList selectAllZKDMAEXPNSDates() { ArrayList result = new ArrayList(); RecordSet rs = m_dbSession.getRecordSet(); String sql = "SELECT " + DbConstants.ZKDMAEXPNS.C_DATUM + " FROM " + DbConstants.ZKDMAEXPNS.T_ZKDMAEXPNS + " ORDER BY " + DbConstants.ZKDMAEXPNS.C_DATUM + " ASC" ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(rs.getDate(DbConstants.CALENDAR.C_DATUM)); } } finally { rs.dispose(); } return result; } DBSession m_dbSession; TransactionHandlerImpl m_trHandler; ProgressDlg m_dlg; DBManager m_dbman = null; ConnectionManager m_connectionManager = null; ApplicationManager m_applicationManager = null; FrameworkController m_fc = FrameworkController.getInstance(new Class[] { FrameworkController.FCOMP_DB_MANAGER, FrameworkController.FCOMP_REGISTRY, FrameworkController.FCOMP_CONNECTION_MANAGER, FrameworkController.FCOMP_TRANSACTION_HANDLER, FrameworkController.FCOMP_LICENSE_ADAPTER, FrameworkController.FCOMP_DEPLOYMENT_MANAGER, FrameworkController.FCOMP_APPLICATION_MANAGER}); Thread m_thread; protected void setUp() throws Exception { m_thread = m_fc.runAsThread(); m_dbman = m_fc.getDBManager(); m_trHandler = (TransactionHandlerImpl) m_fc.getTransactionHandler(); m_dbSession = m_dbman.connect("database"); m_dlg = ProgressDlg.createProgressDlg(true, true, true); m_trHandler.startQueueProcessing(); try { m_applicationManager = m_fc.getApplicationManager(); } catch (Exception e) { e.getMessage(); } m_applicationManager.startApplication(CommonConstants.Application.TIMESHEET_APP, null); } protected void tearDown() throws Exception { m_applicationManager.inject(new KolibriRunnable() { public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { // Auto-generated method stub return appman.exitFramework(); } }, false); m_thread.join(); } */ } package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.Calendar; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import junit.framework.TestCase; public class TimeSheetDetailFormSavePolicyTest extends TestCase { public TimeSheetDetailFormSavePolicyTest(String name) { super(name); } public void testExpenseSaveIsNotAllowedForFutureDates() { Date today = DateTimeUtil.getToday().getTime(); Date futureDate = addDays(today, 1); assertFalse(TimeSheetDetailForm.canSaveExpenseForDate(futureDate, today)); } public void testExpenseSaveIsAllowedForTodayAndPastDates() { Date today = DateTimeUtil.getToday().getTime(); Date todayWithTime = addHours(today, 12); Date pastDate = addDays(today, -1); assertTrue(TimeSheetDetailForm.canSaveExpenseForDate(today, today)); assertTrue(TimeSheetDetailForm.canSaveExpenseForDate(todayWithTime, today)); assertTrue(TimeSheetDetailForm.canSaveExpenseForDate(pastDate, today)); } private Date addDays(Date date, int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, days); return calendar.getTime(); } private Date addHours(Date date, int hours) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.HOUR_OF_DAY, hours); return calendar.getTime(); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarDateRangeTest extends TestCase { public CalendarDateRangeTest(String name) { super(name); } public void testInitialMonthRangeIncludesBufferAroundMonthEdges() { CalendarDateRange.Range range = CalendarDateRange.initialMonth(date(2026, Calendar.JUNE, 15)); assertDate(2026, Calendar.MAY, 27, range.getStartDate()); assertDate(2026, Calendar.JULY, 5, range.getEndDate()); } public void testNextRangeContinuesAfterCurrentLastDate() { CalendarDateRange.Range range = CalendarDateRange.nextAfter(date(2026, Calendar.JULY, 5)); assertDate(2026, Calendar.JULY, 6, range.getStartDate()); assertDate(2026, Calendar.AUGUST, 5, range.getEndDate()); } public void testPreviousRangeContinuesBeforeCurrentFirstDate() { CalendarDateRange.Range range = CalendarDateRange.previousBefore(date(2026, Calendar.MAY, 27)); assertDate(2026, Calendar.APRIL, 26, range.getStartDate()); assertDate(2026, Calendar.MAY, 26, range.getEndDate()); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarMonthHeaderPolicyTest extends TestCase { public CalendarMonthHeaderPolicyTest(String name) { super(name); } public void testShowsHeaderForFirstVisibleCalendarItem() { assertTrue(CalendarMonthHeaderPolicy.shouldShowHeader(date(2026, Calendar.JUNE, 15), null, 0)); } public void testShowsHeaderWhenMonthChanges() { assertTrue(CalendarMonthHeaderPolicy.shouldShowHeader( date(2026, Calendar.JULY, 1), date(2026, Calendar.JUNE, 30), 1)); } public void testShowsHeaderWhenYearChanges() { assertTrue(CalendarMonthHeaderPolicy.shouldShowHeader( date(2027, Calendar.JANUARY, 1), date(2026, Calendar.DECEMBER, 31), 1)); } public void testDoesNotShowHeaderForSameMonth() { assertFalse(CalendarMonthHeaderPolicy.shouldShowHeader( date(2026, Calendar.JUNE, 15), date(2026, Calendar.JUNE, 14), 1)); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarMonthTitleStateTest extends TestCase { public CalendarMonthTitleStateTest(String name) { super(name); } public void testFirstMonthRequiresTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); assertTrue(state.updateVisibleMonth(date(2026, Calendar.JUNE, 1))); } public void testSameMonthDoesNotRequireTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); state.updateVisibleMonth(date(2026, Calendar.JUNE, 1)); assertFalse(state.updateVisibleMonth(date(2026, Calendar.JUNE, 15))); } public void testDifferentMonthRequiresTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); state.updateVisibleMonth(date(2026, Calendar.JUNE, 30)); assertTrue(state.updateVisibleMonth(date(2026, Calendar.JULY, 1))); } public void testDifferentYearRequiresTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); state.updateVisibleMonth(date(2026, Calendar.JANUARY, 1)); assertTrue(state.updateVisibleMonth(date(2027, Calendar.JANUARY, 1))); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import java.util.List; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import junit.framework.TestCase; public class CalendarTimeSheetCacheTest extends TestCase { private static final int PERSONAL_NUMBER = 99998; public CalendarTimeSheetCacheTest(String name) { super(name); } public void testPreloadsAdjacentMonthSoNextMonthDoesNotLoadAgainAtScrollBoundary() { CountingLoader loader = new CountingLoader(); CalendarTimeSheetCache cache = new CalendarTimeSheetCache(loader, PERSONAL_NUMBER); cache.preloadAdjacentMonths(date(2026, Calendar.JUNE, 15)); int loadsAfterPreload = loader.getLoadCount(); List julyItems = cache.getMonthItems(date(2026, Calendar.JULY, 15)); assertFalse(julyItems.isEmpty()); assertEquals(loadsAfterPreload, loader.getLoadCount()); } public void testInvalidatingOneDayReloadsOnlyThatDay() { CountingLoader loader = new CountingLoader(); CalendarTimeSheetCache cache = new CalendarTimeSheetCache(loader, PERSONAL_NUMBER); Date date = date(2026, Calendar.JUNE, 15); CalendarTimeSheet firstLoad = cache.getCalendar(date); cache.invalidate(date); CalendarTimeSheet secondLoad = cache.getCalendar(date); assertNotSame(firstLoad, secondLoad); assertEquals(2, loader.getLoadCount()); } public void testMonthItemsIncludeBufferBeforeMonthStart() { CalendarTimeSheetCache cache = new CalendarTimeSheetCache(new CountingLoader(), PERSONAL_NUMBER); List juneItems = cache.getMonthItems(date(2026, Calendar.JUNE, 15)); assertDate(2026, Calendar.MAY, 27, juneItems.get(0).getDate()); } public void testMonthItemsIncludeBufferAfterMonthEnd() { CalendarTimeSheetCache cache = new CalendarTimeSheetCache(new CountingLoader(), PERSONAL_NUMBER); List mayItems = cache.getMonthItems(date(2026, Calendar.MAY, 15)); assertDate(2026, Calendar.JUNE, 5, mayItems.get(mayItems.size() - 1).getDate()); } public void testRangeItemsLoadInclusiveDateRange() { CalendarTimeSheetCache cache = new CalendarTimeSheetCache(new CountingLoader(), PERSONAL_NUMBER); List items = cache.getRangeItems( date(2026, Calendar.JUNE, 6), date(2026, Calendar.JUNE, 8)); assertEquals(3, items.size()); assertDate(2026, Calendar.JUNE, 6, items.get(0).getDate()); assertDate(2026, Calendar.JUNE, 8, items.get(2).getDate()); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } private static class CountingLoader implements CalendarTimeSheetCache.Loader { private int loadCount; public CalendarTimeSheet loadCalendar(Date date, int personalNumber) { loadCount++; return new CalendarTimeSheet(date, personalNumber); } public int getLoadCount() { return loadCount; } } } package ch.mfiles.kaba.kolibri.common.businessobjects.types; public class JobStatus { /** * initial * no valid JobStatus, only used by the constructor */ public static final String INITIAL = "00"; //$NON-NLS-1$ /** * new */ public static final String NEW = "01"; //$NON-NLS-1$ /** * received */ public static final String RECEIVED = "02"; //$NON-NLS-1$ /** * rejected */ public static final String REJECTED = "03"; //$NON-NLS-1$ /** * forwarded */ public static final String FORWARDED = "04"; //$NON-NLS-1$ /** * in progress */ public static final String IN_PROGRESS = "05"; //$NON-NLS-1$ /** * finalized (finished) */ public static final String FINALIZED = "06"; //$NON-NLS-1$ /** * partly done */ public static final String PARLTY_DONE = "07"; //$NON-NLS-1$ /** * removed */ public static final String DELETED = "08"; //$NON-NLS-1$ // the states reported to SAP /** * confirmed by client(SAP) */ public static final String SAP_Confirmed = "5"; //$NON-NLS-1$ /** * report time started (SAP) */ public static final String SAP_InProgress = "5a"; //$NON-NLS-1$ /** * finalized (finished)(SAP) */ public static final String SAP_Finished = "12"; //$NON-NLS-1$ /** * forwarded(SAP) */ public static final String SAP_Forwarded = "15"; //$NON-NLS-1$ /** * deleted(SAP) */ public static final String SAP_Deleted = "16"; //$NON-NLS-1$ private String code; // private String value; public JobStatus() { set(INITIAL); } public JobStatus(String code) { set(code); } public String getCode() { return code; } // public String getValue() { // return value; // } public void set(String code) { this.code = code; // this.value = loadLocalizedStatus(code); } public boolean isEquals(String code) { return this.code.equalsIgnoreCase(code); } public boolean isInitial() { return this.code.equalsIgnoreCase(INITIAL); } public boolean isNew() { return this.code.equalsIgnoreCase(NEW); } public boolean isReceived() { return this.code.equalsIgnoreCase(RECEIVED); } public boolean isRejected() { return this.code.equalsIgnoreCase(REJECTED); } public boolean isForwarded() { return this.code.equalsIgnoreCase(FORWARDED); } public boolean isInProgress() { return this.code.equalsIgnoreCase(IN_PROGRESS); } public boolean isPartlyDone() { return this.code.equalsIgnoreCase(PARLTY_DONE); } public boolean isFinalized() { return this.code.equalsIgnoreCase(FINALIZED); } public boolean isDeleted() { return this.code.equalsIgnoreCase(DELETED); } } package ch.mfiles.kaba.kolibri.common.businessobjects; import java.io.File; import java.util.Date; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ExpenseValidation; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; /* * In the Database -> ZKDMAEXPNS */ public class Expenses { public static final String EXPENSE_COMPENSATION = "A"; //$NON-NLS-1$ private int personalNumber = 0; private Date date = new Date(); private Date expensesDate = new Date(); private String noExpenses = ""; //$NON-NLS-1$ private String dailyExpenses = ""; //$NON-NLS-1$ private String variousExpenses = ""; //$NON-NLS-1$ private String deduction = ""; //$NON-NLS-1$ private String expensesKey = ""; //$NON-NLS-1$ private String pikettExpenses = ""; //$NON-NLS-1$ private String expensesDescription = ""; //$NON-NLS-1$ private String operatingHoursOf = ""; //$NON-NLS-1$ private String operatingHoursUpTo = ""; //$NON-NLS-1$ private String operatingHoursTotal = ""; //$NON-NLS-1$ private String deductionDescription = ""; //$NON-NLS-1$ private String compensation = ""; //$NON-NLS-1$ Expenses() { } public Expenses(Date datum, int pernr) { this.setDate(datum); this.setPersonalNumber(pernr); this.setExpensesDate(datum); } public Expenses(RecordSet rs) { this.setDeduction(rs.getString(DbConstants.Expenses.DECUCTION)); this.setDeductionDescription(rs.getString(DbConstants.Expenses.DEDUCTION_DESCRIPTION)); this.setOperatingHoursUpTo(rs.getString(DbConstants.Expenses.OPERATION_HOURS_UP_TO)); this.setOperatingHoursTotal(rs.getString(DbConstants.Expenses.OPERATION_HOURS_TOTAL)); this.setOperatingHoursOf(rs.getString(DbConstants.Expenses.OPERATING_HOURS_OF)); this.setDate(rs.getDate(DbConstants.Expenses.DATE)); this.setNoExpenses(rs.getString(DbConstants.Expenses.NO_EXPENSES)); this.setPersonalNumber(rs.getInt(DbConstants.Expenses.PERSONAL_NUMBER)); this.setPikettExpenses(rs.getString(DbConstants.Expenses.PIKETT_EXPENSES)); this.setExpensesKey(rs.getString(DbConstants.Expenses.EXPENSES_KEY)); this.setVariousExpenses(rs.getString(DbConstants.Expenses.VARIOUS_EXPENSES)); this.setExpensesDescription(rs.getString(DbConstants.Expenses.EXPENSES_DESCRIPTION)); this.setExpensesDate(rs.getDate(DbConstants.Expenses.EXPENSES_DATE)); this.setDailyExpenses(rs.getString(DbConstants.Expenses.DAILY_EXPENSES)); this.setCompensation(rs.getString(DbConstants.Expenses.COMPENSTION)); } public boolean isInitial() { return ( getDailyExpenses().isEmpty() && getNoExpenses().isEmpty() && getExpensesDescription().isEmpty() && getPikettExpenses().isEmpty() && getVariousExpenses().isEmpty() && getDeduction().isEmpty() && getDeductionDescription().isEmpty() && getOperatingHoursOf().isEmpty() && getOperatingHoursUpTo().isEmpty() && getOperatingHoursTotal().isEmpty() && isCompensation() ); } public String getDeduction() { return this.deduction; } public void setDeduction(String abzg) { this.deduction = abzg; } public String getDeductionDescription() { return this.deductionDescription; } public void setDeductionDescription(String abzgtxt) { this.deductionDescription = abzgtxt; } public String getOperatingHoursUpTo() { return this.operatingHoursUpTo; } public void setOperatingHoursUpTo(String bbis) { this.operatingHoursUpTo = bbis; } public String getOperatingHoursTotal() { return this.operatingHoursTotal; } public void setOperatingHoursTotal(String btot) { this.operatingHoursTotal = btot; } public String getOperatingHoursOf() { return this.operatingHoursOf; } public void setOperatingHoursOf(String bvon) { this.operatingHoursOf = bvon; } public Date getDate() { return this.date; } public void setDate(Date datum) { this.date = datum; } public String getVariousExpenses() { return this.variousExpenses; } public void setVariousExpenses(String divspns) { this.variousExpenses = divspns; } public int getPersonalNumber() { return this.personalNumber; } public void setPersonalNumber(int pernr) { this.personalNumber = pernr; } public String getPikettExpenses() { return this.pikettExpenses; } public void setPikettExpenses(String pikett) { this.pikettExpenses = pikett; } public String getExpensesKey() { return this.expensesKey; } public void setExpensesKey(String spnskey) { this.expensesKey = spnskey; } public String getExpensesDescription() { return this.expensesDescription; } public void setExpensesDescription(String spnstxt) { this.expensesDescription = spnstxt; } public Date getExpensesDate() { return this.expensesDate; } public void setExpensesDate(Date expensesDate) { this.expensesDate = expensesDate; } public String getDailyExpenses() { return this.dailyExpenses; } public void setDailyExpenses(String tgspsn) { this.dailyExpenses = tgspsn; } public String getNoExpenses() { return this.noExpenses; } public void setNoExpenses(String noExpenses) { this.noExpenses = noExpenses; } public boolean isNoExpenses() { return "X".equalsIgnoreCase(this.getNoExpenses()); //$NON-NLS-1$ } public void setNoExpenses(boolean noExpenses) { if (noExpenses) { this.setNoExpenses("X"); //$NON-NLS-1$ } else { this.setNoExpenses(""); //$NON-NLS-1$ } } public String getCompensation() { return this.compensation; } public void setCompensation(String mverg) { this.compensation = mverg; } public boolean isCompensation() { return EXPENSE_COMPENSATION.equalsIgnoreCase(this.getCompensation()); } public void setExpenseCompensation() { this.setCompensation(EXPENSE_COMPENSATION); } public void setCompensation(boolean compensation) { this.setExpenseCompensation(); } public ExpenseValidation validate() { ExpenseValidation result = new ExpenseValidation(); // "Keine Spesen" nicht gew�hlt, jedoch weder einen Tages-, noch einen // Div.-Spesenbetrag eingegeben if ("".equalsIgnoreCase(getNoExpenses()) && "".equalsIgnoreCase(getDailyExpenses())) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ result.setValid(false); result.setTgSpesenError(true); result.setDivSpesenError(true); } // Abzug ausgef�llt, jedoch keinen Betrag eingegeben if (!"".equalsIgnoreCase(getDeductionDescription()) && "".equalsIgnoreCase(getDeduction())) { //$NON-NLS-1$ //$NON-NLS-2$ result.setValid(false); result.setAbzugError(true); } if (!isNoExpenses() && getOperatingHoursTotal().length() == 0 && (getOperatingHoursOf().length() == 0 || getOperatingHoursUpTo().length() == 0)) { if (getOperatingHoursTotal().length() == 0) { result.setValid(false); result.setBTotError(true); } if (getOperatingHoursOf().length() == 0) { result.setValid(false); result.setBVonError(true); } if (getOperatingHoursUpTo().length() == 0) { result.setValid(false); result.setBBisError(true); } try { if (Float.parseFloat(getOperatingHoursOf()) >= Float.parseFloat(getOperatingHoursUpTo())) { result.setValid(false); result.setBBisError(true); } } catch (NumberFormatException e) { result.setValid(false); result.setBVonError(true); result.setBBisError(true); } } return result; } public static int backup(Application app, File folder) { return BaseEntity.backup(DbConstants.Expenses.EXPENSES, app, folder); } public static void restore(DBSession db, File folder) { BaseEntity.restore(DbConstants.Expenses.EXPENSES, db, folder); } } package ch.mfiles.kaba.kolibri.common.forms.adapters; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; public class CustomAutoCompleteItemAdapter extends ArrayAdapter { /** * - items for original list passed from activity code. - tempItems for closing original one and do compare with editable character from user - suggestions for actual filter dropdown values */ private List items, tempItems, suggestions; public CustomAutoCompleteItemAdapter(Context context, int textViewResourceId, List items) { super(context, textViewResourceId, items); this.items = items; tempItems = new ArrayList<>(items); suggestions = new ArrayList<>(); } // Affects default (closed) state of the spinner @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); CustomSpinnerItem customSpinner = getItem(position); view.setText(customSpinner.getName()); return view; } @Nullable @Override public CustomSpinnerItem getItem(int position) { return items.get(position); } @Override public int getCount() { return items.size(); } @Override public long getItemId(int position) { return position; } @NonNull @Override public Filter getFilter() { return CustomSpinnerItemFilter; } private Filter CustomSpinnerItemFilter = new Filter() { @Override public CharSequence convertResultToString(Object resultValue) { CustomSpinnerItem CustomSpinnerItem = (CustomSpinnerItem) resultValue; return CustomSpinnerItem.getName(); } @Override protected FilterResults performFiltering(CharSequence charSequence) { if (charSequence != null) { suggestions.clear(); for (CustomSpinnerItem CustomSpinnerItem : tempItems) { if (CustomSpinnerItem.getName().toLowerCase().startsWith(charSequence.toString().toLowerCase())) { suggestions.add(CustomSpinnerItem); } } FilterResults filterResults = new FilterResults(); filterResults.values = suggestions; filterResults.count = suggestions.size(); return filterResults; } else { return new FilterResults(); } } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { ArrayList tempValues = (ArrayList) filterResults.values; if (filterResults != null && filterResults.count > 0) { clear(); for (CustomSpinnerItem CustomSpinnerItemObj : tempValues) { add(CustomSpinnerItemObj); } notifyDataSetChanged(); } else { clear(); notifyDataSetChanged(); } } }; /** * Gets Item Name By Id. * * @param id * @return */ public String getNameById(String id) { for (int i = 0; i < items.size(); i++) { CustomSpinnerItem customSpinner = items.get(i); if (id.equals(customSpinner.getId())) { return customSpinner.getName(); } } return ""; } /** * Gets Item Position By Id. * * @param id * @return */ public int getPositionById(String id) { for (int i = 0; i < items.size(); i++) { CustomSpinnerItem customSpinner = items.get(i); if (id.equals(customSpinner.getId())) { return i; } } return 0; } } package ch.mfiles.kaba.kolibri.common.forms.widgets.lists; import java.util.List; import android.R.color; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Typeface; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; @SuppressLint("NewApi") public class DetailListWidgetAdapter extends ListWidgetAdapter { public DetailListWidgetAdapter(Context context, List coll) { super(context, coll); this.context = context; } public static final int ID_HEADER_ITEM = 1001; public static final int ID_TITLE = 1020; public static final int ID_TEXE_LINE_ONE = 1030; public static final int ID_TEXE_LINE_TWO = 1040; public static final int ID_TEXE_LINE_THREE = 1050; public static final int ID_BUTTON = 1060; private View leftView; private View middleView; private View rightView; /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { return createView(position, convertView, parent); } public void setLeftView(View view) { this.leftView = view; } public void setMiddleView(View view) { this.middleView = view; } public void setRightView(View view) { this.rightView = view; } public View createView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { LinearLayout rootLinearLayout = new LinearLayout(context); rootLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout headerTextLayout = new LinearLayout(context); headerTextLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerTextLayout.setOrientation(LinearLayout.HORIZONTAL); headerTextLayout.setGravity(Gravity.CENTER); TextView headerTextView = new TextView(context); headerTextView.setId(ID_HEADER_ITEM); headerTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); headerTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); headerTextLayout.addView(headerTextView); rootLinearLayout.addView(headerTextLayout); LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); contentItemLayout.setBackgroundColor(color.white); contentItemLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); LinearLayout leftIconLinearLayout = new LinearLayout(context); leftIconLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0,0); leftIconLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; leftIconLinearLayoutParams.width = 0; leftIconLinearLayoutParams.height = LayoutParams.FILL_PARENT; leftIconLinearLayoutParams.weight = 0f; leftIconLinearLayout.setLayoutParams(leftIconLinearLayoutParams); if (leftView != null) { leftIconLinearLayoutParams.weight = 0.55f; leftIconLinearLayout.addView(leftView); } contentItemLayout.addView(leftIconLinearLayout); if (middleView != null) { contentItemLayout.addView(middleView); } else { contentItemLayout.addView(createMiddleLayout()); } LinearLayout buttonLinearLayout = new LinearLayout(context); buttonLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams buttonLinearLayoutParams = new LinearLayout.LayoutParams(LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); buttonLinearLayoutParams.gravity = Gravity.CENTER | Gravity.RIGHT; buttonLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; buttonLinearLayout.setLayoutParams(buttonLinearLayoutParams); if (rightView != null) { buttonLinearLayout.addView(rightView); } else { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.RIGHT | Gravity.CENTER_HORIZONTAL; endFrameLayout.setLayoutParams(endFrameParams); endFrameLayout.setBackgroundColor(color.holo_green_light); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setId(ID_BUTTON); endFrameLayout.addView(imageButton); buttonLinearLayout.addView(endFrameLayout); } contentItemLayout.addView(buttonLinearLayout); rootLinearLayout.addView(contentItemLayout); v = rootLinearLayout; } else { v = convertView; } bindView(position, v); return v; } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 3f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(25, 0, 0, 0); TextView titleTextView = new TextView(context); titleTextView.setId(ID_TITLE); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(titleTextView); TextView textLineOneTextView = new TextView(context); textLineOneTextView.setId(ID_TEXE_LINE_ONE); textLineOneTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineOneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineOneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineOneTextView.setEllipsize(TruncateAt.END); textLineOneTextView.setMaxLines(1); textLineOneTextView.setSingleLine(); textLineOneTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(textLineOneTextView); TextView textLineTwoTextView = new TextView(context); textLineTwoTextView.setId(ID_TEXE_LINE_TWO); textLineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineTwoTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(textLineTwoTextView); TextView textLineThreeTextView = new TextView(context); textLineThreeTextView.setId(ID_TEXE_LINE_THREE); textLineThreeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineThreeTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineThreeTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineThreeTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); midLinearLayout.addView(textLineThreeTextView); return midLinearLayout; } public void bindView(int position, View view) { final DetailListWidgetItem dataSet = (DetailListWidgetItem)mData.get(position); if (dataSet == null) { return; } TextView headerTextView = (TextView) view.findViewById(ID_HEADER_ITEM); TextView titleTextView = (TextView) view.findViewById(ID_TITLE); TextView lineOneTextView = (TextView) view .findViewById(ID_TEXE_LINE_ONE); TextView lineTwoTextView = (TextView) view .findViewById(ID_TEXE_LINE_TWO); TextView lineThreeTextView = (TextView) view .findViewById(ID_TEXE_LINE_THREE); ImageButton imageButton = (ImageButton) view .findViewById(ID_BUTTON); setViewText(titleTextView, dataSet.getTitleText()); setViewText(lineOneTextView, dataSet.getStringLine1()); setViewText(lineTwoTextView, dataSet.getStringLine2()); if (null != lineThreeTextView) { setViewText(lineThreeTextView, dataSet.getStringLine3()); } if (dataSet.isShowEllipInEndOfText()) { titleTextView.setMaxLines(2); lineOneTextView.setMaxLines(1); lineTwoTextView.setMaxLines(1); titleTextView.setEllipsize(TruncateAt.END); lineOneTextView.setEllipsize(TruncateAt.END); lineTwoTextView.setEllipsize(TruncateAt.END); if (null != lineThreeTextView) { lineThreeTextView.setMaxLines(1); lineThreeTextView.setEllipsize(TruncateAt.END); } } if (null == imageButton) { return; } if (null != dataSet.getButtonImage()) { if (null != dataSet.getButtonImageTag()) { imageButton.setTag(dataSet.getButtonImageTag()); } imageButton.setBackground(dataSet.getButtonImage()); if (null != dataSet.getOnClickListener()) { imageButton.setOnClickListener(dataSet.getOnClickListener()); } imageButton.setFocusable(false); imageButton.setVisibility(View.VISIBLE); } else { imageButton.setVisibility(View.INVISIBLE); } if (dataSet.isShowRightLayout()) { LinearLayout linearLayout = (LinearLayout) imageButton.getParent().getParent(); linearLayout.setVisibility(View.VISIBLE); } else { LinearLayout linearLayout = (LinearLayout) imageButton.getParent().getParent(); linearLayout.setVisibility(View.GONE); } if(dataSet.getHeader() == null) { headerTextView.setVisibility(View.GONE); } } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.Application; public class CommissionNumberText extends MDEditText { private static Log log = LogFactory.getLog(CommissionNumberText.class); private JobType jobType; private String commissionNumberFormat; public CommissionNumberText(Context context) { super(context); } public static CommissionNumberText createDefaultEditText(ViewGroup parent, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); CommissionNumberText editText = new CommissionNumberText(context); editText.initialize(required); TextInputLayout textInputLayout = new TextInputLayout(context); textInputLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLayout.addView(editText); parent.addView(textInputLayout); return editText; } private void initialize(final boolean required) { final CommissionNumberText editText = this; editText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); editText.setRawInputType(InputType.TYPE_TEXT_VARIATION_NORMAL); editText.setHint(Messages.getString("commNo")); if (required) { editText.setRequired(required); } editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { if(hasFocus) { if(jobType.isMON()) { editText.setRawInputType(InputType.TYPE_CLASS_NUMBER); } else { editText.setRawInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } } // new AsyncTask(app.getCurrentForm()) { // // @Override // protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, // TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { // // return null; // } // // @Override // protected void runOnUIThread() { // if (!hasFocus && !editText.isValid()) { // editText.setError(editText.getErrorMessage()); //$NON-NLS-1$ // } else { // editText.clearError(); // } // } // }; } }); editText.addTextChangedListener(new TextWatcher() { private int beforeCharSequence; private int afterCharSequence; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeCharSequence = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { afterCharSequence = s.length(); } @Override public void afterTextChanged(Editable s) { String value = s.toString().trim(); if (StringUtil.isEmpty(value) || jobType == null) { return; } if(value.contains(",")) { value = value.replace(",", ""); } if(value.contains(".")) { value = value.replace(".", ""); } if(value.contains(" ")) { value = value.replace(" ", ""); } editText.removeTextChangedListener(this); if(jobType.isMON()) { if (isFormatCH()) { //'CH' 'MON' xxxxxx } else { //'DE' 'MON' xxxxxxxxxx } } else { if (isFormatCH()) { //'CH' 'REP' 'SAV' 0xxxxxx-yy if (!value.startsWith("0")) { //$NON-NLS-1$ value = "0" + value; //$NON-NLS-1$ editText.setText(value); } } //'DE' 'REP' 'SAV' xxxxxxx-yy if (value.length() == CommonConstants.CommissionNumber.DASH_POSITION && beforeCharSequence < afterCharSequence) { value = value + "-"; //$NON-NLS-1$ editText.setText(value); } // check dash position if (value.length() >= CommonConstants.CommissionNumber.DASH_POSITION +1 && value.charAt(CommonConstants.CommissionNumber.DASH_POSITION) != '-' && beforeCharSequence < afterCharSequence) { String temp = value.substring(0, CommonConstants.CommissionNumber.DASH_POSITION); String number = value.substring(CommonConstants.CommissionNumber.DASH_POSITION, value.length()); value = temp + "-" + number; //$NON-NLS-1$ editText.setText(value); } // remove "-" position 0..6 if(value.indexOf('-') != CommonConstants.CommissionNumber.DASH_POSITION || value.endsWith("-")) { value = value.replace("-", ""); } // remove "-" position 8..10 if (value.length() > CommonConstants.CommissionNumber.DASH_POSITION+1) { if(value.charAt(value.length()-1) == '-') { value = value.substring(0, value.length()-1); } } } Pattern pattern = Pattern.compile(getRegx()); Matcher matcher = pattern.matcher(value.trim()); if (matcher.matches() || matcher.hitEnd()) { editText.setText(value.trim()); } if (editText.hasFocus()) { editText.clearError(); } editText.addTextChangedListener(this); } }); editText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); editText.setHintTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); editText.setTypeface(CommonConstants.Font.getDefaultLightFont()); // editText.getBackground().setColorFilter(LayoutUtils.DEFAULT_HIGHLIGHT, Mode.SRC_ATOP); } public void setJobTypeAndFormat(JobType jobType, String commissionNumberFormat) { log.info("jobType " + jobType.toString() + " commissionNumberFormat " + commissionNumberFormat); this.jobType = jobType; this.commissionNumberFormat = commissionNumberFormat; setFilters(new InputFilter[0]); setFilters(new InputFilter[] {new InputFilter.LengthFilter(getCommissionNumberMaxLenght())}); } public boolean isValid() { return isMatch(getText().toString()); } private boolean isMatch(String value) { Pattern pattern = Pattern.compile(getRegx()); Matcher matcher = pattern.matcher(value); return matcher.matches(); } public String getErrorMessage() { String errorMessage = ""; Object[] arguments = new Object[] { getFormat() }; errorMessage = MessageFormat .format(Messages.getString("WrongFormat"), arguments); //$NON-NLS-1$ return errorMessage; } public void setLabel(String label) { setHint(label); } /** * REP, SAV 0xxxxxx-yy x: [0-9] y: [0-9][A-Z] numpad (numeric only) default. *

* MON (CH) xxxxxx x: [0-9] numpad (numeric only) hide the leading 0's leading 0's have to be transmitted to backend → xxxxxxxxxx (x: [0-9]). */ public void setText(String text) { log.info("jobType " + jobType.toString() + " commissionNumberFormat " + commissionNumberFormat + " text " + text); if(jobType.isMON() && isFormatCH() && text.length() > CommonConstants.MaxLength.SIX) { setTextAndSelection(text.substring(text.length()-CommonConstants.MaxLength.SIX)); } else { setTextAndSelection(text); } } /** * MON leading 0's have to be transmitted to backend → xxxxxxxxxx (x: [0-9]). */ public String getCommissionNumber() { if(jobType != null && jobType.isMON() && isFormatCH() && !super.getText().toString().isEmpty()) { String text = super.getText().toString(); log.info("Job type MON commission number -> " + text); StringBuilder builder = new StringBuilder(); if(text.length() < CommonConstants.MaxLength.TEN) { for (int i = 0; i < CommonConstants.MaxLength.TEN - text.length(); i++) { builder.append("0"); } text = builder.toString() + text; log.info("MON leading 0's have to be transmitted to backend → xxxxxxxxxx (x: [0-9]). -> " + text); return text; } } return super.getText().toString(); } private boolean isFormatCH() { return commissionNumberFormat.equalsIgnoreCase(CommonConstants.CommissionNumber.CH); } private String getRegx() { if (isFormatCH()) { if(jobType.isMON()) { return CommonConstants.CommissionNumber.REGX_MON_CH; } else { return CommonConstants.CommissionNumber.REGX_REP_SAV_CH; } } else { if(jobType.isMON()) { return CommonConstants.CommissionNumber.REGX_MON_DE; } else { return CommonConstants.CommissionNumber.REGX_REP_SAV_DE; } } } private int getCommissionNumberMaxLenght() { if(jobType.isMON() && isFormatCH()) { return CommonConstants.MaxLength.SIX; } else { return CommonConstants.MaxLength.TEN; } } private String getFormat() { if (isFormatCH()) { if(jobType.isMON()) { return "XXXXXX"; } else { return "0XXXXXX-YY"; } } else { if(jobType.isMON()) { return "XXXXXXXXXX"; } else { return "0XXXXXX-YY"; } } } } package ch.mfiles.kaba.kolibri.common.net; import java.io.File; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.db.FORMINSTANCE; import ch.mfiles.kaba.kolibri.common.db.LocalizedTexts; import ch.mfiles.kaba.kolibri.common.db.ZKDMOB; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.FatalApplicationException; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.gen.TableCursor; import ch.mfiles.kolibri.net.Element; import ch.mfiles.kolibri.net.ElementTemplate; import ch.mfiles.kolibri.net.Request; import ch.mfiles.kolibri.net.Response; import ch.mfiles.kolibri.net.TableElement; import ch.mfiles.kolibri.net.Transaction; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.ProgressMonitor; public class RemoteTransactionHandler { private Log log = LogFactory.getLog(RemoteTransactionHandler.class); private DatabaseUtil dbutil; private TransactionHandler tr; /** * instantiates a new RemoteTransactionHandler * * @param application the application. * @param transactionHandler the transaction handler to be used for communication. */ public RemoteTransactionHandler() { this.dbutil = DatabaseUtil.getInstance(); this.tr = Runtime.getTransactionHandler(); } /** * Make sure we are *not* running on the UI thread. */ private void ensureAMThread() { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); if (appman.getContext().getMainLooper().getThread() == Thread.currentThread()) throw new FatalApplicationException(Messages.getString("RemoteTransactionHandler.0")); //$NON-NLS-1$ } public boolean runRefreshMasterdata(int perno, String tableName, String initalRequest, ProgressMonitor monitor) { ensureAMThread(); monitor.begin(Messages.getString("RemoteTransactionHandler.1"), 3); //$NON-NLS-1$ DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); try { // REFRESHED Flag bei allen Stammdatentabellen zur�cksetzten // (unabh�ngig davon, ob sie aktualisiert werden oder nicht) dbutil.updateRefreshFlag(); monitor.comment(Messages.getString("RemoteTransactionHandler.2")); //$NON-NLS-1$ monitor.worked(1); // Transaktion ausf�hren RemoteTransactionHandler rth = new RemoteTransactionHandler(); dbutil.deleteAllReason(); dbutil.deleteAllJobReason(); dbutil.deleteAllJobMonText(); dbutil.deleteAllIncident(); dbutil.deleteAllJobFormDesc(); dbutil.deleteAllJobNoForm(); dbutil.deleteAllReportMessage(); dbutil.deleteAllDrive(); dbutil.deleteAllBilling(); dbutil.deleteAllInvoice(); dbutil.deleteAllInternalWorkType(); dbutil.deleteAllAbsenceType(); dbutil.deleteAllServiceRefused(); dbutil.deleteAllChecklist(); dbutil.deleteAllProgress(); dbutil.deleteFormMetadata(); dbutil.deleteAllStateOfInstallation(); dbutil.deleteAllNextIntervention(); dbutil.deleteAllInventoryStock(); dbutil.deleteAllInventory(); dbutil.deleteAllReceiptOfGoods(); if (rth.refreshMasterdata(perno, tableName, initalRequest)) { monitor.comment(Messages.getString("RemoteTransactionHandler.3")); //$NON-NLS-1$ monitor.worked(1); // Records ohne REFRESHED Flag l�schen if ("X".equalsIgnoreCase(initalRequest)) { //$NON-NLS-1$ dbutil.deleteAllWorkTypeNonRefreshed(); dbutil.deleteAllErrorCodeNonRefreshed(); dbutil.deleteAllMaterialNonRefreshed(); dbutil.deleteAllEmployeeNonRefreshed(); dbutil.deleteAllReasonNonRefreshed(); dbutil.deleteAllJobDeleteReasonNonRefreshed(); dbutil.deleteAllJobMonTextNonRefreshed(); dbutil.deleteAllIncIdentNonRefreshed(); dbutil.deleteAllJobFormDescNonRefreshed(); dbutil.deleteAllJobNoFormNonRefreshed(); dbutil.deleteAllInvoiceNonRefreshed(); dbutil.deleteAllInternalWorkTypeNonRefreshed(); dbutil.deleteAllAbsenceTypeNonRefreshed(); dbutil.deleteAllServiceRefusedNonRefreshed(); dbutil.deleteAllChecklistNonRefreshed(); dbutil.deleteAllProgresstNonRefreshed(); dbutil.deleteAllStateOfInstallationNonRefreshed(); dbutil.deleteAllNextInterventionNonRefreshed(); dbutil.deleteAllInventoryNonRefreshed(); dbutil.deleteAllReceiptOfGoodsNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.WorkType.WORK_TYPE)) { dbutil.deleteAllWorkTypeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.ErrorCode.ERROR_CODE)) { dbutil.deleteAllErrorCodeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Material.MATERIAL)) { dbutil.deleteAllMaterialNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Employee.EMPLOYEE)) { dbutil.deleteAllEmployeeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.InternalWorkType.INTERNAL_WORK_TYPE)) { dbutil.deleteAllInternalWorkTypeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.AbsenceType.ABSENCE_TYPE)) { dbutil.deleteAllAbsenceTypeNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.ServiceRefused.SERVICE_REFUSED)) { dbutil.deleteAllServiceRefusedNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Checklist.CHECK_LIST)) { dbutil.deleteAllChecklistNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Progress.PROGRESS)) { dbutil.deleteAllProgresstNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.StateOfInstallation.STATE_OF_INSTALLATION)) { dbutil.deleteAllStateOfInstallationNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.NextIntervention.NEXT_INVENTION)) { dbutil.deleteAllNextInterventionNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.Inventory.INVENTORY)) { dbutil.deleteAllInventoryNonRefreshed(); } else if (tableName.equalsIgnoreCase(DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS)) { dbutil.deleteAllReceiptOfGoodsNonRefreshed(); } db.commit(); monitor.comment(Messages.getString("RemoteTransactionHandler.4")); //$NON-NLS-1$ monitor.worked(1); countFromTable("LocalizedTexts", LocalizedTexts.TABLE); countFromTable("Reason", DbConstants.Reason.REASON); countFromTable("Job return reason", DbConstants.JobReturnReason.JOB_RETURN_REASON); countFromTable("JobMon text", DbConstants.JobMonText.JOB_MON_TEXT); countFromTable("Incident", DbConstants.Incident.INCIDENT); countFromTable("Report message", DbConstants.ReportMessage.REPORT_MESSAGE); countFromTable("Drive", DbConstants.Drive.DRIVE); countFromTable("Billing", DbConstants.Billing.BILLING); countFromTable("Work type", DbConstants.WorkType.WORK_TYPE); countFromTable("Internal work type", DbConstants.InternalWorkType.INTERNAL_WORK_TYPE); countFromTable("Absence type", DbConstants.AbsenceType.ABSENCE_TYPE); countFromTable("Service Refused", DbConstants.ServiceRefused.SERVICE_REFUSED); countFromTable("Check list", DbConstants.Checklist.CHECK_LIST); countFromTable("PROGRESS", DbConstants.Progress.PROGRESS); countFromTable("FORM", DbConstants.Form.FORM); countFromTable("FORMITEM", DbConstants.FormItem.FORMITEM); countFromTable("FORMVALUELIST", DbConstants.FormValueList.FORMVALUELIST); countFromTable("State of installation", DbConstants.StateOfInstallation.STATE_OF_INSTALLATION); countFromTable("Next intervention", DbConstants.NextIntervention.NEXT_INVENTION); countFromTable("inventory", DbConstants.Inventory.INVENTORY); countFromTable("ReceiptOfGoods", DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS); // reload user profile (might have changed by master data refresh) // and update user's warehouse number from employee master data Person user = dbutil.getUser(true); user.setWarehouseNumber(""); Employee userEmployee = dbutil.selectEmployeeByPerNr(user.getPersonalNumber()); if (userEmployee != null) user.setWarehouseNumber(userEmployee.getWarehouseNumber()); dbutil.updateUser(user); } } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { db.rollback(); } } return true; } private void countFromTable(String name, String table) { int rowsCount = dbutil.selectCountFromTable(table, ""); log.info(name + " " + table + " -> " + rowsCount); //reduce number of toasts... //if (rowsCount == 0) { // MessageUtil.getInstance().showMessage(name + " not received from server."); //} } /** * runs the operation REFRESH_MASTERDATA in order to retrieve the entire set * of master data tables * * @param perno employee ID * @param tableName name of the requested master data table. * @param initalRequest flag that defines an initial download of all master data tables. * @return */ private boolean refreshMasterdata(int perno, String tableName, String initalRequest) { boolean result = true; Transaction transaction = tr.getSynchronousTransaction("REFRESH_MASTERDATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); // get generic form draft download flag from registry boolean genericFormsDraftDownload = RegistryUtil.isGenericFormsDraftDownload(); try { transaction.start(false) .addElement("PERNR", perno) //$NON-NLS-1$ .addElement("TABLENAME", tableName) //$NON-NLS-1$ .addElement("INIT", initalRequest) //$NON-NLS-1$ .addElement("DRAFT", genericFormsDraftDownload); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // String reason = response.getStringElement("ZKDMOBMVCAS"); //$NON-NLS-1$ // String plan = response.getStringElement("ZKDMOBMONTXT"); //$NON-NLS-1$ // success // if (log.isDebugEnabled()) log.info("REFRESH_MASTERDATA(TABLENAME=" + tableName + ", INIT=" + initalRequest + ") completed successfully"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // log.info("ZKDMOBMVCAS " + reason + " ZKDMOBMONTXT " + plan); } else { // error if (log.isDebugEnabled()) { log.error("communication error: ", transaction.getLastException().fillInStackTrace()); //$NON-NLS-1$ } android.util.Log.e("ERROR", Arrays.toString(transaction.getLastException().getStackTrace()), transaction.getLastException().fillInStackTrace()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * runs the operation REGISTER_USER in order to retrieve a new user record * * @param perno employee ID * @param pwd password * @return */ public boolean runRegisterUser(int perno, String pwd) { ensureAMThread(); boolean result = false; Transaction transaction = tr.getSynchronousTransaction("REGISTER_USER"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addElement("PERNR", perno).addElement("PWD", pwd); //$NON-NLS-1$ //$NON-NLS-2$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success String info = response.getStringElement("INFO"); //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("REGISTER_USER(PERNR=" + perno + ", PWD=" + pwd + ") completed successfully with info code " + info); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if ("01".equalsIgnoreCase(info)) { //$NON-NLS-1$ return true; } else if ("02".equalsIgnoreCase(info)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("invalidUsernameOrPassword")); //$NON-NLS-1$ } else if ("03".equalsIgnoreCase(info)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("userLocked")); //$NON-NLS-1$ } else if ("04".equalsIgnoreCase(info)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("userIsNotRegistred")); //$NON-NLS-1$ } } else { // error if (log.isDebugEnabled()) { log.debug("communication error: "); //$NON-NLS-1$ } showCommunicationErrorMessage(transaction.getLastException().getMessage()); } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); } finally { // clean up transaction.dispose(); } return result; } /** * runs the operation GET_ORDER in order to retrieve a certain order from * the server * * @param orderId the id of the order * @param orderType the type of the order * @param pernr the personal number of the order * @return */ public RemoteTransactionResult runGetOrder(String orderId, String orderType, int pernr) { ensureAMThread(); log.info("orderId " + orderId + " orderType " + orderType + " pernr " + pernr); Transaction transaction = tr.getSynchronousTransaction("GET_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false) .addElement("MLDNR", orderId) .addElement("AUART", orderType) .addElement("PERNR", pernr); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { String msgType = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String msg = response.getStringElement("MSG"); //$NON-NLS-1$ if ("E".equalsIgnoreCase(msgType)) { //$NON-NLS-1$ // error log.info("SAP error message: " + msg); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + msg); //$NON-NLS-1$ return new RemoteTransactionResult(RemoteTransactionResult.Status.error, msg, msgType); } else { // success if (log.isDebugEnabled()) { log.debug("GET_ORDER completed successfully"); //$NON-NLS-1$ } } if (log.isDebugEnabled()) { log.debug("MSGTYPE /" + msgType + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); return new RemoteTransactionResult(RemoteTransactionResult.Status.error); } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); return new RemoteTransactionResult(RemoteTransactionResult.Status.error); } finally { // clean up transaction.dispose(); } return new RemoteTransactionResult(RemoteTransactionResult.Status.success); } /** * runs the operation CREATE_ORDER in order to request SAP (the server) to * create a new order * * @param personalNumber * @param kommissionNumber * @return */ public Job runCreateOrder(int personalNumber, String kommissionNumber) { ensureAMThread(); Job newJob = null; Transaction transaction = tr.getSynchronousTransaction("CREATE_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("CREATE_ORDER (kommissionNumber=" + kommissionNumber + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { transaction.start(true).addElement("PERNR", personalNumber).addElement("VBELN", kommissionNumber.toUpperCase()); //$NON-NLS-1$ //$NON-NLS-2$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("CREATE_ORDER completed successfully"); //$NON-NLS-1$ } String msgtype = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String msg = response.getStringElement("MSG"); //$NON-NLS-1$ String mldnr = response.getStringElement("MLDNR"); //$NON-NLS-1$ String auart = response.getStringElement("AUART"); //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("MSGTYPE /" + msgtype + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MLDNR /" + mldnr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("AUART /" + auart + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } if ("S".equalsIgnoreCase(msgtype)) { //$NON-NLS-1$ MessageUtil.getInstance().showMessage(msg); newJob = dbutil.selectJobByJobIdAndJobType(mldnr, auart); } else if ("E".equalsIgnoreCase(msgtype)) { //$NON-NLS-1$ // error log.info("SAP error message: " + msg); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + msg); //$NON-NLS-1$ // app.inform(Messages.getString("SAPErrorMessage") + msg); } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); } finally { // clean up transaction.dispose(); } return newJob; } /** * saves an order * * Note: the name of this transaction is misleading, it is used for two use * cases:

    *
  • inform SAP that an address or other order data has been edited (case 1)
  • *
  • inform SAP that a new job has been created (case 2)
  • *
* The two cases are only distinct with respect to the addresses to transfer. * * @param job the job * @param address the address edited, null otherwise * @return */ public boolean runSaveOrder(Job job, Address address) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("SAVE_ORDER"); //$NON-NLS-1$ } try { Request request = transaction.start(true) .addElement("PERNR", job.getPersonalNumber()) //$NON-NLS-1$ .addQuery("ZKDMOB", sqlQuerySelectJob(job.getJobNumber(), job.getJobType().getCode(), job.getPersonalNumber(), job.isDriveTypeUpdated()), jobElementTempLate()); //$NON-NLS-1$ if (address != null) { // add the address that has been edited request.addQuery("ZKDMOBADR", sqlQuerySelectAddress(address), addressElementTemplate()); //$NON-NLS-1$ } else if (job.isLocalJob() && !job.isDriveTypeUpdated()) { // add all addressed linked to this job if the job was created in the app request.addQuery("ZKDMOBADR", sqlQuerySelectAddress(job), addressElementTemplate()); //$NON-NLS-1$ } log.info(sqlQuerySelectAddress(job)); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("SAVE_ORDER completed successfully"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetOrderList(String orderId, int pernr, String auart, String vbeln, String street, String city1, String postCode1, String name4, String savOff) { ensureAMThread(); boolean result = true; log.info("pernr " + pernr + " jobType " + auart + " commission " + vbeln); Transaction transaction = tr.getSynchronousTransaction("GET_ORDER_LIST"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false) .addElement("PERNR", pernr) .addElement("AUART", auart) .addElement("MLDNR", orderId) .addElement("VBELN", vbeln.toUpperCase()) .addElement("STREET", street) .addElement("CITY1", city1) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ .addElement("POST_CODE1", postCode1) .addElement("NAME4", name4) .addElement("SAVOFF", savOff); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("GET_ORDER_LIST completed successfully"); //$NON-NLS-1$ } String msg = response.getStringElement("MSG"); //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } if (msg.length() > 0) { MessageUtil.getInstance().showMessage(msg); } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetShortMSG(int pernr, String tdName) { ensureAMThread(); boolean result = true; SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Transaction transaction = tr.getSynchronousTransaction("GET_SHORT_MSG"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runGetShortMSG - PERNR /" + pernr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.info("runGetShortMSG - TDNAME /" + tdName + "/"); //$NON-NLS-1$ //$NON-NLS-2$ transaction.start(false).addElement("PERNR", pernr).addElement("TDNAME", tdName); //$NON-NLS-1$ //$NON-NLS-2$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success ShortMessage newMsg = dbutil.selectShortMessageByPerNoAndTdName(pernr, tdName); newMsg.setReceiveDate(format.format(new Date())); newMsg.setReceiveTime(new Date()); dbutil.updateShortMessage(newMsg); if (log.isDebugEnabled()) { log.debug("GET_SHORT_MSG completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runComfirmShortMSG(ShortMessage shortMessage) { ensureAMThread(); boolean result = true; DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); Transaction transaction = tr.getAsynchronousTransaction("CONFIRM_SHORTMSG"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { shortMessage.setStatus(CommonConstants.ShortMessage.Status.CONFIRMED); dbutil.updateShortMessage(shortMessage); transaction.start(false).addQuery("ZSHORTMSG", //$NON-NLS-1$ "SELECT " + DbConstants.ShortMessage.MESSAGE_KEY + ", " + DbConstants.ShortMessage.PERSONAL_NUMBER + ", " + DbConstants.ShortMessage.CONFIRM + DbConstants.From.FROM_TEXT //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + DbConstants.ShortMessage.SHORT_MESSAGE + DbConstants.Where.WHERE_TEXT + DbConstants.ShortMessage.PERSONAL_NUMBER + " = " + shortMessage.getPersonalNumber() + " AND " + DbConstants.ShortMessage.MESSAGE_KEY //$NON-NLS-1$ //$NON-NLS-2$ + " ='" + shortMessage.getMessageKey() + "'", //$NON-NLS-1$ //$NON-NLS-2$ new ElementTemplate[] { Element.STRING(DbConstants.ShortMessage.MESSAGE_KEY), Element.INT(DbConstants.ShortMessage.PERSONAL_NUMBER), Element.STRING(DbConstants.ShortMessage.CONFIRM) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("CONFIRM_SHORTMSG queued"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up if (db.isTransactionPending()) { db.rollback(); } } return result; } private boolean runSaveReportWithSignatureFileAttachment(int perno, String orderId, String orderType, String guid, File file) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_REPORT"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addElement("PERNR", perno) //$NON-NLS-1$ .addQuery("ZKDMOBREP", sqlQuerySelectActivedReport(orderId, orderType), reportElementTemplate()) //$NON-NLS-1$ .addQuery("ZKDMOBMSG", sqlQuerySelectMessage(guid), jobMessageElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMATORD", sqlQuerySelectReportMaterial(guid), reportMaterialElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMOBRTIM", sqlQuerySelectJobReportTime(guid), jobTimeElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMOBMEAS", sqlQuerySelectReportMeasurements(guid), reportMeasurementElementTempLate()) //$NON-NLS-1$ .addQuery("FORMINSTANCE", sqlQuerySelectFormInstances(guid), reportFormInstancesElementTempLate()) //$NON-NLS-1$ .addAttachmentElement(DbConstants.Report.SIGNATURE, file); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSavePicture(JobFile jobFile) { boolean result = true; log.info("MLDNR " + jobFile.getJobNumber() + "\nAUART " + jobFile.getJobType().getCode() + "\nGUID " + jobFile.getGuid() + "\nATTCLAS " + jobFile.getType() + "\nIDX " + jobFile.getJobFileId() + "\nDESC " + jobFile.getDescription() + "\nSIGNPIC_AT " + (jobFile.getSignpicAt().length() > 20 ? jobFile.getSignpicAt().substring(0, 20) + "..." : "") + "\nFORMTYPE " + jobFile.getFormType().getCode() + "\nFORMDESC " + jobFile.getFormDesc() ); Transaction transaction = tr.getAsynchronousTransaction("SAVE_PICTURE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false) .addElement("MLDNR", jobFile.getJobNumber()) .addElement("AUART", jobFile.getJobType().getCode()) .addElement("GUID", jobFile.getGuid()) .addElement("ATTCLAS", jobFile.getType()) .addElement("IDX", jobFile.getJobFileId()) .addElement("DESC", jobFile.getDescription()) .addElement("SIGNPIC_AT", jobFile.getSignpicAt()) .addElement("FORMTYPE", jobFile.getFormType().getCode()) .addElement("FORMDESC", jobFile.getFormDesc()); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSavePicture(String orderId, String orderType, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PICTURE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addQuery(DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE, sqlQuerySelectJobFile(orderId, orderType, guid), pictureElementTempLate()); // $NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSavePersonalPicture(String orderId, String orderType, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_PICS"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addQuery("ZKDMOBMV", sqlQuerySelectJobFile(orderId, orderType, guid), pictureElementTempLate()); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update reports to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSynchronize(int pernr) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("SYNCHRONIZE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runSynchronize - PERNR /" + pernr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ transaction.start(true).addElement("PERNR", pernr); //$NON-NLS-1$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { // success response.getDateElement("SERVER_TIME"); //$NON-NLS-1$ try { // app.appman.setSystemDateTime(srvTime); } catch (Exception e) { log.error("Setting system date and time failed: " + e.getMessage()); //$NON-NLS-1$ log.error(e); } if (log.isDebugEnabled()) { log.debug("SYNCHRONIZE completed successfully"); //$NON-NLS-1$ } } else { // error if (log.isDebugEnabled()) { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ } showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveAbsence(Date date, int pernr, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_ABSENCE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addQuery("ZKDMAABSENCE", sqlQuerySelectAbsenceNotification(date, pernr, guid), absenceNotificationElementTempLate()); //$NON-NLS-1$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("save absence to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * Selects one single address * * @param address * @return */ private String sqlQuerySelectAddress(Address address) { return "SELECT " + DbConstants.Address.JOB_NUMBER + " ," + DbConstants.Address.JOB_TYPE + " ," + DbConstants.Address.PARTNER_NUMBER + " ," + DbConstants.Address.COMMISSION_NUMBER + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Address.CUSTOMER_NUMBER + " ," + DbConstants.Address.TITLE + " ," + DbConstants.Address.NAME1 + " ," + DbConstants.Address.NAME2 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.NAME3 + " ," + DbConstants.Address.LOCATION + " ," + DbConstants.Address.STREET + " ," + DbConstants.Address.CITY + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.PASTAL_CODE + " ," + DbConstants.Address.PHONE_1 + " ," + DbConstants.Address.PHONE_2 + " ," + DbConstants.Address.FAX + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.EMAIL + " FROM " + DbConstants.Address.ADDRESS + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + address.getJobNumber() + "'" + " AND " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Address.JOB_TYPE + " = '" + address.getJobType() + "'" + " AND " + DbConstants.Address.PARTNER_NUMBER + " = '" + address.getPartnerNummer() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } /** * selects all addresses linked to a job * * @param job * @return */ private String sqlQuerySelectAddress(Job job) { return "SELECT " + DbConstants.Address.JOB_NUMBER + " ," + DbConstants.Address.JOB_TYPE + " ," + DbConstants.Address.PARTNER_NUMBER + " ," + DbConstants.Address.COMMISSION_NUMBER + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Address.CUSTOMER_NUMBER + " ," + DbConstants.Address.TITLE + " ," + DbConstants.Address.NAME1 + " ," + DbConstants.Address.NAME2 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.NAME3 + " ," + DbConstants.Address.LOCATION + " ," + DbConstants.Address.STREET + " ," + DbConstants.Address.CITY + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.PASTAL_CODE + " ," + DbConstants.Address.PHONE_1 + " ," + DbConstants.Address.PHONE_2 + " ," + DbConstants.Address.FAX + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Address.EMAIL + " FROM " + DbConstants.Address.ADDRESS + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + job.getJobNumber() + "'" + " AND " + DbConstants.Address.JOB_TYPE //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + " = '" + job.getJobType() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ } private ElementTemplate[] addressElementTemplate() { return new ElementTemplate[] { Element.STRING(DbConstants.Address.JOB_NUMBER), Element.STRING(DbConstants.Address.JOB_TYPE), Element.STRING(DbConstants.Address.PARTNER_NUMBER), Element.STRING(DbConstants.Address.COMMISSION_NUMBER), Element.STRING(DbConstants.Address.CUSTOMER_NUMBER), Element.STRING(DbConstants.Address.TITLE), Element.STRING(DbConstants.Address.NAME1), Element.STRING(DbConstants.Address.NAME2), Element.STRING(DbConstants.Address.NAME3), Element.STRING(DbConstants.Address.LOCATION), Element.STRING(DbConstants.Address.STREET), Element.STRING(DbConstants.Address.CITY), Element.STRING(DbConstants.Address.PASTAL_CODE), Element.STRING(DbConstants.Address.PHONE_1), Element.STRING(DbConstants.Address.PHONE_2), Element.STRING(DbConstants.Address.FAX), Element.STRING(DbConstants.Address.EMAIL) }; } private String sqlQuerySelectJob(String MLDNR, String AUART, int pernr, boolean driveTypeUpdated) { StringBuilder sb = new StringBuilder(); sb.append("SELECT "); //$NON-NLS-1$ sb.append(DbConstants.Job.JOB_NUMBER); sb.append(" ," + DbConstants.Job.JOB_TYPE); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.PERSONAL_NUMBER); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.CUSTOMER_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.PARTNER_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.OBJECT_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.OWNER_ADDRESS_ID); //$NON-NLS-1$ sb.append(" ," + DbConstants.Job.COMMISSION_NUMBER); //$NON-NLS-1$ // send driver type only if entered/updated in app if (driveTypeUpdated) sb.append(" ," + DbConstants.Job.DRIVER_TYPE); //$NON-NLS-1$ sb.append(" FROM " + DbConstants.Job.JOB); //$NON-NLS-1$ sb.append(" WHERE " + DbConstants.Job.JOB_NUMBER + " = '" + MLDNR + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append(" AND " + DbConstants.Job.JOB_TYPE + " = '" + AUART + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sb.append(" AND " + DbConstants.Job.PERSONAL_NUMBER + " = " + pernr + ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return sb.toString(); } private ElementTemplate[] jobElementTempLate() { return new ElementTemplate[] { Element.INT(DbConstants.Job.PERSONAL_NUMBER) }; } private String sqlQuerySelectActivedReport(String orderId, String orderType) { return "SELECT " + DbConstants.Report.GUID + " ," + DbConstants.Report.CREATE_DATE + " ," + DbConstants.Report.JOB_NUMBER + " ," + DbConstants.Report.JOB_TYPE + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Report.COMMISSION_NUMBER + " ," + DbConstants.Report.PERSONAL_NUMBER + " ," + DbConstants.Report.PARTICAL_REPAIR + " ," + DbConstants.Report.FINAL_REPAIR + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.REASONING + " ," + DbConstants.Report.INCIDENT_AB + " ," + DbConstants.Report.BILLING + " ," + DbConstants.Report.SAFETY_REPORT + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.CUSTOMER_SUPPORT + " ," + DbConstants.Report.CUSTOMRE_SUPPORT_TEXT + " ," + DbConstants.Report.CHECK_LIST + " ," + DbConstants.Report.ERROR_ID_1 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.ERROR_H_1 + " ," + DbConstants.Report.ERROR_FLAG_1 + " ," + DbConstants.Report.ERROR_ID_2 + " ," + DbConstants.Report.ERROR_H_2 + " ," + DbConstants.Report.ERROR_FLAG_2 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " ," + DbConstants.Report.ERROR_ID_3 + " ," + DbConstants.Report.ERROR_H_3 + " ," + DbConstants.Report.ERROR_FLAG_3 + " ," + DbConstants.Report.SYSTEM_ERROR + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Report.DISTANCE + " ," + DbConstants.Report.EXPENSES + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_1 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_2 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.SERVICE_PLAN_MENTH_3 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_4 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_5 + " ," + DbConstants.Report.SERVICE_PLAN_MENTH_6 + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.MONTH_YEAR + " ," + DbConstants.Report.ORDER_NUMBER + " ," + DbConstants.Report.SIGNATURE_GUID + " ," + DbConstants.Report.SIGNATURE_FLAG + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Report.SIGNATURE_INFO + " ," //$NON-NLS-1$ // TODO Was erwartet Sven im Feld SIGNPIC? (sollte m. E. den // Dateinamen enthalten obder besser gar nicht �bermittelt // werden) + DbConstants.Report.SIGNATURE + " ," + DbConstants.Report.WORK_TYPE // MIG-513 CHANGE: NOMATUSED isn't necessary anymore in SAVE_REPORT // + " ," + DbConstants.Report.NO_MATERIAL + " ," + DbConstants.Report.CYCLE_OF_INSTALLATION + " ," + DbConstants.Report.NO_FORM1 + " ," + DbConstants.Report.NO_FORM2 + " ," + DbConstants.Report.NO_FORM3 + " ," + DbConstants.Report.SERVICE_REFUSED + " ," + DbConstants.Report.OPEN_PENDING + " ," + DbConstants.Report.GOVERNMENT_REPORT + " ," + DbConstants.Report.CHECKLIST_STATE + " ," + DbConstants.Report.CHECKLIST_SIA + " ," + DbConstants.Report.CHECKLIST_READY + " ," + DbConstants.Report.CHECKLIST_INSTRUCTION + " ," + DbConstants.Report.CHECKLIST_VKF + " ," + DbConstants.Report.CHECKLIST_TEST + " ," + DbConstants.Report.SIGNATURE_NAME + " ," + DbConstants.Report.MON_STK + " ," + DbConstants.Report.NEXT_INTERVENTION_DATE + " ," + DbConstants.Report.STATE_OF_INSTALLATION + " ," + DbConstants.Report.NEXT_INTERVENTION_CODE + " FROM " + DbConstants.Report.REPORT + " WHERE " + DbConstants.Report.JOB_NUMBER + " = '" + orderId //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + "'" + " AND " + DbConstants.Report.JOB_TYPE + " = '" + orderType + "'" + " AND " + DbConstants.Report.IDX + " = (" + "SELECT MAX(" + DbConstants.Report.IDX + ") " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + "FROM " + DbConstants.Report.REPORT + " WHERE MLDNR = '" + orderId + "'" + " AND AUART = '" + orderType + "' )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } private ElementTemplate[] reportElementTemplate() { return new ElementTemplate[] { Element.STRING(DbConstants.Report.GUID), Element.DATETIME(DbConstants.Report.CREATE_DATE), Element.STRING(DbConstants.Report.JOB_NUMBER), Element.STRING(DbConstants.Report.JOB_TYPE), Element.STRING(DbConstants.Report.COMMISSION_NUMBER), Element.INT(DbConstants.Report.PERSONAL_NUMBER), Element.STRING(DbConstants.Report.PARTICAL_REPAIR), Element.STRING(DbConstants.Report.FINAL_REPAIR), Element.STRING(DbConstants.Report.REASONING), Element.STRING(DbConstants.Report.INCIDENT_AB), Element.STRING(DbConstants.Report.BILLING), Element.STRING(DbConstants.Report.SAFETY_REPORT), Element.STRING(DbConstants.Report.CUSTOMER_SUPPORT), Element.STRING(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT), Element.STRING(DbConstants.Report.CHECK_LIST), Element.STRING(DbConstants.Report.ERROR_ID_1), Element.STRING(DbConstants.Report.ERROR_H_1), Element.STRING(DbConstants.Report.ERROR_FLAG_1), Element.STRING(DbConstants.Report.ERROR_ID_2), Element.STRING(DbConstants.Report.ERROR_H_2), Element.STRING(DbConstants.Report.ERROR_FLAG_2), Element.STRING(DbConstants.Report.ERROR_ID_3), Element.STRING(DbConstants.Report.ERROR_H_3), Element.STRING(DbConstants.Report.ERROR_FLAG_3), Element.STRING(DbConstants.Report.SYSTEM_ERROR), Element.STRING(DbConstants.Report.DISTANCE), Element.STRING(DbConstants.Report.EXPENSES), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_1), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_2), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_3), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_4), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_5), Element.STRING(DbConstants.Report.SERVICE_PLAN_MENTH_6), Element.STRING(DbConstants.Report.MONTH_YEAR), Element.STRING(DbConstants.Report.ORDER_NUMBER), Element.STRING(DbConstants.Report.SIGNATURE_GUID), Element.STRING(DbConstants.Report.SIGNATURE_FLAG), Element.STRING(DbConstants.Report.SIGNATURE_INFO), Element.STRING(DbConstants.Report.SIGNATURE), Element.STRING(DbConstants.Report.WORK_TYPE) , Element.STRING(DbConstants.Report.CYCLE_OF_INSTALLATION) , Element.STRING(DbConstants.Report.NO_FORM1), Element.STRING(DbConstants.Report.NO_FORM2), Element.STRING(DbConstants.Report.NO_FORM3), Element.STRING(DbConstants.Report.SERVICE_REFUSED), Element.STRING(DbConstants.Report.OPEN_PENDING),Element.STRING(DbConstants.Report.GOVERNMENT_REPORT), Element.STRING(DbConstants.Report.CHECKLIST_STATE), Element.STRING(DbConstants.Report.CHECKLIST_SIA), Element.STRING(DbConstants.Report.CHECKLIST_READY),Element.STRING(DbConstants.Report.CHECKLIST_INSTRUCTION), Element.STRING(DbConstants.Report.CHECKLIST_VKF), Element.STRING(DbConstants.Report.CHECKLIST_TEST), Element.STRING(DbConstants.Report.SIGNATURE_NAME), Element.STRING(DbConstants.Report.MON_STK), Element.DATETIME(DbConstants.Report.NEXT_INTERVENTION_DATE),Element.STRING(DbConstants.Report.STATE_OF_INSTALLATION),Element.STRING(DbConstants.Report.NEXT_INTERVENTION_CODE),}; } private String sqlQuerySelectReportMaterial(String guid) { return "SELECT " + DbConstants.ReportMaterial.GUID + " , " + DbConstants.ReportMaterial.IDX + " , " + DbConstants.ReportMaterial.NUMBER + " , " + DbConstants.ReportMaterial.PERSONAL_NUMBER + " , " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.ReportMaterial.COMMISSION_NUMBER + " , " + DbConstants.ReportMaterial.AMOUNT + " , " + DbConstants.ReportMaterial.DELIVERY + " , " + DbConstants.ReportMaterial.EXPRESS_DELIVERY + " , " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.ReportMaterial.ACCOUNT_CODE + " , " + DbConstants.ReportMaterial.NAME + " , " + DbConstants.ReportMaterial.PRICE + " , " + DbConstants.ReportMaterial.BARCODE + " , " + DbConstants.ReportMaterial.K14 + " , " + DbConstants.ReportMaterial.EXPLANATION_TEXT + " , " + DbConstants.ReportMaterial.OTHER_TYPE_FLAG + " FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.ReportMaterial.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ } private ElementTemplate[] reportMaterialElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.ReportMaterial.GUID), Element.INT(DbConstants.ReportMaterial.IDX), Element.STRING(DbConstants.ReportMaterial.NUMBER), Element.INT(DbConstants.ReportMaterial.PERSONAL_NUMBER), Element.STRING(DbConstants.ReportMaterial.COMMISSION_NUMBER), Element.STRING(DbConstants.ReportMaterial.AMOUNT), Element.STRING(DbConstants.ReportMaterial.DELIVERY), Element.STRING(DbConstants.ReportMaterial.EXPRESS_DELIVERY), Element.STRING(DbConstants.ReportMaterial.NAME), Element.STRING(DbConstants.ReportMaterial.PRICE), Element.STRING(DbConstants.ReportMaterial.BARCODE), Element.STRING(DbConstants.ReportMaterial.K14), Element.STRING(DbConstants.ReportMaterial.EXPLANATION_TEXT), Element.STRING(DbConstants.ReportMaterial.OTHER_TYPE_FLAG) }; } private String sqlQuerySelectMessage(String guid) { return "SELECT " + DbConstants.JobMessage.GUID + " ," + DbConstants.JobMessage.MESSAGE_ID + " ," + DbConstants.JobMessage.TEXT_1 + " ," + DbConstants.JobMessage.TEXT_2 + " ," + DbConstants.JobMessage.MoreText + " ," + DbConstants.JobMessage.MESSAGE_CODE + " FROM " + DbConstants.JobMessage.JOB_MESSAGE + " WHERE " + DbConstants.JobMessage.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } private ElementTemplate[] jobMessageElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.JobMessage.GUID) , Element.STRING(DbConstants.JobMessage.MESSAGE_ID) , Element.STRING(DbConstants.JobMessage.TEXT_1) , Element.STRING(DbConstants.JobMessage.TEXT_2) , Element.STRING(DbConstants.JobMessage.MoreText) , Element.STRING(DbConstants.JobMessage.MESSAGE_CODE) }; } private String sqlQuerySelectJobReportTime(String guid) { return "SELECT " + DbConstants.JobReportTime.GUID + " , " + DbConstants.JobReportTime.IDX + " , " + DbConstants.JobReportTime.START_TIME + " , " + DbConstants.JobReportTime.STOP_TIME + " , " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobReportTime.WORK_TYPE_CODE + " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } private ElementTemplate[] jobTimeElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.JobReportTime.GUID), Element.INT(DbConstants.JobReportTime.IDX), Element.DATETIME(DbConstants.JobReportTime.START_TIME), Element.DATETIME(DbConstants.JobReportTime.STOP_TIME), Element.STRING(DbConstants.JobReportTime.WORK_TYPE_CODE) }; } private String sqlQuerySelectJobFile(String orderId, String orderType, String guid) { return "SELECT " + DbConstants.JobFile.JOB_NUMBER + " ," + DbConstants.JobFile.JOB_TYPE + " ," + DbConstants.JobFile.GUID + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.TYPE + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.IDX + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.DESCRIPTION + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.JobFile.SIGN_PIC_AT + " ," + DbConstants.JobFile.FORM_TYPE + " ," + DbConstants.JobFile.FORM_DESC + " ," + DbConstants.JobFile.SENT_DATE + " FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.JOB_NUMBER + " = '" + orderId + "'" + " AND " + DbConstants.JobFile.JOB_TYPE + " = '" + orderType + "'" + " AND " + DbConstants.JobFile.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } private ElementTemplate[] pictureElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.JobFile.JOB_NUMBER), Element.STRING(DbConstants.JobFile.JOB_TYPE), Element.STRING(DbConstants.JobFile.GUID), Element.STRING(DbConstants.JobFile.TYPE), Element.STRING(DbConstants.JobFile.IDX), Element.STRING(DbConstants.JobFile.DESCRIPTION), Element.STRING(DbConstants.JobFile.SIGN_PIC_AT), Element.STRING(DbConstants.JobFile.FORM_TYPE), Element.STRING(DbConstants.JobFile.FORM_DESC), Element.STRING(DbConstants.JobFile.SENT_DATE) }; } private String sqlQuerySelectReportMeasurements(String guid) { return "SELECT " + DbConstants.ReportMeasurement.GUID + " ," + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ," + DbConstants.ReportMeasurement.MEASURING_POINT + " ," + DbConstants.ReportMeasurement.MEASUREMENT + " ," + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ," + DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE + " ," + DbConstants.ReportMeasurement.DYNAMIC_TIME + " ," + DbConstants.ReportMeasurement.STATIC_END_POWER + " ," + DbConstants.ReportMeasurement.DEVICE_TYPE + " ," + DbConstants.ReportMeasurement.SN_OF_DEVICE + " ," + DbConstants.ReportMeasurement.CALIBRATION_DATE + " FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " = '" + guid + "'"; } private ElementTemplate[] reportMeasurementElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.ReportMeasurement.GUID), Element.STRING(DbConstants.ReportMeasurement.COMMISSION_NUMBER), Element.STRING(DbConstants.ReportMeasurement.MEASURING_POINT), Element.STRING(DbConstants.ReportMeasurement.MEASUREMENT), Element.STRING(DbConstants.ReportMeasurement.PERSONAL_NUMBER), Element.STRING(DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE), Element.STRING(DbConstants.ReportMeasurement.DYNAMIC_TIME), Element.STRING(DbConstants.ReportMeasurement.STATIC_END_POWER), Element.STRING(DbConstants.ReportMeasurement.DEVICE_TYPE), Element.STRING(DbConstants.ReportMeasurement.SN_OF_DEVICE), Element.DATETIME(DbConstants.ReportMeasurement.CALIBRATION_DATE) }; } private String sqlQuerySelectFormInstances(String guid) { return "SELECT " + FORMINSTANCE.COL_GUID + " ," + FORMINSTANCE.COL_FORMID + " ," + FORMINSTANCE.COL_FORMVERSION + " ," + FORMINSTANCE.COL_FORMITEMID + " ," + FORMINSTANCE.COL_VALUELISTID + " ," + FORMINSTANCE.COL_VALUEID + " ," + FORMINSTANCE.COL_FORMITEMTYPE + " ," + FORMINSTANCE.COL_STRINGVALUE + " ," + FORMINSTANCE.COL_BOOLEANVALUE + " ," + FORMINSTANCE.COL_FLOATVALUE + " ," + FORMINSTANCE.COL_ATTACHMENTVALUE + " FROM " + FORMINSTANCE.TABLE + " WHERE " + FORMINSTANCE.COL_GUID + " = '" + guid + "'"; } private ElementTemplate[] reportFormInstancesElementTempLate() { return new ElementTemplate[] { Element.STRING(FORMINSTANCE.COL_GUID), Element.STRING(FORMINSTANCE.COL_FORMID), Element.INT(FORMINSTANCE.COL_FORMVERSION), Element.STRING(FORMINSTANCE.COL_FORMITEMID), Element.STRING(FORMINSTANCE.COL_VALUELISTID), Element.STRING(FORMINSTANCE.COL_VALUEID), Element.STRING(FORMINSTANCE.COL_FORMITEMTYPE), Element.STRING(FORMINSTANCE.COL_STRINGVALUE), Element.BOOLEAN(FORMINSTANCE.COL_BOOLEANVALUE), Element.DOUBLE(FORMINSTANCE.COL_FLOATVALUE), Element.ATTACHMENT(FORMINSTANCE.COL_ATTACHMENTVALUE) }; } private String sqlQuerySelectAbsenceNotification(Date date, int pernr, String guid) { return "SELECT " + DbConstants.AbsenceNotification.GUID + " ," + DbConstants.AbsenceNotification.DATE + " ," + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " ," + DbConstants.AbsenceNotification.ABSENCE_TYPE + " ," + DbConstants.AbsenceNotification.DATE_FROM + " ," + DbConstants.AbsenceNotification.DATE_TO + " ," + DbConstants.AbsenceNotification.TIME_FROM + " ," + DbConstants.AbsenceNotification.TIME_TO + " ," + DbConstants.AbsenceNotification.TEXT + " FROM " + DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION + " WHERE " + DbConstants.AbsenceNotification.DATE + " = '" + date.getTime() + "'" + " AND " + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " = " + pernr + "" + " AND " + DbConstants.JobFile.GUID + " = '" + guid + "'"; } private ElementTemplate[] absenceNotificationElementTempLate() { return new ElementTemplate[] { Element.STRING(DbConstants.AbsenceNotification.GUID), Element.DATETIME(DbConstants.AbsenceNotification.DATE), Element.STRING(DbConstants.AbsenceNotification.PERSONAL_NUMBER), Element.STRING(DbConstants.AbsenceNotification.ABSENCE_TYPE), Element.DATE(DbConstants.AbsenceNotification.DATE_FROM), Element.DATE(DbConstants.AbsenceNotification.DATE_TO), Element.TIME(DbConstants.AbsenceNotification.TIME_FROM), Element.TIME(DbConstants.AbsenceNotification.TIME_TO), Element.STRING(DbConstants.AbsenceNotification.TEXT) }; } public boolean saveReport(DBSession db, Job job, String signaturePath) { ensureAMThread(); boolean result = true; Report report = job.getLatestReport(); db.startTransaction(); try { // assign value to objects if ((!report.isFinalRepair() && !report.isPartialRepair()) || report.isFinalRepair()) { job.setStatus(JobStatus.FINALIZED); } else if (report.isPartialRepair()) { job.setStatus(JobStatus.PARLTY_DONE); } job.setStatusEdit(new Date()); log.info("saveReport " + report.getGuId() + " job " + job.getJobNumber()); report.setReportStatus(ReportStatus.RECEIVED); // replace "U" with empty before send to server if (report.isChecklistStateUnselected()) { report.setChecklistState(false); } if (report.isChecklistSIAUnselected()) { report.setChecklistSIA(false); } if (report.isChecklistReadyUnselected()) { report.setChecklistReady(false); } if (report.isChecklistInstructionUnselected()) { report.setChecklistInstruction(false); } if (report.isChecklistVKFUnselected()) { report.setChecklistVKF(false); } if (report.isChecklistTestUnselected()) { report.setChecklistTest(false); } // update status dbutil.updateJob(job); // update report dbutil.updateReport(report); log.info("Next intervention date " + DateTimeUtil.showDate(report.getNextInterventionDate())); log.info("State of installation " + report.getStateOfInstallation()); log.info("Next intervention code " + report.getNextInterventionCode()); // Save report to backend (doing an implicit dbutil commit // on success) if(new RemoteTransactionHandler().runSaveReport(job.getPersonalNumber(), job.getJobNumber(), job.getJobType().getCode(), report, signaturePath)) { List reportImageAttachmentsList = dbutil.selectReportJobFileImageListByReport(report); for (JobFile image : reportImageAttachmentsList) { runSavePicture(image); image.setSentDate(new Date()); dbutil.updateJobFile(image); } List reportDocAttachmentsList = dbutil.selectReportJobFileListByReport(report); for (JobFile jobFile : reportDocAttachmentsList) { runSavePicture(jobFile); } List formImagesList = dbutil.selectFormImageListByReport(report); for (JobFile formImage : formImagesList) { runSavePicture(formImage); } } else { result = false; } } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { db.rollback(); } } return result; } public boolean runSaveReport(int perno, String orderId, String orderType, Report report, String signaturePath) { ensureAMThread(); String guid = report.getGuId(); if (StringUtil.isNotEmpty(report.getSignature())) { File att = new File(FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, signaturePath, report.getSignature(), false)); return runSaveReportWithSignatureFileAttachment(perno, orderId, orderType, guid, att); } else { return runSaveReportWithoutFile(perno, orderId, orderType, guid); } } private boolean runSaveReportWithoutFile(int perno, String orderId, String orderType, String guid) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_REPORT"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { transaction.start(false).addElement("PERNR", perno).addQuery("ZKDMOBREP", sqlQuerySelectActivedReport(orderId, orderType), reportElementTemplate()) //$NON-NLS-1$ //$NON-NLS-2$ .addQuery("ZKDMOBMSG", sqlQuerySelectMessage(guid), jobMessageElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMATORD", sqlQuerySelectReportMaterial(guid), reportMaterialElementTempLate()) //$NON-NLS-1$ .addQuery("ZKDMOBRTIM", sqlQuerySelectJobReportTime(guid), jobTimeElementTempLate()) .addQuery("ZKDMOBMEAS", sqlQuerySelectReportMeasurements(guid), reportMeasurementElementTempLate()) .addQuery("FORMINSTANCE", sqlQuerySelectFormInstances(guid), reportFormInstancesElementTempLate()); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("update reports to remote server"); //$NON-NLS-1$ } else { // error if (log.isDebugEnabled()) { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * Updates job on SAP side in case that a wrong Kommissionnummer has been * sent with the job. * * In case that the transaction completes successfully then - the existing * job is deleted from the local database - the SAP returns a new job with * the very same primary key, but updated information * * In case that the transaction fails the existing job remains in the * database * * * @param job the job where the Kommissionummer has to be changed * @param user current user * @return true if successfully, false otherwise. */ public boolean runUpdateOrder(Job job, Person user) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("UPDATE_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); try { dbutil.deleteJob(job); transaction.start(false) .addElement("MLDNR", job.getJobNumber()) .addElement("AUART", job.getJobType().getCode()) .addElement("VBELN", job.getCommissionNumber().toUpperCase()) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ .addElement("PERNR", user.getPersonalNumber()); //$NON-NLS-1$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { String MSGTYPE = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String MSG = response.getStringElement("MSG"); //$NON-NLS-1$ if ("E".equalsIgnoreCase(MSGTYPE) && MSG.length() > 0) { //$NON-NLS-1$ // error log.info("SAP error message: " + MSG); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + MSG); //$NON-NLS-1$ result = false; } else { if (log.isDebugEnabled()) log.debug("MSG /" + MSG + "/"); //$NON-NLS-1$ //$NON-NLS-2$ // success if (log.isDebugEnabled()) log.debug("UPDATE_ORDER successfully"); //$NON-NLS-1$ db.commit(); } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { if (db.isTransactionPending()) { db.rollback(); } // clean up transaction.dispose(); } return result; } public boolean updateStatus(DBSession db, Job job, String status, String sapStatus, String reason) { ensureAMThread(); boolean result = true; db.startTransaction(); try { // update status job.setStatus(status); dbutil.updateJob(job); // send update status to backend (doing an implicit dbutil commit on // success) result = this.runUpdateStatus(job.getJobNumber(), job.getJobType().getCode(), sapStatus, job.getJobForward(), reason); } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { String logMsg = MessageFormat.format( "DB transaction is still pending after backend communication and will be rolled back! Tried to update job status: job = {0}/{1}, new job status = {2}, SAP status = {3}", //$NON-NLS-1$ new Object[] { job.getJobNumber(), job.getJobType(), status, sapStatus }); log.warn(logMsg); db.rollback(); } } return result; } private boolean runUpdateStatus(String orderId, String orderType, String orderStatus, int persno2, String reason) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("UPDATE_STATUS"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isInfoEnabled()) { log.info("UPDATE_STATUS (mldnr= " + orderId + ", auart= " + orderType + ", new status= " + orderStatus + ", if forwarded pernr= " + persno2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } try { transaction.start(true) .addElement("MLDNR", orderId) .addElement("AUART", orderType) .addElement("STATUS", orderStatus) .addElement("PERSNO2", persno2) .addElement("RETTXT", reason); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveTimeSheet(int perNr, CalendarTimeSheet calendar) { if (dbutil.getUser().getExpensesActive()) { return runSaveTimeSheetWitExpenses(perNr, calendar); } else { return runSaveTimeSheetWitoutExpenses(perNr, calendar); } } public boolean runSaveTimeSheetWitoutExpenses(int perNr, CalendarTimeSheet calendar) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_DATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("SAVE_PERSONAL_DATA (perNr=" + perNr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { String sqlTimeSheetE = "SELECT " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ," + DbConstants.TimeSheet.DATE + " ," + DbConstants.TimeSheet.START_TIME + " ," + DbConstants.TimeSheet.STOP_TIME + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.COST_CENTER + " ," + DbConstants.TimeSheet.WORK_TYPE_CODE + " ," + DbConstants.TimeSheet.CALL_FLAG + " FROM " + DbConstants.TimeSheet.TIME_SHEET + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.TimeSheet.START_TIME + " >='" + calendar.getDate().getTime() + "'" + " AND " + DbConstants.TimeSheet.START_TIME + " <='" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DateTimeUtil.getLateNight(calendar.getDate()).getTime().getTime() + "'" + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + perNr + "'" + " ORDER BY " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("Select ZKDMATIME for: '" + sqlTimeSheetE + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } transaction.start(true) .addQuery("ZKDMATIME", sqlTimeSheetE, //$NON-NLS-1$ new ElementTemplate[] { Element.INT(DbConstants.TimeSheet.PERSONAL_NUMBER), Element.DATETIME(DbConstants.TimeSheet.DATE), Element.DATETIME(DbConstants.TimeSheet.START_TIME), Element.DATETIME(DbConstants.TimeSheet.STOP_TIME), Element.STRING(DbConstants.TimeSheet.COST_CENTER), Element.STRING(DbConstants.TimeSheet.WORK_TYPE_CODE), Element.STRING(DbConstants.TimeSheet.CALL_FLAG) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveTimeSheetWitExpenses(int perNr, CalendarTimeSheet calendar) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_DATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); if (log.isDebugEnabled()) { log.debug("SAVE_PERSONAL_DATA (perNr=" + perNr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { String sqlTimeSheetE = "SELECT " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ," + DbConstants.TimeSheet.DATE + " ," + DbConstants.TimeSheet.START_TIME + " ," + DbConstants.TimeSheet.STOP_TIME + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.COST_CENTER + " ," + DbConstants.TimeSheet.WORK_TYPE_CODE + " ," + DbConstants.TimeSheet.CALL_FLAG + " FROM " + DbConstants.TimeSheet.TIME_SHEET + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.TimeSheet.START_TIME + " >='" + calendar.getDate().getTime() + "'" + " AND " + DbConstants.TimeSheet.START_TIME + " <='" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DateTimeUtil.getLateNight(calendar.getDate()).getTime().getTime() + "'" + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + perNr + "'" + " ORDER BY " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ String sqlExpenses = "SELECT " + DbConstants.Expenses.PERSONAL_NUMBER + " ," + DbConstants.Expenses.DATE + " ," + DbConstants.Expenses.EXPENSES_DATE + " ," + DbConstants.Expenses.DAILY_EXPENSES //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " ," + DbConstants.Expenses.VARIOUS_EXPENSES + " ," + DbConstants.Expenses.DECUCTION + " ," + DbConstants.Expenses.EXPENSES_KEY + " ," + DbConstants.Expenses.PIKETT_EXPENSES + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.Expenses.EXPENSES_DESCRIPTION + " ," + DbConstants.Expenses.OPERATING_HOURS_OF + " ," + DbConstants.Expenses.OPERATION_HOURS_UP_TO + " ," + DbConstants.Expenses.OPERATION_HOURS_TOTAL + " ," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + DbConstants.Expenses.DEDUCTION_DESCRIPTION + " ," + DbConstants.Expenses.COMPENSTION + " FROM " + DbConstants.Expenses.EXPENSES + " WHERE " + DbConstants.Expenses.DATE + " = '" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + calendar.getDate().getTime() + "'" + " AND " + DbConstants.Expenses.PERSONAL_NUMBER + " = " + perNr + " ORDER BY " + DbConstants.Expenses.DATE + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ if (log.isDebugEnabled()) { log.debug("Select ZKDMATIME for: '" + sqlTimeSheetE + "'"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("Select ZKDMAEXPNS for: '" + sqlExpenses + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } transaction.start(true) .addQuery("ZKDMATIME", sqlTimeSheetE, //$NON-NLS-1$ new ElementTemplate[] { Element.INT(DbConstants.TimeSheet.PERSONAL_NUMBER), Element.DATETIME(DbConstants.TimeSheet.DATE), Element.DATETIME(DbConstants.TimeSheet.START_TIME), Element.DATETIME(DbConstants.TimeSheet.STOP_TIME), Element.STRING(DbConstants.TimeSheet.COST_CENTER), Element.STRING(DbConstants.TimeSheet.WORK_TYPE_CODE), Element.STRING(DbConstants.TimeSheet.CALL_FLAG) }) .addQuery("ZKDMAEXPNS", sqlExpenses, //$NON-NLS-1$ new ElementTemplate[] { Element.INT(DbConstants.Expenses.PERSONAL_NUMBER), Element.DATETIME(DbConstants.Expenses.DATE), Element.DATE(DbConstants.Expenses.EXPENSES_DATE), Element.STRING(DbConstants.Expenses.DAILY_EXPENSES), Element.STRING(DbConstants.Expenses.VARIOUS_EXPENSES), Element.STRING(DbConstants.Expenses.DECUCTION), Element.STRING(DbConstants.Expenses.EXPENSES_KEY), Element.STRING(DbConstants.Expenses.PIKETT_EXPENSES), Element.STRING(DbConstants.Expenses.EXPENSES_DESCRIPTION), Element.STRING(DbConstants.Expenses.OPERATING_HOURS_OF), Element.STRING(DbConstants.Expenses.OPERATION_HOURS_UP_TO), Element.STRING(DbConstants.Expenses.OPERATION_HOURS_TOTAL), Element.STRING(DbConstants.Expenses.DEDUCTION_DESCRIPTION), Element.STRING(DbConstants.Expenses.COMPENSTION) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean saveMaterial(int perNr, Order order) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_PERSONAL_DATA"); //$NON-NLS-1$ transaction.setInsertOnly(false); DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); order.setStatus(CommonConstants.Order.Status.SENT_ORDER); order.setSentDate(DateTimeUtil.getTimestamp().getTime()); dbutil.updateOrder(order); if (log.isDebugEnabled()) { log.debug("SAVE_PERSONAL_DATA (perNr=" + perNr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } try { transaction.start(true).addQuery("ZKDMAMAT", //$NON-NLS-1$ "SELECT " + DbConstants.OrderMaterial.PERSONAL_NUMBER + ", " + DbConstants.OrderMaterial.DATE + ", " + DbConstants.OrderMaterial.AMOUNT + ", " + DbConstants.OrderMaterial.NUMBER + ", " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + DbConstants.OrderMaterial.EXPRESS_FLAG + ", " + DbConstants.OrderMaterial.VARIOUS_MATERIAL + " FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL + " WHERE " + DbConstants.OrderMaterial.PERSONAL_NUMBER + " = '" + perNr //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + "'" + " AND " + DbConstants.OrderMaterial.ORDER_DATE + " = '" + order.getCreateDate().getTime() + "'", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ new ElementTemplate[] { Element.INT(DbConstants.OrderMaterial.PERSONAL_NUMBER), Element.DATETIME(DbConstants.OrderMaterial.DATE), Element.STRING(DbConstants.OrderMaterial.AMOUNT), Element.STRING(DbConstants.OrderMaterial.NUMBER), Element.STRING(DbConstants.OrderMaterial.EXPRESS_FLAG), Element.STRING(DbConstants.OrderMaterial.VARIOUS_MATERIAL) }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { if (db.isTransactionPending()) { db.rollback(); } // clean up transaction.dispose(); } return result; } private void showCommunicationErrorMessage(String message) { MessageUtil.getInstance().showMessage(Messages.getString("communicationErrorWithColon") + message); //$NON-NLS-1$ } public boolean runUpdateEdate(String orderId , String orderType , Date eDate , Date eDateTime , String reason) { boolean result = true; SimpleDateFormat dateFormate = new SimpleDateFormat("dd.MM.yyyy", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ SimpleDateFormat timeFormate = new SimpleDateFormat("HH:mm", new Locale("de", "CH")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Transaction transaction = tr.getAsynchronousTransaction("UPDATE_EDATE"); //$NON-NLS-1$ transaction.setInsertOnly(false); String date = dateFormate.format(eDate); String time = timeFormate.format(eDateTime); log.info("EDATE_DT " + date + " EDATE_TI " + time); try { transaction.start(true) .addElement("MLDNR", orderId) .addElement("AUART", orderType) .addDateElement("EDATE", eDate) .addTimeElement("EDATE", eDateTime) .addElement("MVCASTXT", reason); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("UPDATE_STATUS queued"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetInventryStock(int pernr, String wareHouseNumber, String language) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("SYNC_FZLG"); transaction.setInsertOnly(false); try { log.info("runSYNC_FZLG - PERNR /" + pernr + "/"); log.info("runSYNC_FZLG - LGORT /" + wareHouseNumber + "/"); transaction.start(false).addElement("PERNR", pernr).addElement("LGORT", wareHouseNumber).addElement("SPRAS", language); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success countFromTable("inventory Stock", DbConstants.VehicleInventory.VEHICLE_INVENTORY); if (log.isDebugEnabled()) { log.debug("SYNC_FZLG completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetMaterialMoveMent(String guid, int pernr, Date date) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("GET_MBEW"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runGetMaterialMoveMent - GUID /" + guid + "/ PERNR /" + pernr + "/"); transaction.start(false).addElement("GUID", guid).addElement("PERNR", pernr).addDateTimeElement("DATUM", date); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("GET_MBEW completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runSaveMaterialMoveMent(MaterialMovement materialMovement) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("SAVE_MBEW"); transaction.setInsertOnly(false); log.info("SAVE_MBEW (GUID= " + materialMovement.getGuid() + ", PERNR= " + materialMovement.getPersonalNumber() + ", MATNR= " + materialMovement.getMaterialNumber() + ", from= " + materialMovement.getFrom() + ", to= " + materialMovement.getTo() + ", ENTRY_QNT= " + materialMovement.getEntryCount() + ", ENTRY_UOM= " + materialMovement.getEntryUnit() + ", WEGRND= " + materialMovement.getReceiptOfGoods() + ", BARC= " + materialMovement.getBarcode() + ", BARCTXT= " + materialMovement.getBarcodeText() + ")"); try { dbutil.insertMaterialMovement(materialMovement); transaction.start(true).addQuery("ZKDMOBFZGMBEW", "SELECT " + DbConstants.MaterialMovement.GUID + ", " + DbConstants.MaterialMovement.PERSONAL_NUMBER + ", " + DbConstants.MaterialMovement.MATERIAL_NUMBER + ", " + DbConstants.MaterialMovement.FROM + ", " + DbConstants.MaterialMovement.TO + ", " + DbConstants.MaterialMovement.ENTRY_COUNT + ", " + DbConstants.MaterialMovement.ENTRY_UNIT + ", " + DbConstants.MaterialMovement.RECEIPT_OF_GOODS + ", " + DbConstants.MaterialMovement.BARCODE + ", " + DbConstants.MaterialMovement.BARCODE_TEXT + " FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + materialMovement.getGuid() + "'" + " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " = " + materialMovement.getPersonalNumber(), new ElementTemplate[] { Element.STRING(DbConstants.MaterialMovement.GUID), Element.INT(DbConstants.MaterialMovement.PERSONAL_NUMBER), Element.STRING(DbConstants.MaterialMovement.MATERIAL_NUMBER), Element.STRING(DbConstants.MaterialMovement.FROM), Element.STRING(DbConstants.MaterialMovement.TO), Element.STRING(DbConstants.MaterialMovement.ENTRY_COUNT), Element.STRING(DbConstants.MaterialMovement.ENTRY_UNIT), Element.STRING(DbConstants.MaterialMovement.RECEIPT_OF_GOODS), Element.STRING(DbConstants.MaterialMovement.BARCODE), Element.STRING(DbConstants.MaterialMovement.BARCODE_TEXT), }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("SAVE_MBEW queued"); //$NON-NLS-1$ } dbutil.deleteMaterialMovement(materialMovement); } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runConfirmMaterialMoveMent(MaterialMovement materialMovement) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("CONFIRM_MBEW"); transaction.setInsertOnly(false); log.info("CONF_MBEW (GUID= " + materialMovement.getGuid() + ", PERNR= " + materialMovement.getPersonalNumber() + ", EBELN= " + materialMovement.getOrderNumber() + ", EBELP= " + materialMovement.getOrderPosition() + ", ENTRY_QNT = " + materialMovement.getEntryCount() + ", ENTRY_UOM = " + materialMovement.getEntryUnit() + ")"); try { if (dbutil.selectMaterialMovement(materialMovement.getGuid()) != null) { dbutil.deleteMaterialMovement(materialMovement); } dbutil.insertMaterialMovement(materialMovement); transaction.start(true).addQuery("ZKDMOBFZGMBEW", "SELECT " + DbConstants.MaterialMovement.GUID + ", " + DbConstants.MaterialMovement.PERSONAL_NUMBER + ", " + DbConstants.MaterialMovement.ORDER_NUMBER + ", " + DbConstants.MaterialMovement.ORDER_POSITION + ", " + DbConstants.MaterialMovement.ENTRY_COUNT + ", " + DbConstants.MaterialMovement.ENTRY_UNIT + " FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + materialMovement.getGuid() + "'" + " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " = " + materialMovement.getPersonalNumber(), new ElementTemplate[] { Element.STRING(DbConstants.MaterialMovement.GUID), Element.INT(DbConstants.MaterialMovement.PERSONAL_NUMBER), Element.STRING(DbConstants.MaterialMovement.ORDER_NUMBER), Element.INT(DbConstants.MaterialMovement.ORDER_POSITION), Element.STRING(DbConstants.MaterialMovement.ENTRY_COUNT), Element.STRING(DbConstants.MaterialMovement.ENTRY_UNIT), }); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("CONF_MBEW queued"); //$NON-NLS-1$ } dbutil.deleteMaterialMovement(materialMovement); } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } public boolean runGetDeliveryList(int pernr, ProgressMonitor monitor) { ensureAMThread(); monitor.begin("run get Delivery list", 2); //$NON-NLS-1$ DBSession db = Runtime.getApplicationManager().getDBSession(); db.startTransaction(); try { // Transaktion ausf�hren RemoteTransactionHandler rth = new RemoteTransactionHandler(); monitor.comment(Messages.getString(("updatingDeliveryList"))); //$NON-NLS-1$ monitor.worked(1); dbutil.deleteAllDeliveryList(); if (rth.runGetDeliveryList(pernr)) { monitor.comment(Messages.getString(("deliveryListDownloaded"))); //$NON-NLS-1$ monitor.worked(1); // Records ohne REFRESHED Flag l�schen db.commit(); } } finally { // finally rollback if dbutil transaction is still pending if (db.isTransactionPending()) { db.rollback(); } } return true; } public boolean runGetDeliveryList(int pernr) { ensureAMThread(); boolean result = true; Transaction transaction = tr.getSynchronousTransaction("GET_DELVRY_LIST"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { log.info("runGetDeliveryList - PERNR /" + pernr + "/"); dbutil.updateRefreshFlag(); // Transaktion ausf�hren transaction.start(false).addElement("PERNR", pernr); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("GET_DELVRY_LIST completed successfully"); //$NON-NLS-1$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } /** * Runs the operation SYNC_ORDER in order to synchronize local orders with * centrally dispatched orders from the server. As a result, new orders are * retrieved, present orders updated (regarding order schedule) and no more * dispatched orders deleted. * * @param pernr the personal number of the order * @return */ public boolean runSyncOrder(int pernr) { ensureAMThread(); log.info("SYNC_ORDER: pernr " + pernr); Transaction transaction = tr.getSynchronousTransaction("SYNC_ORDER"); //$NON-NLS-1$ transaction.setInsertOnly(false); TableElement withdrawnOrders = null; // lokal vorhandene Auftr�ge festhalten um sp�ter neu hinzugekommene // erkennen zu k�nnen HashSet localOrders = new HashSet(); DBSession db = Runtime.getApplicationManager().getDBSession(); ZKDMOB zkdmob = new ZKDMOB(db); TableCursor cursor = ZKDMOB.queryByPrimaryKey(zkdmob); try { while (cursor.next()) { localOrders.add(zkdmob.getAUART() + zkdmob.getMLDNR()); } } finally { cursor.dispose(); } try { transaction.start(false).addElement("PERNR", pernr) //$NON-NLS-1$ .addQuery("ZKDMOB", //$NON-NLS-1$ "SELECT " + DbConstants.Job.JOB_NUMBER + //$NON-NLS-1$ ", " + DbConstants.Job.JOB_TYPE + //$NON-NLS-1$ ", " + DbConstants.Job.STATUS + //$NON-NLS-1$ ", " + DbConstants.Job.APPOINTMENT_DATE + //$NON-NLS-1$ " FROM " + DbConstants.Job.JOB, //$NON-NLS-1$ new ElementTemplate[] { Element.DATETIME(DbConstants.Job.APPOINTMENT_DATE) }) .requestResponseTableElement("ZKDMOB_DEL"); //$NON-NLS-1$ // commit the transaction Response response = transaction.commit(); if (transaction.getLastException() == null) { String msgType = response.getStringElement("MSGTYPE"); //$NON-NLS-1$ String msg = response.getStringElement("MSG"); //$NON-NLS-1$ if ("E".equalsIgnoreCase(msgType)) { //$NON-NLS-1$ // error log.info("SAP error message: " + msg); //$NON-NLS-1$ MessageUtil.getInstance().showMessage(Messages.getString("SAPErrorMessage") + msg); //$NON-NLS-1$ return false; } else { // success if (log.isDebugEnabled()) { log.debug("SYNC_ORDER completed successfully"); //$NON-NLS-1$ } // extract withdrawn orders for later processing withdrawnOrders = response.getTableElement("ZKDMOB_DEL"); } if (log.isDebugEnabled()) { log.debug("MSGTYPE /" + msgType + "/"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("MSG /" + msg + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { // error log.error("communication error: " + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); return false; } } catch (ApplicationException e) { log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); return false; } finally { // clean up transaction.dispose(); } // delete withdrawn orders in state 00, 01 and 02 without further feedback db.startTransaction(); try { for (int i = 0; i < (withdrawnOrders != null ? withdrawnOrders.getSize() : 0); i++) { withdrawnOrders.readRow(i); String jobNumber = withdrawnOrders.getStringElement(DbConstants.Job.JOB_NUMBER); String jobType = withdrawnOrders.getStringElement(DbConstants.Job.JOB_TYPE); log.info("Withdrawing job " + jobNumber + ", type " + jobType); DatabaseUtil dbUtil = DatabaseUtil.getInstance(); Job job = dbUtil.selectJobByJobIdAndJobType(jobNumber, jobType); // check stop date for deletability: still a new not yet in progress or somehow completed order? JobStatus jobState = job.getStatus(); if (!(jobState.isInitial() || jobState.isNew() || jobState.isReceived())) { log.info("... not changed due to current state: " + jobState.getCode()); continue; } // check report data if (job.hasReportedData(dbUtil)) { log.info("... not changed due to existing report data."); continue; } dbUtil.deleteJob(job); log.info("... deleted"); } db.commit(); } finally { if (db.isTransactionPending()) db.rollback(); } // post update state for newly received orders cursor = ZKDMOB.queryByPrimaryKey(zkdmob); try { while (cursor.next()) { String jobNumber = zkdmob.getMLDNR(); String jobType = zkdmob.getAUART(); // new order? if (localOrders.contains(jobType + jobNumber)) continue; // no // update_status log.info("Confirming new job " + jobNumber + ", type " + jobType); Job job = dbutil.selectJobByJobIdAndJobType(zkdmob.getMLDNR(), zkdmob.getAUART()); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } } finally { cursor.dispose(); } return true; } /** * Send presence state to SAP. * @param pernr Currently logged in user for which the presence state is reported. * @param arba The work type associated with the presence update (optional). * @param state The new presence state. * @return true if successfully, false otherwise. */ public boolean runUpdatePresence(int pernr, String arba, PresenceState state) { boolean result = true; Transaction transaction = tr.getAsynchronousTransaction("UPDATE_PRESENCE"); //$NON-NLS-1$ transaction.setInsertOnly(false); try { Request req = transaction.start(true); req.addElement("PERNR", pernr); req.addDateTimeElement("TIMESTAMP", new Date()); req.addElement("STATE", state.toString()); if (!StringUtil.isEmpty(arba)) req.addElement("ARBA", arba); // commit the transaction transaction.commit(); if (transaction.getLastException() == null) { // success if (log.isDebugEnabled()) { log.debug("update presence to remote server"); //$NON-NLS-1$ } } else { // error log.error(Messages.getString("communicationErrorWithColon") + transaction.getLastException().getMessage()); //$NON-NLS-1$ showCommunicationErrorMessage(transaction.getLastException().getMessage()); result = false; } } catch (ApplicationException e) { // error log.error("communication error: " + e); //$NON-NLS-1$ showCommunicationErrorMessage(e.getMessage()); result = false; } finally { // clean up transaction.dispose(); } return result; } }
package ch.mfiles.kaba.kolibri.common.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.net.PresenceState; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class TimeUtil { private static Log log = LogFactory.getLog(TimeUtil.class); private Application app; private DatabaseUtil dbutil; private static final String WARNING_MESSAGE = "warning"; //$NON-NLS-1$ private static final String OVERLAPPING_MESSAGE = "overlapping"; //$NON-NLS-1$ private Form form; Calendar latestTime; TimeUtilThread timeUtilThread; public TimeUtil(Application app, DatabaseUtil dbutil, Form form){ this.app = app; this.dbutil = dbutil; this.form = form; latestTime = Calendar.getInstance(); latestTime.set(latestTime.get(Calendar.YEAR), latestTime.get(Calendar.MONTH), latestTime.get(Calendar.DATE), 23, 59, 59); } /** * - Check if the current date is still the same date as of the other JobTimeSheet entries * - Check if the current date/time does not overlap with existing JobTimeSheet entries * - Adds a new JobTimeSheet (ZKDMOBRTIM) entry to the latest report of the current job * - Define new record as selected line in the table * - Changes the job status to "in arbeit" * @return true if time capturing was started successful, false otherwise */ public boolean startJobTimeCapturing(Job job) { Report report = job.getLatestReport(); Date now = DateTimeUtil.getTimestamp().getTime(); Date today = DateTimeUtil.getToday().getTime(); report.loadTimes(dbutil); List jobReportTimes = job.getLatestReport().getTimes(); // Creates a new JobTimeSheet (ZKDMOBRTIM) entry to the latest report of the current job JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReportGuId(dbutil)); newJobTime.setDate(today); newJobTime.setIdx(jobReportTimes.size()); newJobTime.setStartTime(now); newJobTime.setStopTime(DateUtils.getInitialDateTime()); //Setting ARBA correct: //MON: Default value "00 Bitte w�hlen" //REP (1-st entry): Default value "00 Bitte w�hlen" //REP (n-th entry): Same value as the already existing JobTimeSheets have //SAV (1-st entry): Default value "05 Vertragsservice" //SAV (n-th entry): Same value as the already existing JobTimeSheets have if (jobReportTimes.isEmpty()) newJobTime.setWorkTypeCode(job.getDefaultJobTimeARBA()); else newJobTime.setWorkTypeCode((jobReportTimes.get(0)).getWorkTypeCode()); TreeSet set = new TreeSet(); set.add((JobReportTime) newJobTime); for (int i = 0; i < jobReportTimes.size(); i++) { set.add((JobReportTime) jobReportTimes.get(i)); } Iterator itr = set.iterator(); int idx = 0; // number the timesheet entries consecutively in chronological order while (itr.hasNext()) { JobReportTime zkdmobrtim = itr.next(); zkdmobrtim.setIdx(idx++); Date zkdmobrtimDate = DateTimeUtil.getDate(zkdmobrtim.getDate()).getTime(); // Checks if the current date is still the same date as of the other JobTimeSheet entries if (!zkdmobrtimDate.equals(today)) { Object[] arguments = new Object[] { DateTimeUtil.tableDate(zkdmobrtim.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString("reportCannotContainTimesMoreThanOneDay"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } // Checks if the current date/time does not overlap with existing JobTimeSheet entries // Don't use compareTo() at this point, accuracy of time values is seconds (not minutes) if (!(now.before(zkdmobrtim.getStartTime()) || now.after(zkdmobrtim.getStopTime()))) { Object[] arguments = new Object[] { DateTimeUtil.showDateTime(zkdmobrtim.getStartTime()), DateTimeUtil.showDateTime(zkdmobrtim.getStopTime()) }; String errorMessage = MessageFormat.format(Messages.getString("newTimeEntryConfictsWithExistingOne"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } } if(timeUtilThread == null) { timeUtilThread = new TimeUtilThread(job); timeUtilThread.start(); } // Changes the job status to "in arbeit" job.setStatus(new JobStatus(JobStatus.IN_PROGRESS)); // Save the list of timesheet entries to the current report job.getLatestReport().setTimes(dbutil, new ArrayList(set)); dbutil.updateJob(job); return true; } /** * Starts time capturing in the time sheet of the current day *
- Load the CALENDAR Object of the current day *
- Check if time capturing is already running *
- Ask the user if time capturing should be started *
- Create a new ZKDMATIME object. Set default ARBA and current time *
- Save the CALENDAR object * @param app The currently running application (is needed for DB access) */ private boolean startWorkTimeCapturing(String arba, boolean pikett) { Date now = DateTimeUtil.getNow().getTime(); Date today = DateTimeUtil.getToday().getTime(); // Check for running work time capturing List capturingDays = dbutil.selectCalendarDateWithRunningTimeCapturing(dbutil.getUser().getPersonalNumber()); Date capturingDay; if (!capturingDays.isEmpty()) { // Error situation: at least 1 capturing time sheet found. If they belong // to an already sent CALENDAR, reopen it. So the user can enter missing // information and send it again List errorDates = new ArrayList(); Iterator itr = capturingDays.iterator(); while (itr.hasNext()) { capturingDay = itr.next(); CalendarTimeSheet calendar = dbutil.loadCalendar(capturingDay, dbutil.getUser().getPersonalNumber()); errorDates.add(calendar.getDateString()); if (calendar.getStatus().isSENT()) { calendar.setStatus(CalendarStatus.SAVED); dbutil.saveCALENDAR(calendar); } } // Don't show error message in the following situation: // - if exactly 1 capturing time sheet was found // - if the capturing time sheet is from today // - if the ServiceApplication is running if (!(capturingDays.size() == 1 && (capturingDays.get(0)).equals(today) && app.getApplicationDescriptor().getApplication().equals(CommonConstants.Application.SERVICE_APP))) { Object[] arguments = new Object[] { errorDates }; String errorMessage = MessageFormat.format(Messages.getString("foundErrorsInTimesheetsOnDate"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } else return true; } else { CalendarTimeSheet calendar = dbutil.loadCalendar(today, dbutil.getUser().getPersonalNumber()); if (!calendar.isTimeCapturing()) { if (calendar.getStatus().isSENT()) { showWarningMessageBox(Messages.getString("timesheetCannotBeStartet")); //$NON-NLS-1$ return false; } TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { TimeSheet zkdmatime = itr.next(); // Checks if the current date/time does not overlap with existing JobTimeSheet entries if (!(now.compareTo(zkdmatime.getStartTime()) <= 0 || now.compareTo(zkdmatime.getStopTime()) >= 0)) { Object[] arguments = new Object[] { DateTimeUtil.showDateTime(zkdmatime.getStartTime()), DateTimeUtil.showDateTime(zkdmatime.getStopTime()) }; String errorMessage = MessageFormat.format(Messages.getString("TimeIsOverlapping"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return false; } } // Adds a new JobTimeSheet (ZKDMATIME) entry to the latest report of the current job TimeSheet newTimeSheet = new TimeSheet(dbutil.getUser().getPersonalNumber()); log.info(DateTimeUtil.showDateTime(newTimeSheet.getDate())); newTimeSheet.setIdx(times.size()); newTimeSheet.setStartTime(now); newTimeSheet.setStopTime(new Date(0)); newTimeSheet.setWorkTypeCode(arba); newTimeSheet.setCallFlag(pikett); times.add(newTimeSheet); // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database dbutil.saveCALENDAR(calendar); new RemoteTransactionHandler().runUpdatePresence(dbutil.getUser().getPersonalNumber(), arba, PresenceState.PRESENT); if (dbutil.loadCalendar(today, dbutil.getUser().getPersonalNumber()).isTimeCapturing()) { app.inform(Messages.getString("workTimeCapturingStartet")); //$NON-NLS-1$ } } } return true; } public void stopTime(final Job job, final RunOnUIThread runOnUIThread) { new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { boolean result = stopJobTimeCapturing(job); if (result) { app.inform(Messages.getString("timeStopped")); //$NON-NLS-1$ if(timeUtilThread != null) { timeUtilThread.interrupt(); timeUtilThread = null; } if (job.getJobType().isMON()) { stopWorkTimeCapturing(); } } else { app.inform(Messages.getString("timeNotStopped")); //$NON-NLS-1$ } return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); runOnUIThread.runOnUIThread(); } }; } /** * - Loads the latest report and in the report time records. * - looks for the one time record without BIS time. * - checks if more than 3min passed since BIS time. If not, informs user and terminates without stopping time capturing * - checks if time capturing was started today. * @param app * @param dbutil * @param job * @return true if time was stopped successfully, false otherwise */ private boolean stopJobTimeCapturing(Job job) { Date timestamp = DateTimeUtil.getTimestamp().getTime(); Date bis = DateTimeUtil.getNow().getTime(); Date today = DateTimeUtil.getTodayEarlyMorning().getTime(); Date yesterday = DateTimeUtil.getYesterdayLateNight().getTime(); job.loadReports(dbutil); Report report = job.getLatestReport(); report.loadTimes(dbutil); JobReportTime jobReportTime = null; TreeSet times = new TreeSet(report.getTimes()); Iterator itr = times.iterator(); while (itr.hasNext()) { jobReportTime = itr.next(); if (jobReportTime.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) break; } if (jobReportTime != null) { // Check if a minimum of 3 minutes is recorded before stopping the time capturing if (!checkMinumumCapturingTime(jobReportTime.getStartTime())) return false; Date capturingDay = DateTimeUtil.getDate(jobReportTime.getStartTime()).getTime(); if (isToday(capturingDay)) { jobReportTime.setStopTime(bis); // check if there are no overlapping entries int selOverlappingRowIdx = checkJobTimesheetOverlapping(times); if (selOverlappingRowIdx > -1) { return false; } report.setTimes(dbutil, new ArrayList(times)); job.setStatus(JobStatus.RECEIVED); // check if job is partly done Report previousReport = null; if(job.getReports().size() >1) { previousReport = job.getReports().get(job.getReports().size()-1); if(previousReport.getReportStatus().isReceived() && previousReport.isPartialRepair()) { job.setStatus(JobStatus.PARLTY_DONE); } } dbutil.updateJob(job); return true; } else if (isYesterday(capturingDay)) { jobReportTime.setStopTime(yesterday); JobReportTime newZkdmobrtim = new JobReportTime(); newZkdmobrtim.setGuid(jobReportTime.getGuId()); newZkdmobrtim.setIdx(times.size()); newZkdmobrtim.setWorkTypeCode(jobReportTime.getWorkTypeCode()); newZkdmobrtim.setDate(timestamp); newZkdmobrtim.setStopTime(bis); newZkdmobrtim.setStartTime(today); times.add(newZkdmobrtim); // check if there are no overlapping entries int selOverlappingRowIdx = checkJobTimesheetOverlapping(times); if (selOverlappingRowIdx > -1) { return false; } report.setTimes(dbutil, new ArrayList(times)); job.setStatus(JobStatus.RECEIVED); dbutil.updateJob(job); return true; } else if (isOlderThan2Days(capturingDay)) { jobReportTime.setStopTime(DateTimeUtil.getLateNight(capturingDay).getTime()); // check if there are no overlapping entries int selOverlappingRowIdx = checkJobTimesheetOverlapping(times); if (selOverlappingRowIdx > -1) { return false; } report.setTimes(dbutil, new ArrayList(times)); job.setStatus(JobStatus.RECEIVED); dbutil.updateJob(job); return true; } else { log.error("Running report time sheet for a day in the future found: " + capturingDay.toString()); //$NON-NLS-1$ return false; } } else { log.info("No time sheet found to stop"); //$NON-NLS-1$ return false; } } private boolean stopWorkTimeCapturingOlderThan2Days(CalendarTimeSheet calendar) { Date stopCalendarDay = DateTimeUtil.getLateNight(calendar.getDate()).getTime(); showWarningMessageBox(Messages.getString("workTimeCapturingStartetBeforeYesterday")); //$NON-NLS-1$ TimeSheet timeSheet; TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { timeSheet = itr.next(); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { timeSheet.setStopTime(stopCalendarDay); } } if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database return dbutil.saveCALENDAR(calendar); } else return false; } /** * Stops time capturing in the time sheet of the current day *
- Load the CALENDAR Object of the day with the running time capturing *
- Check if time capturing is running *
- Ask the user if time capturing should be stopped *
- Search the running ZKDMATIME object and set current time to BIS *
- Check if time entries are not overlapping *
- Save the CALENDAR object * @param app The currently running application (is needed for DB access) * @return true if report time could be stopped successfully */ private boolean stopWorkTimeCapturing() { CalendarTimeSheet calendar; Date bis = DateTimeUtil.getNow().getTime(); List capturingDays = dbutil.selectCalendarDateWithRunningTimeCapturing(dbutil.getUser().getPersonalNumber()); Date capturingDay; if (capturingDays.isEmpty()) return false; else if (capturingDays.size() > 1) { // Error situation: more than 1 capturing time sheet found. If they belong // to an already sent CALENDAR, reopen it. So the user can enter missing // information and send it again ArrayList errorDates = new ArrayList(); Iterator itr = capturingDays.iterator(); while (itr.hasNext()) { capturingDay = itr.next(); calendar = dbutil.loadCalendar(capturingDay, dbutil.getUser().getPersonalNumber()); errorDates.add(calendar.getDateString()); if (calendar.getStatus().isSENT()) { calendar.setStatus(CalendarStatus.SAVED); dbutil.saveCALENDAR(calendar); } } Object[] arguments = new Object[] { errorDates }; String errorMessage = MessageFormat.format(Messages.getString("foundErrorsInTimesheetsOnDate"), arguments); //$NON-NLS-1$ showWarningMessageBox(errorMessage); return true; } else capturingDay = capturingDays.get(0); calendar = dbutil.loadCalendar(capturingDay, dbutil.getUser().getPersonalNumber()); if (calendar.isTimeCapturing() && (app.getApplicationDescriptor().getApplication().equals(CommonConstants.Application.TIMESHEET_APP) || app.showMessageBox(Messages.getString("doYouWantToStopTimesheet"), //$NON-NLS-1$ Messages.getString(WARNING_MESSAGE), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES)) { if (isToday(capturingDay)) return stopWorkTimeCapturingToday(calendar, bis) && updatePresenceToGone(); else if (isYesterday(capturingDay)) return stopWorkTimeCapturingYesterday(calendar, bis) && updatePresenceToGone(); else if (isOlderThan2Days(capturingDay)) return stopWorkTimeCapturingOlderThan2Days(calendar) && updatePresenceToGone(); else log.error("Running time sheet for a day in the future found: " + capturingDays.toString()); //$NON-NLS-1$ } return false; } private boolean stopWorkTimeCapturingYesterday(CalendarTimeSheet calendar, Date bis) { Date today = DateTimeUtil.getToday().getTime(); Date startToday = DateTimeUtil.getTodayEarlyMorning().getTime(); Date stopYesterday = DateTimeUtil.getYesterdayLateNight().getTime(); showWarningMessageBox(Messages.getString("WorkTimeRecordingWasStartedYesterday.")); //$NON-NLS-1$ TimeSheet timeSheet = new TimeSheet(dbutil.getUser().getPersonalNumber()); TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { timeSheet = itr.next(); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { timeSheet.setStopTime(stopYesterday); } } if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database if (!dbutil.saveCALENDAR(calendar)) return false; } else return false; calendar = dbutil.loadCalendar(today, dbutil.getUser().getPersonalNumber()); times = calendar.getTimeSheets(); TimeSheet timeSheetToday = new TimeSheet(dbutil.getUser().getPersonalNumber()); timeSheetToday.setIdx(calendar.getTimeSheets().size()); timeSheetToday.setWorkTypeCode(timeSheet.getWorkTypeCode()); timeSheetToday.setCostCenter(timeSheet.getCostCenter()); timeSheetToday.setCallFlag(timeSheet.isCallFlag()); timeSheetToday.setCommissionNumber(timeSheet.getCommissionNumber()); timeSheetToday.setStartTime(startToday); timeSheetToday.setStopTime(bis); times.add(timeSheetToday); if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database return dbutil.saveCALENDAR(calendar); } else return false; } private boolean stopWorkTimeCapturingToday(CalendarTimeSheet calendar, Date bis) { TimeSheet timeSheet; TreeSet times = calendar.getTimeSheets(); Iterator itr = times.iterator(); while (itr.hasNext()) { timeSheet = itr.next(); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { // Check if a minimum of 3 minutes is recorded before stopping the time capturing if (checkMinumumCapturingTime(timeSheet.getStartTime())) { calendar.setStatus(CalendarStatus.SAVED); timeSheet.setStopTime(bis); } else { return false; } } } if (checkWorkTimesheetOverlapping(times) == -1) { // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(times); // Save hole CALENDAR Object to the database return dbutil.saveCALENDAR(calendar); } else return false; } private static boolean isOlderThan2Days(Date capturingDay) { Date beforeYesterday = DateTimeUtil.getDayBeforeYesterday().getTime(); return (capturingDay.compareTo(beforeYesterday) <= 0); } private boolean updatePresenceToGone() { return new RemoteTransactionHandler().runUpdatePresence(dbutil.getUser().getPersonalNumber(), "", PresenceState.GONE); } private static boolean isYesterday(Date capturingDay) { Date yesterday = DateTimeUtil.getYesterday().getTime(); return (capturingDay.compareTo(yesterday) == 0); } private static boolean isToday(Date capturingDay) { Date today = DateTimeUtil.getToday().getTime(); return (capturingDay.compareTo(today) == 0); } /** * - Search for a running time capturing * - Check if the current date is still the same date as the running JobTimeSheet entry * - Same day: * 1. Terminate the running JobTimeSheet (ZKDMOBRTIM) entry with the current time * - Next day: * 1. Terminate the running JobTimeSheet (ZKDMOBRTIM) entry with 23:59 of yesterday * 2. Create an new JobTimeSheet (ZKDMOBRTIM) entry starting at 00:00 and ending at the current time * - Any other day: * 1. Inform the user * 2. Terminate the running JobTimeSheet (ZKDMOBRTIM) entry with 23:59 of the day the entry was started * - Check if the current date/time does not overlap with existing JobTimeSheet entries * - Changes the job status to "angenommen" */ private void stopJobTimeCapturing() { List openJobTimeList = dbutil.selectJobWithOpenTimesheet(); Iterator itr = openJobTimeList.iterator(); while (itr.hasNext()) { stopJobTimeCapturing(itr.next()); } } /** * @param set List with all time sheet entries to check. The elements in the list must be ordered chronological (sort attribute VON) * @return The index (IDX) of the overlapping time sheet entry or -1 if no problems are detected. */ public int checkWorkTimesheetOverlapping(SortedSet timeSheetList) { int resultIdx = -1; Date temp = DateUtils.getInitialDateTime(); Iterator itr = timeSheetList.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = itr.next(); if (temp.compareTo(timeSheet.getStartTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || timeSheet.getStartTime().equals(DateUtils.getInitialDateTime())) temp = timeSheet.getStartTime(); else { resultIdx = timeSheet.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(timeSheet.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } if (temp.compareTo(timeSheet.getStopTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) temp = timeSheet.getStopTime(); else { resultIdx = timeSheet.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(timeSheet.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } } return resultIdx; } /** * @param set List with all time sheet entries to check. The elements in the list must be ordered chronological (sort attribute VON) * @return The index (IDX) of the overlapping time sheet entry or -1 if no problems are detected. */ private int checkJobTimesheetOverlapping(SortedSet timesheetList) { int resultIdx = -1; Date temp = DateUtils.getInitialDateTime(); Iterator itr = timesheetList.iterator(); while (itr.hasNext()) { JobReportTime jobReportTime = itr.next(); if (temp.compareTo(jobReportTime.getStartTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || jobReportTime.getStartTime().equals(DateUtils.getInitialDateTime())) temp = DateTimeUtil.getTime(jobReportTime.getStartTime()).getTime(); else { resultIdx = jobReportTime.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(jobReportTime.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } if (temp.compareTo(jobReportTime.getStopTime()) <= 0 || temp.equals(DateUtils.getInitialDateTime()) || jobReportTime.getStopTime().equals(DateUtils.getInitialDateTime())) temp = jobReportTime.getStopTime(); else { resultIdx = jobReportTime.getIdx(); Object[] arguments = new Object[] { DateTimeUtil.showDateTime(temp), DateTimeUtil.showDateTime(jobReportTime.getStartTime()) }; String errorMessage = MessageFormat.format(Messages.getString(OVERLAPPING_MESSAGE), arguments); showWarningMessageBox(errorMessage); break; } } return resultIdx; } /** * @param startTime * @param app * @return true if difference between start- and stop time is bigger than 3 minutes or if user agrees on a difference smaller than 3 minutes. * false if user cancels warning. */ protected boolean checkMinumumCapturingTime(Date startTime) { boolean result = false; // Check if a minimum of 3 minutes is recorded before stopping the time capturing Date now = DateTimeUtil.getNow().getTime(); Calendar cal = DateTimeUtil.getTime(startTime); cal.add(Calendar.MINUTE, 3); if (cal.getTime().before(now)) { result = true; } else { if (app.showMessageBox(Messages.getString("StartEndLessThan3MinutesApart"), Messages.getString("warning"), Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { //$NON-NLS-1$ //$NON-NLS-2$ result = true; } } return result; } public void showWarningMessageBox(final String warningMessage){ app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { app.showMessageBox(warningMessage, Messages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } public void stopWorkTimeCapturing(final RunOnUIThread runOnUIThread) { new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if(stopWorkTimeCapturing()) { stopJobTimeCapturing(); } return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); runOnUIThread.runOnUIThread(); } }; } public void startWorkTimeCapturing(final String arba, final boolean pikett, final RunOnUIThread runOnUIThread) { startWorkTimeCapturing(arba, pikett, null, runOnUIThread); } public void startWorkTimeCapturing(final String arba, final boolean pikett, final Job job, final RunOnUIThread runOnUIThread) { new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (job != null) { new RemoteTransactionHandler().updateStatus(paramDBSession, job, JobStatus.IN_PROGRESS, JobStatus.SAP_InProgress, ""); //$NON-NLS-1$ } startWorkTimeCapturing(arba, pikett); return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); runOnUIThread.runOnUIThread(); } }; } public class TimeUtilThread extends Thread { Job job; public TimeUtilThread (Job job) { this.job = job; this.setName("TimeUtilThread"); } public void run() { log.info(this.getName() + " started."); long timeDiff = latestTime.getTimeInMillis() - Calendar.getInstance().getTimeInMillis(); while(Calendar.getInstance().getTimeInMillis() < latestTime.getTimeInMillis()){ log.info("sleep for " + DateTimeUtil.showTime(timeDiff) + " minutes."); try { Thread.sleep(timeDiff); } catch (InterruptedException e) { log.info("Stop waiting thread."); return; } } log.info(this.getName() + " very late at night."); job.getLatestReport().checkIfTimeStartOverOndDay(dbutil); new AsyncTask(form) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { app.getCurrentForm().onFormShow(); } }; } } }
plugins { id("ch.mfiles.kolibri-application") } tasks.named("processResources", Copy::class).configure { from("data") { this.into("data") } } sourceSets { test { java { srcDir("javatest") } } } repositories { mavenCentral() } // Create separate configuration for JUnit dependencies in order to put them 1st on the test compile/runtime classpath. // If we don't do this, the android.jar is placed before junit.jar which breaks JUnit tests with a // "RuntimeException Stub!" val junitConfiguration: Configuration by configurations.creating dependencies { junitConfiguration("junit:junit:4.12") junitConfiguration("commons-logging:commons-logging:1.2") testImplementation(junitConfiguration) } tasks.named("test", Test::class).configure { classpath = junitConfiguration + classpath } package ch.mfiles.kaba.kolibri.service.forms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The commission number form for job details. * * @author nop (27-02-2017) * * @see "[MIG-43] implement of "Falsche Kommissionsnummer"" */ public class JobDetailInfoCommissionNumberForm extends SuperForm{ private static Log log = LogFactory.getLog(JobDetailInfoCommissionNumberForm.class); protected Job job; private CommissionNumberLayout commissionNumberLayout; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArguments = (JobDetailFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, contentLinearLayout, true); //$NON-NLS-1$ commissionNumberLayout.getCommissionNumberText().setLabel(ServiceMessages.getString("correctCommissionNumber")); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("commNotCorrect")); //$NON-NLS-1$ commissionNumberLayout.setJobTypeAndFormat(job.getJobType(), app.dbutil.getUser().getCommunicationNumberFormat()); if (!job.getCommissionNumber().isEmpty()) { commissionNumberLayout.setText(job.getCommissionNumber()); } else { commissionNumberLayout.setText("0"); //$NON-NLS-1$ } return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job)); } @Override protected boolean isValid() { boolean result = true; if ("".equals(commissionNumberLayout.getCommissionNumber().trim())) { //$NON-NLS-1$ commissionNumberLayout.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ result = false; } else { result = commissionNumberLayout.getCommissionNumberText().isValid(); } return result; } @Override protected boolean onSave() { saveButton.setEnabled(false); new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { log.info("Comm no " + job.getCommissionNumber()); job.setCommissionNumber(commissionNumberLayout.getCommissionNumber()); log.info("New Comm no " + job.getCommissionNumber()); if(new RemoteTransactionHandler().runUpdateOrder(job, app.dbutil.getUser())) { job = app.dbutil.selectJobByJobIdAndJobType(job.getJobNumber(), job.getJobType().toString()); job.loadReports(app.dbutil); return onBackPressed(); } return null; } }; return true; } @Override public void onFormReset() { super.onFormReset(); commissionNumberLayout.clear(); saveButton.setEnabled(true); } @Override protected void clearErrorMessages() { super.clearErrorMessages(); commissionNumberLayout.clearError(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Billing; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDCheckBox; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportMaterialListForm.ReportMaterialListFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ReportMaterialNewEditForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(ReportMaterialNewEditForm.class); public static ServiceApplication app; // don't make this CommonApplication private Job job; private ReportMaterial part; private boolean isKMaterial; private MDEditText priceEditText; private MDSpinner billingeTypeValue; private AmountEditText amountEditText; private MDSpinner unitValueText; private MDEditText sizeEditText; public MDEditText barcodeEditText; private MDCheckBox otherTypeCheckBox; private MDCheckBox expressCheckBox; private MDEditText explanation; private TextView explanationLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; public Button deleteButton; private Material selectedMaterial = null; private MaterialPerson selectedMaterialPerson = null; @Override public void onFormCall(Object argument) { if (argument instanceof ReportMaterialNewEditFormArguments) { ReportMaterialNewEditFormArguments formArguments = (ReportMaterialNewEditFormArguments) argument; job = formArguments.getJob(); part = formArguments.getPart(); isKMaterial = formArguments.isK14; barcode = formArguments.getBarcode(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); saveButton.setVisible(false); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } else { loadMaterialsList(numberEditText.getText().toString()); if(selectedMaterial != null || selectedMaterialPerson != null) { // hideSoftInputFromWindow(); } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); } else { nameEditText.clearError(); } } }); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout detailItemLinearLayout = new LinearLayout(context); detailItemLinearLayout.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); priceEditText = MDEditText.createDefaultEditText(detailItemLinearLayout, ServiceMessages.getString("price"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ priceEditText.setTag("PRICE"); //$NON-NLS-1$ priceEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.ELEVEN) }); priceEditText.setEnabled(false); priceEditText.setDirectionRight(false); priceEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { priceEditText.setText(getPrice()); } else { String userInput = priceEditText.getText().toString(); // if (userInput.startsWith(CommonConstants.TimeSheet.EXPENSES_PREFIX)) { // userInput = userInput.replaceAll(CommonConstants.TimeSheet.EXPENSES_PREFIX, ""); // } // String temps[] = userInput.split(" "); // if (temps.length > 1 && !TextUtils.isEmpty(temps[1])) { // userInput = temps[1]; // } priceEditText.setTextAndSelection(userInput); } } }); LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); priceInputLayoutParams.gravity = Gravity.CENTER; priceInputLayoutParams.width = 0; priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; priceInputLayoutParams.weight = 0.3f; priceEditText.getParentTextInputLayout().setLayoutParams(priceInputLayoutParams); final LinearLayout billingLinearLayout = new LinearLayout(context); billingLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams billingValueParams = new LinearLayout.LayoutParams(0, 0); billingValueParams.gravity = Gravity.CENTER | Gravity.LEFT; billingValueParams.width = 0; billingValueParams.height = LayoutParams.MATCH_PARENT; billingValueParams.weight = 0.7f; billingLinearLayout.setLayoutParams(billingValueParams); billingeTypeValue = MDSpinner.createDefaultSpinner(billingLinearLayout, Messages.getString("billing"), true); //$NON-NLS-1$ billingeTypeValue.setTag("BILLING"); //$NON-NLS-1$ billingeTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (part != null && selectedMaterial == null) { selectedMaterial = app.dbutil.selectMaterialByMatNo(part.getSparePartNumber()); } setPrice(); } }); detailItemLinearLayout.addView(billingLinearLayout); contentLinearLayout.addView(detailItemLinearLayout); LinearLayout stockItemLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); stockItemLinearLayout.setOrientation(LinearLayout.HORIZONTAL); amountEditText = AmountEditText.createDefaultEditText(stockItemLinearLayout, ServiceMessages.getString("amount"), true); //$NON-NLS-1$ LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.CENTER; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); // Unit final LinearLayout mUnitValueLinearLayout = new LinearLayout(context); mUnitValueLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams mUnitValueParams = new LinearLayout.LayoutParams(0, 0); mUnitValueParams.gravity = Gravity.LEFT; mUnitValueParams.width = 0; mUnitValueParams.height = LayoutParams.MATCH_PARENT; mUnitValueParams.weight = 0.3f; mUnitValueLinearLayout.setLayoutParams(mUnitValueParams); unitValueText = MDSpinner.createDefaultSpinner(mUnitValueLinearLayout, ServiceMessages.getString("unit"), false); //$NON-NLS-1$ unitValueText.setTag("UNIT"); //$NON-NLS-1$ unitValueText.setEnabled(false); LinearLayout.LayoutParams unitValueUnderlineLinearLayout = (LinearLayout.LayoutParams) billingeTypeValue.getUnderline().getLayoutParams(); unitValueUnderlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); unitValueText.getUnderline().setLayoutParams(unitValueUnderlineLinearLayout); unitValueText.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { unitValueText.clearError(); if (isKMaterial) { numberEditText.setInputType(InputType.TYPE_CLASS_TEXT); numberEditText.removeTextChangedListener(materialNumberMaskWatcher); numberEditText.setText(getKmaterialNumberByUnit(unitValueText.getSelectedId())); } else { numberEditText.setInputType(InputType.TYPE_CLASS_PHONE); numberEditText.addTextChangedListener(materialNumberMaskWatcher); } } }); stockItemLinearLayout.addView(mUnitValueLinearLayout); sizeEditText = MDEditText.createDefaultEditText(stockItemLinearLayout, Messages.getString("Containersize"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ sizeEditText.setTag("SIZE"); //$NON-NLS-1$ sizeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); sizeEditText.setEnabled(false); LinearLayout.LayoutParams sizeInputLayoutParams = new LinearLayout.LayoutParams(0, 0); sizeInputLayoutParams.gravity = Gravity.LEFT; sizeInputLayoutParams.width = 0; sizeInputLayoutParams.height = LayoutParams.MATCH_PARENT; sizeInputLayoutParams.weight = 0.3f; sizeEditText.getParentTextInputLayout().setLayoutParams(sizeInputLayoutParams); contentLinearLayout.addView(stockItemLinearLayout); LinearLayout barcodeLinearLayout = new LinearLayout(context); barcodeLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams barcodeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLinearLayoutParams.gravity = Gravity.CENTER; barcodeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.weight = 1; barcodeLinearLayout.setLayoutParams(barcodeLinearLayoutParams); barcodeEditText = MDEditText.createDefaultEditText(barcodeLinearLayout, ServiceMessages.getString("GuaranteeMaterial"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ barcodeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); // LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); // priceInputLayoutParams.gravity = Gravity.CENTER; // priceInputLayoutParams.width = 0; // priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; // priceInputLayoutParams.weight = 0.3f; LinearLayout.LayoutParams barcodeLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLayoutParams.gravity = Gravity.CENTER; barcodeLayoutParams.width = 0; barcodeLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLayoutParams.weight = 0.9f; barcodeEditText.getParentTextInputLayout().setLayoutParams(barcodeLayoutParams); barcodeEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (s.toString().isEmpty() && explanation.isRequired()) { explanation.setRequired(false); explanation.clearError(); } if (!s.toString().isEmpty() && !explanation.isRequired()) { explanation.setRequired(true); } } }); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.1f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { private String barcode = ""; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { if (!barcode.isEmpty()) { barcodeEditText.setInputType(InputType.TYPE_CLASS_TEXT); barcodeEditText.setText(barcode); barcodeEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } } }; } }); cameraLinearLayout.addView(gridImageView); barcodeLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(barcodeLinearLayout); explanation = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("explanationForReturn"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ explanation.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); explanation.setSingleLine(false); explanation.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { explanationLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); explanationLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; explanationLengthView.setLayoutParams(messageLengthViewParams); explanationLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(explanationLengthView); LinearLayout expressOtherTypeLinearLayout = new LinearLayout(context); expressOtherTypeLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams expressOtherTypeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); expressOtherTypeLinearLayoutParams.gravity = Gravity.CENTER; expressOtherTypeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; expressOtherTypeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; expressOtherTypeLinearLayoutParams.weight = 0.5f; expressOtherTypeLinearLayout.setLayoutParams(expressOtherTypeLinearLayoutParams); LinearLayout.LayoutParams otherTypeCheckBoxLayoutParams = new LinearLayout.LayoutParams(0, 0); otherTypeCheckBoxLayoutParams.gravity = Gravity.CENTER; otherTypeCheckBoxLayoutParams.width = 0; otherTypeCheckBoxLayoutParams.height = LayoutParams.MATCH_PARENT; otherTypeCheckBoxLayoutParams.weight = 0.5f; otherTypeCheckBox = MDCheckBox.createDefaultCheckBox(expressOtherTypeLinearLayout, ServiceMessages.getString("otherTypeOfMaterial")); //$NON-NLS-1$ ((LinearLayout) otherTypeCheckBox.getParent()).setLayoutParams(otherTypeCheckBoxLayoutParams); LinearLayout.LayoutParams expressCheckBoxLayoutParams = new LinearLayout.LayoutParams(0, 0); expressCheckBoxLayoutParams.gravity = Gravity.CENTER; expressCheckBoxLayoutParams.width = 0; expressCheckBoxLayoutParams.height = LayoutParams.MATCH_PARENT; expressCheckBoxLayoutParams.weight = 0.5f; expressCheckBox = MDCheckBox.createDefaultCheckBox(expressOtherTypeLinearLayout, ServiceMessages.getString("additionalDelivery")); //$NON-NLS-1$ ((LinearLayout) expressCheckBox.getParent()).setLayoutParams(expressCheckBoxLayoutParams); contentLinearLayout.addView(expressOtherTypeLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(Messages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (part == null) { resetView(); return; } appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { DatabaseUtil.getInstance().deleteReportMaterial(part); List listParts = DatabaseUtil.getInstance().selectReportMaterialList(job.getCurrentReportGuId(DatabaseUtil.getInstance())); for (int i = 0; i < listParts.size(); i++) { DatabaseUtil.getInstance().updateReportMaterialIdx(listParts.get(i), i); } } finally { db.commit(); } return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } }, false); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); addContentLinearLayout(contentLinearLayout); return view; } private String getPrice(){ String userInput = priceEditText.getText().toString(); String temp = StringUtil.removeLettersAndCountDot(userInput, '.'); if (temp.isEmpty()) { return ""; } try { Locale locale = Locale.ENGLISH; if (temp.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(temp))); if (floatValue > 499.99) { floatValue = (float) 499.99; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("##0.00", symbols); format.setMaximumFractionDigits(2); if (floatValue > 0) { temp = format.format(floatValue); userInput = temp; } else { userInput = ""; } } catch (NumberFormatException e) { return ""; } catch (ParseException e) { return ""; } return userInput; } @Override protected void loadData() { super.loadData(); fillBillingTypeCombo(); fillUnitCombo(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); if (part == null) { resetView(); deleteButton.setText(ServiceMessages.getString("clear")); //$NON-NLS-1$ searchView.setVisibility(View.VISIBLE); } else { nameEditText.setText(part.getProductName()); numberEditText.setText(part.getSparePartNumber()); priceEditText.setText(part.getPrice()); // format with CHF priceEditText.setText(getPrice()); billingeTypeValue.setSelectionById(part.getAccountCode()); amountEditText.setText(part.getAmount()); //$NON-NLS-1$ //$NON-NLS-2$ barcodeEditText.setText(part.getBarcode()); unitValueText.setSelectionById(part.getUnit()); expressCheckBox.setChecked(part.isDelivery()); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ barcodeEditText.setText(part.getBarcode()); explanation.setText(part.getExplanationText()); otherTypeCheckBox.setChecked(part.isOtherType()); searchView.setVisibility(View.INVISIBLE); } if (isKMaterial) { priceEditText.setRequired(true); unitValueText.setRequired(true); numberEditText.setRequired(false); numberEditText.setEnabled(false); priceEditText.setEnabled(true); unitValueText.setEnabled(true); String value = ServiceConstants.KMaterialNumber.K_14; if (part != null && !part.getUnit().isEmpty()) { value =part.getUnit(); } unitValueText.setSelectionById(value); expressCheckBox.setEnabled(false); } else { priceEditText.setRequired(false); unitValueText.setRequired(false); numberEditText.setRequired(true); numberEditText.setEnabled(true); priceEditText.setEnabled(false); unitValueText.setEnabled(false); expressCheckBox.setEnabled(true); } System.out.println("loadData barcode " + barcode); } @Override public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(queryText, queryText); List materialPersonList = app.dbutil.selectMaterialPersonListByMatNoAndMatName(queryText, queryText); for (Material matPart : materialList) { searchView.getSuggessionItemList().add(new SuggessionItem(matPart.getMaterialNumber(), matPart.getMaterialShortText())); } for (MaterialPerson zkdmobmatpers : materialPersonList) { searchView.getSuggessionItemList().add(new SuggessionItem(zkdmobmatpers.getMaterialNumber(), zkdmobmatpers.getMaterialShortText())); } int matHits = materialList.size() + materialPersonList.size(); if (matHits > 0 && matHits == 1) { // Exactly found an article from the StammMat if (materialList.size() == 1) { selectedMaterial = materialList.get(0); } else if (materialPersonList.size() == 1) { // Exactly found an article from PersMat selectedMaterialPerson = materialPersonList.get(0); } } if (selectedMaterial != null) { unitValueText.setSelectionById(selectedMaterial.getUnit().toUpperCase()); setPrice(); amountEditText.getText().clear(); barcodeEditText.getText().clear(); expressCheckBox.setChecked(false); } else if (selectedMaterialPerson != null) { amountEditText.getText().clear(); barcodeEditText.getText().clear(); sizeEditText.getText().clear(); unitValueText.setSelection(0); expressCheckBox.setChecked(false); explanation.getText().clear(); } if (isKMaterial) { numberEditText.setText(getKmaterialNumberByUnit(unitValueText.getSelectedId())); } } private void fillBillingTypeCombo() { List billingValueList = new ArrayList(); List billings = app.dbutil.selectBillingTypeListByJobType(job.getJobType()); for (Billing billing : billings) { log.info("VRCD (id) " + billing.getCode() + " Text " + billing.getText()); billingValueList.add(new CustomSpinnerItem((String) billing.getCode(), billing.getText())); } billingeTypeValue.setContents(billingValueList); } private void fillUnitCombo() { List unitValueList = new ArrayList(); unitValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, Messages.getString("pleaseSelect"))); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.M, ServiceConstants.MatUnit.M)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.MM, ServiceConstants.MatUnit.MM)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.KG, ServiceConstants.MatUnit.KG)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.ST, ServiceConstants.MatUnit.ST)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueText.setContents(unitValueList); } @Override protected void resetView() { super.resetView(); priceEditText.clearError(); amountEditText.clearError(); barcodeEditText.clearError(); sizeEditText.clearError(); selectedMaterial = null; selectedMaterialPerson = null; priceEditText.getText().clear(); billingeTypeValue.setSelection(0); billingeTypeValue.clearError(); amountEditText.getText().clear(); barcodeEditText.getText().clear(); sizeEditText.getText().clear(); unitValueText.setSelection(0); unitValueText.clearError(); expressCheckBox.setChecked(false); explanation.getText().clear(); explanation.clearError(); otherTypeCheckBox.setChecked(false); } @Override public ApplicationEvent onBackPressed() { if (isKMaterial) { if (nameEditText.getText().toString().isEmpty()) { return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } } else { if (nameEditText.getText().toString().isEmpty() && numberEditText.getText().toString().isEmpty()) { return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } } new AsyncTask(this) { private List editErrorList = new ArrayList(); private List spinnerErrorList = new ArrayList(); private List checkBoxErrorList = new ArrayList(); @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { editErrorList.clear(); spinnerErrorList.clear(); checkBoxErrorList.clear(); if (nameEditText.getText().toString().isEmpty()) { editErrorList.add(nameEditText); } if (amountEditText.isRequired() && amountEditText.getText().toString().isEmpty()) { editErrorList.add(amountEditText); } if (isKMaterial) { if (priceEditText.getText().toString().isEmpty()) { editErrorList.add(priceEditText); } if (unitValueText.getSelectedItemPosition() == 0) { spinnerErrorList.add(unitValueText); } } else { if (numberEditText.getText().toString().isEmpty()) { editErrorList.add(numberEditText); } } if (explanation.isRequired() && explanation.getText().toString().isEmpty()) { editErrorList.add(explanation); } return null; } @Override public void runOnUIThread() { priceEditText.clearFocus(); amountEditText.clearFocus(); sizeEditText.clearFocus(); barcodeEditText.clearFocus(); numberEditText.clearError(); nameEditText.clearError(); amountEditText.clearError(); sizeEditText.clearError(); priceEditText.clearError(); barcodeEditText.clearError(); explanation.clearError(); // Create a new, empty report object and save it to the database if (job.getLatestReport().getReportStatus().isReceived()) { DatabaseUtil.getInstance().insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(DatabaseUtil.getInstance()), job.getNextReportIdx(DatabaseUtil.getInstance()), job.isCycleOfInstallationFlag())); job.loadReports(DatabaseUtil.getInstance()); } if (editErrorList.isEmpty() && spinnerErrorList.isEmpty() && checkBoxErrorList.isEmpty()) { if ((part == null) && (selectedMaterial == null) && (selectedMaterialPerson == null) && !isKMaterial) { if (addMaterialPerson()) { insertUpdateMaterial(); } } else { insertUpdateMaterial(); } } else { if (!editErrorList.isEmpty()) { for (MDEditText errorText : editErrorList) { errorText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ } } if (!spinnerErrorList.isEmpty()) { for (MDSpinner spinner : spinnerErrorList) { spinner.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } if (!checkBoxErrorList.isEmpty()) { for (MDCheckBox checkBox : checkBoxErrorList) { checkBox.setError(ServiceMessages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } } } }; return null; } private void insertUpdateMaterial() { insertUpdateSpareParts(); app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } }, false); } private boolean addMaterialPerson() { // Mat: sum of the articles from the excise and the pers. // Mat table (exact match of article number necessary!) loadMaterialsList(nameEditText.getText().toString()); String materialName = ""; if (selectedMaterial != null) { materialName = selectedMaterial.getMaterialShortText(); } else if (selectedMaterialPerson != null) { materialName = selectedMaterialPerson.getMaterialShortText(); } if (!materialName.isEmpty() && materialName.equalsIgnoreCase(numberEditText.getText().toString())) { MessageUtil.getInstance().showMessage(ServiceMessages.getString("materialWithThisNameAlreadyExists")); return false; } loadMaterialsList(numberEditText.getText().toString()); if(!numberEditText.getText().toString().isEmpty() && !nameEditText.getText().toString().isEmpty()) { String materialNumber = ""; if (selectedMaterial != null) { materialNumber = selectedMaterial.getMaterialNumber(); } else if (selectedMaterialPerson != null) { materialNumber = selectedMaterialPerson.getMaterialNumber(); } if (!materialNumber.isEmpty() && materialNumber.equalsIgnoreCase(numberEditText.getText().toString())) { MessageUtil.getInstance().showMessage(ServiceMessages.getString("materialWithThisNumberAlreadyExists")); return false; } } if (!isKMaterial) { // Article does not yet exist and can be used as Pers. Mat Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { app.showMessageBox(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ return null; } @Override public void runOnUIThread() { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } }; return false; } } selectedMaterialPerson = new MaterialPerson(); selectedMaterialPerson.setMaterialNumber(numberEditText.getText().toString()); selectedMaterialPerson.setMaterialShortText(nameEditText.getText().toString()); app.dbutil.insertMaterialPerson(selectedMaterialPerson); return true; } private void insertUpdateSpareParts() { ReportMaterial reportMaterial = new ReportMaterial(); boolean newReportMaterial = part == null; if (part != null) { reportMaterial = part; } else { reportMaterial.setGuid(job.getLatestReport().getGuId()); reportMaterial.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); reportMaterial.setCommissionNumber(job.getCommissionNumber()); reportMaterial.setExpressDelivery(""); //$NON-NLS-1$ } reportMaterial.setAmount(amountEditText.getText().toString()); reportMaterial.setDelivery(expressCheckBox.isChecked()); reportMaterial.setAccountCode(billingeTypeValue.getSelectedId()); reportMaterial.setProductName(nameEditText.getText().toString()); reportMaterial.setSparePartNumber(numberEditText.getText().toString()); reportMaterial.setUnit(unitValueText.getSelectedItemPosition() == 0 ? "" : unitValueText.getSelectedId()); reportMaterial.setBarcode(barcodeEditText.getText().toString()); reportMaterial.setExplanationText(explanation.getText().toString()); reportMaterial.setOtherType(otherTypeCheckBox.isChecked()); reportMaterial.setK14(isKMaterial); reportMaterial.setPrice(isKMaterial ? getPrice().replace("0.0", "") : ""); if (newReportMaterial) { app.dbutil.insertNewReportMaterial(reportMaterial); } else { app.dbutil.updateReportMaterial(reportMaterial); } } public static class ReportMaterialNewEditFormArguments { private Job job; private ReportMaterial part; private boolean isK14; private String barcode; public ReportMaterialNewEditFormArguments(Job job, ReportMaterial part, boolean isK14, String barcode) { this.job = job; this.part = part; this.isK14 = isK14; this.barcode = barcode; } public Job getJob() { return job; } public ReportMaterial getPart() { return part; } public boolean isK14() { return isK14; } public String getBarcode() { return barcode; } } private String getKmaterialNumberByUnit(String unit) { if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.M)) { return ServiceConstants.KMaterialNumber.K_11; } else if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.MM)) { return ServiceConstants.KMaterialNumber.K_12; } else if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.KG)) { return ServiceConstants.KMaterialNumber.K_13; } else if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.ST)) { return ServiceConstants.KMaterialNumber.K_14; } else { return ServiceConstants.KMaterialNumber.K_Material; } } private void setPrice() { if (selectedMaterial != null) { log.info("billing " + billingeTypeValue.getSelectedId() + " " + billingeTypeValue.getSelectedName()); log.info("new price " + selectedMaterial.getNewPrice()); log.info("Substitute Price " + selectedMaterial.getSubstitutePrice()); if (billingeTypeValue.getSelectedId().equalsIgnoreCase(ServiceConstants.MATERIAL_BILLING_NEW_PRICE)) { priceEditText.setText(selectedMaterial.getNewPrice()); } else { priceEditText.setText(selectedMaterial.getSubstitutePrice()); } priceEditText.setText(getPrice()); } } } package ch.mfiles.kaba.kolibri.service.forms; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.SignatureUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.ui.SignatureView; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.LayoutHelper; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (05-06-2017) * * @see "[MIG-41 GUI] report signature / view" */ public class SignatureForm extends SuperForm { private static Log log = LogFactory.getLog(SignatureForm.class); private List jobList; private boolean isCollectiveSignature; private SignatureView signatureView; private Integer signatureSelected = null; List signatureValues = new ArrayList(); List signatureKeys = new ArrayList(); private MDEditText name; private TextView nameLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; private CardView signatureCard = null; private CardView messageCard = null; protected Context context; @Override public void onFormCall(Object argument) { if (argument instanceof Arguments) { Arguments formArguments = (Arguments) argument; jobList = formArguments.getJobList(); isCollectiveSignature = formArguments.isCollectiveSignature(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); setScreenOrientation(ScreenOrientation.PORTRAIT); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return appman.getActiveApplication().closeForm(); } }, false); } }); // create report view action ActionCtrl reportViewAction = addActionCtrl(false, false, 1, "reportViewAction"); //$NON-NLS-1$ reportViewAction.setTitle(ServiceMessages.getString("reportView")); //$NON-NLS-1$ reportViewAction.setImage(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.PAGE_VIEW_WHITE, CommonConstants.Images.IMAGE_DPI))); // create no signature action ActionCtrl noSignatureAction = addActionCtrl(false, false, 1, "noSignatureAction"); //$NON-NLS-1$ noSignatureAction.setTitle(ServiceMessages.getString("noSignature")); //$NON-NLS-1$ noSignatureAction.setImage(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_DPI))); // create delete action ActionCtrl deleteAction = addActionCtrl(false, false, 1, "deleteAction"); //$NON-NLS-1$ deleteAction.setTitle(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); relativeLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); LinearLayout cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); cardLinearLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); int height = LayoutParams.MATCH_PARENT; if (LayoutHelper.getDisplayMetrics().widthPixels > SignatureUtil.TARGET_WIDTH) { height = (int) (LayoutHelper.getDisplayMetrics().widthPixels * SignatureUtil.ASPECT_RATIO); } signatureView = new SignatureView(context); signatureCard = createCard(context, signatureView, height); ((LayoutParams) signatureCard.getLayoutParams()).bottomMargin = 30; cardLinearLayout.addView(signatureCard); messageCard = createNameCard(context); cardLinearLayout.addView(messageCard); CardView cardView = new CardView(context); RelativeLayout.LayoutParams cardViewParams = new RelativeLayout.LayoutParams(0, 0); cardViewParams.width = LayoutParams.MATCH_PARENT; cardViewParams.height = LayoutParams.WRAP_CONTENT; cardViewParams.addRule(RelativeLayout.CENTER_IN_PARENT); cardViewParams.setMargins(0, 0, 0, 0); cardView.setLayoutParams(cardViewParams); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.addView(cardLinearLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); cardView.addView(linearLayout); relativeLayout.addView(cardView); view.addView(relativeLayout); return view; } private CardView createNameCard(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); name = MDEditText.createDefaultEditText(contentLinearLayout, "Name", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ name.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); name.setSingleLine(false); name.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { if (name.isRequired() && name.getError() != null) { name.clearError(); } nameLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); nameLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams nameLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); nameLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; nameLengthView.setLayoutParams(nameLengthViewParams); nameLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(nameLengthView); return createCard(context, contentLinearLayout); } private static CardView createCard(Context context, View view, int height) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardViewParams.setMargins(0, 0, 0, 0); cardViewParams.width = LayoutParams.MATCH_PARENT; if (height > 0) { cardViewParams.height = height; } cardView.setLayoutParams(cardViewParams); cardView.setPadding(0, 0, 0, 30); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(view); cardView.addView(linearLayout); return cardView; } private static CardView createCard(Context context, View view) { return createCard(context, view, 0); } private String getName() { return name.getText().toString(); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(Messages.getString("signature")); //$NON-NLS-1$ name.setText(""); name.clearFocus(); name.clearError(); name.setEnabled(true); if (!jobList.isEmpty()) { name.setRequired(jobList.get(0).getJobType().isMON()); } if(isCollectiveSignature) { app.showMessage(MessageFormat.format(ServiceMessages.getString("YouAreSingingNReport"), new Object[] { jobList.size()})); } loadSignature(); return null; } @Override public ApplicationEvent onBackPressed() { return appman.getActiveApplication().closeForm(); } private void loadSignature() { // integrity of selected reports means all reports have got the same (or // no) signature. // --> it doesn't matter which of the pictures is shown. if (checkSelectionIntegrity()) { Report report = jobList.get(0).getLatestReport(); if (report.isSignatureFlag() && !report.isSignatureInfo() && StringUtil.isNotEmpty(report.getSignature())) { // Load file name an generate path for the signature file String imageName = report.getSignature(); String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, imageName, false); name.setEnabled(true); name.setText(report.getSignatureName()); if (log.isDebugEnabled()) log.debug("Load signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ try { signatureView.load(SignatureUtil.getOriginalSignatureFileName(imagePath)); signatureView.lock(); name.setEnabled(false); } catch (IOException e) { log.error("Found IOException:", e); //$NON-NLS-1$ app.showMessageBox(ServiceMessages.getString("signatureCanNotBeLoadedFromFile"), //$NON-NLS-1$ ServiceMessages.getString("error"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_ERROR); } } else { signatureView.clear(); } } else { signatureView.clear(); } } protected ApplicationEvent reportViewAction() { return app.callForm(ReportSummaryForm.class, new Arguments(jobList, false)); } protected ApplicationEvent noSignatureAction() { signatureValues.clear(); signatureKeys.clear(); Iterator> itr = app.enumUtil.noSignatureReasonEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); signatureValues.add((String) entry.getValue()); signatureKeys.add((String) entry.getKey()); } signatureSelected = 0; MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("noSignature"), //$NON-NLS-1$ ServiceMessages.getString("cancel")); //$NON-NLS-1$ // CustomArrayAdapter customArrayAdapter = new // CustomArrayAdapter(context, // android.support.v7.appcompat.R.layout.select_dialog_singlechoice_material, // signatureValues); alertDialog.setSingleChoiceItems(signatureValues.toArray(new String[0]), signatureSelected, new OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { signatureSelected = which; } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new OnClickListener() { //$NON-NLS-1$ @Override public void onClick(android.content.DialogInterface dialog, int which) { if (signatureSelected > 0) { saveSignInfo(); dialog.dismiss(); } } }); alertDialog.show(); return null; } private void saveSignInfo() { // If more than one report is signed, get the GUID of the master report // (-> 1st in the list) and save it as sign-GUID String signGuid = ""; //$NON-NLS-1$ if (jobList.size() > 1) { signGuid = jobList.get(0).getLatestReport().getGuId(); } // Update current report of all selected jobs Iterator itr = jobList.iterator(); while (itr.hasNext()) { Report report = itr.next().getLatestReport(); app.deleteSignatureFile(report.getSignature()); updateSignatureAttributes(report, signGuid, true, signatureValues.get(signatureSelected), "", getName()); //$NON-NLS-1$ signatureView.clear(); } app.showMessage(ServiceMessages.getString("noSignatureReasonSaved")); //$NON-NLS-1$ } protected ApplicationEvent deleteAction() { new AsyncTask(this) { private boolean isDelete; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (signatureView == null) { return null; } if (signatureView.isDirty() || signatureView.isLocked()) { // inform user he's going to delete the signature for more than // one report (from requirement mail 17.4.2012) if (isCollectiveSignature) { Object[] arguments = new Object[] { String.valueOf(jobList.size()) }; String warningMsg = MessageFormat .format(ServiceMessages.getString("signatureBelongsToJobsDoYouWanToDeleteIt"), arguments); //$NON-NLS-1$ if (app.showMessageBox(warningMsg, ServiceMessages.getString("collectiveSignature"), //$NON-NLS-1$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) isDelete = true; } else { if (app.showMessageBox(ServiceMessages.getString("doYouWantToDeleteThisSignature"), //$NON-NLS-1$ ServiceMessages.getString("Signature"), Application.MBOX_BUTTON_OK_CANCEL, //$NON-NLS-1$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { isDelete = true; } } } return null; } @Override public void runOnUIThread() { if (signatureView == null) { return; } if (isDelete) { signatureView.clear(); name.setText(""); name.setEnabled(true); Iterator itr = jobList.iterator(); while (itr.hasNext()) { Job job = itr.next(); Report report = job.getLatestReport(); if (report.isSignatureFlag() && !report.isSignatureInfo() && StringUtil.isNotEmpty(report.getSignature())) { app.deleteSignatureFile(report.getSignature()); updateSignatureAttributes(report, "", false, "", "", getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } app.showMessage(ServiceMessages.getString("signatureDeleted")); //$NON-NLS-1$ } } }; return null; } protected static void updateSignatureAttributes(Report report, String guiId, boolean signFlag, String signInfo, String signature, String name) { report.setSignatureGuId(guiId); report.setSignatureFlag(signFlag); report.setSignatureInfo(signInfo); report.setSignature(signature); report.setSignatureName(name); app.dbutil.updateReport(report); } @Override public void onFormReset() { super.onFormReset(); signatureView.clear(); } /** * -> A file is created for the report of the first entry in the job list -> * The file name is generated according to the previous pattern -> The * co-signed rapporteurs receive a reference to the signed report (also * asbefore) */ @Override protected boolean onSave() { if (jobList.get(0).getJobType().isMON()) { if (name.isRequired() && name.getText().toString().isEmpty()) { name.setError(Messages.getString("pleaseProvideValue")); return true; } } if (signatureView.isLocked()) app.showMessage(ServiceMessages.getString("signatureAlreadySaved")); //$NON-NLS-1$ else if (!signatureView.isDirty()) app.showMessage(ServiceMessages.getString("noSignatureCaptured")); //$NON-NLS-1$ else { saveSignature(); signatureView.lock(); } return true; } private void saveSignature() { String timeStamp = Long.toString(new Date().getTime()); signatureView.stamp(SignatureView.BOTTOM_RIGHT, timeStamp); // If more than one report is signed, get the GUID of the master // report(-> 1st in the list) and save it as sign-GUID String signGuid = ""; //$NON-NLS-1$ if (!jobList.isEmpty()) { if (jobList.size() > 1) { signGuid = jobList.get(0).getLatestReport().getGuId(); } Iterator itr = jobList.iterator(); try { while (itr.hasNext()) { Job job = itr.next(); // Generate file name and path for the signature file String imageName = job.getJobNumber() + "_" + job.getJobType() + "_" + timeStamp + ".bmp"; String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, imageName, true); log.info("image path " + imagePath); if (log.isDebugEnabled()) log.debug("Save signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ String originalImagePath = SignatureUtil.getOriginalSignatureFileName(imagePath); signatureView.save(originalImagePath); signatureView.save(imagePath, SignatureUtil.TARGET_WIDTH, SignatureUtil.TARGET_HEIGHT, SignatureUtil.TARGET_DENSITY); log.info("originalImagePath path " + originalImagePath); // Update current report of all selected jobs updateSignatureAttributes(job.getLatestReport(), signGuid, true, "", imageName, getName()); //$NON-NLS-1$ } } catch (IOException e) { throw new ApplicationException(e); } name.setEnabled(false); app.showMessage(ServiceMessages.getString("signatureSaved")); //$NON-NLS-1$ } else { log.error("User tried to sign a job, but job list is empty!"); //$NON-NLS-1$ } } /** * Checks the integrity of reports in the job list. Integrity is given, if - * Only one job is in the list - No job in the list is signed (signflg = * false) - All jobs are signed (signflg = false) and refer to the same GUID * * @return */ private boolean checkSelectionIntegrity() { if (jobList.size() == 1) return true; HashSet signFlagSet = new HashSet(); HashSet signGuidSet = new HashSet(); Iterator itr = jobList.iterator(); while (itr.hasNext()) { Job job = itr.next(); Report report = job.getLatestReport(); Boolean signFlag = report.isSignatureFlag(); String signGuid = report.getSignatureGuId(); if (signFlagSet.isEmpty()) { signFlagSet.add(signFlag); signGuidSet.add(signGuid); } else if (signFlagSet.contains(signFlag)) { if (!signGuidSet.contains(signGuid)) return false; } else return false; } return true; } public static class Arguments { private List jobList; private boolean isCollectiveSignature; protected Arguments() { } public Arguments(List jobList, boolean isCollectiveSignature) { super(); this.jobList = jobList; this.isCollectiveSignature = isCollectiveSignature; } public List getJobList() { return jobList; } public void setJobList(List jobList) { this.jobList = jobList; } public boolean isCollectiveSignature() { return isCollectiveSignature; } public void setCollectiveSignature(boolean isCollectiveSignature) { this.isCollectiveSignature = isCollectiveSignature; } } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarDateSelection { public static boolean isSameCalendarDay(Date first, Date second) { if (first == null || second == null) { return false; } Calendar firstCalendar = Calendar.getInstance(); firstCalendar.setTime(first); Calendar secondCalendar = Calendar.getInstance(); secondCalendar.setTime(second); return firstCalendar.get(Calendar.YEAR) == secondCalendar.get(Calendar.YEAR) && firstCalendar.get(Calendar.DAY_OF_YEAR) == secondCalendar.get(Calendar.DAY_OF_YEAR); } public static Date getPickerDate(Date visibleDate, Date selectedDate) { if (visibleDate == null) { return selectedDate == null ? new Date() : new Date(selectedDate.getTime()); } if (selectedDate == null || !isSameCalendarMonth(visibleDate, selectedDate)) { return new Date(visibleDate.getTime()); } return new Date(selectedDate.getTime()); } public static Date getVisibleDate(Date calendarDate, Date selectedDate) { if (selectedDate != null) { return new Date(selectedDate.getTime()); } if (calendarDate != null) { return new Date(calendarDate.getTime()); } return new Date(); } private static boolean isSameCalendarMonth(Date first, Date second) { Calendar firstCalendar = Calendar.getInstance(); firstCalendar.setTime(first); Calendar secondCalendar = Calendar.getInstance(); secondCalendar.setTime(second); return firstCalendar.get(Calendar.YEAR) == secondCalendar.get(Calendar.YEAR) && firstCalendar.get(Calendar.MONTH) == secondCalendar.get(Calendar.MONTH); } } package ch.mfiles.kaba.kolibri.timesheet.util; public class CalendarListWindow { public static int getTrimCount(int itemCount, int maxItems) { if (maxItems <= 0 || itemCount <= maxItems) { return 0; } return itemCount - maxItems; } public static int getPositionAfterStartTrim(int position, int removedFromStart) { int adjustedPosition = position - removedFromStart; if (adjustedPosition < 0) { return 0; } return adjustedPosition; } public static int getToolbarTitlePosition(int firstVisiblePosition, int itemCount) { if (itemCount <= 0) { return 0; } if (firstVisiblePosition < 0) { return 0; } if (firstVisiblePosition >= itemCount) { return itemCount - 1; } return firstVisiblePosition; } private CalendarListWindow() { } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarMonthScroll { public static Target nextMonth(Date focusDate) { Calendar target = firstDayOfMonth(focusDate); target.add(Calendar.MONTH, 1); return new Target(target.getTime(), target.getTime()); } public static Target previousMonth(Date focusDate) { Calendar target = firstDayOfMonth(focusDate); target.add(Calendar.MONTH, -1); return new Target(target.getTime(), target.getTime()); } private static Calendar firstDayOfMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } public static class Target { private final Date focusDate; private final Date selectedDate; private Target(Date focusDate, Date selectedDate) { this.focusDate = new Date(focusDate.getTime()); this.selectedDate = new Date(selectedDate.getTime()); } public Date getFocusDate() { return new Date(focusDate.getTime()); } public Date getSelectedDate() { return new Date(selectedDate.getTime()); } } } package ch.mfiles.kaba.kolibri.timesheet; import java.io.File; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.timesheet.forms.CalendarOverviewForm; import ch.mfiles.kaba.kolibri.timesheet.forms.TimeSheetDetailForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Main application class. */ public class TimeSheetApplication extends Application { private Log log = LogFactory.getLog(TimeSheetApplication.class); public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public EnumUtil enumUtil; public MessageUtil messageUtil; private static final int RETENTION_PERIOD_TIMESHEET = 3; // Month /** * Called by the framework each time the application is started. * * @param obj An (optional) object supplied by the application that started this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { boolean isServiceApp = false; if (obj !=null && Boolean.valueOf(obj.toString())) { isServiceApp = true; } // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); // create a DbHelper dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); enumUtil = EnumUtil.getInstance(this.dbutil); messageUtil = MessageUtil.getInstance(); Calendar retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.DAY_OF_MONTH, -30); List datesOlderThanOneMonth = dbutil.selectCalendarDatesOlderThan(retentionPeriodEnd.getTime()); Iterator datesOlderThanOneMonthIter = datesOlderThanOneMonth.iterator(); while (datesOlderThanOneMonthIter.hasNext()) { Date date = datesOlderThanOneMonthIter.next(); // Make sure that date is a date value and not a time value! if(!DateTimeUtil.isDate(date)) { showWarningMessageBox(Messages.getString("loadCALENDARObjectWithDatetime") + date + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } CalendarTimeSheet calendar = dbutil.loadCalendar(date, dbutil.getUser().getPersonalNumber()); if(!calendar.getStatus().isSENT()) { Object[] arguments = new Object[] { DateTimeUtil.showDate(date) }; String errorMessage = MessageFormat.format(TimeSheetMessages.getString("timeSheetNotSentOlderThanThirTyDays"), arguments); //$NON-NLS-1$ if (showMessageBox(errorMessage, TimeSheetMessages.getString("personalTimeAndExpensesNotSent"), Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { //$NON-NLS-1$ //go to timesheet return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(calendar.getDate(), 0, isServiceApp)); } } } retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.MONTH, -RETENTION_PERIOD_TIMESHEET); List dates = dbutil.selectCalendarDatesOlderThan(retentionPeriodEnd.getTime()); int cnt = dates.size(); Iterator itr = dates.iterator(); while (itr.hasNext()) { inform(TimeSheetMessages.getString("removingOldTimesheets") + cnt-- + "/" + dates.size()); //$NON-NLS-1$ //$NON-NLS-2$ Date date = itr.next(); CalendarTimeSheet calendar = dbutil.loadCalendar(date, dbutil.getUser().getPersonalNumber()); if (dbutil.deleteCalendarTimeSheet(calendar)) log.info("Calendar " + date + " is older than " + RETENTION_PERIOD_TIMESHEET + " months -> deleted"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else log.error("CALENDAR " + date + " can not be deleted"); //$NON-NLS-1$ //$NON-NLS-2$ } setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // Load the CALENDAR to display. This could be the oldest (if older than 3 days) not yet transmitted or the current day. Date date = dbutil.selectOldestUnsavedCalendarDate(dbutil.getUser().getPersonalNumber()); CalendarTimeSheet calendar = dbutil.loadCalendar(date, dbutil.getUser().getPersonalNumber()); return leaveToForm(CalendarOverviewForm.class, new CalendarOverviewForm.CalendarOverviewFormArgument(calendar, isServiceApp)); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { deleteExtractedFiles(); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // do nothings } /** * Called by the framework after the application has been upgraded but * before the upgrade is commited to the database. Additional upgrade * postprocessing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } public void deleteExtractedFiles() { deleteExtractedDirAndFiles(new File(Runtime.getInstallationFolder() + File.separator + CommonConstants.Application.COMMON + File.separator)); } public boolean deleteExtractedDirAndFiles(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteExtractedDirAndFiles(files[i]); } else { files[i].delete(); } } } return (path.delete()); } public CalendarTimeSheet sendTimeSheet(CalendarTimeSheet calendar) { if (showMessageBox(TimeSheetMessages.getString("timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) != Application.MBOX_RESULT_OK) { return calendar; } db.startTransaction(); try { if (!calendar.isValid()) { Object[] arguments = new Object[] { TimeSheetMessages.getString("timeSheet"), DateTimeUtil.tableDate(calendar.getDate()), TimeSheetMessages.getString("expenseSheet") }; //$NON-NLS-1$ //$NON-NLS-2$ String errorMessage = MessageFormat.format(TimeSheetMessages.getString("noPresentCannotBeSent"), arguments); //$NON-NLS-1$ showMessageBox(errorMessage, TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ return calendar; } else { log.info("sendTimeSheet -> Compensation " + calendar.getExpense().getCompensation()); calendar.setStatus(CalendarStatus.SENT); calendar.getExpense().setExpenseCompensation(); dbutil.saveCALENDAR(calendar); RemoteTransactionHandler transactionHandler = new RemoteTransactionHandler(); transactionHandler.runSaveTimeSheet(dbutil.getUser().getPersonalNumber(), calendar); if (db.isTransactionPending()) { db.rollback(); } // Reload calendar object from database and return. return dbutil.loadCalendar(calendar.getDate(), dbutil.getUser().getPersonalNumber()); } } // finally rollback if dbutil transaction is still pending finally { if (db.isTransactionPending()) { db.rollback(); } } } public void showWarningMessageBox(final String warningMessage){ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { showMessageBox(warningMessage, TimeSheetMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } public void showWarningMessageBox(final String warningMessage, final RunOnUIThread runOnUIThread){ new AsyncTask(getCurrentForm()) { private CalendarTimeSheet sendCalendar; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { showMessageBox(warningMessage, TimeSheetMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); if(runOnUIThread!=null) runOnUIThread.runOnUIThread(); } }; } public void showMessage(String message) { messageUtil.showMessage(message); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarDateSelectionTest extends TestCase { public CalendarDateSelectionTest(String name) { super(name); } public void testMatchesSameCalendarDayIgnoringTime() { assertTrue(CalendarDateSelection.isSameCalendarDay( date(2026, Calendar.JUNE, 1, 0), date(2026, Calendar.JUNE, 1, 20))); } public void testDoesNotMatchSameDayOfYearInDifferentYears() { assertFalse(CalendarDateSelection.isSameCalendarDay( date(2026, Calendar.JUNE, 1, 0), date(2027, Calendar.JUNE, 1, 0))); } public void testUsesSelectedDateForPickerWhenAvailable() { Date visibleDate = date(2026, Calendar.JULY, 1, 0); Date selectedDate = date(2026, Calendar.JULY, 12, 0); assertDate(2026, Calendar.JULY, 12, CalendarDateSelection.getPickerDate(visibleDate, selectedDate)); } public void testUsesVisibleDateForPickerWhenSelectedDateIsFromDifferentMonth() { Date visibleDate = date(2026, Calendar.JULY, 1, 0); Date selectedDate = date(2026, Calendar.JUNE, 20, 0); assertDate(2026, Calendar.JULY, 1, CalendarDateSelection.getPickerDate(visibleDate, selectedDate)); } public void testUsesVisibleDateForPickerWhenNothingSelected() { Date visibleDate = date(2026, Calendar.JULY, 1, 0); assertDate(2026, Calendar.JULY, 1, CalendarDateSelection.getPickerDate(visibleDate, null)); } public void testUsesCalendarDateWhenNoCalendarDayWasSelectedYet() { Date calendarDate = date(2026, Calendar.JULY, 1, 0); assertDate(2026, Calendar.JULY, 1, CalendarDateSelection.getVisibleDate(calendarDate, null)); } public void testKeepsSelectedCalendarDayWhenAvailable() { Date calendarDate = date(2026, Calendar.JULY, 1, 0); Date selectedDate = date(2026, Calendar.JULY, 15, 0); assertDate(2026, Calendar.JULY, 15, CalendarDateSelection.getVisibleDate(calendarDate, selectedDate)); } private static Date date(int year, int month, int day, int hour) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } } package ch.mfiles.kaba.kolibri.timesheet.util; import junit.framework.TestCase; public class CalendarListWindowTest extends TestCase { public CalendarListWindowTest(String name) { super(name); } public void testNoTrimWhenListIsWithinLimit() { assertEquals(0, CalendarListWindow.getTrimCount(90, 120)); } public void testTrimCountIsOverflowAboveLimit() { assertEquals(10, CalendarListWindow.getTrimCount(130, 120)); } public void testAnchorPositionMovesUpWhenRowsAreTrimmedFromStart() { assertEquals(50, CalendarListWindow.getPositionAfterStartTrim(70, 20)); } public void testAnchorPositionDoesNotBecomeNegativeAfterStartTrim() { assertEquals(0, CalendarListWindow.getPositionAfterStartTrim(10, 20)); } public void testToolbarTitlePositionUsesFirstVisibleRow() { assertEquals(30, CalendarListWindow.getToolbarTitlePosition(30, 62)); } public void testToolbarTitlePositionDoesNotBecomeNegative() { assertEquals(0, CalendarListWindow.getToolbarTitlePosition(-1, 62)); } public void testToolbarTitlePositionDoesNotExceedLastRow() { assertEquals(61, CalendarListWindow.getToolbarTitlePosition(70, 62)); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarMonthScrollTest extends TestCase { public CalendarMonthScrollTest(String name) { super(name); } public void testForwardFromMonthEndTargetsBeginningOfNextMonth() { CalendarMonthScroll.Target target = CalendarMonthScroll.nextMonth(date(2026, Calendar.JANUARY, 31)); assertDate(2026, Calendar.FEBRUARY, 1, target.getFocusDate()); assertDate(2026, Calendar.FEBRUARY, 1, target.getSelectedDate()); } public void testBackwardFromNextMonthTargetsBeginningOfPreviousMonth() { CalendarMonthScroll.Target target = CalendarMonthScroll.previousMonth(date(2026, Calendar.JULY, 1)); assertDate(2026, Calendar.JUNE, 1, target.getFocusDate()); assertDate(2026, Calendar.JUNE, 1, target.getSelectedDate()); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.graphics.Typeface; import android.support.v7.widget.AppCompatSpinner; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.adapters.SpinnerTextStyle; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.impl.android.ui.UIActivity; /** * A view for easy creation and use of an {@link AppCompatSpinner} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * @author cyu */ public class MDCalendar extends MDSpinner implements OnItemSelectedListener{ private int color = LayoutUtils.DEFAULT_LABEL_COLOR; private Typeface typeface = CommonConstants.Font.getDefaultRegularFont(Typeface.NORMAL); private int textSize = CommonConstants.Font.DEFAULT_FONT_SIZE; private int unit = TypedValue.COMPLEX_UNIT_SP; private boolean customTextStyle; private static SimpleDateFormat format = new SimpleDateFormat("MMMM yyyy"); private static MDCalendar mdCalendar; private static Calendar calendar; private static DatePickerDialog datePickerDialog; public MDCalendar(Context context) { super(context); setOnItemSelectedListener(this); setFocusable(false); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param required * @return */ public static MDCalendar createDefaultCalendar(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); MDCalendar calendar = createCalendar(context, label, required); LinearLayout linearLayout = (LinearLayout) calendar.getParent(); parent.addView(linearLayout); return calendar; } private static MDCalendar createCalendar(Context context, String label, boolean required) { mdCalendar = new MDCalendar(context); mdCalendar.createSpinnerView(context, mdCalendar); mdCalendar.setLabel(label); mdCalendar.setRequired(required); mdCalendar.setContents(new ArrayList()); // make clicking the view group the same as clicking the spinner // linearLayout.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // calendar.performClick(); // } // }); // // calendar.setOnItemSelectedListener(new OnItemSelectedListener() { // // @Override // public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { // calendar.clearError(); // } // // @Override // public void onNothingSelected(AdapterView arg0) { // // Auto-generated method stub // // } // }); mdCalendar.setFocusableInTouchMode(false); calendar = Calendar.getInstance(); datePickerDialog = createDatePickerDialog(); mdCalendar.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { mdCalendar.setEnabled(false); datePickerDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mdCalendar.setEnabled(true); mdCalendar.clearError(); } }); datePickerDialog.show(); return true; } }); return mdCalendar; } private static DatePickerDialog createDatePickerDialog() { return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); mdCalendar.setSelectedDate(calendar.getTime()); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { applyTextStyle(parent, view); } @Override public void setContents(List list) { super.setContents(list); applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } @Override protected CustomSpinnerAdapter createSpinnerAdapter(List customSpinnerItemList) { CustomSpinnerAdapter adapter = super.createSpinnerAdapter(customSpinnerItemList); if (isStyleChanged()) { adapter.setClosedViewTextStyle(getTextStyle()); } return adapter; } private TextView getSelectedTextView(AdapterView parent, View view) { if (view instanceof TextView) { return (TextView) view; } if (parent != null && parent.getSelectedView() instanceof TextView) { return (TextView) parent.getSelectedView(); } if (parent != null && parent.getChildAt(0) instanceof TextView) { return (TextView) parent.getChildAt(0); } return null; } private boolean isStyleChanged() { return customTextStyle; } @Override public void onNothingSelected(AdapterView parent) { // do nothing } public void setTextColor(int color) { this.color = color; customTextStyle = true; applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } public void setTypeface(Typeface typeface) { this.typeface = typeface; customTextStyle = true; applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } public void setTextSize(int unit, int textSize) { this.unit = unit; this.textSize = textSize; customTextStyle = true; applyTextStyleToAdapter(); applyTextStyle(this, getSelectedView()); } private void applyTextStyleToAdapter() { if (!isStyleChanged() || !(getAdapter() instanceof CustomSpinnerAdapter)) { return; } ((CustomSpinnerAdapter) getAdapter()).setClosedViewTextStyle(getTextStyle()); } private void applyTextStyle(AdapterView parent, View view) { if (!isStyleChanged()) { return; } getTextStyle().applyTo(getSelectedTextView(parent, view)); } private SpinnerTextStyle getTextStyle() { return SpinnerTextStyle.custom(color, typeface, unit, textSize); } public void setSelectedDate(Date select) { calendar.setTime(select); String date = format.format(calendar.getTime()); List dateTypeValueList = new ArrayList(); dateTypeValueList.add(new CustomSpinnerItem(date, date)); mdCalendar.setContents(dateTypeValueList); datePickerDialog = createDatePickerDialog(); } public Date getSelectedDate() { return calendar.getTime(); } public void setSimpleDateFormat(SimpleDateFormat simpleDateFormat) { format = simpleDateFormat; } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.PorterDuff.Mode; import android.support.v7.widget.AppCompatSpinner; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; /** * A view for easy creation and use of an {@link AppCompatSpinner} that is * embedded in a {@link LinearLayout} which is the way input fields are created * in Material design. * * MDSpinner structure: * LinearLayout * --TextView(label) * --AppCompatSpinner * --View(Underline) * --TextView(Error message) * * @author nop */ public class MDSpinner extends AppCompatSpinner { private TextView labelTextView; public MDSpinner(Context context) { super(context); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param required * @return */ public static MDSpinner createDefaultSpinner(Context context, boolean required) { return createDefaultSpinner(context, null, required); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param context * @param label * @param required * @return */ public static MDSpinner createDefaultSpinner(Context context, String label, boolean required) { return createSpinner(context, label, required); } /** * Creates a new {@link MDSpinner} with default layout: matching the parent * horizontally and wrapping its content vertically. * * @param parent * @param label * @param required * @return */ public static MDSpinner createDefaultSpinner(ViewGroup parent, String label, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); MDSpinner spinner = createSpinner(context, label, required); LinearLayout linearLayout = (LinearLayout) spinner.getParent(); parent.addView(linearLayout); return spinner; } private static MDSpinner createSpinner(Context context, final String label, boolean required) { final MDSpinner spinner = new MDSpinner(context); LinearLayout linearLayout = spinner.createSpinnerView(context, spinner); spinner.setLabel(label); spinner.setRequired(required); // make clicking the view group the same as clicking the spinner linearLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { spinner.performClick(); } }); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { spinner.clearError(); } @Override public void onNothingSelected(AdapterView arg0) { // Auto-generated method stub } }); return spinner; } public LinearLayout createSpinnerView(Context context, View view) { LinearLayout linearLayout = new LinearLayout(context); LinearLayout.LayoutParams linearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.VERTICAL); labelTextView = new TextView(context); labelTextView.setTag("TEXT"); //$NON-NLS-1$ labelTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); labelTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); textLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); labelTextView.setLayoutParams(textLayoutParams); labelTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(labelTextView); LinearLayout.LayoutParams viewLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); viewLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), 0, 0, 0); view.setLayoutParams(viewLayoutParams); view.getBackground().setColorFilter(LayoutUtils.DEFAULT_TEXT_COLOR, Mode.SRC_ATOP); linearLayout.addView(view); View underline = new View(context); underline.setTag("UNDERLINE"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutUtils.convertDpToPixel(context, 1)); underlineLinearLayout.setMargins(LayoutUtils.convertDpToPixel(context, 4) , 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); underline.setLayoutParams(underlineLinearLayout); underline.setBackgroundColor(LayoutUtils.DEFAULT_UNDERLINE_COLOR); linearLayout.addView(underline); TextView errorText = new TextView(context); errorText.setTag("ERRORTEXT"); //$NON-NLS-1$ errorText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); errorText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams errorTextLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); errorTextLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, 4), 0, 0, 0); errorText.setLayoutParams(errorTextLayoutParams); errorText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); errorText.setVisibility(View.GONE); linearLayout.addView(errorText); return linearLayout; } /** * Sets contents. * * @param list */ public void setContents(List list) { List customSpinnerItemList = new ArrayList(); if (list != null && list.isEmpty()) { customSpinnerItemList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, "")); } else { for (int i = 0; i < list.size(); i++) { CustomSpinnerItem item = list.get(i); if (item.getName().startsWith("Bitte w") && item.getName().endsWith("...")) { list.remove(item); if(customSpinnerItemList.isEmpty()) { customSpinnerItemList.add(item); } } } customSpinnerItemList.addAll(list); } if (this.getAdapter() != null) { this.setAdapter(null); } CustomSpinnerAdapter adapter = createSpinnerAdapter(customSpinnerItemList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); this.setAdapter(adapter); this.setSelection(0); // default } protected CustomSpinnerAdapter createSpinnerAdapter(List customSpinnerItemList) { return new CustomSpinnerAdapter(this.getContext(), android.R.layout.simple_spinner_item, customSpinnerItemList); } /** * Clears contents. */ public void clearContents() { if (this.getAdapter() != null) { this.setAdapter(null); } } /** * Sets selection by id. * * @param id */ public void setSelectionById(String id) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) this.getAdapter(); if (adapter == null) { return; } this.setSelection(adapter.getPositionById(id)); } /** * Sets selection by name. * * @param name */ public void setSelectionByName(String name) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) this.getAdapter(); this.setSelection(adapter.getPositionByName(name)); } /** * Sets selection by description. * * @param description */ public void setSelectionByDescription(String description) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) this.getAdapter(); this.setSelection(adapter.getPositionByDescription(description)); } /** * Sets an error. * * @param error */ public void setError(CharSequence error) { TextView errorText = getErrorText(); errorText.setText(error); errorText.setVisibility(View.VISIBLE); View underline = getUnderline(); underline.setBackgroundColor(LayoutUtils.DEFAULT_ERROR_COLOR); } /** * Gets top parent. * * @return */ public View getTopParent() { return (View) this.getParent(); } /** * Gets selected item id. * * @return */ public String getSelectedId() { CustomSpinnerItem customSpinnerItem = ((CustomSpinnerItem) this.getSelectedItem()); if (customSpinnerItem == null) { return ""; } return ((CustomSpinnerItem) this.getSelectedItem()).getId(); } /** * Gets selected item name. * * @return */ public String getSelectedName() { return ((CustomSpinnerItem) this.getSelectedItem()).getName(); } /** * Gets selected item Description. * * @return */ public String getSelectedDescription() { return ((CustomSpinnerItem) this.getSelectedItem()).getDescription(); } /** * Clears an error. */ public void clearError() { TextView errorText = getErrorText(); errorText.setText(""); //$NON-NLS-1$ errorText.setVisibility(View.GONE); View underline = getUnderline(); underline.setBackgroundColor(isEnabled() ? LayoutUtils.DEFAULT_UNDERLINE_COLOR : LayoutUtils.DEFAULT_UNDERLINE_DISABLED_COLOR); } /** * Adds an asterisk to the hint that was set to the receiver marking the * input field as 'required'. * * @param required */ public void setRequired(boolean required) { TextView textView = getTextView(); String text = textView.getText().toString().replaceAll("\\*", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ textView.setText(text); if (required) { textView.setText(text + " *"); //$NON-NLS-1$ } } /** * Is required. * @return */ public boolean isRequired() { TextView textView = getTextView(); return textView.getText().toString().contains("*"); //$NON-NLS-1$ } /** * Gets a text. * @return */ public TextView getTextView() { LinearLayout linearLayout = (LinearLayout) getTopParent(); View view = linearLayout.getChildAt(0); if (view instanceof TextView && "TEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } /** * Gets an underline. * @return */ public View getUnderline() { int childIndex = 2; LinearLayout linearLayout = (LinearLayout) getTopParent(); if (linearLayout.getChildCount() == 3) { childIndex = 1; } View view = linearLayout.getChildAt(childIndex); if ("UNDERLINE".equals(view.getTag().toString())) { //$NON-NLS-1$ return view; } return null; } /** * Gets an error text. * @return */ public TextView getErrorText() { int childIndex = 3; LinearLayout linearLayout = (LinearLayout) getTopParent(); if (linearLayout.getChildCount() == 3) { childIndex = 2; } View view = linearLayout.getChildAt(childIndex); if (view instanceof TextView && "ERRORTEXT".equals(view.getTag().toString())) { //$NON-NLS-1$ return (TextView) view; } return null; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); this.setClickable(enabled); // set Enabled/Disabled click event LinearLayout linearLayout = (LinearLayout) getTopParent(); linearLayout.setClickable(enabled); // set Enabled/Disabled style. int spinnerColor = LayoutUtils.DEFAULT_TEXT_COLOR; int underlineColor = LayoutUtils.DEFAULT_UNDERLINE_COLOR; if (!enabled) { spinnerColor = LayoutUtils.DEFAULT_DISABLED_COLOR; underlineColor = LayoutUtils.DEFAULT_UNDERLINE_DISABLED_COLOR; } TextView textView = (TextView) this.getSelectedView(); if (textView == null) { textView = (TextView) this.getChildAt(0); } if (textView != null) { textView.setTextColor(spinnerColor); textView.setEnabled(enabled); this.getBackground().setColorFilter(spinnerColor, Mode.SRC_ATOP); } View underlineView = getUnderline(); if (underlineView != null) { underlineView.setBackgroundColor(underlineColor); underlineView.setEnabled(enabled); } TextView labelView = getTextView(); if (labelView != null) { labelView.setTextColor(spinnerColor); labelView.setHintTextColor(spinnerColor); labelView.setEnabled(enabled); } } public void setLabel(String label) { labelTextView.setText(label); } } package ch.mfiles.kaba.kolibri.service.forms; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLayoutChangeListener; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.util.BackupHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil.JobStatusFilter; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.SoundUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDeleteForm.JobDeleteFormArguments; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm.JobSearchFormArguments; import ch.mfiles.kaba.kolibri.service.forms.RescheduleJobForm.RescheduleJobFormArguments; import ch.mfiles.kaba.kolibri.service.util.ReportUtil; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; public class JobListForm extends ServiceNavigationForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(JobListForm.class); private JobStatusFilter jobStatusFilter = JobStatusFilter.active; private DefaultListWidget listWidget; private RelativeLayout listItemLayout; private LinearLayout emptyMessageView; private LinearLayout checkAllFinalizeJobLayout; private TextView finalizeText; private ImageView checkImageView; private AHBottomNavigation bottomNavigation; private SearchView searchView; private ActionCtrl searchAction; private ActionCtrl downloadAction; private ActionCtrl scanAction; private TimeUtil timeUtil; private ActionCtrl deleteAction; private List selectedJobList; /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; timeUtil = new TimeUtil(app, app.dbutil, this); // hide runtime menu items setRuntimeMenuHidden(true); // create SearchView searchView = new SearchView(context); searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END)); searchView.setOnQueryTextListener(this); // create search action searchAction = addActionCtrl(false, true, 1, "actionSearch"); //$NON-NLS-1$ searchAction.setTitle(ServiceMessages.getString("search")); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); // create scan action scanAction = addActionCtrl(false, true, 1, "actionScan"); //$NON-NLS-1$ scanAction.setTitle(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); // create save action downloadAction = addActionCtrl(false, true, 1, "actionDownload"); //$NON-NLS-1$ downloadAction.setTitle(ServiceMessages.getString("download")); //$NON-NLS-1$ downloadAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_WHITE, CommonConstants.Images.IMAGE_DPI))); // create delete action deleteAction = addActionCtrl(false, true, 1, "actionDelete"); //$NON-NLS-1$ deleteAction.setTitle(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setVisible(false); setVisibleAction(true); log.info("creating listWidgetView"); //$NON-NLS-1$ checkAllFinalizeJobLayout = new LinearLayout(context); checkAllFinalizeJobLayout.setOrientation(LinearLayout.HORIZONTAL); checkAllFinalizeJobLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS())); LinearLayout.LayoutParams checkFinalizeLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); checkFinalizeLayoutParams.width = LayoutParams.MATCH_PARENT; checkAllFinalizeJobLayout.setLayoutParams(checkFinalizeLayoutParams); checkAllFinalizeJobLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); checkAllFinalizeJobLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); checkAllFinalizeJobLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean checkAll = false; if (selectedJobList.size() == listWidget.getAdapter().getCount()) { log.info("remvoe all cheked"); checkAll = false; selectedJobList.clear(); } else { log.info("check all"); checkAll = true; selectedJobList.clear(); for (int i = 0; i < listWidget.getAdapter().getCount(); i++) { Job job = (Job) ((DetailListWidgetItem) listWidget.getAdapter().getItem(i)).getData(); selectedJobList.add(job); } } ArrayList items = new ArrayList(); for (int i=0;i * * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); log.info("onFormShow content " + getContentView().getHeight() + " buttom size " + bottomNavigation.getHeight()); if(CommSetupHelper.isProductionEnvironment()) { app.refreshMasterData(false); app.messageUtil.showContinueMessage(); // check for a valid and recent backup... BackupHandler.getInstance().checkOverdueBackup(app); if(emptyMessageView.getChildCount() > 0) emptyMessageView.removeAllViewsInLayout(); // FIXME: remove test code File testFile1 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time1: " + testFile1.lastModified()); try { Thread.sleep(100); } catch (InterruptedException e) { } File testFile2 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time2: " + testFile2.lastModified()); File testFile3 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time3: " + testFile3.lastModified()); try (FileInputStream in = new FileInputStream(testFile3)) { while (in.read(new byte[1024]) > 0) ; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } File testFile4 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time4: " + testFile4.lastModified()); } setFormTitle(ServiceMessages.getString("jobList")); bottomNavigation.refresh(); if (jobStatusFilter != null && bottomNavigation !=null) { if (jobStatusFilter == JobStatusFilter.planned) { bottomNavigation.setCurrentItem(1); } else if (jobStatusFilter == JobStatusFilter.finalized) { bottomNavigation.setCurrentItem(2); } else { jobStatusFilter = JobStatusFilter.active; bottomNavigation.setCurrentItem(0); } } // TODO for test only Person user = app.dbutil.getUser(); // app.dbutil.deleteOldUser(user.getPersonalNumber()); // user.setPersonalNumber(98102); // user.setWarehouseNumber("F032"); // user.setFirstName("Zehnder Jörg"); // user.setCommunicationNumberFormat("DE"); // user.setExpensesActive(false); // app.dbutil.updateUser(user); // user.setPersonalNumber(1644); // user.setWarehouseNumber("F996"); // user.setFirstName("Christoph"); // app.dbutil.switchUser(user); return null; } protected ApplicationEvent actionDownload() { // SoundUtil.playRawSound(context, "zxing_beep"); SoundUtil.playRawSound(context, "ssm 11"); KeyboardUtil.closeKeyboard(appman, getView()); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().callForm(JobSearchForm.class, new JobSearchFormArguments(null)); } }, false); return null; } protected ApplicationEvent actionSearch() { KeyboardUtil.closeKeyboard(appman, getView()); // hide menu setVisibleAction(false); searchView.setIconified(false); MenuItem searchItem = JobListForm.this.getToolbar().getMenu().getItem(0); searchItem.setIcon(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); searchItem.setActionView(searchView); searchItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_WITH_TEXT); MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem menuItem) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { setVisibleAction(true); return null; } }, false); return true; } }); return null; } protected ApplicationEvent actionScan() { app.scanSavJob(); return null; } protected ApplicationEvent actionDelete() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if(selectedJobList.isEmpty()) { return null; } if (app.showConfirmDeleteDialog()) { // inform SAP about the status change (only SAV) // Requirement, mail 17.5.2012: // Do not transmit deleted state to SAP if job status is 'abgeschlossen' or 'weitergelietet'. for (Job job : selectedJobList) { deleteJob(job); } selectedJobList.clear(); } return app.leaveToForm(JobListForm.class); } }, false); return null; } public void loadTable() { List jobList = app.dbutil.selectJobList(); int listWidgetHeight = getContentView().getHeight() - bottomNavigation.getHeight(); if(listWidget.getHeight() > 0 && listWidget.getHeight() != listWidgetHeight) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, listWidgetHeight); listWidget.setLayoutParams(params); } if (jobStatusFilter == JobStatusFilter.finalized) { ((LayoutParams) listWidget.getLayoutParams()).topMargin = checkAllFinalizeJobLayout.getHeight(); ((LayoutParams) listWidget.getLayoutParams()).bottomMargin = checkAllFinalizeJobLayout.getHeight(); ((LayoutParams) listWidget.getLayoutParams()).height -= checkAllFinalizeJobLayout.getHeight(); } else { ((LayoutParams) listWidget.getLayoutParams()).topMargin = 0; ((LayoutParams) listWidget.getLayoutParams()).bottomMargin = 0; } listWidget.clean(); selectedJobList = new ArrayList(); log.info("Job /" + jobList.size()); ArrayList items = new ArrayList<>(); for (int i = 0; i < jobList.size(); i++) { final Job job = jobList.get(i); job.loadReports(app.dbutil); job.getLatestReport().checkIfTimeStartOverOndDay(app.dbutil); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setData(job); setItemContent(job, item); setClickListener(job, item); setItemStatus(job, item); if(jobStatusFilter == JobStatusFilter.active && ServiceJobUtil.isJobActive(job)){ log.info("Active"); items.add(item); } if(jobStatusFilter == JobStatusFilter.planned && ServiceJobUtil.isJobInPlanned(job)){ log.info("Planed"); items.add(item); } if(jobStatusFilter == JobStatusFilter.finalized && ServiceJobUtil.isJobFinalized(job)){ log.info("Finalized"); items.add(item); } log.info(DateTimeUtil.showDateTime(job.getStatusEdit()) + " status edit date STEDTDATE"); log.info("EDATE -> " + DateTimeUtil.showDateTime(job.getAppointmentDate())); log.info("EDATE_DT -> " + DateTimeUtil.showDateTime(job.getJobRescheduleDate())); log.info("EDATE_TI -> " + DateTimeUtil.showDateTime(job.getJobRescheduleTime())); log.info("ACTIVE_DATE -> " + DateTimeUtil.showDateTime(job.getActiveJobDate())); log.info("STATUS -> " + job.getStatus().getCode().toString()); listWidget.setOnItemClickListener(createOnItemClickListener()); } if (!items.isEmpty()) { emptyMessageView.setVisibility(View.GONE); listWidget.addItems(items); } else { emptyMessageView.setVisibility(View.VISIBLE); if (jobStatusFilter == JobStatusFilter.finalized) { ((LayoutParams) emptyMessageView.getLayoutParams()).topMargin = checkAllFinalizeJobLayout.getHeight(); } else { ((LayoutParams) emptyMessageView.getLayoutParams()).topMargin = 0; } } } private void setItemStatus(final Job job, final DefaultListWidgetItem item) { if (jobStatusFilter == JobStatusFilter.finalized) { item.isShowCheckBox(true); } item.setOverlayIcon(null); if(job.getStatus().isInProgress()) { item.setOverlayIcon(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ALARM_RED, CommonConstants.Images.IMAGE_MAX_DPI))); } else { if(job.getLatestReport() != null) { List reportTimeList = job.getLatestReport().getTimes(); if(!reportTimeList.isEmpty()) { item.setOverlayIcon(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ALARM_BLACK, CommonConstants.Images.IMAGE_MAX_DPI))); } } } } private void setClickListener(final Job job, final DefaultListWidgetItem item) { item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setSelectedJob(job); if (v instanceof CheckBox) { item.setCheck(((CheckBox) v).isChecked()); if(((CheckBox) v).isChecked()) { selectedJobList.add(job); } else { selectedJobList.remove(job); } setEnableDeleteAction(); } else { showPopupMenu(v); } } }); } private void setItemContent(final Job job, final DefaultListWidgetItem item) { item.setStatusColor(job.getStatusColor()); item.setStatusType(job.getStatusType()); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.MENU, CommonConstants.Images.IMAGE_MAX_DPI))); job.loadAddresses(app.dbutil); Address objAddress = job.getObjectAddress(); Address customerAddress = job.getCustomerAddress(); item.setTitleText(objAddress.getPostalCode() + " " + objAddress.getCity()); item.setStringLine1(objAddress.getStreet() + ", " + app.getAddressTitle(customerAddress)); if (job.getJobType().isMON()) { item.setStringLine2(job.getCommissionNumberNoLeadingZero()); } else { item.setStringLine2(job.getCommissionNumber()+ ' ' + '/' + ' ' + (job.getWeek() > 0 ? "KW: " + job.getWeek() : ServiceMessages.getString("AppointmentDate") + ' ' + DateTimeUtil.showDateTime(job.getAppointmentDate())) ); } item.setStringLine3(objAddress.getLocation()); } private OnItemClickListener createOnItemClickListener() { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { Job jobClicked = (Job) ((DetailListWidgetItem) listWidget.getAdapter().getItem(position)).getData(); log.info(" job " + jobClicked.getJobNumber() + " commm " + (jobClicked.getJobType().isMON() ? jobClicked.getCommissionNumberNoLeadingZero():jobClicked.getCommissionNumber())); setSelectedJob(jobClicked); app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailFormArgument(getSelectedJob())); } }; } private void showPopupMenu(View v) { /* * Create the context menu. * see "[MIG-67] Context menu for jobs doesn't work" */ ImageButton imageButton = (ImageButton) v; PopupMenu popupMenu = new PopupMenu(context, imageButton); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); // Accept Images acceptStatusImage = ImagesUtil.Images.ASSIGNMENT_TURNED_IN_DISABLED; if (ServiceJobUtil.isJobAcceptable(getSelectedJob())) { acceptStatusImage = ImagesUtil.Images.ASSIGNMENT_TURNED_IN; } addPopupMenuItem(popupMenu, ServiceConstants.Index.ONE, ServiceMessages.getString("accept"), acceptStatusImage); //$NON-NLS-1$ // Forward Images forwardStatusImage = ImagesUtil.Images.ASSIGNMENT_IND_DISABLED; if (ServiceJobUtil.isJobForwardable(getSelectedJob())) { forwardStatusImage = ImagesUtil.Images.ASSIGNMENT_IND; } addPopupMenuItem(popupMenu, ServiceConstants.Index.TWO, ServiceMessages.getString("forward"), forwardStatusImage); //$NON-NLS-1$ // Delete Images deleteStatusImage = ImagesUtil.Images.DELETE_DISABLED_BLACK; if (ServiceJobUtil.isJobDeletable(getSelectedJob())) { deleteStatusImage = ImagesUtil.Images.DELETE_BLACK; } addPopupMenuItem(popupMenu, ServiceConstants.Index.THREE, ServiceMessages.getString("erase"), deleteStatusImage); //$NON-NLS-1$ // Reschedule Images rscheduleImage = ImagesUtil.Images.SCHEDULE_DISABLED_BLACK; if (ServiceJobUtil.isJobRescheduleable(getSelectedJob())) { rscheduleImage = ImagesUtil.Images.SCHEDULE_BLACK; } addPopupMenuItem(popupMenu, ServiceConstants.Index.FOUR, ServiceMessages.getString("reschedule"), rscheduleImage); //$NON-NLS-1$ // Call createCallMenuItem(popupMenu); // Send Images sendImage = ImagesUtil.Images.SEND_DISABLED_BLACK; if (app.isJobAndReportComplete(getSelectedJob())) { sendImage = ImagesUtil.Images.SEND_BLACK; } addPopupMenuItem(popupMenu, ServiceConstants.Index.SIX, ServiceMessages.getString("send"), sendImage); //$NON-NLS-1$ // Time createTimeMenuItem(popupMenu); //forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem); return true; } }); popupMenu.show(); } private void createTimeMenuItem(PopupMenu popupMenu) { String timeLabel = "start"; //$NON-NLS-1$ Images timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; if (ServiceJobUtil.isJobStartTimeable(getSelectedJob())) { if (app.dbutil.selectPlayingJobReportTimeByReport(getSelectedJob().getCurrentReport()) != null) { timeLabel = "stop"; //$NON-NLS-1$ timeStatusImage = ImagesUtil.Images.STOP_TIME; } else { if(app.dbutil.selectJobWithOpenTimesheet().isEmpty()) { timeStatusImage = ImagesUtil.Images.START_TIME; } else { timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; } } } addPopupMenuItem(popupMenu, ServiceConstants.Index.SEVEN, ServiceMessages.getString(timeLabel), timeStatusImage); } private void createCallMenuItem(PopupMenu popupMenu) { Address partnerOfInstallAddress = getSelectedJob().getPartnerOfInstallAddress(); String contact = ServiceMessages.getString("NoPhoneNumber"); //$NON-NLS-1$ Images phoneStatusImage = ImagesUtil.Images.PHONE_DISABLED; if (StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber1()) || StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber2())) { phoneStatusImage = ImagesUtil.Images.PHONE; contact = app.enumUtil.titelEnum.get(partnerOfInstallAddress.getTitle()); contact += "\n" + partnerOfInstallAddress.getName1(); //$NON-NLS-1$ if (!"0003".equals(partnerOfInstallAddress.getTitle())) { //$NON-NLS-1$ contact += "\n" + partnerOfInstallAddress.getName2(); //$NON-NLS-1$ } log.info("contact " + contact); } addPopupMenuItem(popupMenu, ServiceConstants.Index.FIVE, contact, phoneStatusImage); } private void addPopupMenuItem(PopupMenu popupMenu, int index, String label, Images image) { popupMenu.getMenu() .add(Menu.NONE, index, Menu.NONE, label) .setIcon(getBitmanDrawable(app.imagesUtil.getImage(image, CommonConstants.Images.IMAGE_DPI))); } private void handleMenuItemClicked(MenuItem menuItem) { if (menuItem.getItemId() == ServiceConstants.Index.ONE) { if (ServiceJobUtil.isJobAcceptable(getSelectedJob())) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { getSelectedJob().calculateActiveDate(); updateJobStatus(JobStatus.RECEIVED, JobStatus.SAP_Confirmed); // If there's a job in status NEW with a planned date and the user confirms the job, //there should be a notification, that the job is now displayed in filter "planned". if (ServiceJobUtil.isJobInPlanned(getSelectedJob())) { showPlannedJobDialog(); } return app.leaveToForm(JobListForm.class); } }, false); } } else if (menuItem.getItemId() == ServiceConstants.Index.TWO) { if (ServiceJobUtil.isJobForwardable(getSelectedJob())) { app.injectAndLeaveToForm(JobForwardForm.class, new JobForwardForm.JobForwardFormArgument(getSelectedJob())); } } else if (menuItem.getItemId() == ServiceConstants.Index.THREE) { if (ServiceJobUtil.isJobDeletable(getSelectedJob())) { actionDelete(getSelectedJob()); } else { app.showMessage(ServiceMessages.getString("jobCannotBeDeletedPleaseSendBackOpenReports")); //$NON-NLS-1$ } } else if (menuItem.getItemId() == ServiceConstants.Index.FOUR) { if (ServiceJobUtil.isJobRescheduleable(getSelectedJob())) { app.injectAndLeaveToForm(RescheduleJobForm.class, new RescheduleJobFormArguments(getSelectedJob())); } } else if (menuItem.getItemId() == ServiceConstants.Index.FIVE) { actionCall(); } else if (menuItem.getItemId() == ServiceConstants.Index.SIX) { actionSend(getSelectedJob()); } else if (menuItem.getItemId() == ServiceConstants.Index.SEVEN && ServiceJobUtil.isJobStartTimeable(getSelectedJob())) { actionTime(getSelectedJob()); } } private void actionDelete(final Job job) { if ((job.getStatus().isNew() || job.getStatus().isReceived() || job.getStatus().isPartlyDone()) && (job.getJobType().isREP() || job.getJobType().isSAV())) { //Delete a job with reason //The job has the status NEW, RECEIVED (without report data) or PARTLY_DONE. //The job has the type REP or SAV. app.injectAndLeaveToForm(JobDeleteForm.class, new JobDeleteFormArguments(job)); } else { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showConfirmDeleteDialog()) { // inform SAP about the status change (only SAV) // Requirement, mail 17.5.2012: // Do not transmit deleted state to SAP if job status is 'abgeschlossen' or 'weitergelietet'. deleteJob(job); } return app.leaveToForm(JobListForm.class); } }, false); } } private void showPlannedJobDialog() { MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("plannedJob"),ServiceMessages.getString("ok")); //$NON-NLS-1$ //$NON-NLS-2$ alertDialog.setMessage(ServiceMessages.getString("showPlannedJobDialogText")); alertDialog.show(); } private void deleteJob(final Job job) { log.info("deleteJob status isNew " + job.getStatus().isNew()); if (job.getStatus().isNew() || job.getStatus().isReceived() || job.getStatus().isPartlyDone()) { updateJobStatus(JobStatus.DELETED, JobStatus.SAP_Deleted); if (job.getStatus().isDeleted() && app.dbutil.deleteJob(job)) { app.showMessage(ServiceMessages.getString("jobDeleted"), true); //$NON-NLS-1$ } } else { if (app.dbutil.deleteJob(job)) app.showMessage(ServiceMessages.getString("jobDeleted"), true); //$NON-NLS-1$ } } private void actionCall() { Address partnerOfInstallAddress = getSelectedJob().getPartnerOfInstallAddress(); if (StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber1()) || StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber2())) { String tel = ""; //$NON-NLS-1$ if (StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber1())) { tel = partnerOfInstallAddress.getTelNumber1(); } if (StringUtil.isEmpty(tel) && StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber2())) { tel = partnerOfInstallAddress.getTelNumber2(); } String phoneNumber = tel.replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(appman.getContext(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { appman.requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } private void actionSend(Job job) { if (app.isJobAndReportComplete(getSelectedJob())) { ReportUtil reportUtil = new ReportUtil(this, app); reportUtil.onSendingReport(job); reloadSelectedJob(); loadTable(); } } private void actionTime(final Job job) { if (ServiceJobUtil.isJobStartTimeable(getSelectedJob()) && app.dbutil.selectPlayingJobReportTimeByReport(getSelectedJob().getCurrentReport()) == null && !app.dbutil.selectJobWithOpenTimesheet().isEmpty()) { return; } app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.dbutil.selectPlayingJobReportTimeByReport(getSelectedJob().getCurrentReport()) != null) { timeUtil.stopTime(job, new RunOnUIThread() { @Override public void runOnUIThread() { //Auto-generated method stub } }); } else { boolean result = timeUtil.startJobTimeCapturing(getSelectedJob()); if (result) { timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, getSelectedJob(), new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { // do nothing } }); } } return app.leaveToForm(JobListForm.class); } }, false); } public static class JobListFormArguments { private Job job; protected JobListFormArguments() { } public JobListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } private void setVisibleAction(boolean visible) { searchAction.setVisible(visible); downloadAction.setVisible(visible); scanAction.setVisible(visible); } private void setEnableDeleteAction() { if (selectedJobList != null && !selectedJobList.isEmpty()) { deleteAction.setEnabled(true); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); String message = MessageFormat.format(ServiceMessages.getString("jobsSelected"), new Object[] { selectedJobList.size(), listWidget.getItems().size()}); //$NON-NLS-1$ if (selectedJobList.size() == listWidget.getAdapter().getCount()) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_CHECKED, CommonConstants.Images.IMAGE_DPI))); finalizeText.setText(message); } else { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_SOME, CommonConstants.Images.IMAGE_DPI))); finalizeText.setText(message); } } else { deleteAction.setEnabled(false); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_UNCHECKED, CommonConstants.Images.IMAGE_DPI))); finalizeText.setText(ServiceMessages.getString("noJobSelected")); } } }
package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.stepstone.stepper.StepperLayout; import com.stepstone.stepper.VerificationError; import com.stepstone.stepper.internal.type.AbstractStepperType; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RadioGroup.OnCheckedChangeListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.StepAdapter; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StepUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Create new Job with 2 steps form. * * @author cyu (05-07-2017) * * @see "[MIG-156] Rework of create a job: Search jobs / Create a job" */ public class JobNewForm extends JobEditForm implements OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(JobNewForm.class); private CommissionNumberLayout commissionNumberLayout; private AppCompatCheckBox unknownCheckBox; private StepperLayout stepper; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; vbeln = formArguments.getComNo(); job = formArguments.getJob(); objectAddress = job.getObjectAddress(); partnerAddress = job.getPartnerAddress(); job.setCommissionNumber(vbeln); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobSearchForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); view.addView(createStepView()); return view; } private View createStepView() { StepUtil commissionNumberStep = new StepUtil(createCommissionNumberView(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(unknownCheckBox.isChecked()) { job = new Job(); return null; } else { if(commissionNumberLayout.getCommissionNumber().length() == 0) { return new VerificationError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ } else { commissionNumberLayout.clearError(); } stepper.setNextButtonEnabled(false); runCreateOrder(); return new VerificationError(""); //$NON-NLS-1$ } } @Override public void onSelected() { //update UI when selected saveButton.setVisible(false); } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText commissionNumberLayout.setError(error.getErrorMessage()); stepper.setNextButtonEnabled(true); } }); StepUtil jobContentStep = new StepUtil(createJobDetailNewEditView(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(isValid()) { stepper.setCompleteButtonEnabled(false); onSave(); return null; } else { return new VerificationError(""); //$NON-NLS-1$ } } @Override public void onSelected() { //update UI when selected // MIG-220 "Form of Address" filed (Anrede) is not mandatory on the GUI "create order" street.setRequired(true); zip.setRequired(true); city.setRequired(true); } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText } }); StepAdapter myStepAdapter = new StepAdapter(context, commissionNumberStep, jobContentStep); // create a mobile stepper with 'dot' progress stepper = new StepperLayout.Builder(context) .setStepperType(AbstractStepperType.DOTS).create(); // link layout to step adapter stepper.setAdapter(myStepAdapter); return stepper; } private void runCreateOrder() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { job = new RemoteTransactionHandler() .runCreateOrder(personalNumber, commissionNumberLayout.getCommissionNumber()); if(job == null) { return null; } job.calculateActiveDate(); log.info("Received job from server with status " + job.getStatus().getCode() + " comNo. " + job.getCommissionNumber()); //$NON-NLS-1$ //$NON-NLS-2$ app.showMessage("create order success."); //$NON-NLS-1$ new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); // Calendar calendar = Calendar.getInstance(); // calendar.set(Calendar.MONTH, +2); // job.setDateTime(calendar.getTime()); // app.dbutil.updateJob(job); return app.leaveToForm(JobListForm.class); } @Override public void runOnUIThread() { if(job == null) { commissionNumberLayout.setError(ServiceMessages.getString("CannotCreateOrder")); } } }; } private View createCommissionNumberView(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); // Commission Number commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, contentLinearLayout, true); //$NON-NLS-1$ commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); commissionNumberLayout.setJobTypeAndFormat(new JobType(JobType.REP), app.dbutil.getUser().getCommunicationNumberFormat()); // Unknown checkBox unknownCheckBox = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("unknown")); //$NON-NLS-1$ unknownCheckBox.setChecked(false); unknownCheckBox.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { if (((AppCompatCheckBox) v).isChecked()) { commissionNumberLayout.setEnabled(false); commissionNumberLayout.setRequired(false); commissionNumberLayout.clear(); //$NON-NLS-1$ commissionNumberLayout.clearError(); } else { commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); commissionNumberLayout.getCommissionNumberText().requestFocus(); } } }); contentLinearLayout.addView(unknownCheckBox); return contentLinearLayout; } @Override public void loadData() { // set dialog's title super.loadData(); setFormTitle(ServiceMessages.getString("createREPJob")); //$NON-NLS-1$ Person user = app.dbutil.getUser(); personalNumber = user.getPersonalNumber(); commissionFormat = user.getCommunicationNumberFormat(); commissionNumberLayout.setJobTypeAndFormat(new JobType(JobType.REP), commissionFormat); } @Override public void onFormReset() { super.onFormReset(); stepper.setCurrentStepPosition(0); commissionNumberLayout.clearError(); commissionNumberLayout.clear(); unknownCheckBox.setChecked(false); commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); stepper.setNextButtonEnabled(true); stepper.setCompleteButtonEnabled(true); } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { createNewJob(); assignToObject(); log.info("active date " + job.getActiveJobDate()); app.dbutil.insertJob(job); log.info("Save order with status " + job.getStatus().getCode()); //$NON-NLS-1$ job.loadAddresses(app.dbutil); job.loadReports(app.dbutil); log.info("save order PARANMNR " + job.getPartnerAddressId() + " OBJNR " + job.getObjectAddressId()); log.info("address PARANMNR " + job.getPartnerAddress().getPartnerNummer() + " OBJNR " + job.getObjectAddress().getPartnerNummer()); if(new RemoteTransactionHandler().runSaveOrder(job, null)) { new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } return onBackPressed(); } }; return true; } private void createNewJob() { try { GuidGenerator generator = new GuidGenerator(); // prepare a new GUID for the next report (will be committed // to the DB if the transaction is successful only) job.setCurrentReportGuId(generator.generate()); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } String mldnr = null; String parnrJob = null; String parnrParanmnr = null; while (!checkDbKeys(mldnr, parnrJob, parnrParanmnr)) { mldnr = "$" + CommonConstants.randomInt(9); //$NON-NLS-1$ parnrJob = "$" + CommonConstants.randomInt(9); //$NON-NLS-1$ parnrParanmnr = "$" + CommonConstants.randomInt(9); //$NON-NLS-1$ // if (log.isDebugEnabled()) { log.info("Generierte Keys: MLDNR:" + mldnr + ", PARNR(Job):" + parnrJob + ", PARNR(Paranmnr):" + parnrParanmnr); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } // } job.setJobNumber(mldnr); job.setJobType(JobType.REP); job.setPriority("1"); //$NON-NLS-1$ job.setStatus(JobStatus.INITIAL); // for address objectAddress.setChangeFlag(true); objectAddress.setPartnerNummer(parnrJob); //$NON-NLS-1$ objectAddress.setJobNumber(job.getJobNumber()); objectAddress.setJobType(job.getJobType()); job.setIdObjectAddress(objectAddress); partnerAddress.setChangeFlag(true); partnerAddress.setPartnerNummer(parnrParanmnr); //$NON-NLS-1$ partnerAddress.setJobNumber(job.getJobNumber()); partnerAddress.setJobType(job.getJobType()); job.setIdByPartnerAddress(partnerAddress); } public static class FormArguments { private boolean isNewJob; private String comNo; private Job job; private Address objectAddress; private Address partnerAddress; protected FormArguments() { } protected FormArguments(Job job) { } public FormArguments(boolean isNewJob, String comNo, Job job, Address objectAddress, Address partnerAddress) { this.isNewJob = isNewJob; this.comNo = comNo; this.job = job; this.objectAddress = objectAddress; this.partnerAddress = partnerAddress; } public boolean isNewJob() { return isNewJob; } public String getComNo() { return comNo; } public Job getJob() { return job; } public Address getObjectAddress() { return objectAddress; } public Address getPartnerAddress() { return partnerAddress; } } } package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobSearchListForm.JobSearchListFormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; /** * @author nop (20-04-2017) * * @see "[MIG-52] implement of "search job"" */ public class JobSearchForm extends SuperForm implements OnItemSelectedListener, OnClickListener { private static Log log = LogFactory.getLog(JobSearchForm.class); private MDSpinner jobTypeValue; private MDEditText jobNumber; private CommissionNumberLayout commissionNumberLayout; private MDEditText street; private MDEditText zip; private MDEditText city; private MDSpinner month; private MDSpinner year; private AppCompatButton scanButton; private String jobType; private Map jobSearchMap = new HashMap<>(); private String communicationNumberFormat; private static final String COMMISSION_NUMBER = "commissionNumber"; //$NON-NLS-1$ @Override public void onFormCall(Object argument) { if (argument instanceof JobSearchFormArguments) { JobSearchFormArguments formArguments = (JobSearchFormArguments) argument; this.jobType = formArguments.getJobType(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobListForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create add action ActionCtrl addAction = addActionCtrl(false, true, 1, "addAction"); //$NON-NLS-1$ addAction.setTitle(ServiceMessages.getString("add")); //$NON-NLS-1$ addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE))); // create reset action ActionCtrl resetAction = addActionCtrl(false, true, 1, "resetAction"); //$NON-NLS-1$ resetAction.setTitle(Messages.getString("reset")); //$NON-NLS-1$ resetAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.RESTORE_WHITE))); // create search action ActionCtrl searchAction = addActionCtrl(false, true, 1, "searchAction"); //$NON-NLS-1$ searchAction.setTitle(ServiceMessages.getString("search")); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.YOUTUBE_SEARCHED_WHITE))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); // job type jobTypeValue = MDSpinner.createDefaultSpinner(contentLinearLayout, Messages.getString("typeOfJob"), //$NON-NLS-1$ true); jobTypeValue.setTag("JOBTYPE"); //$NON-NLS-1$ jobTypeValue.setOnItemSelectedListener(this); jobNumber = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("jobNumber"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); jobNumber.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); // Commission Number commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, contentLinearLayout, false); // Street./No. street = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("streetOrNumber"), //$NON-NLS-1$ InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); street.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SIXTY) }); // ZIP zip = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("zip"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); zip.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); // City city = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("city"), //$NON-NLS-1$ InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); city.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout monthYearLinearLayout = new LinearLayout(context); LinearLayout.LayoutParams monthYearLinearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); monthYearLinearLayoutParams.topMargin = 0; monthYearLinearLayout.setLayoutParams(monthYearLinearLayoutParams); monthYearLinearLayout.setOrientation(LinearLayout.HORIZONTAL); monthYearLinearLayout.setPadding(0, 0, 0, 0); contentLinearLayout.addView(monthYearLinearLayout); month = MDSpinner.createDefaultSpinner(monthYearLinearLayout, ServiceMessages.getString("month"), false); //$NON-NLS-1$ month.setTag("MONTH"); //$NON-NLS-1$ LinearLayout.LayoutParams monthParams = (LayoutParams) ((LinearLayout) month.getParent()).getLayoutParams(); monthParams.gravity = Gravity.CENTER | Gravity.START; monthParams.weight = 0.5f; month.setOnItemSelectedListener(this); year = MDSpinner.createDefaultSpinner(monthYearLinearLayout, ServiceMessages.getString("year"), false); //$NON-NLS-1$ year.setTag("YEAR"); //$NON-NLS-1$ LinearLayout.LayoutParams yearParams = (LayoutParams) ((LinearLayout) year.getParent()).getLayoutParams(); yearParams.gravity = Gravity.CENTER | Gravity.END; yearParams.weight = 0.5f; year.setOnItemSelectedListener(this); // Scan Button LinearLayout scanButtonLinearLayout = new LinearLayout(context); scanButtonLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); scanButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); scanButton = new AppCompatButton(context); LinearLayout.LayoutParams scanButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); scanButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; scanButtonParams.topMargin = LayoutUtils.convertDpToPixel(context, 16); scanButton.setLayoutParams(scanButtonParams); scanButton.setText(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanButton.setOnClickListener(this); scanButton.setBackgroundDrawable(gradientDrawable); scanButtonLinearLayout.addView(scanButton); contentLinearLayout.addView(scanButtonLinearLayout); ScrollView scroll = new ScrollView(context); scroll.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scroll.addView(contentLinearLayout); relativeLayout.addView(scroll); view = new LinearLayout(context); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); jobSearchMap.clear(); // set dialog's title setFormTitle(ServiceMessages.getString("searchJob")); //$NON-NLS-1$ fillJobTypeCombo(); fillMonthCombo(); fillYearCombo(); communicationNumberFormat = app.dbutil.getUser().getCommunicationNumberFormat(); if (jobTypeValue.getSelectedItemPosition()==0) { reset(false); } else { setFieldsState(jobTypeValue.getSelectedName()); } return null; } @SuppressWarnings("unused") private ApplicationEvent addAction() { hideSoftInputFromWindow(); reset(false); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { ch.mfiles.kaba.kolibri.service.forms.JobNewForm.FormArguments formArguments = new JobNewForm.FormArguments( true, "", new Job(), new Address(), new Address()); //$NON-NLS-1$ return appman.getActiveApplication().callForm(JobNewForm.class, formArguments); } }, false); return null; } @SuppressWarnings("unused") private ApplicationEvent resetAction() { hideSoftInputFromWindow(); app.dbutil.deleteAllServerJob(); reset(true); return null; } @SuppressWarnings("unused") private ApplicationEvent searchAction() { hideSoftInputFromWindow(); if (isValid()) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (JobType.REP.equals(jobTypeValue.getSelectedName())) { if (new RemoteTransactionHandler().runGetOrder(jobNumber.getText().toString() , jobTypeValue.getSelectedName() , app.dbutil.getUser().getPersonalNumber()).getStatus() == RemoteTransactionResult.Status.success) { StringBuilder builder = new StringBuilder(); String jobNr = jobNumber.getText().toString(); if(jobNr.length() < 10) { for (int i = 0; i < 10 - jobNr.length(); i++) { builder.append("0"); } jobNr = builder.toString() + jobNr; } Job job = app.dbutil.selectJobByJobIdAndJobType(jobNr, jobTypeValue.getSelectedName()); job.calculateActiveDate(); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); return app.leaveToForm(JobListForm.class); } } else { JobSearchCriteria jobSearchCriteria = getJobSearchCriteria(); app.dbutil.deleteAllServerJob(); String vbeln = jobSearchCriteria.getCommissionNumber(); if (new RemoteTransactionHandler().runGetOrderList( jobSearchCriteria.getJobNumber(), app.dbutil.getUser().getPersonalNumber(), jobSearchCriteria.getJobType() , vbeln.trim() , jobSearchCriteria.getStreet().trim() , jobSearchCriteria.getCity().trim() , jobSearchCriteria.getZip().trim(), "", //$NON-NLS-1$ jobSearchCriteria.getMonth() + "/" + jobSearchCriteria.getYear().substring(2, 4))) { //$NON-NLS-1$ return app.leaveToForm(JobSearchListForm.class, new JobSearchListFormArguments(jobSearchCriteria.getJobType())); } } return null; } }; } return null; } @Override protected boolean isValid() { boolean result = super.isValid(); if (jobTypeValue.getSelectedItemPosition() == 0) { jobTypeValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } if (jobTypeValue.getSelectedName().equalsIgnoreCase(JobType.SAV) && month.getSelectedItemPosition() != 0 && year.getSelectedItemPosition() == 0) { year.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } return result; } public void reset(boolean isResetJobType) { super.onFormReset(); jobNumber.getText().clear(); commissionNumberLayout.clear(); street.getText().clear(); zip.getText().clear(); city.getText().clear(); if (isResetJobType) { jobTypeValue.clearContents(); fillJobTypeCombo(); } month.clearContents(); fillMonthCombo(); year.clearContents(); fillYearCombo(); setEnableAndVisibility(false); month.setSelection(0); year.setEnabled(false); jobNumber.setEnabled(false); commissionNumberLayout.setEnabled(false); } private void setEnableAndVisibility(boolean enabled) { street.setEnabled(enabled); zip.setEnabled(enabled); city.setEnabled(enabled); month.setEnabled(enabled); if (!month.isEnabled()) { month.setSelection(0); } year.setEnabled(enabled); int visibility = View.VISIBLE; if (!enabled) { visibility = View.GONE; } scanButton.setVisibility(visibility); } private void setFieldsState(String jobName) { jobType = jobTypeValue.getSelectedName(); commissionNumberLayout.setJobTypeAndFormat(new JobType(jobType), communicationNumberFormat); jobNumber.setEnabled(false); jobNumber.setRequired(false); commissionNumberLayout.setEnabled(false); commissionNumberLayout.setRequired(false); if (JobType.MON.equals(jobName) || JobType.SAV.equals(jobName)) { if (JobType.SAV.equals(jobName)) { year.setSelection(2); setEnableAndVisibility(true); } else { year.setSelection(0); setEnableAndVisibility(false); } commissionNumberLayout.setHint(ServiceMessages.getString(COMMISSION_NUMBER)); commissionNumberLayout.clearError(); commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(false); if (JobType.SAV.equals(jobName)) { jobNumber.clearError(); jobNumber.setEnabled(true); } } else if (JobType.REP.equals(jobName)) { jobNumber.clearError(); jobNumber.setEnabled(true); jobNumber.setRequired(true); } else { setEnableAndVisibility(false); month.setSelection(0); year.setEnabled(false); } } @Override public void clearErrorMessages() { super.clearErrorMessages(); jobTypeValue.clearError(); commissionNumberLayout.clearError(); year.clearError(); } private void fillJobTypeCombo() { if (jobTypeValue.getAdapter() == null) { List jobTypeValueList = new ArrayList(); Iterator itr = app.enumUtil.jobTypeEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); jobTypeValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } jobTypeValue.setContents(jobTypeValueList); } } private void fillMonthCombo() { if (month.getAdapter() == null) { List monthList = new ArrayList(); Iterator itr = app.enumUtil.monthEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); monthList.add(new CustomSpinnerItem((String) entry.getKey(), monthList.isEmpty() ? "-" : (String) entry.getValue())); //$NON-NLS-1$ } month.setContents(monthList); } } private void fillYearCombo() { if (year.getAdapter() == null) { List yearList = new ArrayList(); yearList.add(new CustomSpinnerItem("0000", "-")); //$NON-NLS-1$ //$NON-NLS-2$ int currentYear = GregorianCalendar.getInstance().get(GregorianCalendar.YEAR); for (int i = currentYear - 1; i < currentYear + 2; i++) { yearList.add(new CustomSpinnerItem(Integer.toString(i), Integer.toString(i))); } year.setContents(yearList); } } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("JOBTYPE".equals(parent.getTag())) { if(!StringUtil.isEmpty(jobType) && !jobType.equalsIgnoreCase(jobTypeValue.getSelectedName())) { jobSearchMap.put(jobType, getJobSearchCriteria()); } jobTypeValue.clearError(); reset(false); setFieldsState(jobTypeValue.getSelectedName()); scanButton.setEnabled(jobType.equalsIgnoreCase(JobType.SAV) ? true:false); if(jobSearchMap.containsKey(jobTypeValue.getSelectedName())) { loadJobSearchCriteria(jobSearchMap.get(jobTypeValue.getSelectedName())); } } else if ("YEAR".equals(parent.getTag())) { year.clearError(); } } @Override public void onNothingSelected(AdapterView arg0) { // do nothing } private JobSearchCriteria getJobSearchCriteria() { JobSearchCriteria result = new JobSearchCriteria(); result.setJobType(jobTypeValue.getSelectedName()); result.setJobNumber(jobNumber.getText().toString()); result.setCommissionNumber(commissionNumberLayout.getCommissionNumber()); result.setStreet(street.getText().toString()); result.setZip(zip.getText().toString()); result.setCity(city.getText().toString()); result.setMonth(month.getSelectedId()); result.setYear(year.getSelectedId()); return result; } private void loadJobSearchCriteria(JobSearchCriteria jobSearchCriteria) { jobNumber.setText(jobSearchCriteria.getJobNumber()); commissionNumberLayout.setText(jobSearchCriteria.getCommissionNumber()); street.setText(jobSearchCriteria.getStreet()); zip.setText(jobSearchCriteria.getZip()); city.setText(jobSearchCriteria.getCity()); month.setSelectionById(jobSearchCriteria.getMonth()); year.setSelectionById(jobSearchCriteria.getYear()); } /** * The Job Search Form Arguments Class. * * @author nop */ public static class JobSearchFormArguments { private String jobType; public JobSearchFormArguments(String jobType) { this.jobType = jobType; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } } private class JobSearchCriteria { private volatile String jobType; private volatile String jobNumber; private volatile String commissionNumber; private volatile String street; private volatile String zip; private volatile String city; private volatile String month; private volatile String year; public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public String getCommissionNumber() { return commissionNumber; } public void setCommissionNumber(String commissionNumber) { this.commissionNumber = commissionNumber; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } } @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String commissionNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ return null; } else { app.showMessage(result.toString()); commissionNumber = result.getContents(); log.info("scan result -> " + commissionNumber); //$NON-NLS-1$ commissionNumberLayout.setText(commissionNumber); } return null; } }; } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; public class CalendarToolbarTitleText { private CalendarMonthTitleState titleState = new CalendarMonthTitleState(); public String updateVisibleMonthTitle(Date date) { if (!titleState.updateVisibleMonth(date)) { return null; } return DateTimeUtil.showMonthNameYear(date); } } package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import junit.framework.TestCase; public class CalendarToolbarTitleTextTest extends TestCase { public CalendarToolbarTitleTextTest(String name) { super(name); } public void testReturnsMonthTitleForFirstVisibleMonth() { CalendarToolbarTitleText titleText = new CalendarToolbarTitleText(); Date date = date(2026, Calendar.JULY, 1); assertEquals(DateTimeUtil.showMonthNameYear(date), titleText.updateVisibleMonthTitle(date)); } public void testDoesNotReturnTitleForSameVisibleMonth() { CalendarToolbarTitleText titleText = new CalendarToolbarTitleText(); titleText.updateVisibleMonthTitle(date(2026, Calendar.JULY, 1)); assertNull(titleText.updateVisibleMonthTitle(date(2026, Calendar.JULY, 31))); } public void testReturnsMonthTitleWhenVisibleMonthChanges() { CalendarToolbarTitleText titleText = new CalendarToolbarTitleText(); titleText.updateVisibleMonthTitle(date(2026, Calendar.JULY, 31)); Date nextMonth = date(2026, Calendar.AUGUST, 1); assertEquals(DateTimeUtil.showMonthNameYear(nextMonth), titleText.updateVisibleMonthTitle(nextMonth)); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } } package ch.mfiles.kaba.kolibri.common.forms.adapters; import java.util.List; import android.content.Context; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; public class CustomSpinnerAdapter extends ArrayAdapter { private final List spinnerList; private SpinnerTextStyle closedViewTextStyle = SpinnerTextStyle.none(); public CustomSpinnerAdapter(Context context, int textViewResourceId, List spinnerList) { this(context, textViewResourceId, spinnerList, SpinnerTextStyle.none()); } public CustomSpinnerAdapter(Context context, int textViewResourceId, List spinnerList, SpinnerTextStyle closedViewTextStyle) { super(context, textViewResourceId, spinnerList); this.spinnerList = spinnerList; setClosedViewTextStyle(closedViewTextStyle); } // Affects default (closed) state of the spinner @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); closedViewTextStyle.applyTo(view); CustomSpinnerItem customSpinner = spinnerList.get(position); view.setText(customSpinner.getName()); return view; } // Affects opened state of the spinner @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getDropDownView(position, convertView, parent); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); view.setTypeface(CommonConstants.Font.getDefaultRegularFont()); return view; } public void setClosedViewTextStyle(SpinnerTextStyle closedViewTextStyle) { if (closedViewTextStyle == null) { this.closedViewTextStyle = SpinnerTextStyle.none(); return; } this.closedViewTextStyle = closedViewTextStyle; } /** * Gets Item Position. * * @param input * @return */ public int getPosition(String input) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if (input.equals(customSpinner.getId()) || input.equals(customSpinner.getName())) { return i; } } return 0; } /** * Gets Item Position By Id. * * @param id * @return */ public int getPositionById(String id) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if (id.equals(customSpinner.getId())) { return i; } } return 0; } /** * Gets Item Position By Name. * * @param id * @return */ public int getPositionByName(String name) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if (name.equals(customSpinner.getName())) { return i; } } return 0; } /** * Gets Item Position By Description. * * @param id * @return */ public int getPositionByDescription(String description) { for (int i = 0; i < spinnerList.size(); i++) { CustomSpinnerItem customSpinner = spinnerList.get(i); if ((customSpinner.getDescription() != null && description.equals(customSpinner.getDescription()))) { return i; } } return 0; } } package ch.mfiles.kaba.kolibri.service.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; public class ServiceJobUtil { private static Log log = LogFactory.getLog(ServiceJobUtil.class); ServiceJobUtil() { } /** * Checks whether the remaining report requires the job to return to partly * done after a newer report was deleted. * * @param job job whose reports have already been reloaded after deletion * @return {@code true} when the latest remaining report was sent as partial */ public static boolean shouldRestorePartlyDoneAfterReportDeletion(Job job) { Report report = job.getLatestReport(); return report != null && report.getReportStatus().isReceived() && report.isPartialRepair(); } /** * Checks Is Job Acceptable. * * @param job * @return */ public static boolean isJobAcceptable(Job job) { return job.getStatus().isNew(); } /** * Checks Is Job Forwardable. * * To send a job forward to a partner, the job have to be in status NEW or RECEIVED or PARTLY_DONE; * forward a job to a partner isn't possible with another job status or job type REP. * The job cannot be forwarded too, if there is any report things added by user (time, material, report itself, messages). * * Forward of a job is new only possible for job type REP. * * A job cannot be forwarded if the user already have done followed inputs: * - Create a report * - Add report time * - Add report material * - Add report messages * @param job * @return */ public static boolean isJobForwardable(Job job) { return job.getJobType().isREP() && (job.getStatus().isNew() || job.getStatus().isPartlyDone() || (job.getStatus().isReceived() && isEmptyReportContent(job))); } /** * Checks Is Job can Delete. * * Check whether the order can be deleted: * - NEW -> delete (with SAP status 16 update) * - Accept -> delete (with SAP status 16 update) * - No times on the akt. rapport * - No unsolicited report * - REPEATED -> there is not * - RELEASED -> delete (without SAP status update) * - IN WORK -> do not delete * - COMPLETED -> delete (without SAP status update) * - PARTLED -> delete (with SAP status 16 update) * (if a report has already been sent, no more has opened and no time is running) * * A job cannot be deleted if the user already have done followed inputs: * - Create a report * - Add report time * - Add report material * - Add report messages * @param job * @return */ public static boolean isJobDeletable(Job job) { // Check whether the order can be deleted: // - NEW -> delete (with SAP status 16 update) // - Accept -> delete (with SAP status 16 update) // - No times on the akt. rapport // - No unsolicited report // - REPEATED -> there is not // - RELEASED -> delete (without SAP status update) // - IN WORK -> do not delete // - COMPLETED -> delete (without SAP status update) // - PARTLED -> delete (with SAP status 16 update) (if a report has already been sent, no more has opened and no time is running) boolean isJobDeletable = true; isJobDeletable = job.getStatus().isNew() || (job.getStatus().isReceived() && job.getCurrentReport().getReportStatus().isInitial()) || job.getStatus().isRejected() || job.getStatus().isForwarded() || job.getStatus().isFinalized() || (job.getStatus().isPartlyDone() && job.getCurrentReport().getReportStatus().isInitial()) || job.getStatus().isDeleted() ; return isJobDeletable && isEmptyReportContent(job); } public static boolean isEmptyReportContent(Job job) { List reportMatList = job.getLatestReport().getParts(); List reportTextList = job.getLatestReport().getMessages(); List reportTimeList = job.getLatestReport().getTimes(); boolean isEmptyMessage = true; for (int i = 0; i < reportTextList.size(); i++) { JobMessage jobMessage = reportTextList.get(i); if (!"".equals(jobMessage.getMessageId()) || !jobMessage.getFullText().isEmpty()) { isEmptyMessage = false; } } String jobContent = job.getJobNumber() + " " + job.getObjectAddress().getPostalCode(); if (job.getJobType().isMON()) { jobContent += " " + StringUtil.removeAllLeadingZero(job.getJobNumber()); } else { jobContent += " " + job.getCommissionNumber(); } boolean isEmptyReportContent = false; isEmptyReportContent = !job.getLatestReport().getReportStatus().isNew()/*new report*/ && reportMatList.isEmpty() && isEmptyMessage && (reportTimeList.isEmpty() || job.getLatestReport().getReportStatus().isReceived()); log.debug(jobContent + " time " + reportTimeList.size() + " report status " + job.getLatestReport().getReportStatus().toString() + " isEmptyReportContent " + isEmptyReportContent + " material " + reportMatList.size() + " isEmptyMessage " + isEmptyMessage); return isEmptyReportContent; } /** * Checks is job start time able. * * @param job * @return */ public static boolean isJobStartTimeable(Job job) { return (job.getStatus().isReceived() || job.getStatus().isPartlyDone() || job.getStatus().isInProgress()); } /** * Checks Is Max Download. * * @param list * @return */ public static boolean isMaxDownload(List list) { return (list != null && list.size() > ServiceConstants.MAX_DOWNLOAD); } /** * Checks Is Max Confirm To Download. * * @param list * @return */ public static boolean isMaxConfirmDownload(List list) { return (list != null && list.size() > ServiceConstants.MAX_COMFIRM_DOWNLOAD); } /** * Checks Is valid job number. * * @see "[MIG-88] Integrate of SCAN-button in joblist" * * @param jobNumber * @return */ public static boolean isValidJobNumber(String jobNumber) { return StringUtil.isNotEmpty(jobNumber) && jobNumber.length() == 10; } /** * Checks Is job Editable. * * @see "[MIG-135] Edit of job informations is only possible by self created jobs" * * @param job * @return */ public static boolean isJobEditable(Job job) { return (job.isLocalJob() && job.getJobType().isREP()); } /** * Checks Is job can reschedule. * * @see "[MIG-349] Rescheduling of jobs" * * - RECEIVED\n * - PARTLY_DONE\n * @param job * @return */ public static boolean isJobRescheduleable(Job job) { return (job.getStatus().isReceived() || job.getStatus().isPartlyDone()); } /** * Checks Is valid ZIP. * * @see "[MIG-127] Validation of ZIP (PLZ)" * * @param zip * @return */ public static boolean isValidZIP(String zip) { return StringUtil.isNotEmpty(zip) && StringUtil.isNumeric(zip) && zip.length() == 5; } public static boolean isJobActive(Job job) { boolean isAppointmentDateInActive = false; Date today = new Date(); Calendar appointmentDateCalendar = Calendar.getInstance(); appointmentDateCalendar.setTime(job.getAppointmentDate()); if(job.getJobType().isSAV()) { appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(!appointmentDateCalendar.getTime().after(today)) { isAppointmentDateInActive = true; } appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, 90); if ((job.getStatus().isNew() || job.getStatus().isPartlyDone()) && !appointmentDateCalendar.before(today)) { isAppointmentDateInActive = true; } } else { appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(!appointmentDateCalendar.getTime().after(today)) { isAppointmentDateInActive = true; } appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, 3); if ((job.getStatus().isNew() || (job.getStatus().isPartlyDone()) && !appointmentDateCalendar.getTime().after(today))) { isAppointmentDateInActive = true; } } boolean isActiveJobDateInActive = false; Calendar activeDateCalendar = Calendar.getInstance(); activeDateCalendar.setTime(job.getActiveJobDate()); if(job.getJobType().isSAV()) { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(!activeDateCalendar.getTime().after(today)) { isActiveJobDateInActive = true; } } else { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(!activeDateCalendar.getTime().after(today)) { isActiveJobDateInActive = true; } } boolean isJobStatusActive = false; JobStatus status = job.getStatus(); isJobStatusActive = status.isNew() || status.isReceived() || status.isInProgress() || status.isPartlyDone(); log.info("isJobStatusActive " + isJobStatusActive + " isEdateInActive " + isAppointmentDateInActive + " isActiveJobDateInActive " + isActiveJobDateInActive); isJobStatusActive = isJobStatusActive && (isAppointmentDateInActive && isActiveJobDateInActive) || (!isEmptyReportContent(job) && isJobStatusActive); log.info("This job is in Active -> " + isJobStatusActive); return isJobStatusActive; } public static boolean isJobInPlanned(Job job) { boolean isEdateInPlaned = false; Date today = new Date(); Calendar edateCalendar = Calendar.getInstance(); edateCalendar.setTime(job.getAppointmentDate()); if(job.getJobType().isSAV()) { edateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(edateCalendar.getTime().getTime() >= today.getTime()) { isEdateInPlaned = true; } } else { edateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(edateCalendar.getTime().getTime() >= today.getTime()) { isEdateInPlaned = true; } } boolean isActiveJobDateInPlaned = false; Calendar activeDateCalendar = Calendar.getInstance(); activeDateCalendar.setTime(job.getActiveJobDate()); if(job.getJobType().isSAV()) { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(activeDateCalendar.getTime().getTime() >= today.getTime()) { isActiveJobDateInPlaned = true; } } else { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(activeDateCalendar.getTime().getTime() >= today.getTime()) { isActiveJobDateInPlaned = true; } } boolean isJobStatusPlanned = false; JobStatus status = job.getStatus(); isJobStatusPlanned = status.isReceived() || status.isPartlyDone(); log.info("isJobStatusPlaned " + isJobStatusPlanned + " isEdateInPlaned " + isEdateInPlaned + " isActiveJobDateInPlaned " + isActiveJobDateInPlaned); isJobStatusPlanned = isJobStatusPlanned && (isEdateInPlaned || isActiveJobDateInPlaned) && isEmptyReportContent(job); log.info("This job is in planned -> " + isJobStatusPlanned); if (!isJobStatusPlanned) { log.info("EDATE -> " + DateTimeUtil.showDate(job.getAppointmentDate())); log.info("ACTIVE_DATE -> " + DateTimeUtil.showDate(job.getActiveJobDate())); log.info("today-------" + DateTimeUtil.showDate(today) ); log.info("edate-------" + DateTimeUtil.showDate(edateCalendar.getTime()) ); log.info("active date-" + DateTimeUtil.showDate(activeDateCalendar.getTime()) ); } return isJobStatusPlanned; } public static boolean isJobFinalized(Job job) { return job.getStatus().isForwarded() || job.getStatus().isFinalized(); } /** * Checks is JobReportTime overlapping * * * @param jobReportTimeList * @param newJobReportTime * @return */ public static List isJobTimesheetOverlapping(List jobReportTimeList, String start, String stop) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setStartTime(DateTimeUtil.parseDateFromHHmm(start, DateTimeUtil.getToday().getTime())); newJobTime.setStopTime(DateTimeUtil.parseDateFromHHmm(stop, DateTimeUtil.getToday().getTime())); return isJobTimesheetOverlapping(jobReportTimeList, newJobTime); } /** * Checks is JobReportTime overlapping * * * @param jobReportTimeList * @param newJobReportTime * @return */ public static List isJobTimesheetOverlapping(List jobReportTimeList, JobReportTime newJobReportTime) { List overlappingJobReportTimeList = new ArrayList(); for (JobReportTime jobReportTime : jobReportTimeList) { boolean isStartBefor = newJobReportTime.getStartTime().before(jobReportTime.getStartTime()); boolean isStopAfter = newJobReportTime.getStopTime().after(jobReportTime.getStopTime()); boolean isStartOverlapping = (newJobReportTime.getStartTime().compareTo(jobReportTime.getStartTime()) > 0) && (newJobReportTime.getStartTime().compareTo(jobReportTime.getStopTime()) < 0); boolean isStopOverlapping = (newJobReportTime.getStopTime().compareTo(jobReportTime.getStopTime()) < 1) && (newJobReportTime.getStopTime().compareTo(jobReportTime.getStartTime()) > 0);; if (isStartOverlapping || isStopOverlapping) { overlappingJobReportTimeList.add(jobReportTime); } if (isStartBefor && isStopAfter) { overlappingJobReportTimeList.add(jobReportTime); } } if (overlappingJobReportTimeList.size() > 0) { Object[] arguments = new Object[] { DateTimeUtil.showTime(newJobReportTime.getStartTime()) + " - " + DateTimeUtil.showTime(newJobReportTime.getStopTime()) , DateTimeUtil.showTime(overlappingJobReportTimeList.get(0).getStartTime()) + " - " + DateTimeUtil.showTime(overlappingJobReportTimeList.get(0).getStopTime())}; log.info(MessageFormat.format(Messages.getString("overlapping"), arguments)); } return overlappingJobReportTimeList; } /** * Checks If report has doc that require for job. * * @param job * @param jobFileList * @param reportImageAttachmentsList * * @return list of formDesc code that require for the job, report. */ public static List isReportDocsComplete(Job job) { boolean isFormDesc1Valid = false; boolean isFormDesc2Valid = false; boolean isFormDesc3Valid = false; boolean isSecurityReportValid = false; boolean isModernisationNecessaryValid = false; boolean isSecurityReportRequire = false; boolean isModernisationNecessaryRequire = false; isModernisationNecessaryRequire = isMandatoryByReportMessage(job); isModernisationNecessaryValid = !isModernisationNecessaryRequire; isSecurityReportRequire = job.getLatestReport().isSafetyReport(); isSecurityReportValid = !isSecurityReportRequire; log.info("comNo " + job.getCommissionNumber() + " FormDesc1 " + job.getFormDesc1() + " FormDesc2 " + job.getFormDesc2() + " FormDesc3 " + job.getFormDesc3()); Map> documentFormDescMap = job.getLatestReport().getDocumentFormDescMap(); if (documentFormDescMap.containsKey(ServiceConstants.ModernisationNecessary)) { if (isModernisationNecessaryRequire) { isModernisationNecessaryValid = true; } } if (documentFormDescMap.containsKey(job.getFormDesc1())) { if (isDocumentOrNoFormValid(job.getFormDesc1(), documentFormDescMap.get(job.getFormDesc1()), job.getLatestReport().getNoForm1())) { isFormDesc1Valid = true; } } if (documentFormDescMap.containsKey(job.getFormDesc2())) { if (isDocumentOrNoFormValid(job.getFormDesc2(), documentFormDescMap.get(job.getFormDesc2()), job.getLatestReport().getNoForm2())) { isFormDesc2Valid = true; } } if (documentFormDescMap.containsKey(job.getFormDesc3())) { if (isDocumentOrNoFormValid(job.getFormDesc3(), documentFormDescMap.get(job.getFormDesc3()), job.getLatestReport().getNoForm3())) { isFormDesc3Valid = true; } } if (documentFormDescMap.containsKey(ServiceConstants.SecurityReport)) { if (isSecurityReportRequire) { isSecurityReportValid = true; } } for (FormInstance formInstance : job.getCurrentReport().getFormInstances()) { if (isGenericFormValid(ServiceConstants.ModernisationNecessary, formInstance) && !isModernisationNecessaryValid) { isModernisationNecessaryValid = true; } if (isGenericFormValid(job.getFormDesc1(), formInstance) && !isFormDesc1Valid) { isFormDesc1Valid = true; } if (isGenericFormValid(job.getFormDesc2(), formInstance) && !isFormDesc2Valid) { isFormDesc2Valid = true; } if (isGenericFormValid(job.getFormDesc3(), formInstance) && !isFormDesc3Valid) { isFormDesc3Valid = true; } if (isGenericFormValid(ServiceConstants.SecurityReport, formInstance) && !isSecurityReportValid) { isSecurityReportValid = true; } } List result = new ArrayList(); if (!isModernisationNecessaryValid) { if (!result.contains(ServiceConstants.ModernisationNecessary)) result.add(ServiceConstants.ModernisationNecessary); } if (isJobRequireFormDesc(job.getFormDesc1()) && !isFormDesc1Valid) { result.add(job.getFormDesc1()); } if (isJobRequireFormDesc(job.getFormDesc2()) && !isFormDesc2Valid) { result.add(job.getFormDesc2()); } if (isJobRequireFormDesc(job.getFormDesc3()) && !isFormDesc3Valid) { result.add(job.getFormDesc3()); } if (!isSecurityReportValid) { result.add(ServiceConstants.SecurityReport); } if (!result.isEmpty()) log.info("result " + result); return result; } public static boolean isGenericFormValid(String formDesc, FormInstance formInstance) { if (isJobRequireFormDesc(formDesc) && formInstance.getFormId().substring(1, 3).contains(formDesc)) { return true; } return false; } public static boolean isDocumentOrNoFormValid(String formDesc, List documentImages, String noForm) { if (!documentImages.isEmpty() && isFormDescFileOrNoFormValid(formDesc, documentImages.get(0).getFormDesc(), noForm)) { return true; } else { return false; } } public static boolean isFormDescFileOrNoFormValid(String formDesc, String formDescFile, String noForm) { if (isJobRequireFormDesc(formDesc) && (formDesc.equalsIgnoreCase(formDescFile) || !noForm.isEmpty())) { return true; } return false; } private static boolean isJobRequireFormDesc(String formDesc) { if (!formDesc.isEmpty() && !formDesc.equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { return true; } return false; } public static boolean isJobRequireFormDesc(Job job) { if (isJobRequireFormDesc(job.getFormDesc1())) { return true; } if (isJobRequireFormDesc(job.getFormDesc2())) { return true; } if (isJobRequireFormDesc(job.getFormDesc3())) { return true; } return false; } public static boolean isJobRequireReportMessageToCustomer(Job job) { if (job.getJobType().isMON() || job.getJobType().isSAV()) { if (job.getLatestReport().getMessages().isEmpty()) { return true; } boolean isSavRequireReportMessage = true; for (JobMessage jobMessage : job.getLatestReport().getMessages()) { if (jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.CUSTOMER)) { log.info("MessageId " + jobMessage.getMessageId()); log.info("MessageCode " + jobMessage.getMessageCode() + " FullText " + jobMessage.getFullText()); if (job.getJobType().isMON()) { if (jobMessage.getMessageCode().isEmpty() && jobMessage.getFullText().isEmpty()) { return true; } return false; } else if (job.getJobType().isSAV()) { //ZKDCMSGC.KND = 1, ZKDMOBMSGC.TXT = 18 or 19 or 20 for job type (ZKDMOB.AUART) 'SAV' if (jobMessage.getMessageCode().equalsIgnoreCase(CommonConstants.Message.SYSTEM_IS_SAVE) || jobMessage.getMessageCode().equalsIgnoreCase(CommonConstants.Message.SYSTEM_WITH_MINOR_DEFECTS) || jobMessage.getMessageCode().equalsIgnoreCase(CommonConstants.Message.SYSTEM_EXHIBITS_DEFECTS)) { isSavRequireReportMessage = false; } } } } return isSavRequireReportMessage; } return false; } public static boolean isMandatoryByReportTime(Job job) { if (job.getJobType().isMON() && !job.getLatestReport().getTimes().isEmpty()) { for (JobReportTime jobReportTime : job.getLatestReport().getTimes()) { if (jobReportTime.getWorkTypeCode().equalsIgnoreCase(CommonConstants.Report.WORKTYPE_INSTALLATION)) { return true; } } } return false; } public static boolean isInstallationWorkTypeComplete(Job job) { if (isMandatoryByReportTime(job)) { if (job.getLatestReport().getImageAttachments().size() >= ServiceConstants.REQUIRE_IMAGE) { return true; } } else { return true; } return false; } public static boolean isChecklistComplete(Job job) { if (isMandatoryByReportTime(job)) { if (job.getLatestReport().isChedklistEdited()) { return true; } } else { return true; } return false; } public static boolean isMandatoryByReportMessage(Job job) { if (job.getJobType().isREP() || job.getJobType().isSAV()) { for (JobMessage jobMessage : job.getLatestReport().getMessages()) { log.info("MessageCode " + jobMessage.getMessageCode() + " FullText " + jobMessage.getFullText()); if ((jobMessage.getMessageCode().equalsIgnoreCase(ServiceConstants.ModernisationNecessary) || jobMessage.getMessageCode().equalsIgnoreCase(ServiceConstants.OfferModernisation))) { if (!jobMessage.getMessageCode().isEmpty() || !jobMessage.getFullText().isEmpty()) { return true; } } } } return false; } /** * Only the document type 01 and 02 and Job type 'SAV' and 'REP' needs images * * @param job * @return */ public static boolean isReportImageComplete(Job job) { log.info("isReportImageComplete "); boolean isReportImageRequireisByReportMessage = isMandatoryByReportMessage(job); boolean isReportImageRequireisByReportTime = isMandatoryByReportTime(job); log.info("isReportImageRequireisByReportMessage " + isReportImageRequireisByReportMessage); log.info("isReportImageRequireisByReportTime " + isReportImageRequireisByReportTime); log.info("isReportDocsComplete " + isReportDocsComplete(job)); if (!isReportDocsComplete(job).isEmpty()) { if (isReportDocsComplete(job).contains(ServiceConstants.ModernisationNecessary) || isReportDocsComplete(job).contains(ServiceConstants.OfferModernisation)) { isReportImageRequireisByReportMessage = true; } } log.info("isReportImageRequire " + isReportImageRequireisByReportMessage); log.info("ImageAttachments " + job.getLatestReport().getImageAttachments().size()); if (isReportImageRequireisByReportMessage) { if (!job.getLatestReport().getImageAttachments().isEmpty()) { return true; } } else { return true; } return false; } /** * The application have to check if there are more than 3 measurements in a measuring point. * @param reportMeasurementList * @return */ public static boolean isTooMuchMeasurementAreMadeForOnemeasurePoint(List reportMeasurementList) { Map> measurementMap = new HashMap>(); for (ReportMeasurement reportMeasurement : reportMeasurementList) { if (measurementMap.containsKey(reportMeasurement.getMeasurementPoint())) { measurementMap.get(reportMeasurement.getMeasurementPoint()).add(reportMeasurement); } else { measurementMap.put(reportMeasurement.getMeasurementPoint(), new ArrayList()); measurementMap.get(reportMeasurement.getMeasurementPoint()).add(reportMeasurement); } } for (List reportMeasurement : measurementMap.values()) { log.info("reportMeasurement size " + reportMeasurement.size()); if (reportMeasurement.size() > ServiceConstants.MAX_MEASUREMENT_FOR_ONE_POINT) { return true; } } return false; } public static String getTooMuchMeasurementAreMadeForOnemeasurePointMessage() { return MessageFormat.format(ServiceMessages.getString("MeasurementMaximum"), new Object[] { ServiceConstants.MAX_MEASUREMENT_FOR_ONE_POINT}); } public static boolean isReportFormVonoviaComplete(Job job) { if (job.getLatestReport().getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA)) { for (FormInstance formInstance : job.getLatestReport().getFormInstances()) { if (formInstance.getFormId().equalsIgnoreCase(CommonConstants.Report.FORM_VONOVIA)) { return true; } } return false; } else { return true; } } } package ch.mfiles.kaba.kolibri.service.forms.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil.JobStatusFilter; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.util.DateUtils; import junit.framework.TestCase; public class ServiceJobUtilTest extends TestCase { public ServiceJobUtilTest(String name) { super(name); } @Test public void testIsJobAcceptable() { // new assertEquals(true, ServiceJobUtil.isJobAcceptable(getJobObjectByStatus(JobStatus.NEW))); } @Test public void testIsJobForwardable() { Job newJob = getJobObjectByStatus(JobStatus.NEW); newJob.setJobType(JobType.REP); // new assertEquals(true, ServiceJobUtil.isJobForwardable(newJob)); newJob.setStatus(JobStatus.RECEIVED); // received assertEquals(true, ServiceJobUtil.isJobForwardable(newJob)); } @Test public void testIsJobDeletable() { // new assertEquals(true, ServiceJobUtil.isJobDeletable(getJobObjectByStatus(JobStatus.NEW))); // received assertEquals(true, ServiceJobUtil.isJobDeletable(getJobObjectByStatus(JobStatus.RECEIVED))); // partly done assertEquals(true, ServiceJobUtil.isJobDeletable(getJobObjectByStatus(JobStatus.PARLTY_DONE))); } @Test public void testIsJobStartTimeable() { // received assertEquals(true, ServiceJobUtil.isJobStartTimeable(getJobObjectByStatus(JobStatus.RECEIVED))); // in progress assertEquals(true, ServiceJobUtil.isJobStartTimeable(getJobObjectByStatus(JobStatus.IN_PROGRESS))); // partly done assertEquals(true, ServiceJobUtil.isJobStartTimeable(getJobObjectByStatus(JobStatus.PARLTY_DONE))); } @Test public void testIsMaxDownload() { assertEquals(true, ServiceJobUtil.isMaxDownload(getSelectedList())); assertEquals(false, ServiceJobUtil.isMaxDownload(new ArrayList())); } @Test public void testIsMaxConfirmDownload() { assertEquals(true, ServiceJobUtil.isMaxConfirmDownload(getSelectedList())); assertEquals(false, ServiceJobUtil.isMaxConfirmDownload(new ArrayList())); } /** * @see "[MIG-88] Integrate of SCAN-button in joblist" */ @Test public void testIsValidJobNumber() { String jobNumber = "0000434704"; //$NON-NLS-1$ // empty assertEquals(false, ServiceJobUtil.isValidJobNumber("")); //$NON-NLS-1$ // null assertEquals(false, ServiceJobUtil.isValidJobNumber(null)); // when the length < 10 assertEquals(9, jobNumber.substring(1).length()); assertEquals(false, ServiceJobUtil.isValidJobNumber(jobNumber.substring(1))); // when the length > 10 assertEquals(11, (jobNumber + "7").length()); //$NON-NLS-1$ assertEquals(false, ServiceJobUtil.isValidJobNumber(jobNumber + "7")); //$NON-NLS-1$ // valid job number, length == 10 assertEquals(10, jobNumber.length()); assertEquals(true, ServiceJobUtil.isValidJobNumber(jobNumber)); } /** * @see "[MIG-135] Edit of job informations is only possible by self created jobs" */ @Test public void testIsJobEditable() { Job newJob = getJobObjectByStatus(JobStatus.NEW); newJob.setJobNumber("$0000434704"); //$NON-NLS-1$ newJob.setJobType(JobType.REP); //self created jobs with the type REP. assertEquals(true, ServiceJobUtil.isJobEditable(newJob)); Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); //Isn't the job self created and/or has the type SAV / MON receivedJob.setJobType(JobType.SAV); assertEquals(false, ServiceJobUtil.isJobEditable(receivedJob)); receivedJob.setJobType(JobType.MON); assertEquals(false, ServiceJobUtil.isJobEditable(receivedJob)); receivedJob.setJobType(JobType.REP); assertEquals(false, ServiceJobUtil.isJobEditable(receivedJob)); } /** * @see "[MIG-150] Report edit, commission number: Show the comission number" */ @Test public void testReportCommissionNumberType() { Job job = getJobObjectByStatus(JobStatus.RECEIVED); Report report = job.getLatestReport(); // job commission number and report commission number are not the same. assertSame(CommonConstants.CommissionNumber.Type.INVALID, job.getReportCommissionNumberType()); report.setCommissionNumber(CommonConstants.CommissionNumber.DEFAULT); assertSame(CommonConstants.CommissionNumber.Type.UNKNOWN, job.getReportCommissionNumberType()); // job commission number and commission number are the same. report.setCommissionNumber(job.getCommissionNumber()); assertSame(CommonConstants.CommissionNumber.Type.CORRECT, job.getReportCommissionNumberType()); } private Job getJobObjectByStatus(String jobStatus) { Random random = new Random(); Job job = new Job(); job.setJobNumber(getSelectedList().get(random.nextInt(getSelectedList().size()))); //$NON-NLS-1$ job.setJobType(JobType.SAV); job.setPersonalNumber(99998); job.setStatus(jobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); Report reoprt = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ reoprt.setIdx(1); reoprt.setPersonalNumber(job.getPersonalNumber()); reoprt.setReportStatus(ReportStatus.INITIAL); ArrayList reports = new ArrayList(); reports.add(reoprt); job.setReports(reports); if(jobStatus == JobStatus.IN_PROGRESS) { job.getLatestReport().setReportStatus(ReportStatus.NEW); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); } if(jobStatus == JobStatus.PARLTY_DONE) { job.getCurrentReport().setReportStatus(ReportStatus.INITIAL); job.setStatus(JobStatus.PARLTY_DONE); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } if(jobStatus == JobStatus.FINALIZED) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); job.getCurrentReport().setCreateDate((job.getCurrentReport().getTimes().get(0)).getStartTime()); job.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); job.setStatus(JobStatus.FINALIZED); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } return job; } private List getSelectedList() { String[] data = {"0000434704","0000436584","0000436138","0000434318","0000434324" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000433101","0000436565","0000434729","0000757569","0000757825" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000757825","0000757826","0000434324","0000434324","0000434704" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000434704","0000757569","0000757569","0000434728","0000434729" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000436584","0000436585","0000436138","0000436139","0000434318" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000434319","0000776941","0000776942","0000776943","0000776944" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000776945","0000776946","0000776947","0000776948","0000776949"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ return Arrays.asList(data); } /** * @see "[MIG-167] Every job is displayed in the list for collective signature" */ @Test public void testCollectiveSignature() { List reportList = new ArrayList(); for (int i = 0; i < 6; i++) { Job newJob = getJobObjectByStatus(JobStatus.NEW); newJob.setJobNumber(getSelectedList().get(i)); //$NON-NLS-1$ Report report = newJob.getLatestReport(); if(i == 2 || i == 4) { report.setSignatureFlag(true); } reportList.add(report); } int singnatureCollectiveToShow = 0; for (Report report : reportList) { if(report.isSignatureFlag()) { singnatureCollectiveToShow ++; } } assertEquals(false, singnatureCollectiveToShow == 0); assertEquals(true, singnatureCollectiveToShow == 2); assertEquals(false, singnatureCollectiveToShow == reportList.size()-1); } /** * @see "[MIG-127] Validation of ZIP (PLZ)" */ @Test public void testIsValidZIP() { String zip = "12345"; //$NON-NLS-1$ // empty assertEquals(false, ServiceJobUtil.isValidZIP("")); //$NON-NLS-1$ // null assertEquals(false, ServiceJobUtil.isValidZIP(null)); // when the length < 5 assertEquals(4, zip.substring(1).length()); assertEquals(false, ServiceJobUtil.isValidZIP(zip.substring(1))); // when the length > 5 assertEquals(6, (zip + "5").length()); //$NON-NLS-1$ assertEquals(false, ServiceJobUtil.isValidZIP(zip + "5")); //$NON-NLS-1$ // valid job number, length == 5 assertEquals(5, zip.length()); assertEquals(true, ServiceJobUtil.isValidZIP(zip)); } /** * @see "[MIG-437] REP jobs disappears, if you start the report time while they're in filter "planned"" */ @Test public void testPlanedJob() { List jobList = getPlannedJobList(); for (int i = 0; i < jobList.size(); i++) { final Job job = jobList.get(i); assertTrue("This job is not in planned", ServiceJobUtil.isJobInPlanned(job)); } // Partly_Done and Active_Date => current date with report data Job job = jobList.get(jobList.size() -1); job.getCurrentReport().getParts().add(new ReportMaterial()); assertFalse("This job is still in planned", ServiceJobUtil.isJobInPlanned(job)); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); // 1. The user downloads a job and rescheduled it in the future. // -> The job stays with status received, but is now displayed in planned // 2. The user goes to planned filter and starts the report time // -> The status is changed from received to in_progress // -> Now the job is displayed in active // 3. He stops the time // -> The status is changed from in_progress to received (but with report data) // -> The job is still displayed in active // Received and Edate => current date Job planjob1 = getJobObjectByStatus(JobStatus.RECEIVED); planjob1.setJobType(JobType.REP); Calendar edateCalendar = DateTimeUtil.getTimestamp(); edateCalendar.add(Calendar.DAY_OF_YEAR, +4); planjob1.setActiveJobDate(edateCalendar.getTime()); assertFalse("This job is still in planned", ServiceJobUtil.isJobInPlanned(job)); Job receivedJob = jobList.get(jobList.size() -1); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(receivedJob.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); receivedJob.getCurrentReport().getTimes().add(newJobTime); // With started time assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); // Stopped job time receivedJob.getCurrentReport().getTimes().get(receivedJob.getCurrentReport().getTimes().size() - 1).setStopTime(DateTimeUtil.getNow().getTime()); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); // 1. The user downloads a job and send a report with "partly_done" to backend // -> The job changed the status from received / in_progress to partly_done // 2. The user rescheduled the job // -> The job stays in status partly_done and is displayed in planned // 3. Now the user starts the time from this job // -> The status is changed from partly_done to in_progress // -> It is displayed in active // 4. The user now stops the time // -> The status is changed from in_progress to partly_done (but with report data) // -> The job is still displayed in active // send report receivedJob.getCurrentReport().setCreateDate((receivedJob.getCurrentReport().getTimes().get(0)).getStartTime()); receivedJob.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); receivedJob.setStatus(JobStatus.PARLTY_DONE); receivedJob.setStatusEdit(new Date()); edateCalendar.add(Calendar.DAY_OF_YEAR, +4); receivedJob.setActiveJobDate(edateCalendar.getTime()); assertTrue("Job status not Partly done", receivedJob.getStatus().isPartlyDone()); assertFalse("This job is still in planned", ServiceJobUtil.isJobInPlanned(job)); newJobTime.setGuid(receivedJob.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); receivedJob.getCurrentReport().getTimes().add(newJobTime); receivedJob.getCurrentReport().setCreateDate((receivedJob.getCurrentReport().getTimes().get(receivedJob.getCurrentReport().getTimes().size()-1)).getStartTime()); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); receivedJob.getCurrentReport().getTimes().get(receivedJob.getCurrentReport().getTimes().size() - 1).setStopTime(DateTimeUtil.getNow().getTime()); assertTrue("Job status not Partly done", receivedJob.getStatus().isPartlyDone()); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); } private List getPlannedJobList() { List result = new ArrayList(); Calendar edateCalendar = DateTimeUtil.getTimestamp(); edateCalendar.add(Calendar.DAY_OF_YEAR, +4); // Received and Edate => current date Job planjob1 = getJobObjectByStatus(JobStatus.RECEIVED); planjob1.setJobType(JobType.REP); planjob1.setAppointmentDate(edateCalendar.getTime()); result.add(planjob1); // Received and Active_Date => current date Job planjob2 = getJobObjectByStatus(JobStatus.RECEIVED); planjob2.setJobType(JobType.REP); planjob2.setActiveJobDate(edateCalendar.getTime()); result.add(planjob2); // Partly_Done and Active_Date => current date Job planjob3 = getJobObjectByStatus(JobStatus.PARLTY_DONE); planjob3.setJobType(JobType.REP); planjob3.setActiveJobDate(edateCalendar.getTime()); result.add(planjob3); return result; } /** * * @param jobType * @param jobStatus * @param idleTimeFlag * @param isReschedule * @param isNewReport * @param isReportSent * @param jobStatusFilter */ public void checkJobFilter(String jobType, String jobStatus , boolean idleTimeFlag , boolean isReschedule , boolean isNewReport , boolean isReportSent , JobStatusFilter jobStatusFilter) { Random random = new Random(); Job job = new Job(); job.setJobNumber(getSelectedList().get(random.nextInt(getSelectedList().size()))); //$NON-NLS-1$ job.setJobType(jobType); job.setPersonalNumber(99998); job.setStatus(jobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); Calendar idleTime = DateTimeUtil.getTimestamp(); int idleTimeDays =0; if(jobType == JobType.SAV ) { if (idleTimeFlag) { idleTimeDays = 91; // idleTime.add(Calendar.DAY_OF_YEAR, +90); } else { idleTimeDays = -90; // idleTime.add(Calendar.DAY_OF_YEAR, -90); } } else { if (idleTimeFlag) { idleTimeDays = 4; // idleTime.add(Calendar.DAY_OF_YEAR, +3); } else { idleTimeDays = -3; // idleTime.add(Calendar.DAY_OF_YEAR, -3); } } idleTime.add(Calendar.DAY_OF_YEAR, idleTimeDays); if(isReschedule) { job.setJobRescheduleDate(idleTime.getTime()); job.setJobRescheduleTime(idleTime.getTime()); job.setAppointmentDate(idleTime.getTime()); job.calculateActiveDate(); } else { job.setAppointmentDate(idleTime.getTime()); } Report reoprt = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ reoprt.setIdx(1); reoprt.setPersonalNumber(job.getPersonalNumber()); reoprt.setReportStatus(ReportStatus.INITIAL); ArrayList reports = new ArrayList(); reports.add(reoprt); job.setReports(reports); if(jobStatus == JobStatus.RECEIVED) { job.calculateActiveDate(); } if(jobStatus == JobStatus.IN_PROGRESS) { job.getLatestReport().setReportStatus(ReportStatus.NEW); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); } if(isNewReport) { job.getLatestReport().setReportStatus(ReportStatus.NEW); } if(isReportSent) { if(jobStatus == JobStatus.PARLTY_DONE) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); job.getCurrentReport().setCreateDate((job.getCurrentReport().getTimes().get(0)).getStartTime()); job.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); job.setStatus(JobStatus.PARLTY_DONE); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } if(jobStatus == JobStatus.FINALIZED) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); job.getCurrentReport().setCreateDate((job.getCurrentReport().getTimes().get(0)).getStartTime()); job.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); job.setStatus(JobStatus.FINALIZED); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } } String resultMessage = "Job " + job.getJobNumber() + ", job type -> " + jobType + ", State -> " + jobStatus + ", idle time " + idleTimeDays + " days " + ", Rescheduled -> " + (isReschedule == true ?"YES":"NO") + ", Report -> " + (isNewReport == true ?"YES":"NO") + ", Sent -> " + (isReportSent == true ?"YES":"NO"); switch (jobStatusFilter) { case active: resultMessage += " --> Job filter -> ACTIVE."; assertTrue(resultMessage, ServiceJobUtil.isJobActive(job)); break; case planned: resultMessage += " --> Job filter -> PLANNED."; assertTrue(resultMessage, ServiceJobUtil.isJobInPlanned(job)); break; case finalized: resultMessage += " --> Job filter -> FINALIZED."; assertTrue(resultMessage, ServiceJobUtil.isJobFinalized(job)); break; default: break; } System.out.println(resultMessage); } /** * @see "[MIG-437] REP jobs disappears, if you start the report time while they're in filter "planned"" * * https://dev.mfiles.ch/confluence/gilgen/pages/viewpage.action?pageId=106299428 */ @Test public void testFilterJobs() { filterJobsByJobType(JobType.REP); filterJobsByJobType(JobType.MON); filterJobsByJobType(JobType.SAV); } private void filterJobsByJobType(String jobType) { boolean less = false; boolean more = true; boolean yes = true; boolean no = false; checkJobFilter(jobType, JobStatus.NEW, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.NEW, more, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, more, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, more, yes, no, no, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.RECEIVED, more, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, more, no, no, no, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, no, no, no, JobStatusFilter.active); // checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, yes, yes, yes, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, no, yes, yes, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, yes, yes, yes, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, yes, no, no, JobStatusFilter.planned); // checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, no, yes, yes, JobStatusFilter.active); not exist checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, no, no, no, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.FINALIZED, less, yes, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FINALIZED, less, no, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FINALIZED, more, yes, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FINALIZED, more, no, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, less, yes, no, no, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, less, no, no, no, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, more, yes, no, no, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, more, no, no, no, JobStatusFilter.finalized); } /** * @see "[MIG-445] User cannot edit a report time (always overlapping)" * */ @Test public void testJobReportTimeOverlapping() { Job newJob = getJobObjectByStatus(JobStatus.RECEIVED); Calendar todayCalendar = DateTimeUtil.getToday(); JobReportTime jobTime = new JobReportTime(); jobTime.setGuid(newJob.getCurrentReport().getGuId()); jobTime.setDate(todayCalendar.getTime()); jobTime.setIdx(0); todayCalendar.set(Calendar.HOUR_OF_DAY, 8); jobTime.setStartTime(todayCalendar.getTime()); todayCalendar.set(Calendar.HOUR_OF_DAY, 9); jobTime.setStopTime(todayCalendar.getTime()); newJob.getCurrentReport().getTimes().add(jobTime); testTimeOverlapping(newJob, "07:50", "08:10", true); testTimeOverlapping(newJob, "08:50", "09:10", true); testTimeOverlapping(newJob, "08:10", "08:50", true); testTimeOverlapping(newJob, "07:50", "09:10", true); testTimeOverlapping(newJob, "01:35", "01:36", false); testTimeOverlapping(newJob, "07:00", "08:00", false); testTimeOverlapping(newJob, "08:00", "08:10", true); testTimeOverlapping(newJob, "09:00", "09:30", false); } private void testTimeOverlapping(Job newJob, String start, String stop, boolean isOverlap) { Object[] arguments = new Object[] { start + " - " + stop , DateTimeUtil.showTime(newJob.getCurrentReport().getTimes().get(0).getStartTime()) + " - " + DateTimeUtil.showTime(newJob.getCurrentReport().getTimes().get(0).getStopTime())}; String errorMessage = MessageFormat.format(Messages.getString("overlapping"), arguments); String resultMessage = errorMessage ; boolean isJobTimesheetOverlapping = ServiceJobUtil.isJobTimesheetOverlapping(newJob.getCurrentReport().getTimes(), start, stop).size() > 0; if(isOverlap) { assertTrue(resultMessage, isJobTimesheetOverlapping); } else { assertFalse(resultMessage, isJobTimesheetOverlapping); } } /** * @see "MIG-466 Report message to client is now mandatory for job type MON" * */ @Test public void testReportMessageForMONJob() { Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); receivedJob.setJobType(JobType.MON); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode("02"); jobMessage.setMessageId(CommonConstants.Message.CUSTOMER); jobMessage.setFullText("Test message"); receivedJob.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); } /** * @see "MIG-993 New mandatory for report message for job type 'SAV'" * */ @Test public void testReportMessageForSAVJob() { Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); receivedJob.setJobType(JobType.SAV); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); JobMessage customerMessage = new JobMessage(); customerMessage.setMessageCode("02"); customerMessage.setMessageId(CommonConstants.Message.CUSTOMER); customerMessage.setFullText("Test message"); receivedJob.getLatestReport().getMessages().add(customerMessage); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); customerMessage.setMessageCode(CommonConstants.Message.SYSTEM_IS_SAVE); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); customerMessage.setMessageCode(CommonConstants.Message.SYSTEM_WITH_MINOR_DEFECTS); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); customerMessage.setMessageCode(CommonConstants.Message.SYSTEM_EXHIBITS_DEFECTS); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); JobMessage supervisorMessage = new JobMessage(); supervisorMessage.setMessageId(CommonConstants.Message.HEAD_OF_DEPARTMENT); supervisorMessage.setMessageCode(CommonConstants.Message.SYSTEM_IS_SAVE); supervisorMessage.setFullText("Test message 2"); receivedJob.getLatestReport().getMessages().add(supervisorMessage); customerMessage.setMessageCode("17"); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); } /** * @see "MIG-545 If user chooses ZKDMOBMONTXT.MONTXT = 01 the app is requiring a document incorrectly" * */ @Test public void testModernisationNecessaryFormDescRequire() { Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); receivedJob.setJobType(JobType.MON); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); receivedJob.setJobType(JobType.SAV); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode("02"); jobMessage.setMessageId(CommonConstants.Message.CUSTOMER); jobMessage.setFullText("Test message"); receivedJob.getLatestReport().getMessages().add(jobMessage); assertTrue(ServiceJobUtil.isMandatoryByReportMessage(receivedJob)); receivedJob.getLatestReport().getMessages().get(0).setMessageCode("01"); assertTrue(ServiceJobUtil.isMandatoryByReportMessage(receivedJob)); receivedJob.setJobType(JobType.MON); assertFalse(ServiceJobUtil.isMandatoryByReportMessage(receivedJob)); } } package ch.mfiles.kaba.kolibri.common.forms.widgets; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.text.Editable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class CommissionNumberLayout extends LinearLayout { public CommissionNumberLayout(Context context) { super(context); } private Form currentform; private CommissionNumberText commissionNumberText; private LinearLayout cameraLinearLayout; private ImageView cameraImageView; private BitmapDrawable cameraBlack; private BitmapDrawable cameraDisabled; public static CommissionNumberLayout createCommissionNumberText(Application app, Form form, ViewGroup parent, boolean required) { if (parent == null) { return null; } Context context = parent.getContext(); CommissionNumberLayout content = new CommissionNumberLayout(context); content.currentform = form; content.cameraBlack = form.getBitmanDrawable(ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI)); content.cameraDisabled = form.getBitmanDrawable(ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.CAMERA_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI)); content.createCommissionNumberText(required); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.addView(content); parent.addView(contentLinearLayout); return content; } private void createCommissionNumberText(final boolean required) { Context context = getContext(); setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams barcodeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLinearLayoutParams.gravity = Gravity.CENTER; barcodeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.weight = 1; setLayoutParams(barcodeLinearLayoutParams); commissionNumberText = CommissionNumberText.createDefaultEditText(this, required); //$NON-NLS-1$ LinearLayout.LayoutParams commissionNumberLayoutParams = new LinearLayout.LayoutParams(0, 0); commissionNumberLayoutParams.gravity = Gravity.CENTER; commissionNumberLayoutParams.width = 0; commissionNumberLayoutParams.height = LayoutParams.MATCH_PARENT; commissionNumberLayoutParams.weight = 0.9f; commissionNumberText.getParentTextInputLayout().setLayoutParams(commissionNumberLayoutParams); cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.1f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); cameraImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); cameraImageView.setLayoutParams(gridImageViewParams); cameraImageView.setImageDrawable(cameraBlack); cameraImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(currentform) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String commissionNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(currentform); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { MessageUtil.getInstance().showMessage(Messages.getString("aborted")); //$NON-NLS-1$ } else { commissionNumber = result.getContents(); commissionNumberText.setText(commissionNumber); } return null; } }; } }); cameraLinearLayout.addView(cameraImageView); addView(cameraLinearLayout); } public CommissionNumberText getCommissionNumberText() { return commissionNumberText; } public Editable commissionNumberText() { return commissionNumberText.getText(); } public void setEnabled(boolean enabled) { super.setEnabled(enabled); commissionNumberText.getParentTextInputLayout().setEnabled(enabled); cameraLinearLayout.setEnabled(enabled); cameraImageView.setEnabled(enabled); cameraImageView.setClickable(enabled); if (!enabled) { commissionNumberText.clearFocus(); } if (enabled) { cameraImageView.setImageDrawable(cameraBlack); } else { cameraImageView.setImageDrawable(cameraDisabled); } } public void setJobTypeAndFormat(JobType jobType, String communicationNumberFormat) { commissionNumberText.setJobTypeAndFormat(jobType, communicationNumberFormat); } public void setRequired(boolean isRequired) { commissionNumberText.setRequired(isRequired); } public void setHint(String hint) { commissionNumberText.getParentTextInputLayout().setHint(hint); } public void setError(String errorMessage) { commissionNumberText.setError(errorMessage); } public void clearError() { commissionNumberText.clearError(); } public void clear() { commissionNumberText().clear(); } public String getCommissionNumber() { return commissionNumberText.getCommissionNumber(); } public void setText(String commissionNumber) { commissionNumberText.setText(commissionNumber); } public boolean isRequired() { return commissionNumberText.isRequired(); } public String getErrorMessage() { return commissionNumberText.getErrorMessage(); } } package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.net.ParseException; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.GridLayout; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Checklist; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.businessobjects.ErrorCode; import ch.mfiles.kaba.kolibri.common.businessobjects.Incident; import ch.mfiles.kaba.kolibri.common.businessobjects.Invoice; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.NextIntervention; import ch.mfiles.kaba.kolibri.common.businessobjects.Progress; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ServiceRefused; import ch.mfiles.kaba.kolibri.common.businessobjects.StateOfInstallation; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDCalendar; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.FormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (21-03-2017) * * see "MIG-50] implement of "create/edit report" " */ public class ReportEditForm extends SuperForm implements TextWatcher, OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(ReportEditForm.class); private int lastContentRow = 0; private Job job; private CommonConstants.CommissionNumber.Type commissionType; private CommissionNumberLayout commissionNumberLayout; private MDEditText jobNumber; private GridLayout workTypeGridLayout; private MDSpinner workTypeValue; private AppCompatCheckBox reasoning; private AppCompatCheckBox openPending; private AppCompatCheckBox safetyReport; private AppCompatCheckBox collectively; private AppCompatCheckBox governmentReport; private MDRadioButton partialRepair; private MDRadioButton finalRepair; private LinearLayout interventionLayout; private MDCalendar nextInterventionDateValue; private TimeEditText nextInterventionTimeText; private MDSpinner installationStateValue; private MDSpinner interventioValue; private GridLayout progressGridLayout; private MDSpinner progressValue; private MDSpinner billingValue; private MDSpinner sendReportToValue; private MDSpinner addressValue; private MDEditText customerSupportEditText; private GridLayout checklistGridLayout; private MDSpinner checklistValue; private GridLayout incidentAGridLayout; private MDSpinner incidentAValue; private GridLayout incidentBGridLayout; private MDSpinner incidentBValue; private GridLayout systemErrorGridLayout; private MDEditText systemError; private TextView serviceText; private LinearLayout servicePerformedLayout; private TextView servicePerformedText; private GridLayout servicePerformedMonthGridLayout; private MDSpinner servicePerformedMonthValue; private GridLayout servicePerformedYearGridLayout; private MDSpinner servicePerformedYearValue; private TextView serviceRefusedText; private GridLayout serviceRefusedGridLayout; private MDSpinner serviceRefusedValue; private AppCompatCheckBox january; private AppCompatCheckBox february; private AppCompatCheckBox march; private AppCompatCheckBox april; private AppCompatCheckBox may; private AppCompatCheckBox june; private AppCompatCheckBox july; private AppCompatCheckBox august; private AppCompatCheckBox september; private AppCompatCheckBox october; private AppCompatCheckBox november; private AppCompatCheckBox december; private AppCompatButton monthButton; private MDEditText distance; private MDEditText expenses; private MDEditText cycleOfInstallation; private MDSpinner errorValue; private EditText errorEditText1; private AppCompatCheckBox errorCheckbox; private MDSpinner error2Value; private EditText error2EditText1; private AppCompatCheckBox error2Checkbox; private MDSpinner errorMontValue; private EditText errorMontEditText1; private AppCompatCheckBox errorMontCheckbox; private AppCompatButton deleteButton; private List> monthCheckBoxesList; private Map emailMap = new HashMap(); private ScrollView scrollView; @Override public ApplicationEvent onBackPressed() { onCancel(); leaveToJobDetailForm(); return null; } @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.job = formArguments.getJob(); commissionType = formArguments.getCommissionType(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING , LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); GridLayout gridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); gridLayout.setLayoutParams(gridLayoutParams); gridLayout.setColumnCount(3); // Commission Number LinearLayout commissionNumberLinearLayout = new LinearLayout(context); commissionNumberLinearLayout.setOrientation(LinearLayout.VERTICAL); commissionNumberLinearLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, commissionNumberLinearLayout, true); //$NON-NLS-1$ gridLayout.addView(commissionNumberLinearLayout); // Job Number jobNumber = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("jobNumber"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ jobNumber.setRawInputType(InputType.TYPE_CLASS_TEXT); jobNumber.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY_FIVE)}); jobNumber.addTextChangedListener(this); jobNumber.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); // Type Of Work workTypeGridLayout = new GridLayout(context); workTypeGridLayout.setLayoutParams(gridLayoutParams); workTypeGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); workTypeValue = MDSpinner.createDefaultSpinner(workTypeGridLayout, ServiceMessages.getString("typeOfWork"), true); //$NON-NLS-1$ workTypeValue.setTag("TYPEOFWORK"); //$NON-NLS-1$ workTypeValue.setOnItemSelectedListener(this); workTypeValue.setContentDescription(ServiceMessages.getString("typeOfWork")); gridLayout.addView(workTypeGridLayout); reasoning = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("followup")); //$NON-NLS-1$ reasoning.setTag("REASONING"); //$NON-NLS-1$ reasoning.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 2)); reasoning.setOnCheckedChangeListener(this); gridLayout.addView(reasoning); openPending = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("openPending")); //$NON-NLS-1$ openPending.setTag("OPENPENDING"); //$NON-NLS-1$ openPending.setLayoutParams(getGridLayoutParams(getRowIndex(), 0, 2)); openPending.setOnCheckedChangeListener(this); gridLayout.addView(openPending); safetyReport = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("securityReport")); //$NON-NLS-1$ safetyReport.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); gridLayout.addView(safetyReport); collectively = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("collectiveSignature")); //$NON-NLS-1$ collectively.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); gridLayout.addView(collectively); governmentReport = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("governmentReport")); //$NON-NLS-1$ governmentReport.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); gridLayout.addView(governmentReport); // Repair Type partialRepair = MDRadioButton.createDefaultRadioButton(gridLayout, ServiceMessages.getString("partialRepair")); //$NON-NLS-1$ partialRepair.setTag("PARTIALREPAIR"); //$NON-NLS-1$ partialRepair.setContentDescription("partialRepair"); ((LinearLayout) partialRepair.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 2)); partialRepair.setOnCheckedChangeListener(this); finalRepair = MDRadioButton.createDefaultRadioButton(gridLayout, ServiceMessages.getString("endRepair")); //$NON-NLS-1$ finalRepair.setTag("FINALREPAIR"); //$NON-NLS-1$ finalRepair.setContentDescription("endRepair"); ((LinearLayout) finalRepair.getParent()).setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); finalRepair.setOnCheckedChangeListener(this); interventionLayout = new LinearLayout(context); interventionLayout.setOrientation(LinearLayout.VERTICAL); interventionLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); LinearLayout dayLinearLayout = new LinearLayout(context); dayLinearLayout.setOrientation(LinearLayout.HORIZONTAL); // Next intervention Date // nextInterventionDateValue = new MDCalendar(context); nextInterventionDateValue = MDCalendar.createDefaultCalendar(dayLinearLayout, ServiceMessages.getString("date"), false); //$NON-NLS-1$ // nextInterventionDateValue.setLabel(ServiceMessages.getString("date")); nextInterventionDateValue.setEnabled(false); LinearLayout.LayoutParams daysValueParams = new LinearLayout.LayoutParams(0, 0); // daysValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; daysValueParams.width = 0; daysValueParams.height = LayoutParams.WRAP_CONTENT; daysValueParams.weight = 0.5f; daysValueParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 4); ((LinearLayout) nextInterventionDateValue.getParent()).setLayoutParams(daysValueParams); nextInterventionDateValue.setFocusableInTouchMode(false); nextInterventionDateValue.setSimpleDateFormat(new SimpleDateFormat(DateTimeUtil.DATE_FORMAT, new Locale("de", "CH"))); // nextInterventionDateValue.setOnDateSelected(new onDateSelected() { // // @Override // public void onDateSelected(Date date) { // nextInterventionDateValue.clearError(); // List dateTypeValueList = new ArrayList(); // String dateString = DateTimeUtil.showDate(date); // dateTypeValueList.add(new CustomSpinnerItem(dateString, dateString)); // nextInterventionDateValue.setContents(dateTypeValueList); // } // }); // Next intervention Time nextInterventionTimeText = TimeEditText.createDefaultEditText(dayLinearLayout,ServiceMessages.getString("time"), false); // nextInterventionTimeText.setTag("VON"); //$NON-NLS-1$ nextInterventionTimeText.setEnabled(false); LinearLayout.LayoutParams nextInterventionTimeLayoutParams = new LinearLayout.LayoutParams(0, 0); nextInterventionTimeLayoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; nextInterventionTimeLayoutParams.width = 0; nextInterventionTimeLayoutParams.height = LayoutParams.WRAP_CONTENT; nextInterventionTimeLayoutParams.weight = 0.5f; nextInterventionTimeText.getParentTextInputLayout().setLayoutParams(nextInterventionTimeLayoutParams); nextInterventionTimeText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && nextInterventionTimeText.getText().toString().equalsIgnoreCase("00:00")) { nextInterventionTimeText.getText().clear(); nextInterventionTimeText.append(""); } if (!hasFocus && nextInterventionTimeText.getText().toString().isEmpty()) { nextInterventionTimeText.setText("00:00"); } } }); interventionLayout.addView(dayLinearLayout); installationStateValue = MDSpinner.createDefaultSpinner(interventionLayout, ServiceMessages.getString("installationState"), true); installationStateValue.setContentDescription(ServiceMessages.getString("installationState")); installationStateValue.setEnabled(false); installationStateValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { installationStateValue.clearError(); } }); interventioValue = MDSpinner.createDefaultSpinner(interventionLayout, ServiceMessages.getString("interventionType"), true); interventioValue.setContentDescription(ServiceMessages.getString("interventionType")); interventioValue.setEnabled(false); interventioValue.setOnItemSelectedListener(this); interventioValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { interventioValue.clearError(); } }); gridLayout.addView(interventionLayout); // Progress progressGridLayout = new GridLayout(context); progressGridLayout.setLayoutParams(gridLayoutParams); progressGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); progressValue = MDSpinner.createDefaultSpinner(progressGridLayout, ServiceMessages.getString("progress"), false); //$NON-NLS-1$ progressValue.setTag("PROGRESS"); //$NON-NLS-1$ progressValue.setOnItemSelectedListener(this); gridLayout.addView(progressGridLayout); // Billing billingValue = MDSpinner.createDefaultSpinner(gridLayout, Messages.getString("billing"), true); //$NON-NLS-1$ billingValue.setTag("BILLING"); //$NON-NLS-1$ ((LinearLayout) billingValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); billingValue.setOnItemSelectedListener(this); // Customer Support sendReportToValue = MDSpinner.createDefaultSpinner(gridLayout, ServiceMessages.getString("sendReportTo"), false); //$NON-NLS-1$ sendReportToValue.setTag("CUSTOMERSUPPORT"); //$NON-NLS-1$ ((LinearLayout) sendReportToValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); sendReportToValue.setOnItemSelectedListener(this); LinearLayout customerSupportLayout = new LinearLayout(context); customerSupportLayout.setOrientation(LinearLayout.HORIZONTAL); GridLayout.LayoutParams customerSupportLayoutParams = getGridLayoutParams(getNewRowIndex(), 0, 3); customerSupportLayoutParams.bottomMargin = 10; customerSupportLayout.setLayoutParams(customerSupportLayoutParams); gridLayout.addView(customerSupportLayout); // Address addressValue = MDSpinner.createDefaultSpinner(customerSupportLayout, null, false); addressValue.setTag("ADDRESS"); //$NON-NLS-1$ LinearLayout.LayoutParams addressValueParams = new LinearLayout.LayoutParams(0, 0); addressValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; addressValueParams.width = 0; addressValueParams.height = LayoutParams.WRAP_CONTENT; addressValueParams.weight = 0.5f; addressValueParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 4); addressValue.setOnItemSelectedListener(this); ((LinearLayout) addressValue.getParent()).setLayoutParams(addressValueParams); // Customer support edit text customerSupportEditText = MDEditText.createDefaultEditText(customerSupportLayout, "", InputType.TYPE_TEXT_VARIATION_PERSON_NAME, false); //$NON-NLS-1$ LinearLayout.LayoutParams textInputLayoutParams = new LinearLayout.LayoutParams(0, 0); textInputLayoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; textInputLayoutParams.width = 0; textInputLayoutParams.height = LayoutParams.WRAP_CONTENT; textInputLayoutParams.weight = 0.5f; customerSupportEditText.getParentTextInputLayout().setLayoutParams(textInputLayoutParams); // customerSupportEditText.setOnFocusChangeListener(new OnFocusChangeListener() { // // @Override // public void onFocusChange(View v, boolean hasFocus) { // if ("02".equalsIgnoreCase(sendReportToValue.getSelectedId()) && !hasFocus && !isEmailValid()) { // customerSupportEditText.setSelected(true); // app.showWarningMessageBox(CommonConstants.Regex.EMAIL_VALIDATION_MSG); // } // } // // // }); // Check list checklistGridLayout = new GridLayout(context); checklistGridLayout.setLayoutParams(gridLayoutParams); checklistGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); checklistValue = MDSpinner.createDefaultSpinner(checklistGridLayout, Messages.getString("checkList"), false); //$NON-NLS-1$ checklistValue.setTag("CHECKLIST"); //$NON-NLS-1$ checklistValue.setOnItemSelectedListener(this); gridLayout.addView(checklistGridLayout); // Incident A incidentAGridLayout = new GridLayout(context); incidentAGridLayout.setLayoutParams(gridLayoutParams); incidentAGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); incidentAValue = MDSpinner.createDefaultSpinner(incidentAGridLayout, ServiceMessages.getString("incidentA"), false); //$NON-NLS-1$ incidentAValue.setOnItemSelectedListener(this); gridLayout.addView(incidentAGridLayout); // Incident B incidentBGridLayout = new GridLayout(context); incidentBGridLayout.setLayoutParams(gridLayoutParams); incidentBGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); incidentBValue = MDSpinner.createDefaultSpinner(incidentBGridLayout, ServiceMessages.getString("incidentB"), false); //$NON-NLS-1$ incidentBValue.setOnItemSelectedListener(this); gridLayout.addView(incidentBGridLayout); // System Error systemErrorGridLayout = new GridLayout(context); systemErrorGridLayout.setLayoutParams(gridLayoutParams); systemErrorGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); systemError = MDEditText.createDefaultEditText(systemErrorGridLayout, Messages.getString("installationError"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ systemError.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); gridLayout.addView(systemErrorGridLayout); // service serviceText = CommonUtilForm.getTextView(context, "Service"); //$NON-NLS-1$ serviceText.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); gridLayout.addView(serviceText); // Service Performed servicePerformedLayout = new LinearLayout(context); LinearLayout.LayoutParams linearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); servicePerformedLayout.setLayoutParams(linearLayoutParams); servicePerformedLayout.setOrientation(LinearLayout.VERTICAL); servicePerformedText = CommonUtilForm.getTextView(context, ServiceMessages.getString("servicePerformed")); //$NON-NLS-1$ servicePerformedText.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); servicePerformedText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); servicePerformedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); servicePerformedText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); textLayoutParams.setMargins(0, LayoutUtils.convertDpToPixel(context, 4), 0, 0); servicePerformedText.setLayoutParams(textLayoutParams); servicePerformedLayout.addView(servicePerformedText); servicePerformedLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 0, 1)); gridLayout.addView(servicePerformedLayout); // Month servicePerformedMonthGridLayout = new GridLayout(context); servicePerformedMonthGridLayout.setLayoutParams(gridLayoutParams); servicePerformedMonthGridLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); servicePerformedMonthValue = MDSpinner.createDefaultSpinner(servicePerformedMonthGridLayout, null, false); servicePerformedMonthValue.setTag("COMPLETEMONTH"); //$NON-NLS-1$ servicePerformedMonthValue.setOnItemSelectedListener(this); servicePerformedMonthValue.setEnabled(false); servicePerformedMonthValue.setRequired(false); gridLayout.addView(servicePerformedMonthGridLayout); // Year servicePerformedYearGridLayout = new GridLayout(context); servicePerformedYearGridLayout.setLayoutParams(gridLayoutParams); servicePerformedYearGridLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); servicePerformedYearValue = MDSpinner.createDefaultSpinner(servicePerformedYearGridLayout, null, false); servicePerformedYearValue.setTag("COMPLETEYEAR"); //$NON-NLS-1$ servicePerformedYearValue.setOnItemSelectedListener(this); servicePerformedYearValue.setEnabled(false); servicePerformedYearValue.setRequired(false); gridLayout.addView(servicePerformedYearGridLayout); // Service Refused serviceRefusedText = CommonUtilForm.getTextView(context, ServiceMessages.getString("serviceRefused")); //$NON-NLS-1$ serviceRefusedText.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); serviceRefusedText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); serviceRefusedText.setEnabled(false); gridLayout.addView(serviceRefusedText); serviceRefusedGridLayout = new GridLayout(context); serviceRefusedGridLayout.setLayoutParams(gridLayoutParams); serviceRefusedGridLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 2)); serviceRefusedValue = MDSpinner.createDefaultSpinner(serviceRefusedGridLayout, "", false); serviceRefusedValue.setTag("SERVICEREFUSED"); //$NON-NLS-1$ serviceRefusedValue.setOnItemSelectedListener(this); serviceRefusedValue.setEnabled(false); gridLayout.addView(serviceRefusedGridLayout); january = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ january.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); january.setId(1); january.setTag("JANUARY"); //$NON-NLS-1$ january.setOnCheckedChangeListener(this); gridLayout.addView(january); may = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ may.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); may.setId(5); may.setTag("MAY"); //$NON-NLS-1$ may.setOnCheckedChangeListener(this); gridLayout.addView(may); september = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ september.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); september.setId(9); september.setTag("SEPTEMBER"); //$NON-NLS-1$ september.setOnCheckedChangeListener(this); gridLayout.addView(september); february = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ february.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); february.setId(2); february.setTag("FEBRUARY"); //$NON-NLS-1$ february.setOnCheckedChangeListener(this); gridLayout.addView(february); june = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ june.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); june.setId(6); june.setTag("JUNE"); //$NON-NLS-1$ june.setOnCheckedChangeListener(this); gridLayout.addView(june); october = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ october.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); october.setId(10); october.setTag("OCTOBER"); //$NON-NLS-1$ october.setOnCheckedChangeListener(this); gridLayout.addView(october); march = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ march.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); march.setId(3); march.setTag("MARCH"); //$NON-NLS-1$ march.setOnCheckedChangeListener(this); gridLayout.addView(march); july = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ july.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); july.setId(7); july.setTag("JULY"); //$NON-NLS-1$ july.setOnCheckedChangeListener(this); gridLayout.addView(july); november = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ november.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); november.setId(11); november.setTag("NOVEMBER"); //$NON-NLS-1$ november.setOnCheckedChangeListener(this); gridLayout.addView(november); april = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ april.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); april.setId(4); april.setTag("APRIL"); //$NON-NLS-1$ april.setOnCheckedChangeListener(this); gridLayout.addView(april); august = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ august.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); august.setId(8); august.setTag("AUGUST"); //$NON-NLS-1$ august.setOnCheckedChangeListener(this); gridLayout.addView(august); december = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ december.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); december.setId(12); december.setTag("DECEMBER"); //$NON-NLS-1$ december.setOnCheckedChangeListener(this); gridLayout.addView(december); // Button LinearLayout monthButtonLinearLayout = new LinearLayout(context); monthButtonLinearLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); monthButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); monthButton = new AppCompatButton(context); LinearLayout.LayoutParams monthButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); monthButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; monthButton.setLayoutParams(monthButtonParams); monthButton.setText(ServiceMessages.getString("change")); //$NON-NLS-1$ monthButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { if (january.isEnabled()) { setEnableMonthCheckBoxes(false); } else { setEnableMonthCheckBoxes(true); } } }); monthButton.setBackgroundDrawable(gradientDrawable); monthButtonLinearLayout.addView(monthButton); gridLayout.addView(monthButtonLinearLayout); // Distance distance = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("distance"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ distance.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FOUR)}); distance.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); // Expenses expenses = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("expenses"), InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ expenses.setDirectionRight(true); expenses.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.SIX)}); expenses.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); expenses.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { expenses.setText(getExpense()); } } }); cycleOfInstallation = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("cycleOfInstallation"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ cycleOfInstallation.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT)}); cycleOfInstallation.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); // error errorValue = MDSpinner.createDefaultSpinner(gridLayout, ServiceMessages.getString("errorMessages"), false); //$NON-NLS-1$ ((LinearLayout) errorValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); errorEditText1 = CommonUtilForm.getEditText(context, "H", InputType.TYPE_CLASS_NUMBER); //$NON-NLS-1$ errorEditText1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorEditText1Params = getGridLayoutParams(getNewRowIndex(), 0, 1); errorEditText1.setLayoutParams(errorEditText1Params); gridLayout.addView(errorEditText1); EditText errorEditText2 = CommonUtilForm.getEditText(context, "E", InputType.TYPE_CLASS_TEXT); //$NON-NLS-1$ errorEditText2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorEditText2Params = getGridLayoutParams(getRowIndex(), 1, 1); errorEditText2.setLayoutParams(errorEditText2Params); gridLayout.addView(errorEditText2); errorCheckbox = CommonUtilForm.getCheckBox(context, "FM"); //$NON-NLS-1$ GridLayout.LayoutParams errorCheckboxParams = getGridLayoutParams(getRowIndex(), 2, 1); errorCheckboxParams.setGravity(Gravity.BOTTOM); errorCheckbox.setLayoutParams(errorCheckboxParams); gridLayout.addView(errorCheckbox); error2Value = MDSpinner.createDefaultSpinner(gridLayout, null, false); ((LinearLayout) error2Value.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); error2EditText1 = CommonUtilForm.getEditText(context, "H", InputType.TYPE_CLASS_NUMBER); //$NON-NLS-1$ error2EditText1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams error2EditText1Params = getGridLayoutParams(getNewRowIndex(), 0, 1); error2EditText1.setLayoutParams(error2EditText1Params); gridLayout.addView(error2EditText1); EditText error2EditText2 = CommonUtilForm.getEditText(context, "E", InputType.TYPE_CLASS_TEXT); //$NON-NLS-1$ error2EditText2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams error2EditText2Params = getGridLayoutParams(getRowIndex(), 1, 1); error2EditText2.setLayoutParams(error2EditText2Params); gridLayout.addView(error2EditText2); error2Checkbox = CommonUtilForm.getCheckBox(context, "FM"); //$NON-NLS-1$ GridLayout.LayoutParams error2CheckboxParams = getGridLayoutParams(getRowIndex(), 2, 1); error2CheckboxParams.setGravity(Gravity.BOTTOM); error2Checkbox.setLayoutParams(error2CheckboxParams); gridLayout.addView(error2Checkbox); errorMontValue = MDSpinner.createDefaultSpinner(gridLayout, null, false); ((LinearLayout) errorMontValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); errorMontEditText1 = CommonUtilForm.getEditText(context, "H", InputType.TYPE_CLASS_NUMBER); //$NON-NLS-1$ errorMontEditText1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorMontEditText1Params = getGridLayoutParams(getNewRowIndex(), 0, 1); errorMontEditText1.setLayoutParams(errorMontEditText1Params); gridLayout.addView(errorMontEditText1); EditText errorMontEditText2 = CommonUtilForm.getEditText(context, "E", InputType.TYPE_CLASS_TEXT); //$NON-NLS-1$ errorMontEditText2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorMontEditText2Params = getGridLayoutParams(getRowIndex(), 1, 1); errorMontEditText2.setLayoutParams(errorMontEditText2Params); gridLayout.addView(errorMontEditText2); errorMontCheckbox = CommonUtilForm.getCheckBox(context, "FM"); //$NON-NLS-1$ GridLayout.LayoutParams errorMontCheckboxParams = getGridLayoutParams(getRowIndex(), 2, 1); errorMontCheckboxParams.setGravity(Gravity.BOTTOM); errorMontCheckbox.setLayoutParams(errorMontCheckboxParams); gridLayout.addView(errorMontCheckbox); // Button LinearLayout deleteButtonLinearLayout = new LinearLayout(context); deleteButtonLinearLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); deleteButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable deleteButtonGradientDrawable = new GradientDrawable(); deleteButtonGradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); deleteButtonGradientDrawable.setCornerRadius(7); deleteButtonGradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); deleteButton = new AppCompatButton(context); LinearLayout.LayoutParams deleteButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); deleteButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; deleteButton.setLayoutParams(deleteButtonParams); deleteButton.setText(ServiceMessages.getString("deleteCompleteReport")); //$NON-NLS-1$ deleteButton.setOnClickListener(new View.OnClickListener() { private boolean showConfirmDeleteDialog() { return app.showMessageBox(ServiceMessages.getString("DoYouReallyWantToDeleteTheCompleteReport"), ServiceMessages.getString("DeleteReport"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK; } @Override public void onClick(View paramView) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (showConfirmDeleteDialog()) { if (!app.dbutil.deleteCompleteReport(job.getLatestReport())) { log.error("Unable to delete complete report"); return null; } job.loadReports(app.dbutil); boolean restorePartlyDone = ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job); if (new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, "")) { //$NON-NLS-1$ log.info("after updateStatus" + job.getStatus().toString()); //$NON-NLS-1$ } if (restorePartlyDone) { job.setStatus(JobStatus.PARLTY_DONE); GuidGenerator generator = new GuidGenerator(); try { int nextReportIdx = job.getNextReportIdx(app.dbutil); String nextReportGuId = generator.generate(); job.setCurrentReportGuId(nextReportGuId); Report nextReport = new Report(job.getJobNumber(), job.getJobType(), nextReportGuId, nextReportIdx, job.isCycleOfInstallationFlag()); app.dbutil.insertReplaceReport(nextReport); job.loadReports(app.dbutil); app.dbutil.updateJob(job); } catch (UnknownHostException | NoSuchAlgorithmException e) { throw new ApplicationException(e); } } leaveToJobDetailForm(); return null; } return null; } }; } }); deleteButton.setBackgroundDrawable(deleteButtonGradientDrawable); deleteButton.setContentDescription("delete"); deleteButtonLinearLayout.addView(deleteButton); gridLayout.addView(deleteButtonLinearLayout); linearLayout.addView(gridLayout); saveButton.setTitle(ServiceMessages.getString("save")); scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(linearLayout); view.addView(scrollView); return view; } private GridLayout.LayoutParams getGridLayoutParams(int row, int col, int colspan) { GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = 0; params.height = LayoutParams.WRAP_CONTENT; params.columnSpec = GridLayout.spec(col, colspan, 1f); params.rowSpec = GridLayout.spec(row, 1, 1f); return params; } private int getNewRowIndex() { return lastContentRow += 1; } private int getRowIndex() { return lastContentRow; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title this.setFormTitle(ServiceMessages.getString("report")); //$NON-NLS-1$ scrollView.scrollTo(0, 0); commissionNumberLayout.setRequired(true); progressValue.setRequired(false); commissionNumberLayout.setJobTypeAndFormat(this.job.getJobType(), app.dbutil.getUser().getCommunicationNumberFormat()); if (this.job.getJobType().isSAV()) { checklistValue.setRequired(true); } else { checklistValue.setRequired(false); } setShowReportContentByJobType(this.job.getJobType()); openPending.setChecked(false); errorCheckbox.setChecked(false); error2Checkbox.setChecked(false); errorMontCheckbox.setChecked(false); jobNumber.setText(""); //$NON-NLS-1$ customerSupportEditText.setText(""); //$NON-NLS-1$ fillComboStateOfInstallation(); fillComboIntervention(); fillComboTypeOfWork(); fillComboAddress(); fillComboChecklist(); fillComboError(); fillComboCustomerSupport(); fillComboIncident(); fillComboBilling(); fillComboServiceRefused(); fillComboServicePerformedYear(); initCheckboxMonths(); nextInterventionDateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); nextInterventionTimeText.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); installationStateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); interventioValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); setServicePerformedEnabled(); setServiceRefusedEnabled(); nextInterventionDateValue.setContents(new ArrayList()); if (this.job.getJobType().isMON()) { progressValue.setRequired(true); fillComboProgress(); } loadData(); setEnableMonthCheckBoxes(false); return null; } @Override public void onFormReset() { super.onFormReset(); clearAllValue(); } /** * Loads data. */ public void loadData() { Report report = this.job.getCurrentReport(); log.info("report guid " + report.getGuId() + " has times -> " + report.getTimes().size()); log.info("Report status " + report.getReportStatus());// Create new report log.info("Partial Repair " + report.isPartialRepair() + " Final Repair" + report.isFinalRepair()); clearPartialRepairAndFinalRepair(); if (report.getReportStatus().isInitial() || (report.getReportStatus().isReceived())) { setCheckboxes(this.job.getServicePlanMonth1()); setCheckboxes(this.job.getServicePlanMonth2()); setCheckboxes(this.job.getServicePlanMonth3()); setCheckboxes(this.job.getServicePlanMonth4()); setCheckboxes(this.job.getServicePlanMonth5()); setCheckboxes(this.job.getServicePlanMonth6()); sortCheckBoxesAscList(monthCheckBoxesList); fillComboServicePerformedMonth(monthCheckBoxesList); log.info("OrderNumber " + this.job.getOrderNumber()); log.info("JobNumber " + this.job.getJobNumber()); jobNumber.setText(this.job.getOrderNumber()); if (this.job.getCommissionNumber().length() > 0) { commissionNumberLayout.setText(this.job.getCommissionNumber()); } if (this.job.getJobType().isSAV()) { workTypeValue.setSelectionById(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT); } } else { // load existing report String komnr = ""; //$NON-NLS-1$ if (report.getCommissionNumber().length() > 0) { komnr = report.getCommissionNumber(); } if (StringUtil.isEmpty(komnr) && this.job.getCommissionNumber().length() > 0) { komnr = this.job.getCommissionNumber(); } if (StringUtil.isNotEmpty(komnr)) { commissionNumberLayout.setText(komnr); } loadReport(report); } if (job.getCurrentReport().getReportStatus().isReceived()) { deleteButton.setEnabled(false); } else { deleteButton.setEnabled(true); } log.info("serviceRefusedValue " + serviceRefusedValue + " isServiceRefusedFlag " + job.isServiceRefusedFlag()); setComNo(report); cycleOfInstallation.setRequired(job.isCycleOfInstallationFlag()); log.info("JobType REP " + job.getJobType().isREP() + " isServiceRefusedFlag " + job.isServiceRefusedFlag()); } private void setComNo(Report report) { if(commissionType == null) { commissionType = job.getReportCommissionNumberType(); } if(CommonConstants.CommissionNumber.Type.CORRECT == commissionType) { commissionNumberLayout.setEnabled(false); commissionNumberLayout.setRequired(false); } else if(CommonConstants.CommissionNumber.Type.UNKNOWN == commissionType) { commissionNumberLayout.setEnabled(false); commissionNumberLayout.setText(""); //$NON-NLS-1$ commissionNumberLayout.setRequired(false); } else { // invalid commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); if(!report.getCommissionNumber().isEmpty()) { commissionNumberLayout.setText(report.getCommissionNumber()); } } } private void setShowReportContentByJobType(JobType jobType) { int visibility = View.VISIBLE; boolean required = true; if(jobType.isMON()) { visibility = View.GONE; required = false; } openPending.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); governmentReport.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); progressGridLayout.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); progressValue.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); interventionLayout.setVisibility(!jobType.isMON()? View.VISIBLE:View.GONE); reasoning.setVisibility(visibility); partialRepair.setVisibility(visibility); finalRepair.setVisibility(visibility); workTypeGridLayout.setVisibility(visibility); workTypeValue.setRequired(required); checklistGridLayout.setVisibility(visibility); checklistValue.setVisibility(visibility); checklistValue.setRequired(required); incidentAGridLayout.setVisibility(visibility); incidentAValue.setVisibility(visibility); incidentBGridLayout.setVisibility(visibility); incidentBValue.setVisibility(visibility); systemErrorGridLayout.setVisibility(visibility); systemError.setVisibility(visibility); serviceText.setVisibility(visibility); servicePerformedLayout.setVisibility(visibility); servicePerformedText.setVisibility(visibility); servicePerformedMonthGridLayout.setVisibility(visibility); servicePerformedMonthValue.setVisibility(visibility); servicePerformedYearGridLayout.setVisibility(visibility); servicePerformedYearValue.setVisibility(visibility); january.setVisibility(visibility); february.setVisibility(visibility); march.setVisibility(visibility); april.setVisibility(visibility); may.setVisibility(visibility); june.setVisibility(visibility); july.setVisibility(visibility); august.setVisibility(visibility); september.setVisibility(visibility); october.setVisibility(visibility); november.setVisibility(visibility); december.setVisibility(visibility); monthButton.setVisibility(visibility); distance.setVisibility(visibility); expenses.setVisibility(visibility); cycleOfInstallation.setVisibility(visibility); int serviceRefusedVisibility = View.GONE; if (job.getJobType().isREP()) { serviceRefusedVisibility = View.VISIBLE; } serviceRefusedGridLayout.setVisibility(serviceRefusedVisibility); serviceRefusedText.setVisibility(serviceRefusedVisibility); serviceRefusedValue.setVisibility(serviceRefusedVisibility); } private boolean isEmailValid() { if (!customerSupportEditText.getText().toString().trim().isEmpty()) { Pattern pattern = Pattern.compile(CommonConstants.Regex.EMAIL_VALIDATOR); Matcher matcher = pattern.matcher(customerSupportEditText.getText().toString()); if(!matcher.matches()) { customerSupportEditText.setError(CommonConstants.Regex.EMAIL_VALIDATION_MSG); return false; } } return true; } @Override protected boolean isValid() { boolean result = super.isValid(); View focusView = null; String errorMessage = Messages.getString("pleaseProvideValue"); log.info("commissionType " + commissionType); log.info("commissionNumber.isRequired() " + commissionNumberLayout.isRequired()); if (commissionType == CommonConstants.CommissionNumber.Type.INVALID && commissionNumberLayout.isRequired()) { //$NON-NLS-1$ if("".equals(commissionNumberLayout.getCommissionNumber().trim()) || "0".equals(commissionNumberLayout.getCommissionNumber().trim())) { commissionNumberLayout.setError(errorMessage); //$NON-NLS-1$ result = false; focusView = commissionNumberLayout.getCommissionNumberText(); } else if(!commissionNumberLayout.getCommissionNumberText().isValid()) { commissionNumberLayout.setError(commissionNumberLayout.getErrorMessage()); //$NON-NLS-1$ result = false; focusView = commissionNumberLayout.getCommissionNumberText(); } log.info("commissionNumber " + result); } if (workTypeValue.isRequired() && workTypeValue.getSelectedItemPosition() == 0) { workTypeValue.setError(errorMessage); //$NON-NLS-1$ // berprfung abbrechen, sonst NPE beim prfen der SAV monate! result = false; log.info("workTypeValue " + result); if (focusView == null) focusView = workTypeValue; } if (!job.getJobType().isMON()) { if ( !partialRepair.isChecked() && !finalRepair.isChecked()) { finalRepair.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("partialRepair " + result); if (focusView == null) focusView = finalRepair; } } if (progressValue.isRequired() && progressValue.getSelectedItemPosition() == 0) { progressValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("progressValue " + result); if (focusView == null) focusView = progressValue; } // Arbeitsart 05: Vertragsservice // Checkliste 00: Bitte whlen.. (Initialwert) // SAV ausgefhrt (Monat) 00: --- (Initialwert) if (CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT.equalsIgnoreCase(workTypeValue.getSelectedId()) && servicePerformedMonthValue.getSelectedItemPosition() == 0) { //$NON-NLS-1$ checklistValue.setRequired(true); servicePerformedMonthValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("workTypeValue " + result); if (focusView == null) focusView = servicePerformedMonthValue; } if (checklistValue.isRequired() && checklistValue.getSelectedItemPosition() == 0) { checklistValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("checklistValue " + result); if (focusView == null) focusView = checklistValue; } log.info("servicePerformedYearValue " + servicePerformedYearValue.getSelectedItemPosition()); if (servicePerformedYearValue.isEnabled() && (servicePerformedText.getText().toString().contains("*")) && servicePerformedYearValue.getSelectedItemPosition() == 0) { servicePerformedYearValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("servicePerformedYearValue " + result); if (focusView == null) focusView = servicePerformedYearValue; } if (servicePerformedMonthValue.isEnabled() && (servicePerformedText.getText().toString().contains("*")) && (servicePerformedMonthValue.getSelectedItemPosition() == 0 && serviceRefusedValue.getSelectedItemPosition() == 0)) { servicePerformedMonthValue.setError(errorMessage); result = false; log.info("servicePerformedMonthValue " + result); if (focusView == null) focusView = servicePerformedMonthValue; } if (serviceRefusedValue.isEnabled() && (serviceRefusedText.getText().toString().contains("*")) && serviceRefusedValue.getSelectedItemPosition() == 0){ serviceRefusedValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("serviceRefusedValue " + result); if (focusView == null) focusView = serviceRefusedValue; } if (customerSupportEditText.isEnabled()) { if (customerSupportEditText.getText().toString().trim().isEmpty()) { result = false; customerSupportEditText.setError(errorMessage); } if (!customerSupportEditText.getText().toString().trim().isEmpty() && (CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL.equalsIgnoreCase(sendReportToValue.getSelectedId()))) { //$NON-NLS-1$ result = isEmailValid(); log.info("email " + result); } } log.info("cycleOfInstallation " + cycleOfInstallation.isRequired() + " " + cycleOfInstallation.getText().toString()); if (cycleOfInstallation.isRequired() && cycleOfInstallation.getText().toString().isEmpty()) { cycleOfInstallation.setError(errorMessage); result = false; log.info("cycleOfInstallation " + result); if (focusView == null) focusView = cycleOfInstallation; } if (nextInterventionDateValue.isEnabled() && nextInterventionDateValue.isRequired() && nextInterventionDateValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { nextInterventionDateValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("nextInterventionDateValue " + result); if (focusView == null) focusView = nextInterventionDateValue; } if (nextInterventionTimeText.isEnabled() && !nextInterventionTimeText.isValid() && !nextInterventionTimeText.getText().toString().isEmpty()) { nextInterventionTimeText.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("nextInterventionTimeText " + result); if (focusView == null) focusView = nextInterventionTimeText; } if (installationStateValue.isEnabled() && installationStateValue.isRequired() && installationStateValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { installationStateValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("installationStateValue " + result); if (focusView == null) focusView = installationStateValue; } if (interventioValue.isEnabled() && interventioValue.isRequired() && interventioValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { interventioValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("interventioValue " + result); if (focusView == null) focusView = interventioValue; } if (!result && focusView != null) { scrollView.scrollTo(0, (int) focusView.getY()); focusView.requestFocus(); } return result; } @Override protected boolean onSave() { Report report = this.job.getLatestReport(); boolean isNomaterial = report.isNoMaterial(); report.setNoMaterial(isNomaterial); // assign value to object and insert new report assignToReport(report); if(report.isValid()) { // The dialog is therefore displayed in the following cases: // ZKDMOB.KNZGARANT = true // ZKDMOBREP.ARBA = 01 or 02 // ZKDMOBREP.VERRC = 00 if ( job.isGuarantee() && (workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_REPAIR) || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_ON_CALL)) && billingValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { // show guarantee dialog app.injectAndLeaveToForm(ReportGuaranteeForm.class, new FormArguments(job, null)); } else { app.dbutil.insertReplaceReport(report); log.info("Report saved." + report.getGuId()); leaveToJobDetailForm(); } return true; } return false; } private void assignToReport(Report rep) { rep.setReportStatus(ReportStatus.NEW); rep.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); rep.setOrderNumber(jobNumber.getText().toString()); if (commissionType == CommonConstants.CommissionNumber.Type.UNKNOWN) { rep.setCommissionNumber(CommonConstants.CommissionNumber.DEFAULT); // dummy value } else { rep.setCommissionNumber(commissionNumberLayout.getCommissionNumber()); } if (job.isMoreInformationsFlag() && !job.getJobType().isMON()) { log.info("nextInterventionDateValue " + nextInterventionDateValue.getSelectedId()); if (nextInterventionDateValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { rep.setNextInterventionDate(new Date(0)); } else { String time = nextInterventionTimeText.getText().toString(); Date nextInterventionDate = DateTimeUtil.parseDateFromHHmm(time.isEmpty() ? "00:00" : time, DateTimeUtil.parseDateFromddMMyyyy(nextInterventionDateValue.getSelectedName())); log.info("nextInterventionDate " + DateTimeUtil.showDateTime(nextInterventionDate)); rep.setNextInterventionDate(nextInterventionDate); } if (installationStateValue.getSelectedItemPosition() != 0) { rep.setStateOfInstallation(installationStateValue.getSelectedId()); } if (interventioValue.getSelectedItemPosition() != 0) { rep.setNextInterventionCode(interventioValue.getSelectedId()); } } if (workTypeValue.getSelectedItemPosition() != 0) { rep.setWorkType(workTypeValue.getSelectedId()); rep.setTimesWorkType(workTypeValue.getSelectedId(), app.dbutil); } rep.setSafetyReport(safetyReport.isChecked()); rep.setCollectively(collectively.isChecked()); if (job.getJobType().isMON()) { rep.setOpenPending(openPending.isChecked()); rep.setGovernmentReport(governmentReport.isChecked()); rep.setMonStk(progressValue.getSelectedId()); log.info("set progress " + rep.getMonStk()); } else { rep.setReasoning(reasoning.isChecked()); rep.setPartialRepair(partialRepair.isChecked()); rep.setFinalRepair(finalRepair.isChecked()); if (checklistValue.getSelectedItemPosition() != 0) { rep.setChecklist(checklistValue.getSelectedName()); } else { rep.setChecklist(""); //$NON-NLS-1$ } log.info("checklist " + rep.getChecklist()); setIncident(rep); rep.setSystemError(systemError.getText().toString()); serServicePlan(rep); if (serviceRefusedValue.getSelectedItemPosition() != 0) { rep.setServiceRefused(serviceRefusedValue.getSelectedId()); } else { rep.setServiceRefused(""); } rep.setDistance(distance.getText().toString()); rep.setExpenses(getExpense()); rep.setCycleOfInstallation(cycleOfInstallation.getText().toString()); } rep.setBilling(billingValue.getSelectedId()); log.info("CustomerSupport " + rep.getCustomerSupport() + " text " + rep.getCustomerSupportText()); log.info("Billing " + rep.getBilling()); if (sendReportToValue.getSelectedItemPosition() != 0) { rep.setCustomerSupport(sendReportToValue.getSelectedId()); rep.setCustomerSupportText(customerSupportEditText.getText().toString()); } else { rep.setCustomerSupport(""); //$NON-NLS-1$ rep.setCustomerSupportText(""); //$NON-NLS-1$ } if (errorValue.getSelectedItemPosition() != 0) { rep.setErrorId1(errorValue.getSelectedId()); } rep.setErrorH1(errorEditText1.getText().toString()); rep.setErrorFlag1(errorCheckbox.isChecked()); if (error2Value.getSelectedItemPosition() != 0) { rep.setErrorId2(error2Value.getSelectedId()); } rep.setErrorH2(error2EditText1.getText().toString()); rep.setErrorFlag2(error2Checkbox.isChecked()); if (errorMontValue.getSelectedItemPosition() != 0) { rep.setErrorId3(errorMontValue.getSelectedId()); } rep.setErrorH3(errorMontEditText1.getText().toString()); rep.setErrorFlag3(errorMontCheckbox.isChecked()); } private void setIncident(Report rep) { String incidentA = StringUtil.removeAllLeadingZero(incidentAValue.getSelectedId()); String incidentB = StringUtil.removeAllLeadingZero(incidentBValue.getSelectedId()); if (incidentAValue.getSelectedItemPosition() == 0) { //$NON-NLS-1$ incidentA = ""; //$NON-NLS-1$ } if (incidentBValue.getSelectedItemPosition() == 0) { //$NON-NLS-1$ incidentB = ""; //$NON-NLS-1$ } rep.setIncidentAB(incidentA + incidentB); log.info("IncidentAB " + rep.getIncidentAB()); } private void serServicePlan(Report rep) { String saverl = servicePerformedMonthValue.getSelectedId(); saverl = saverl.concat(servicePerformedYearValue.getSelectedId().substring(2, 4)); rep.setMonthYear(saverl); rep.setServicePlanMonth1(""); //$NON-NLS-1$ rep.setServicePlanMonth2(""); //$NON-NLS-1$ rep.setServicePlanMonth3(""); //$NON-NLS-1$ rep.setServicePlanMonth4(""); //$NON-NLS-1$ rep.setServicePlanMonth5(""); //$NON-NLS-1$ rep.setServicePlanMonth6(""); //$NON-NLS-1$ if (monthCheckBoxesList != null) { sortCheckBoxesAscList(monthCheckBoxesList); for (int i = 0; i < monthCheckBoxesList.size(); i++) { switch (i) { case 0: rep.setServicePlanMonth1((String) monthCheckBoxesList.get(0).get("KEY")); //$NON-NLS-1$ break; case 1: rep.setServicePlanMonth2((String) monthCheckBoxesList.get(1).get("KEY")); //$NON-NLS-1$ break; case 2: rep.setServicePlanMonth3((String) monthCheckBoxesList.get(2).get("KEY")); //$NON-NLS-1$ break; case 3: rep.setServicePlanMonth4((String) monthCheckBoxesList.get(3).get("KEY")); //$NON-NLS-1$ break; case 4: rep.setServicePlanMonth5((String) monthCheckBoxesList.get(4).get("KEY")); //$NON-NLS-1$ break; case 5: rep.setServicePlanMonth6((String) monthCheckBoxesList.get(5).get("KEY")); //$NON-NLS-1$ break; default: break; } } monthCheckBoxesList.clear(); } } private void leaveToJobDetailForm() { app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailForm.JobDetailFormArgument(job, 2)); } public void onCancel() { monthCheckBoxesList.clear(); } private void fillComboTypeOfWork() { List typeOfWorkValueList = new ArrayList(); List workTypeList = app.dbutil.selectWorkTypeListByJobType(job.getJobType()); for (WorkType workType : workTypeList) { log.info("WorkType " + workType.getWorkTypeCode() + " text " + workType.getText() + " Guarantee " + workType.isGuarantee()); typeOfWorkValueList.add(new CustomSpinnerItem((String) workType.getWorkTypeCode(), (String) workType.getText())); } workTypeValue.setContents(typeOfWorkValueList); } private void fillComboProgress() { List billingValueList = new ArrayList(); List progresses = app.dbutil.selectProgress(); for (Progress progress : progresses) { log.info("Progress " + progress.getProgressCode() + " text " + progress.getText() + " Spras " + progress.getSpras()); billingValueList.add(new CustomSpinnerItem( progress.getProgressCode(), progress.getText())); } progressValue.setContents(billingValueList); } private void fillComboBilling() { List billingValueList = new ArrayList(); List invoiceList = app.dbutil.selectInvoiceList(); for (Invoice invoice : invoiceList) { billingValueList.add(new CustomSpinnerItem( invoice.getCode(), invoice.getText())); } billingValue.setContents(billingValueList); /** * Sets the "Standard" as default select. * see "[MIG-122] Create / edit report: The default of billing have to be "Standard"" */ billingValue.setSelection(0); } private void fillComboCustomerSupport() { List customerSupportValueList = new ArrayList(); Iterator> itr = app.enumUtil.reportSendTypeEnum.iterator(); while (itr.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = itr.next(); customerSupportValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } sendReportToValue.setContents(customerSupportValueList); } private void fillComboAddress() { List addressValueList = new ArrayList(); emailMap.clear(); addressValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, Messages.getString("pleaseSelect"))); //$NON-NLS-1$ //$NON-NLS-2$ Map addressesMap = this.job.getAddresses(); // addressValueList.add(new CustomSpinnerItem(this.job.getPartnerOfInstallAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.PARTNER_OF_INSTALLATION_ADDRESS))); retrieveAddressFromList(job.getPartnerOfInstallAddressId()).getEmail(); if (addressesMap.containsKey(this.job.getPartnerOfInstallAddressId())) { emailMap.put(this.job.getPartnerOfInstallAddressId(), retrieveAddressFromList(job.getPartnerOfInstallAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getPartnerOfInstallAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.PARTNER_OF_INSTALLATION_ADDRESS))); } if (addressesMap.containsKey(this.job.getKdnServiceAddressId())) { emailMap.put(this.job.getKdnServiceAddressId(), retrieveAddressFromList(job.getKdnServiceAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getKdnServiceAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.KDN_SERVICE_ADDRESS))); } if (addressesMap.containsKey(this.job.getCustomerAddressId())) { emailMap.put(this.job.getCustomerAddressId(), retrieveAddressFromList(job.getCustomerAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getCustomerAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.CUSTOMER_ADDRESS))); } if (addressesMap.containsKey(this.job.getPartnerAddressId())) { emailMap.put(this.job.getPartnerAddressId(), retrieveAddressFromList(job.getPartnerAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getPartnerAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.PARTNET_ADDRESS))); } if (addressesMap.containsKey(this.job.getObjectAddressId())) { emailMap.put(this.job.getObjectAddressId(), retrieveAddressFromList(job.getObjectAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getObjectAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.OBJECT_ADDRESS))); } if (addressesMap.containsKey(this.job.getOwnerAddressId())) { emailMap.put(this.job.getOwnerAddressId(), retrieveAddressFromList(job.getOwnerAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getOwnerAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.OWNER_ADDRESS))); } NumberFormat formatter = new DecimalFormat(CommonConstants.PLEASE_SELECT); if (CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL.equalsIgnoreCase(sendReportToValue.getSelectedId())) { List emails = app.dbutil.selectEmailListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); for (int i = 0; i < emails.size(); i++) { emails.get(i); String key = formatter.format(emailMap.size() + i + 1); addressValueList.add(new CustomSpinnerItem(key, ServiceMessages.getString("email") + " " + (i+2))); emailMap.put(key, emails.get(i).getEmail()); } } addressValue.setContents(addressValueList); } private void fillComboChecklist() { List checklistValueList = new ArrayList(); List checklists = app.dbutil.selectCheckList(); if (checklists != null) { for (int i = 0; i < checklists.size(); i++) { Checklist checklist = checklists.get(i); checklistValueList.add(new CustomSpinnerItem((String) checklist.getChecklistCode(), (String) checklist.getText())); } checklistValue.setContents(checklistValueList); } } private void fillComboIncident() { List incidentAValueList = new ArrayList(); List incidentBValueList = new ArrayList(); incidentAValueList.add(new CustomSpinnerItem("X", "Bitte w\u00E4hlen...")); incidentBValueList.add(new CustomSpinnerItem("X", "Bitte w\u00E4hlen...")); List incidentList = app.dbutil.selectIncidentList(); if (incidentList != null) { for (int i = 0; i < incidentList.size(); i++) { Incident incident = incidentList.get(i); log.info("Incident " + incident.getErrorCode() + " Fct " + incident.getFct() + " text " + incident.getText()); if ("A".equalsIgnoreCase(incident.getFct())) { //$NON-NLS-1$ incidentAValueList.add(new CustomSpinnerItem((String) incident.getErrorCode(), (String) incident.getText())); } else if ("B".equalsIgnoreCase(incident.getFct())){ incidentBValueList.add(new CustomSpinnerItem((String) incident.getErrorCode(), (String) incident.getText())); } } incidentAValue.setContents(incidentAValueList); incidentBValue.setContents(incidentBValueList); } } private void fillComboServiceRefused() { List serviceRefusedValueList = new ArrayList(); List serviceRefusedList = app.dbutil.selectServiceRefusedList(); log.info("ServiceRefused " + serviceRefusedList.size()); for (ServiceRefused serviceRefused : serviceRefusedList) { log.info("Service Refused " + serviceRefused.getCode() + " Code " + serviceRefused.getCode() + " text " + serviceRefused.getText()); serviceRefusedValueList.add(new CustomSpinnerItem((String) serviceRefused.getCode(), (String) serviceRefused.getText())); } serviceRefusedValue.setContents(serviceRefusedValueList); } private void fillComboServicePerformedMonth(List> comboCheckedList) { Report report = this.job.getLatestReport(); List servicePerformedValueMonthList = new ArrayList(); servicePerformedValueMonthList.add(new CustomSpinnerItem("00", "---")); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < comboCheckedList.size(); i++) { servicePerformedValueMonthList.add( new CustomSpinnerItem(comboCheckedList.get(i).get("KEY").toString(), comboCheckedList.get(i).get("VALUE").toString())); //$NON-NLS-1$ //$NON-NLS-2$ } servicePerformedMonthValue.setContents(servicePerformedValueMonthList); if (!report.getReportStatus().isInitial() && report.getMonthYear().length() > 0) { String saverl = report.getMonthYear().substring(0, 1); servicePerformedMonthValue.setSelectionById(saverl); } } private void fillComboServicePerformedYear() { List servicePerformedYearValueList = new ArrayList(); Report report = job.getLatestReport(); // Get the current year int year = DateTimeUtil.getToday().get(Calendar.YEAR); servicePerformedYearValueList.add(new CustomSpinnerItem("0000", "---")); //$NON-NLS-1$ //$NON-NLS-2$ for (int n=year-1; n<=year+1; n++) { servicePerformedYearValueList.add(new CustomSpinnerItem(String.valueOf(n), String.valueOf(n).substring(2))); } servicePerformedYearValue.setContents(servicePerformedYearValueList); if (!report.getReportStatus().isInitial() && report.getMonthYear().length() > 0 && report.getMonthYear().length() == 4) { String saverl = report.getMonthYear().substring(2, 4); servicePerformedYearValue.setSelectionByName(saverl); } } private void fillComboError() { List errorCodeList = app.dbutil.selectErrorCodeList(); if (errorCodeList != null) { List errorValueList = new ArrayList(); List error2ValueList = new ArrayList(); List errorMontValueList = new ArrayList(); for (int i = 0; i < errorCodeList.size(); i++) { ErrorCode errorCode = errorCodeList.get(i); errorValueList.add(new CustomSpinnerItem(errorCode.getErrorCode(), errorCode.getText())); error2ValueList.add(new CustomSpinnerItem(errorCode.getErrorCode(), errorCode.getText())); errorMontValueList.add(new CustomSpinnerItem(errorCode.getErrorCode(), errorCode.getText())); } errorValue.setContents(errorValueList); error2Value.setContents(error2ValueList); errorMontValue.setContents(errorMontValueList); } } private void fillCustomerSupportEditText() { addressValue.clearError(); customerSupportEditText.clearError(); customerSupportEditText.setEnabled(true); addressValue.setEnabled(true); // Entfernen des eMail-Adressen Valitators customerSupportEditText.setInputType(InputType.TYPE_CLASS_TEXT); // 01: Fax if (CommonConstants.Report.CUSTOMER_SUPPORT_FAX.equalsIgnoreCase(sendReportToValue.getSelectedId())) { //$NON-NLS-1$ // 00: Bitte whlen.. if (addressValue.getSelectedItemPosition() != 0) { customerSupportEditText.setInputType(InputType.TYPE_CLASS_PHONE); Address address = retrieveAddressFromList(addressValue.getSelectedId().toString()); customerSupportEditText.setText(address.getFaxNumber()); } } // 02: eMail else if (CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL.equalsIgnoreCase(sendReportToValue.getSelectedId())) { //$NON-NLS-1$ // eMail adress validator customerSupportEditText.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); String emailFromAddress = emailMap.get(addressValue.getSelectedId()); if (emailFromAddress != null && !emailFromAddress.isEmpty()) { customerSupportEditText.setText(emailFromAddress); } else { if (addressValue.getSelectedItemPosition() > 0) { app.showMessage("No Email form " + addressValue.getSelectedName()); } } } // 03: Formular -> Aufragsnummer als Defaultwert einsetzen else if (CommonConstants.Report.CUSTOMER_SUPPORT_FOMULAR.equalsIgnoreCase(sendReportToValue.getSelectedId())) { //$NON-NLS-1$ customerSupportEditText.setText(this.job.getJobNumber()); addressValue.setEnabled(false); } else { addressValue.setSelection(0); customerSupportEditText.setText(""); //$NON-NLS-1$ customerSupportEditText.setEnabled(false); addressValue.setEnabled(false); } } private void fillComboStateOfInstallation() { List stateOfInstallationList = new ArrayList(); List stateOfInstallations = app.dbutil.selectStateOfInstallation(); for (StateOfInstallation stateOfInstallation : stateOfInstallations) { log.info("StateOfInstallation " + stateOfInstallation.getCode() + " text " + stateOfInstallation.getText()); stateOfInstallationList.add(new CustomSpinnerItem( stateOfInstallation.getCode(), stateOfInstallation.getText())); } installationStateValue.setContents(stateOfInstallationList); } private void fillComboIntervention() { List interventionList = new ArrayList(); List nextInterventions = app.dbutil.selectNextIntervention(); for (NextIntervention nextIntervention : nextInterventions) { log.info("NextIntervention " + nextIntervention.getCode() + " text " + nextIntervention.getText()); interventionList.add(new CustomSpinnerItem( nextIntervention.getCode(), nextIntervention.getText())); } interventioValue.setContents(interventionList); } private Address retrieveAddressFromList(String addressNr) { Map addresses = this.job.getAddresses(); if (addresses.containsKey(addressNr)) { return addresses.get(addressNr); } else { log.error("Attempt to obtain an non existing address from job " + this.job.getJobNumber() + " AddressId = " + addressNr); //$NON-NLS-1$ //$NON-NLS-2$ return new Address(); } } private void clearCheckboxMonths() { january.setChecked(false); february.setChecked(false); march.setChecked(false); april.setChecked(false); may.setChecked(false); june.setChecked(false); july.setChecked(false); august.setChecked(false); september.setChecked(false); october.setChecked(false); november.setChecked(false); december.setChecked(false); } @Override public void onNothingSelected(AdapterView arg0) { // Do nothing } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("TYPEOFWORK".equals(parent.getTag())) { //$NON-NLS-1$ workTypeValue.clearError(); setCheckListEnabled(); setServicePerformedEnabled(); setServiceRefusedEnabled(); } else if ("PROGRESS".equals(parent.getTag())) { //$NON-NLS-1$ progressValue.clearError(); } else if ("BILLING".equals(parent.getTag())) { //$NON-NLS-1$ billingValue.clearError(); } else if ("CUSTOMERSUPPORT".equals(parent.getTag())) { //$NON-NLS-1$ sendReportToValue.clearError(); addressValue.clearError(); customerSupportEditText.clearError(); if(sendReportToValue.getSelectedItemPosition() == 0 || CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER.equalsIgnoreCase(sendReportToValue.getSelectedId())) { customerSupportEditText.setText(""); //$NON-NLS-1$ customerSupportEditText.setEnabled(false); addressValue.setEnabled(false); return; } customerSupportEditText.setEnabled(true); addressValue.setEnabled(true); if (this.job.getCurrentReport().getCustomerSupport().equalsIgnoreCase(sendReportToValue.getSelectedId())) { customerSupportEditText.setText(this.job.getCurrentReport().getCustomerSupportText()); } else { customerSupportEditText.getText().clear(); fillComboAddress(); if(CommonConstants.Report.CUSTOMER_SUPPORT_FOMULAR.equalsIgnoreCase(sendReportToValue.getSelectedId())) { customerSupportEditText.setText(this.job.getJobNumber()); addressValue.setEnabled(false); return; } if (addressValue.getSelectedItemPosition() > 0) { fillCustomerSupportEditText(); } } } else if ("ADDRESS".equals(parent.getTag())) { //$NON-NLS-1$ fillCustomerSupportEditText(); } else if ("CHECKLIST".equals(parent.getTag())) { //$NON-NLS-1$ checklistValue.clearError(); } else if ("COMPLETEMONTH".equals(parent.getTag())) { //$NON-NLS-1$ servicePerformedMonthValue.clearError(); servicePerformedYearValue.setEnabled(false); servicePerformedYearValue.clearError(); if (pos != ServiceConstants.Index.ZERO) { servicePerformedYearValue.setEnabled(true); } setServicePerformedEnabled(); setServiceRefusedEnabled(); } else if ("COMPLETEYEAR".equals(parent.getTag())) { //$NON-NLS-1$ servicePerformedYearValue.clearError(); setServicePerformedEnabled(); setServiceRefusedEnabled(); } else if ("SERVICEREFUSED".equals(parent.getTag())) { serviceRefusedValue.clearError(); setServicePerformedEnabled(); setServiceRefusedEnabled(); } } @Override public void afterTextChanged(Editable s) { // Do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // clear error message if (customerSupportEditText.hasFocus()) customerSupportEditText.clearError(); } @Override public void clearErrorMessages() { super.clearErrorMessages(); workTypeValue.clearError(); nextInterventionDateValue.clearError(); nextInterventionTimeText.clearError(); installationStateValue.clearError(); interventioValue.clearError(); billingValue.clearError(); checklistValue.clearError(); servicePerformedMonthValue.clearError(); commissionNumberLayout.clearError(); finalRepair.clearError(); customerSupportEditText.clearError(); cycleOfInstallation.clearError(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { String tag = buttonView.getTag().toString(); if (buttonView instanceof MDRadioButton) { finalRepair.clearError(); if ("PARTIALREPAIR".equals(buttonView.getTag().toString())) { finalRepair.setChecked(!partialRepair.isChecked()); if (isChecked) { app.showMessage(ServiceMessages.getString("secondVisitNeeded"), true); } } if ("FINALREPAIR".equals(buttonView.getTag().toString())) { app.clearMessage(); partialRepair.setChecked(!finalRepair.isChecked()); } nextInterventionDateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); nextInterventionTimeText.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); installationStateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); interventioValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); nextInterventionDateValue.setRequired(installationStateValue.isEnabled() && partialRepair.isChecked()); installationStateValue.setRequired(installationStateValue.isEnabled() && partialRepair.isChecked()); interventioValue.setRequired(interventioValue.isEnabled() && partialRepair.isChecked()); nextInterventionDateValue.clearError(); nextInterventionTimeText.clearError(); installationStateValue.clearError(); interventioValue.clearError(); } if (buttonView instanceof AppCompatCheckBox) { setCheckMonth(buttonView, tag); if ("REASONING".equals(buttonView.getTag().toString()) && isChecked) { //$NON-NLS-1$ app.showMessage(ServiceMessages.getString("rideToSideNotCharged")); //$NON-NLS-1$ } if ("OPENPENDING".equals(buttonView.getTag().toString()) && isChecked) { //$NON-NLS-1$ // app.showMessage(ServiceMessages.getString("rideToSideNotCharged")); //$NON-NLS-1$ } } } private void setCheckMonth(CompoundButton buttonView, String tag) { if (isMonth(tag.toUpperCase())){ AppCompatCheckBox dummy = (AppCompatCheckBox) buttonView; Map dummyMap = getAppCompatCheckBoxMap(dummy); if (dummy.isChecked()) { if (monthCheckBoxesList == null) monthCheckBoxesList = new ArrayList>(); if (!isContainValueInList(dummyMap)) { monthCheckBoxesList.add(dummyMap); } } else { removeMapFromCheckBoxesList(dummyMap); } if (monthCheckBoxesList.size() > 6) { app.showMessage(ServiceMessages.getString("maximumOfCheckdBoxesIs6")); //$NON-NLS-1$ dummy.setChecked(false); removeMapFromCheckBoxesList(dummyMap); } sortCheckBoxesAscList(monthCheckBoxesList); fillComboServicePerformedMonth(monthCheckBoxesList); } } private boolean isMonth(String tag) { boolean result = false; switch (tag) { case "JANUARY": //$NON-NLS-1$ case "FEBRUARY": //$NON-NLS-1$ case "MARCH": //$NON-NLS-1$ case "APRIL": //$NON-NLS-1$ case "MAY": //$NON-NLS-1$ case "JUNE": //$NON-NLS-1$ case "JULY": //$NON-NLS-1$ case "AUGUST": //$NON-NLS-1$ case "SEPTEMBER": //$NON-NLS-1$ case "OCTOBER": //$NON-NLS-1$ case "NOVEMBER": //$NON-NLS-1$ case "DECEMBER": //$NON-NLS-1$ result = true; break; default: break; } return result; } private Map getAppCompatCheckBoxMap(AppCompatCheckBox checkBox) { Map map = new HashMap(); String id = String.valueOf(checkBox.getId()); String key = id.length() == 1 ? "0" + id : id; //$NON-NLS-1$ map.put("KEY", key); //$NON-NLS-1$ map.put("VALUE", checkBox.getText().toString()); //$NON-NLS-1$ return map; } private void removeMapFromCheckBoxesList(Map input) { if (monthCheckBoxesList != null && !monthCheckBoxesList.isEmpty()) { for (Iterator> iter = monthCheckBoxesList.iterator(); iter.hasNext();) { Map map = iter.next(); Object innerKey = map.get("KEY"); //$NON-NLS-1$ if (innerKey.equals(input.get("KEY"))) { //$NON-NLS-1$ iter.remove(); return; } } } } private boolean isContainValueInList(Map input) { boolean result = false; if (monthCheckBoxesList != null && !monthCheckBoxesList.isEmpty()) { for (Map map : monthCheckBoxesList) { Object innerKey = map.get("KEY"); //$NON-NLS-1$ if (innerKey.equals(input.get("KEY"))) { //$NON-NLS-1$ result = true; return result; } } } return result; } private void setEnableMonthCheckBoxes(boolean enable) { january.setEnabled(enable); february.setEnabled(enable); march.setEnabled(enable); april.setEnabled(enable); may.setEnabled(enable); june.setEnabled(enable); july.setEnabled(enable); august.setEnabled(enable); september.setEnabled(enable); october.setEnabled(enable); november.setEnabled(enable); december.setEnabled(enable); } private AppCompatCheckBox getCheckboxByMonthCode(String monthCode) { AppCompatCheckBox result = null; if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.JAN)) { result = january; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.FEB)) { result = february; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.MAR)) { result = march; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.APR)) { result = april; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.MAY)) { result = may; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.JUN)) { result = june; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.JUL)) { result = july; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.AUG)) { result = august; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.SEP)) { result = september; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.OCT)) { result = october; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.NOV)) { result = november; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.DEC)) { result = december; } return result; } private void setCheckboxes(String savlfd) { if (monthCheckBoxesList == null) monthCheckBoxesList = new ArrayList>(); AppCompatCheckBox checkBoxMonth = getCheckboxByMonthCode(savlfd); if (checkBoxMonth != null) { checkBoxMonth.setChecked(true); } } private void initCheckboxMonths() { Iterator> itr = app.enumUtil.monthEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); // Leerelement ausschliessen if (!CommonConstants.PLEASE_SELECT.equalsIgnoreCase((String) entry.getKey())) { //$NON-NLS-1$ AppCompatCheckBox checkBoxMonth = getCheckboxByMonthCode((String) entry.getKey()); if(checkBoxMonth != null) { checkBoxMonth.setText((String) entry.getValue()); checkBoxMonth.setChecked(false); } } } } private void sortCheckBoxesAscList(List> listToBeSorted) { Comparator> mapComparator = new Comparator>() { @Override public int compare(Map m1, Map m2) { return m1.get("KEY").toString().compareTo(m2.get("KEY").toString()); //$NON-NLS-1$ //$NON-NLS-2$ } }; Collections.sort(listToBeSorted, mapComparator); } private void clearAllValue() { commissionType = null; clearPartialRepairAndFinalRepair(); commissionNumberLayout.clear(); jobNumber.getText().clear(); workTypeValue.setSelection(0); collectively.setChecked(false); safetyReport.setChecked(false); openPending.setChecked(false); governmentReport.setChecked(false); billingValue.setSelection(0); sendReportToValue.setSelection(0); addressValue.setSelection(0); customerSupportEditText.getText().clear(); checklistValue.setSelection(0); incidentAValue.setSelection(0); incidentBValue.setSelection(0); systemError.getText().clear(); serviceRefusedValue.setSelection(0); servicePerformedMonthValue.setSelection(0); servicePerformedYearValue.setSelection(0); distance.getText().clear(); expenses.getText().clear(); errorValue.setSelection(0); errorEditText1.getText().clear(); errorCheckbox.setChecked(false); error2Value.setSelection(0); error2EditText1.getText().clear(); error2Checkbox.setChecked(false); errorMontValue.setSelection(0); errorMontEditText1.getText().clear(); errorMontCheckbox.setChecked(false); monthCheckBoxesList.clear(); reasoning.setChecked(false); cycleOfInstallation.getText().clear(); clearCheckboxMonths(); servicePerformedMonthValue.setSelection(0); servicePerformedYearValue.setSelection(0); serviceRefusedValue.setSelection(0); nextInterventionDateValue.clearContents(); nextInterventionTimeText.getText().clear(); } private void loadReport(Report report) { jobNumber.setText(report.getOrderNumber()); // disable checkbox if report is already part of signature bundle collectively.setChecked(report.isCollectively()); collectively.setEnabled(report.getSignatureGuId().isEmpty()); safetyReport.setChecked(report.isSafetyReport()); setSelectTheSpinner(billingValue, report.getBilling()); setSelectTheSpinner(workTypeValue, report.getWorkType()); if (!report.getCustomerSupport().isEmpty()) { setSelectTheSpinner(sendReportToValue, report.getCustomerSupport()); } if(!report.getCustomerSupportText().isEmpty()) { customerSupportEditText.setText(report.getCustomerSupportText()); Iterator> emailEntrySetIterator = emailMap.entrySet().iterator(); while (emailEntrySetIterator.hasNext()) { java.util.Map.Entry emailEntry = emailEntrySetIterator.next(); if (emailEntry.getValue().equalsIgnoreCase(report.getCustomerSupportText())) { addressValue.setSelectionById(emailEntry.getKey()); } } } else { addressValue.setSelection(1); } setSelectTheSpinner(checklistValue, report.getChecklist()); if (report.getIncidentAB().length() > 0) { //$NON-NLS-1$ setSelectTheSpinner(incidentAValue, "0" + report.getIncidentAB().substring(0, 1)); setSelectTheSpinner(incidentBValue, "0" + report.getIncidentAB().substring(1)); } cycleOfInstallation.setText(report.getCycleOfInstallation()); setSelectTheSpinner(errorValue, report.getErrorId1()); if (StringUtil.isNotEmpty(report.getErrorH1())) errorEditText1.setText(report.getErrorH1()); errorCheckbox.setChecked(report.isErrorFlag1()); setSelectTheSpinner(error2Value, report.getErrorId2()); if (StringUtil.isNotEmpty(report.getErrorH2())) error2EditText1.setText(report.getErrorH2()); error2Checkbox.setChecked(report.isErrorFlag2()); setSelectTheSpinner(errorMontValue, report.getErrorId3()); if (StringUtil.isNotEmpty(report.getErrorH3())) errorMontEditText1.setText(report.getErrorH3()); errorMontCheckbox.setChecked(report.isErrorFlag3()); systemError.setText(report.getSystemError()); setCheckboxes(report.getServicePlanMonth1()); setCheckboxes(report.getServicePlanMonth2()); setCheckboxes(report.getServicePlanMonth3()); setCheckboxes(report.getServicePlanMonth4()); setCheckboxes(report.getServicePlanMonth5()); setCheckboxes(report.getServicePlanMonth6()); sortCheckBoxesAscList(monthCheckBoxesList); fillComboServicePerformedMonth(monthCheckBoxesList); if (report.getMonthYear().length() > 2) { setSelectTheSpinner(servicePerformedMonthValue, report.getMonthYear().substring(0, 2)); setSelectTheSpinner(servicePerformedYearValue, report.getMonthYear().substring(2, 4)); } else { setSelectTheSpinner(servicePerformedMonthValue, report.getMonthYear()); } setSelectTheSpinner(serviceRefusedValue, report.getServiceRefused()); if (job.getJobType().isMON()) { openPending.setChecked(report.isOpenPending()); governmentReport.setChecked(report.isGovernmentReport()); setSelectTheSpinner(progressValue, report.getMonStk()); log.info("progress " + report.getMonStk()); } else { if (!report.isPartialRepair() && !report.isFinalRepair()) { clearPartialRepairAndFinalRepair(); } else { partialRepair.setChecked(report.isPartialRepair()); finalRepair.setChecked(report.isFinalRepair()); } log.info("getNextInterventionDate " + DateTimeUtil.showDateTime(report.getNextInterventionDate())); if (report.getNextInterventionDate().getTime() > 0 ) { nextInterventionDateValue.setSelectedDate(report.getNextInterventionDate()); String nextInterventionTime = DateTimeUtil.showTimeGMT(report.getNextInterventionDate()); // if (!nextInterventionTime.equalsIgnoreCase("00:00") ) { nextInterventionTimeText.setText(nextInterventionTime); // } } installationStateValue.setSelectionById(report.getStateOfInstallation()); interventioValue.setSelectionById(report.getNextInterventionCode()); distance.setText(report.getDistance()); expenses.setText(report.getExpenses()); reasoning.setChecked(report.isReasoning()); } } private void setSelectTheSpinner(Spinner spinner, String input) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) spinner.getAdapter(); int spinnerPosition = adapter.getPosition(input); spinner.setSelection(spinnerPosition); } private String getExpense(){ String userInput = expenses.getText().toString(); if (!TextUtils.isEmpty(userInput)) { try { Locale locale = Locale.ENGLISH; if (userInput.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(userInput))); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("###.##", symbols); format.setMaximumFractionDigits(2); userInput = format.format(floatValue); } catch (NumberFormatException e) { return ""; } catch (ParseException e) { return ""; } catch (java.text.ParseException e) { return ""; } } return userInput; } private void setCheckListEnabled() { // Mandatory: // log.info("select work type " + workTypeValue.getSelectedName() + " is guarantee "); boolean checklisRequired = (job.getJobType().isSAV() || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT) || isWorkTypeMantenanceVonovia() ); checklistValue.setRequired(checklisRequired); checklistValue.clearError(); } private void setServicePerformedEnabled() { // Mandatory: Only if // or // or // servicePerformedMonthValue.setEnabled(false); if (servicePerformedMonthValue.getVisibility() == View.GONE) { return; } boolean isServicePerformedMandatory = ((job.getJobType().isSAV() && !(isWorkTypeMantenanceVonovia())) || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT)); boolean isServicePerformedRequired = (isServicePerformedMandatory || (job.isServiceRefusedFlag() && serviceRefusedValue.getSelectedItemPosition() == 0)); String text = servicePerformedText.getText().toString().replaceAll("\\*", "").trim();servicePerformedText.setEnabled(false); servicePerformedMonthValue.setEnabled(true); servicePerformedMonthValue.clearError(); servicePerformedYearValue.clearError(); servicePerformedText.setText(text); if (isServicePerformedRequired) { servicePerformedText.setText(servicePerformedText.getText().toString() + " *"); } } private void setServiceRefusedEnabled() { // Mandatory: Only if // ZKDMOB.AUART = REP and ZKDMOB.KNZSAVPFL = X and ZKDMOBREP.ARBA = // Displayed: Job type = REP / SAV serviceRefusedValue.setEnabled(false); if (serviceRefusedGridLayout.getVisibility() == View.GONE) { return; } serviceRefusedValue.setEnabled(job.isServiceRefusedFlag()); boolean isServiceRefusedRequired = job.isServiceRefusedFlag() && job.getJobType().isREP() && servicePerformedMonthValue.getSelectedItemPosition() == 0 && servicePerformedYearValue.getSelectedItemPosition() == 0 && (!workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT) && !isWorkTypeMantenanceVonovia()); String text = serviceRefusedText.getText().toString().replaceAll("\\*", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ serviceRefusedValue.clearError(); serviceRefusedText.setText(text); if (job.isServiceRefusedFlag() && isServiceRefusedRequired) { serviceRefusedText.setText(serviceRefusedText.getText().toString() + " *"); } } /** * * @return true if worktype = 98 or 99. */ private boolean isWorkTypeMantenanceVonovia() { return (workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA) || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_MAINTENANCE_VONOVIA)); } private void clearPartialRepairAndFinalRepair() { partialRepair.setOnCheckedChangeListener(null); finalRepair.setOnCheckedChangeListener(null); partialRepair.setChecked(false); finalRepair.setChecked(false); partialRepair.setOnCheckedChangeListener(this); finalRepair.setOnCheckedChangeListener(this); } } package ch.mfiles.kaba.kolibri.common.util; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.support.annotation.Nullable; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Checklist; import ch.mfiles.kaba.kolibri.common.businessobjects.Billing; import ch.mfiles.kaba.kolibri.common.businessobjects.Drive; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.ErrorCode; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.History; import ch.mfiles.kaba.kolibri.common.businessobjects.Incident; import ch.mfiles.kaba.kolibri.common.businessobjects.InternalWorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Invoice; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormDependency; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.FormValueList; import ch.mfiles.kaba.kolibri.common.businessobjects.OrderMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenses; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenseFile; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Progress; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.businessobjects.ReceiptOfGoods; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.NextIntervention; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.ServerJob; import ch.mfiles.kaba.kolibri.common.businessobjects.ServiceRefused; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.JobNoForm; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReturnReason; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Order; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.StateOfInstallation; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.Warehouse; import ch.mfiles.kaba.kolibri.common.db.FORM; import ch.mfiles.kaba.kolibri.common.db.FORMDEPENDENCY; import ch.mfiles.kaba.kolibri.common.db.FORMITEM; import ch.mfiles.kaba.kolibri.common.db.FORMVALUELIST; import ch.mfiles.kaba.kolibri.common.db.LocalizedTexts; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceNotification; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceType; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.FatalApplicationException; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBException; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.DBSqlHelper; import ch.mfiles.kolibri.db.LocalTransaction; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.DateUtils; public class DatabaseUtil { public static final Log log = LogFactory.getLog(DatabaseUtil.class); private static DatabaseUtil instance = null; private DBSession db; private DatabaseUtil() { db = Runtime.getApplicationManager().getDBSession(); } /** * Make sure we are *not* running on the UI thread. */ private void ensureAMThread() { ApplicationManager appman = (ApplicationManager)Runtime.getApplicationManager(); if (appman.getContext().getMainLooper().getThread() == Thread.currentThread()) throw new FatalApplicationException(Messages.getString("error")); //$NON-NLS-1$ } public static final DatabaseUtil getInstance() { if (instance == null) { instance = new DatabaseUtil(); } return instance; } private static Person mUser; public Person getUser() { return getUser(false); } public Person getUser(boolean reload) { if (reload) { mUser = null; } if (mUser == null) { mUser = selectActiveUser(); if (mUser == null) { throw new ApplicationException(Messages.getString("noUserActive")); //$NON-NLS-1$ } } return mUser; } public void setupFixedMasterData(boolean replace) { // reset some tables, if we have no localized texts (unclear, why...) boolean localizedTextsEmpty = LocalizedTexts.listByPrimaryKey(db, 1).length == 0; log.debug("localizedZextsEmpty=" + localizedTextsEmpty); //$NON-NLS-1$ if (localizedTextsEmpty) { db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.ReportMessage.REPORT_MESSAGE); db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.Incident.INCIDENT); db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.Drive.DRIVE); db.executeSql(DbConstants.DeleteFrom.DELETE_FROM + DbConstants.Billing.BILLING); } if (!localizedTextsEmpty && !replace) // texts already loaded... nothing to do return; log.debug("Reloading localized texts"); // create a local transaction (speeding up operations if not transaction was already started) LocalTransaction trans = new LocalTransaction(db); try { LocalizedTexts.delete(db); List listSql = SQLFileConverter.readFile(FileUtils .getAbsoluteFilePathName(CommonConstants.Application.COMMON, FileUtils.Packages.DATA, //$NON-NLS-1$ FileUtils.FileNames.FIXED_MASTERDATA, false)); //$NON-NLS-1$ for (int i = 0; i < listSql.size(); i++) { String sql = listSql.get(i); if (sql.startsWith("INSERT") && sql.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sql); } } trans.commit(); if(log.isDebugEnabled()) log.debug(Messages.getString("insertComplete")); //$NON-NLS-1$ } catch (IOException e) { log.error("Error processing localized texts...", e); } finally { if (trans.isPending()) trans.rollback(); } } public void insertJob(Job job) { Iterator
itr = job.getAddresses().values().iterator(); while (itr.hasNext()) { Address address = itr.next(); insertAddress(address); } DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Job.JOB).in( DbConstants.Job.JOB_NUMBER, job.getJobNumber()).in( DbConstants.Job.JOB_TYPE, job.getJobType().getCode()).in( DbConstants.Job.PERSONAL_NUMBER, job.getPersonalNumber()).in( DbConstants.Job.STATUS, job.getStatus().getCode()).in( DbConstants.Job.PRIORITY, job.getPriority()).in( DbConstants.Job.JOB_FORWARD, job.getJobForward()).in( DbConstants.Job.COMMISSION_NUMBER, job.getCommissionNumber()).in( DbConstants.Job.STAFF_NAME, job.getStaffName()).in( DbConstants.Job.STAFF_PHONE, job.getStaffPhoneNumber()).in( DbConstants.Job.APPOINTMENT_DATE, job.getAppointmentDate()).in( DbConstants.Job.ACTIVE_DATE, job.getActiveJobDate()).in( DbConstants.Job.JOB_RESCHEDULE_DATE, job.getJobRescheduleDate()).in( DbConstants.Job.JOB_RESCHEDULE_TIME, job.getJobRescheduleTime()).in( DbConstants.Job.WEEK, job.getWeek()).in( DbConstants.Job.FIX, job.getFix()).in( DbConstants.Job.APPOINTMENT, job.getAppointment()).in( DbConstants.Job.ORDER_NUMBER, job.getOrderNumber()).in( DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID, job.getPartnerOfInstallAddressId()).in( DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID, job.getKdnServiceAddressId()).in( DbConstants.Job.CUSTOMER_ADDRESS_ID, job.getCustomerAddressId()).in( DbConstants.Job.PARTNER_ADDRESS_ID, job.getPartnerAddressId()).in( DbConstants.Job.OBJECT_ADDRESS_ID, job.getObjectAddressId()).in( DbConstants.Job.OWNER_ADDRESS_ID, job.getOwnerAddressId()).in( DbConstants.Job.NEW_JOB_DATE, job.getNewJobDate()).in( DbConstants.Job.ERROR_ID, job.getErrorId()).in( DbConstants.Job.CALL_SERVICE_FLAG, job.getCallServiceFlag()).in( DbConstants.Job.MAINTENANCE_CONTRACT_TYPE, job.getMaintenanceContractType()).in( DbConstants.Job.SERVICE_PLAN_MONTH_1, job.getServicePlanMonth1()).in( DbConstants.Job.SERVICE_PLAN_MONTH_2, job.getServicePlanMonth2()).in( DbConstants.Job.SERVICE_PLAN_MONTH_3, job.getServicePlanMonth3()).in( DbConstants.Job.SERVICE_PLAN_MONTH_4, job.getServicePlanMonth4()).in( DbConstants.Job.SERVICE_PLAN_MONTH_5, job.getServicePlanMonth5()).in( DbConstants.Job.SERVICE_PLAN_MONTH_6, job.getServicePlanMonth6()).in( DbConstants.Job.SERVICE_OPEN, job.getServiceOpen()).in( DbConstants.Job.CONTACT_NAME, job.getContactName()).in( DbConstants.Job.CONTACT_PHONE, job.getContactPhoneNumber()).in( DbConstants.Job.TECHNICAL_NAME, job.getTechnicalName()).in( DbConstants.Job.TECHNICAL_PHONE, job.getTechnicalPhoneNumber()).in( DbConstants.Job.SELLER_NAME, job.getSellerName()).in( DbConstants.Job.SELLER_PHONE, job.getSellerPhoneNumber()).in( DbConstants.Job.STATUS_EDIT, job.getStatusEdit()).in( DbConstants.Job.DRIVER_TYPE, job.getDriveType()).in( DbConstants.Job.DRIVER_TYPE_UPD, job.isDriveTypeUpdated() ? "X" : "").in( //$NON-NLS-1$ //$NON-NLS-2$ DbConstants.Job.DEFAULT_TIME, job.getDefaultTime()).in( DbConstants.Job.DESCRIPTION, job.getInformation()).in( DbConstants.Job.INFORMATION, job.getDescription()).in( DbConstants.Job.CYCLE_OF_INSTALLATIN_FLAG, job.getCycleOfInstallationFlag()).in( DbConstants.Job.FORM_DESC_1, job.getFormDesc1()).in( DbConstants.Job.FORM_DESC_2, job.getFormDesc2()).in( DbConstants.Job.FORM_DESC_3, job.getFormDesc3()).in( DbConstants.Job.SERVICE_REFUSED_FLAG, job.getServiceRefusedFlag()).in( DbConstants.Job.LINK, job.getLink()).in( DbConstants.Job.GUARANTEE, job.getGuarantee()).in( DbConstants.Job.MORE_INFORMARION_FLAG, job.getGuarantee()).in( DbConstants.Job.CURRENT_REPORT_GUID, job.getCurrentReportGuId(this)) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertAddress(Address address) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Address.ADDRESS).in( DbConstants.Address.JOB_TYPE, address.getJobType().getCode()).in( DbConstants.Address.CITY, address.getCity()).in( DbConstants.Address.EMAIL, address.getEmail()).in( DbConstants.Address.FAX, address.getFaxNumber()).in( DbConstants.Address.CUSTOMER_NUMBER, address.getCustomerNumber()).in( DbConstants.Address.JOB_NUMBER, address.getJobNumber()).in( DbConstants.Address.NAME1, address.getName1()).in( DbConstants.Address.NAME2, address.getName2()).in( DbConstants.Address.NAME3, address.getName3()).in( DbConstants.Address.LOCATION, address.getLocation()).in( DbConstants.Address.PARTNER_NUMBER, address.getPartnerNummer()).in( DbConstants.Address.PASTAL_CODE,address.getPostalCode()).in( DbConstants.Address.STREET, address.getStreet()).in( DbConstants.Address.PHONE_1, address.getTelNumber1()).in( DbConstants.Address.PHONE_2, address.getTelNumber2()).in( DbConstants.Address.TITLE, address.getTitle()).in( DbConstants.Address.CHANGE_FLAG, address.getChangeFlag()).in( DbConstants.Address.COMMISSION_NUMBER, address.getCommissionNumber()).in( DbConstants.Address.DIRTY_FLAG, address.getDirtyFlag()).in( DbConstants.Address.TYPE, address.getType()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertEmail(Email email) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Email.EMAIL).in( DbConstants.Email.PARTNER_NUMBER, email.getPartnerNummer()).in( DbConstants.Email.JOB_TYPE, email.getJobType().getCode()).in( DbConstants.Email.TEXT, email.getEmail()).in( DbConstants.Email.JOB_NUMBER, email.getJobNumber()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } private void insertReplaceExpenses(Expenses expenses) { expenses.setExpenseCompensation(); DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Expenses.EXPENSES) .in(DbConstants.Expenses.DECUCTION ,expenses.getDeduction() ) .in(DbConstants.Expenses.DEDUCTION_DESCRIPTION ,expenses.getDeductionDescription() ) .in(DbConstants.Expenses.OPERATION_HOURS_UP_TO ,expenses.getOperatingHoursUpTo() ) .in(DbConstants.Expenses.OPERATION_HOURS_TOTAL ,expenses.getOperatingHoursTotal() ) .in(DbConstants.Expenses.OPERATING_HOURS_OF ,expenses.getOperatingHoursOf() ) .in(DbConstants.Expenses.DATE ,expenses.getDate() ) .in(DbConstants.Expenses.NO_EXPENSES ,expenses.getNoExpenses()) .in(DbConstants.Expenses.VARIOUS_EXPENSES ,expenses.getVariousExpenses() ) .in(DbConstants.Expenses.PERSONAL_NUMBER ,expenses.getPersonalNumber() ) .in(DbConstants.Expenses.PIKETT_EXPENSES ,expenses.getPikettExpenses() ) .in(DbConstants.Expenses.EXPENSES_KEY ,expenses.getExpensesKey() ) .in(DbConstants.Expenses.EXPENSES_DESCRIPTION ,expenses.getExpensesDescription() ) .in(DbConstants.Expenses.EXPENSES_DATE ,expenses.getExpensesDate() ) .in(DbConstants.Expenses.DAILY_EXPENSES ,expenses.getDailyExpenses() ) .in(DbConstants.Expenses.COMPENSTION ,expenses.getCompensation() ) .toString(); sqlStmt = sqlStmt.substring(0, 6) + " OR REPLACE " + sqlStmt.substring(7, sqlStmt.length()); //$NON-NLS-1$ int result = db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("Number of inserted records:'" + result + "' (SQL Statemant:/" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void insertOrderMaterial(OrderMaterial orderMaterial) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.OrderMaterial.ORDER_MATERIAL).in( DbConstants.OrderMaterial.DATE, orderMaterial.getDate()).in( DbConstants.OrderMaterial.EXPRESS_FLAG, orderMaterial.getExpressFlag()).in( DbConstants.OrderMaterial.VARIOUS_MATERIAL, orderMaterial.getVariousMaterial()).in( DbConstants.OrderMaterial.NUMBER, orderMaterial.getMaterialNumber()).in( DbConstants.OrderMaterial.PERSONAL_NUMBER, orderMaterial.getPersonalNumber()).in( DbConstants.OrderMaterial.AMOUNT, orderMaterial.getAmount()).in( DbConstants.OrderMaterial.UNIT, orderMaterial.getUnit()).in( DbConstants.OrderMaterial.ORDER_DATE, orderMaterial.getOrderDate()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } private void insertTimeSheet(TimeSheet timeSheet) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.TimeSheet.TIME_SHEET).in( DbConstants.TimeSheet.IDX, timeSheet.getIdx()).in( DbConstants.TimeSheet.PERSONAL_NUMBER, timeSheet.getPersonalNumber()).in( DbConstants.TimeSheet.DATE, timeSheet.getDate()).in( DbConstants.TimeSheet.START_TIME, timeSheet.getStartTime()).in( DbConstants.TimeSheet.STOP_TIME, timeSheet.getStopTime()).in( DbConstants.TimeSheet.COST_CENTER, timeSheet.getCostCenter()).in( DbConstants.TimeSheet.WORK_TYPE_CODE, timeSheet.getWorkTypeCode()).in( DbConstants.TimeSheet.CALL_FLAG, timeSheet.getCallFlag()) .toString(); int result = db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("Number of inserted records:'" + result + "' (SQL Statemant:/" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } static int getNextReportMaterialIdx(int requestedIdx, ReportMaterial maxReportMaterial) { if (maxReportMaterial == null) { return requestedIdx; } if (requestedIdx <= maxReportMaterial.getIdx()) { return maxReportMaterial.getIdx() + 1; } return requestedIdx; } public void insertNewReportMaterial(ReportMaterial reportMaterial) { ReportMaterial maxReportMaterial = selectMaxReportMaterial(reportMaterial.getGuId()); reportMaterial.setIdx(getNextReportMaterialIdx(reportMaterial.getIdx(), maxReportMaterial)); try { insertReportMaterial(reportMaterial); } catch (DBException e) { if (!isReportMaterialPrimaryKeyConstraint(e)) { throw e; } maxReportMaterial = selectMaxReportMaterial(reportMaterial.getGuId()); reportMaterial.setIdx(getNextReportMaterialIdx(reportMaterial.getIdx(), maxReportMaterial)); insertReportMaterial(reportMaterial); } } private boolean isReportMaterialPrimaryKeyConstraint(DBException exception) { String message = exception.getMessage(); return message != null && message.indexOf("ZKDMATORD.GUID") >= 0 //$NON-NLS-1$ && message.indexOf("ZKDMATORD.IDX") >= 0; //$NON-NLS-1$ } public void insertReportMaterial(ReportMaterial reportMaterial) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.ReportMaterial.REPORT_MATERIAL).in( DbConstants.ReportMaterial.IDX, reportMaterial.getIdx()).in( DbConstants.ReportMaterial.EXPRESS_DELIVERY, reportMaterial.getExpressDelivery()).in( DbConstants.ReportMaterial.GUID, reportMaterial.getGuId()).in( DbConstants.ReportMaterial.NUMBER, reportMaterial.getSparePartNumber()).in( DbConstants.ReportMaterial.DELIVERY, reportMaterial.getDelivery()).in( DbConstants.ReportMaterial.PERSONAL_NUMBER, reportMaterial.getPersonalNumber()).in( DbConstants.ReportMaterial.AMOUNT, reportMaterial.getAmount()).in( DbConstants.ReportMaterial.COMMISSION_NUMBER, reportMaterial.getCommissionNumber()).in( DbConstants.ReportMaterial.ACCOUNT_CODE, reportMaterial.getAccountCode()).in( DbConstants.ReportMaterial.UNIT, reportMaterial.getUnit()).in( DbConstants.ReportMaterial.NAME, reportMaterial.getProductName()).in( DbConstants.ReportMaterial.PRICE, reportMaterial.getPrice()).in( DbConstants.ReportMaterial.BARCODE, reportMaterial.getBarcode()).in( DbConstants.ReportMaterial.K14, reportMaterial.getK14()).in( DbConstants.ReportMaterial.EXPLANATION_TEXT, reportMaterial.getExplanationText()).in( DbConstants.ReportMaterial.OTHER_TYPE_FLAG, reportMaterial.getOtherTypeFlag()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertMaterialPerson(MaterialPerson materialOfPerson) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.MaterialPerson.MATERIAL_PERSON).in( DbConstants.MaterialPerson.NUMBER, materialOfPerson.getMaterialNumber()).in( DbConstants.MaterialPerson.TEXT, materialOfPerson.getMaterialShortText()).in( DbConstants.MaterialPerson.CUSTOMER_SERVICE_FLAG, materialOfPerson.getCustomerServiceFlag()).in( DbConstants.MaterialPerson.MOUNTING_FLAG, materialOfPerson.getMountingFlag()) .toString(); // if (log.isDebugEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ try { db.executeSql(sqlStmt); } catch (final Exception e) { ApplicationManager appman = (ApplicationManager)Runtime.getApplicationManager(); final Application app = (appman != null) ? (Application)appman.getActiveApplication() : null; if (app != null) appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase paramApplicationManagerBase, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry) { app.inform(e.getMessage()); return null; } }, false); } } public void insertServerJob( ServerJob serverJob) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.ServerJob.SERVER_JOB).in( DbConstants.ServerJob.JOB_TYPE, serverJob.getJobType().getCode()).in( DbConstants.ServerJob.CITY, serverJob.getCity()).in( DbConstants.ServerJob.JOB_NUMBER, serverJob.getJobNumber()).in( DbConstants.ServerJob.LOCATION, serverJob.getLocation()).in( DbConstants.ServerJob.PASTAL_CODE, serverJob.getPostalCode()).in( DbConstants.ServerJob.SERVICE_CONTRACT_TYPE, serverJob.getServiceContractType()).in( DbConstants.ServerJob.MONTH_YEAR, serverJob.getMonthYear()).in( DbConstants.ServerJob.STREET, serverJob.getStreet()).in( DbConstants.ServerJob.COMMISSION_NUMBER, serverJob.getCommissionNumber()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public boolean insertJobMessage(JobMessage jobMessage) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.JobMessage.JOB_MESSAGE).in( DbConstants.JobMessage.GUID, jobMessage.getGuId()).in( DbConstants.JobMessage.MESSAGE_ID, jobMessage.getMessageId()).in( DbConstants.JobMessage.MESSAGE_CODE, jobMessage.getMessageCode()).in( DbConstants.JobMessage.TEXT_1, jobMessage.getMessageCodeText()).in( DbConstants.JobMessage.TEXT_2, jobMessage.geText()).in( DbConstants.JobMessage.MoreText, jobMessage.getMoreText()) .toString(); try { if (log.isDebugEnabled()){ log.debug("sql /" + sqlStmt + "/");} //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMOBMSG:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public boolean insertReportMeasurement(ReportMeasurement reportMeasurement) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.ReportMeasurement.REPORT_MEASUREMENT).in( DbConstants.ReportMeasurement.GUID, reportMeasurement.getGuId()).in( DbConstants.ReportMeasurement.COMMISSION_NUMBER, reportMeasurement.getCommissionNumber()).in( DbConstants.ReportMeasurement.MEASURING_POINT, reportMeasurement.getMeasurementPoint()).in( DbConstants.ReportMeasurement.PERSONAL_NUMBER, reportMeasurement.getPersonalNumber()).in( DbConstants.ReportMeasurement.MEASUREMENT, reportMeasurement.getMeasurement()).in( DbConstants.ReportMeasurement.DYNAMIC_POWER_PEAK_VALUE, reportMeasurement.getDynamicPowerPeakValue()).in( DbConstants.ReportMeasurement.DYNAMIC_TIME, reportMeasurement.getDynamicTime()).in( DbConstants.ReportMeasurement.STATIC_END_POWER, reportMeasurement.getStaticEndPower()).in( DbConstants.ReportMeasurement.DEVICE_TYPE, reportMeasurement.getDeviceType()).in( DbConstants.ReportMeasurement.SN_OF_DEVICE, reportMeasurement.getSNOfDevice()).in( DbConstants.ReportMeasurement.CALIBRATION_DATE, reportMeasurement.getCalibrationDate()) .toString(); try { if (log.isDebugEnabled()){ log.debug("sql /" + sqlStmt + "/");} //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMOBMEAS:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public boolean insertVariousExpenses(VariousExpenses variousExpenses) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.VariousExpenses.VARIOUS_EXPENSES).in( DbConstants.VariousExpenses.PERSONAL_NUMBER, variousExpenses.getPersonalNumber()).in( DbConstants.VariousExpenses.DATE, variousExpenses.getDate().getTime()).in( DbConstants.VariousExpenses.IDX, variousExpenses.getVariousExpensesId()).in( DbConstants.VariousExpenses.AMOUNT, variousExpenses.getAmount()).in( DbConstants.VariousExpenses.EXPENSES_CODE, variousExpenses.getExpensesCode()) .toString(); try { log.info("sql /" + sqlStmt + "/"); if (log.isDebugEnabled()){ log.debug("sql /" + sqlStmt + "/");} //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMOBMEAS:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public boolean insertVariousExpenseFile(VariousExpenseFile variousExpenseFile) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE).in( DbConstants.VariousExpenseFile.PERSONAL_NUMBER, variousExpenseFile.getPersonalNumber()).in( DbConstants.VariousExpenseFile.DATE, variousExpenseFile.getDate().getTime()).in( DbConstants.VariousExpenseFile.IDX, variousExpenseFile.getVariousExpensesFileId()).in( DbConstants.VariousExpenseFile.DESCRIPTION, variousExpenseFile.getDescription()).in( DbConstants.VariousExpenseFile.SIGN_PIC_AT, variousExpenseFile.getSignpicAt()).in( DbConstants.VariousExpenseFile.FORM_TYPE, variousExpenseFile.getFormType().getCode()) .toString(); try { // if (log.isDebugEnabled()){ log.info("sql /" + sqlStmt + "/"); // } //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } catch (DBException e) { log.error("Unable to insert ZKDMAEXPNSPICS:'" + sqlStmt + "', error msg:" + e); //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } public void insertReplaceReport(Report report) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Report.REPORT) .in(DbConstants.Report.IDX, report.getIdx()) .in(DbConstants.Report.JOB_TYPE, report.getJobType().getCode()) .in(DbConstants.Report.COMMISSION_NUMBER, report.getCommissionNumber()) .in(DbConstants.Report.CHECK_LIST, report.getChecklist()) .in(DbConstants.Report.FINAL_REPAIR, report.getFinalRepair()) .in(DbConstants.Report.CREATE_DATE, report.getCreateDate()) .in(DbConstants.Report.ERROR_FLAG_1, report.getErrorFlag1()) .in(DbConstants.Report.ERROR_FLAG_2, report.getErrorFlag2()) .in(DbConstants.Report.ERROR_FLAG_3, report.getErrorFlag3()) .in(DbConstants.Report.SYSTEM_ERROR, report.getSystemError()) .in(DbConstants.Report.ERROR_ID_1, report.getErrorId1()) .in(DbConstants.Report.ERROR_ID_2, report.getErrorId2()) .in(DbConstants.Report.ERROR_ID_3, report.getErrorId3()) .in(DbConstants.Report.ERROR_H_1, report.getErrorH1()) .in(DbConstants.Report.ERROR_H_2, report.getErrorH2()) .in(DbConstants.Report.ERROR_H_3, report.getErrorH3()) .in(DbConstants.Report.REASONING, report.getReasoning()) .in(DbConstants.Report.GUID, report.getGuId()) .in(DbConstants.Report.DISTANCE, report.getDistance()) .in(DbConstants.Report.JOB_NUMBER, report.getJobNumber()) .in(DbConstants.Report.PERSONAL_NUMBER, report.getPersonalNumber()) .in(DbConstants.Report.SIGNATURE_GUID, report.getSignatureGuId()) .in(DbConstants.Report.CUSTOMER_SUPPORT, report.getCustomerSupport()) .in(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT, report.getCustomerSupportText()) .in(DbConstants.Report.REPORT_STATUS,report.getReportStatus().getCode()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_1, report.getServicePlanMonth1()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_2, report.getServicePlanMonth2()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_3, report.getServicePlanMonth3()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_4, report.getServicePlanMonth4()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_5, report.getServicePlanMonth5()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_6, report.getServicePlanMonth6()) .in(DbConstants.Report.MONTH_YEAR, report.getMonthYear()) .in(DbConstants.Report.SAFETY_REPORT, report.getSafetyReport()) .in(DbConstants.Report.SIGNATURE_FLAG, report.getSignatureFlag()) .in(DbConstants.Report.ORDER_NUMBER, report.getOrderNumber()) .in(DbConstants.Report.SIGNATURE, report.getSignature()) .in(DbConstants.Report.SIGNATURE_INFO, report.getSignatureInfo()) .in(DbConstants.Report.EXPENSES, report.getExpenses()) .in(DbConstants.Report.INCIDENT_AB, report.getIncidentAB()) .in(DbConstants.Report.PARTICAL_REPAIR, report.getPartialRepair()) .in(DbConstants.Report.BILLING, report.getBilling()) .in(DbConstants.Report.WORK_TYPE, report.getWorkType()) .in(DbConstants.Report.COLLECTIVELY, report.getCollectively()) .in(DbConstants.Report.NO_MATERIAL, report.getNoMaterial()) .in(DbConstants.Report.CYCLE_OF_INSTALLATION, report.getCycleOfInstallation()) .in(DbConstants.Report.NO_FORM1, report.getNoForm1()) .in(DbConstants.Report.NO_FORM2, report.getNoForm2()) .in(DbConstants.Report.NO_FORM3, report.getNoForm3()) .in(DbConstants.Report.SERVICE_REFUSED, report.getServiceRefused()) .in(DbConstants.Report.OPEN_PENDING, report.getOpenPending()) .in(DbConstants.Report.GOVERNMENT_REPORT, report.getGovernmentReport()) .in(DbConstants.Report.CHECKLIST_STATE, report.getChecklistState()) .in(DbConstants.Report.CHECKLIST_SIA, report.getChecklistSIA()) .in(DbConstants.Report.CHECKLIST_READY, report.getChecklistReady()) .in(DbConstants.Report.CHECKLIST_INSTRUCTION, report.getChecklistInstruction()) .in(DbConstants.Report.CHECKLIST_VKF, report.getChecklistVKF()) .in(DbConstants.Report.CHECKLIST_TEST, report.getChecklistTest()) .in(DbConstants.Report.SIGNATURE_NAME, report.getSignatureName()) .in(DbConstants.Report.MON_STK, report.getMonStk()) .in(DbConstants.Report.NEXT_INTERVENTION_DATE, report.getNextInterventionDate()) .in(DbConstants.Report.STATE_OF_INSTALLATION, report.getStateOfInstallation()) .in(DbConstants.Report.NEXT_INTERVENTION_CODE, report.getNextInterventionCode()) .toString(); sqlStmt = sqlStmt.substring(0, 6) + " OR REPLACE " + sqlStmt.substring(7, sqlStmt.length()); //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } /** * Saves the list of job times and updates the job status to 'in arbeit' * * @param zkdmob * @param zkdmobrtimList */ public void insertJobReportTimeList(Report report) { List jobReportTimeList = report.getTimes(); boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); deleteJobReportTimeByGUID(report.getGuId()); Iterator itr = jobReportTimeList.iterator(); while (itr.hasNext()) { JobReportTime jobReportTime = itr.next(); String sql = "INSERT OR REPLACE INTO " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " (" //$NON-NLS-1$ + DbConstants.JobReportTime.IDX + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.GUID + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.DATE + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.START_TIME + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.STOP_TIME + ", " //$NON-NLS-1$ + DbConstants.JobReportTime.WORK_TYPE_CODE + ") " //$NON-NLS-1$ + " VALUES (" //$NON-NLS-1$ + "'" + jobReportTime.getIdx() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getGuId() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getDate().getTime() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getStartTime().getTime() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getStopTime().getTime() + "', " //$NON-NLS-1$ //$NON-NLS-2$ + "'" + jobReportTime.getWorkTypeCode() + "') "; //$NON-NLS-1$ //$NON-NLS-2$ int affectedRows = db.executeSql(sql); // if (log.isDebugEnabled()) log.info("affected rows:'" + affectedRows + "'/ sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); } public void insertJobReportTime(JobReportTime jobReportTime) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.JobReportTime.JOB_REPORT_TIME) .in(DbConstants.JobReportTime.IDX, jobReportTime.getIdx()) .in(DbConstants.JobReportTime.GUID, jobReportTime.getGuId()) .in(DbConstants.JobReportTime.DATE, jobReportTime.getDate()) .in(DbConstants.JobReportTime.START_TIME, jobReportTime.getStartTime()) .in(DbConstants.JobReportTime.STOP_TIME, jobReportTime.getStopTime()) .in(DbConstants.JobReportTime.WORK_TYPE_CODE, jobReportTime.getWorkTypeCode()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertOrder(Order order) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Order.ORDER).in( DbConstants.Order.PERSONAL_NUMBER, order.getPersonalNumber()).in( DbConstants.Order.STATUS, order.getStatus()).in( DbConstants.Order.ANZ, order.getANZ()).in( DbConstants.Order.CREATED_DATE, order.getCreateDate()).in( DbConstants.Order.SENT_DATE, order.getSentDate()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void insertJobFile(JobFile jobFile) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.JobFile.JOB_FILE).in( DbConstants.JobFile.IDX, jobFile.getJobFileId()).in( DbConstants.JobFile.GUID, jobFile.getGuid()).in( DbConstants.JobFile.JOB_NUMBER, jobFile.getJobNumber()).in( DbConstants.JobFile.JOB_TYPE, jobFile.getJobType().getCode()).in( DbConstants.JobFile.TYPE, jobFile.getType()).in( DbConstants.JobFile.DESCRIPTION, jobFile.getDescription()).in( DbConstants.JobFile.SIGN_PIC_AT, jobFile.getSignpicAt()).in( DbConstants.JobFile.FORM_TYPE, jobFile.getFormType().getCode()).in( DbConstants.JobFile.FORM_DESC, jobFile.getFormDesc()).in( DbConstants.JobFile.SENT_DATE, jobFile.getSentDate()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); // remove image data from memory after update (lazy load; MIG-988) jobFile.setSignPicAt(null); } public void insertAbsenceNotification(AbsenceNotification absenceNotification) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION).in( DbConstants.AbsenceNotification.GUID, absenceNotification.getGuId()).in( DbConstants.AbsenceNotification.PERSONAL_NUMBER, absenceNotification.getPersonalNumber()).in( DbConstants.AbsenceNotification.DATE, absenceNotification.getAbsenceDate()).in( DbConstants.AbsenceNotification.DATE_FROM, absenceNotification.getDateFrom()).in( DbConstants.AbsenceNotification.TIME_FROM, absenceNotification.getTimeFrom()).in( DbConstants.AbsenceNotification.DATE_TO, absenceNotification.getDateTo()).in( DbConstants.AbsenceNotification.TIME_TO, absenceNotification.getTimeTo()).in( DbConstants.AbsenceNotification.ABSENCE_TYPE, absenceNotification.getAbsenceType()).in( DbConstants.AbsenceNotification.TEXT, absenceNotification.getText()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } /** * Saves the list of report form instances * */ public void insertOrReplaceJobReportFormInstanceList(List formInstances) { boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); Iterator itr = formInstances.iterator(); while (itr.hasNext()) { FormInstance formInstance = itr.next(); DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.FormInstance.FORMINSTANCE ).in( DbConstants.FormInstance.GUID, formInstance.getGuid()).in( DbConstants.FormInstance.FORM_ID, formInstance.getFormId()).in( DbConstants.FormInstance.FORM_VERSION, formInstance.getFormVersion()).in( DbConstants.FormInstance.FORM_ITEM_ID, formInstance.getFormItemId()).in( DbConstants.FormInstance.VALUE_LIST_ID, formInstance.getValueListId()).in( DbConstants.FormInstance.VALUE_ID, formInstance.getValueId()).in( DbConstants.FormInstance.FORM_ITEM_TYPE, formInstance.getFormItemType().getCode()).in( DbConstants.FormInstance.STRING_VALUE, formInstance.getStringValue()).in( DbConstants.FormInstance.BOOLEAN_VALUE, formInstance.isBooleanValue()).in( DbConstants.FormInstance.FLOAT_VALUE, formInstance.getFloatValue()).in( DbConstants.FormInstance.ATTACHMENT_VALUE, formInstance.getAttachmentValue()) .toString(); sqlStmt = sqlStmt.substring(0, 6) + " OR REPLACE " + sqlStmt.substring(7, sqlStmt.length()); //$NON-NLS-1$ db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); } public void insertMaterialMovement(MaterialMovement materialMovement) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.MaterialMovement.MATRIAL_MOVEMENT).in( DbConstants.MaterialMovement.GUID, materialMovement.getGuid()).in( DbConstants.MaterialMovement.ORDER_NUMBER, materialMovement.getOrderNumber()).in( DbConstants.MaterialMovement.ORDER_POSITION, materialMovement.getOrderPosition()).in( DbConstants.MaterialMovement.PERSONAL_NUMBER, materialMovement.getPersonalNumber()).in( DbConstants.MaterialMovement.MATERIAL_NUMBER, materialMovement.getMaterialNumber()).in( DbConstants.MaterialMovement.FROM, materialMovement.getFrom()).in( DbConstants.MaterialMovement.TO, materialMovement.getTo()).in( DbConstants.MaterialMovement.ENTRY_COUNT, materialMovement.getEntryCount()).in( DbConstants.MaterialMovement.ENTRY_UNIT, materialMovement.getEntryUnit()).in( DbConstants.MaterialMovement.RECEIPT_OF_GOODS, materialMovement.getReceiptOfGoods()).in( DbConstants.MaterialMovement.BARCODE, materialMovement.getBarcode()).in( DbConstants.MaterialMovement.BARCODE_TEXT, materialMovement.getBarcodeText()).in( DbConstants.MaterialMovement.PERSONAL_NUMBER_CONFIRMED, materialMovement.getPersonalNumberConfirmed()) .toString(); if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } /** * Selects count (number of records) from a table. * * @param table * the table * @return the row count of the table, 0 if it contains no records */ public int selectCountFromTable(String table, String criteria) { RecordSet rs = db.getRecordSet(); try { String sql = "SELECT COUNT(*) FROM " + table; //$NON-NLS-1$ if (!"".equalsIgnoreCase(criteria)) { //$NON-NLS-1$ sql += criteria; } rs.setQuery(sql); if (log.isDebugEnabled()) log.debug("sql / " + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.moveNext(); return rs.getInt(0); } finally { rs.dispose(); } } public LocalizedTexts[] selectLocalizedTextsList(String textType) { return LocalizedTexts.listByPrimaryKey(db, "%", true, setDefaultLanguage(getUser().getLanguage()), false, textType, false, Integer.MAX_VALUE); } public enum JobStatusFilter { active, planned, finalized } public List selectJobList() { // ensureAMThread(); List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String order = " ORDER BY CASE " + DbConstants.Job.STATUS + " WHEN '" + JobStatus.IN_PROGRESS + "' THEN 1" + " WHEN '" + JobStatus.NEW + "' THEN 2" + " WHEN '" + JobStatus.RECEIVED + "' THEN 3" + " WHEN '" + JobStatus.PARLTY_DONE + "' THEN 4" + " ELSE 5 END"; //$NON-NLS-1$ String sql = "SELECT * FROM " + DbConstants.Job.JOB; //$NON-NLS-1$ order += ", " + DbConstants.Job.NEW_JOB_DATE + " DESC" + ", " + DbConstants.Job.APPOINTMENT_DATE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sql = sql + order; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } public List selectJobList( JobStatusFilter jobStatusFilter , boolean filterRep , boolean filterSav , boolean filterMon) { ensureAMThread(); List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String auartList = ""; //$NON-NLS-1$ if (filterRep) { auartList = auartList.concat("'" + JobType.REP + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } if (filterSav && StringUtil.isNotEmpty(auartList)) { auartList = auartList.concat(","); //$NON-NLS-1$ } if (filterSav) { auartList = auartList.concat("'" + JobType.SAV + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } if (filterMon && StringUtil.isNotEmpty(auartList)) { auartList = auartList.concat(","); //$NON-NLS-1$ } if (filterMon) { auartList = auartList.concat("'" + JobType.MON + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } String sortingAuart = "CASE " + DbConstants.Job.JOB_TYPE + " WHEN '" + JobType.MON + "' THEN 1 WHEN '" + JobType.SAV + "' THEN 2 ELSE 3 END"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ String eDate = ""; //$NON-NLS-1$ String activeDate = ""; //$NON-NLS-1$ String statusList = ""; //$NON-NLS-1$ String order = " ORDER BY CASE " + DbConstants.Job.STATUS + " WHEN '" + JobStatus.IN_PROGRESS + "' THEN 1" + " WHEN '" + JobStatus.NEW + "' THEN 2" + " WHEN '" + JobStatus.RECEIVED + "' THEN 3" + " WHEN '" + JobStatus.PARLTY_DONE + "' THEN 4" + " ELSE 5 END"; //$NON-NLS-1$ // String todayDate = "(SELECT CAST(strftime('%s', date('now')) * 1000 AS INT))";//20.09.17 00.00.00->1505860000000 // String tomorrow = "(SELECT CAST(strftime('%s', date('now','+1 day')) * 1000 AS INT))";//21.09.17 00.00.00->1505952000000 String twoDaysInTheFuture = "(SELECT CAST(strftime('%s', date('now','+2 day')) * 1000 AS INT))";//22.09.17 00.00.00->1560384000000 String eightyNightDaysInTheFuture = "(SELECT CAST(strftime('%s', date('now','+2 day')) * 1000 AS INT))";//22.09.17 00.00.00->1560384000000 String timeCount = "SELECT COUNT(" + DbConstants.JobReportTime.GUID + ") FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.JOB_REPORT_TIME + "." + DbConstants.JobReportTime.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String reportCount = "SELECT COUNT(" + DbConstants.Report.GUID + ") FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.REPORT + "." + DbConstants.Report.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String matCount = "SELECT COUNT(" + DbConstants.ReportMaterial.GUID + ") FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.REPORT_MATERIAL + "." + DbConstants.ReportMaterial.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String messageCount = "SELECT COUNT(" + DbConstants.JobMessage.GUID + ") FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.JOB_MESSAGE + "." + DbConstants.JobMessage.GUID + " = " + DbConstants.Job.JOB + "." + DbConstants.Job.CURRENT_REPORT_GUID; String reports = ""; switch (jobStatusFilter) { case active: statusList = "'" + JobStatus.NEW + "'," + "'" + JobStatus.RECEIVED + "'," + "'" + JobStatus.IN_PROGRESS + "'," + "'" + JobStatus.PARLTY_DONE + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //STATUS = NEW OR ZKDMOB.EDATE <= 1 day ( in the past , today and tomorrow) // MON, REP edate - 3 days <= current date // SAV edate - 90 days <= current date eDate = " AND " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " <= " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " <= " + eightyNightDaysInTheFuture + ")" + ")" ; // MON, REP active date - 3 days <= current date // SAV active date - 90 days <= current date activeDate = " AND " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.ACTIVE_DATE + " <= " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.ACTIVE_DATE + " <= " + eightyNightDaysInTheFuture + ")" + ")" ; // check if job active //- report is not empty //- time is not empty //- material is not empty //- message is not empty reports = "" + " OR (" + "(" + timeCount + ") > 0" + " OR (" + reportCount + ") > 0" + " OR (" + matCount + ") > 0" + " OR (" + messageCount + ") > 0" + ") AND ("+ DbConstants.Job.STATUS + " NOT IN ('" + JobStatus.FORWARDED + "', '" + JobStatus.FINALIZED + "'))"; order += ", " + sortingAuart; //$NON-NLS-1$ break; case planned: statusList = "'" + JobStatus.RECEIVED + "'," + "'" + JobStatus.PARLTY_DONE + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //ZKDMOB.EDATE > 1 day ( pass tomorrow and more than 2 days in the future) // MON, REP edate - 3 days >= current date // SAV edate - 90 days >= current date eDate = " AND " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " > " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.APPOINTMENT_DATE + " > " + eightyNightDaysInTheFuture + ")" + ")" ; // MON, REP active date - 3 days ><= current date // SAV active date - 90 days >= current date activeDate = " OR " + "(" + "(" + DbConstants.Job.JOB_TYPE + " NOT IN ('" + JobType.SAV + "')" + " AND " + DbConstants.Job.ACTIVE_DATE + " > " + twoDaysInTheFuture + ")" + " OR (" + DbConstants.Job.JOB_TYPE + " = '" + JobType.SAV + "'" + " AND " + DbConstants.Job.ACTIVE_DATE + " > " + eightyNightDaysInTheFuture + ")" + ")" ; // no reports. reports = "" + " AND (" + "(" + matCount + ") = 0" + " AND (" + timeCount + ") = 0" + " AND (" + reportCount + ") = 0" + " AND (" + messageCount + ") = 0" + ")"; ; break; case finalized: statusList = "'" + JobStatus.FORWARDED + "'," + "'" + JobStatus.FINALIZED + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ order = " ORDER BY " + DbConstants.Job.STATUS_EDIT + " DESC"; break; } order += ", " + DbConstants.Job.NEW_JOB_DATE + " DESC" + ", " + DbConstants.Job.APPOINTMENT_DATE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String sql = "SELECT * FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + DbConstants.Job.STATUS + " IN (" + statusList + ")" + " AND " + DbConstants.Job.JOB_TYPE + " IN (" + auartList + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ if (StringUtil.isNotEmpty(eDate)) { sql = sql + eDate; //$NON-NLS-1$ } if (StringUtil.isNotEmpty(activeDate)) { sql = sql + activeDate; //$NON-NLS-1$ } if (StringUtil.isNotEmpty(reports)) { sql = sql + reports; //$NON-NLS-1$ } sql = sql + order; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } public List selectFinalizedJobList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String statusList = "'" + JobStatus.REJECTED + "'," //$NON-NLS-1$ //$NON-NLS-2$ + "'" + JobStatus.FINALIZED + "'," //$NON-NLS-1$ //$NON-NLS-2$ + "'" + JobStatus.DELETED + "' "; //$NON-NLS-1$ //$NON-NLS-2$ String sql = "SELECT * FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + DbConstants.Job.STATUS + " IN (" + statusList + ")" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.Job.STATUS + ",rowid"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } public Job selectJobByJobIdAndJobType( String jobId, String jobType) { Job result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Job.JOB + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.Job.JOB_NUMBER + " = '" + jobId + "'" + " AND " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + DbConstants.Job.JOB_TYPE + " = '" + jobType + "'"; //$NON-NLS-1$ //$NON-NLS-2$ // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Job(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple /" + jobId + "/ and /" + jobType + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } finally { rs.dispose(); } return result; } public List
selectAddressListByJobIdAndJobType(String jobId, String jobType) { List
result = new ArrayList
(); String sql = "SELECT * FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + jobType + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info(sql); if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); if (rs.isEmpty()) { result.add(new Address()); } else { while (rs.moveNext()) { result.add(new Address(rs)); } } } finally { rs.dispose(); } return result; } public List selectEmailListByJobIdAndJobType(String jobId, String jobType) { List result = new ArrayList(); String sql = "SELECT * FROM " + DbConstants.Email.EMAIL //$NON-NLS-1$ + " WHERE " + DbConstants.Email.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Email.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER By " + DbConstants.Email.TEXT + " ASC"; log.info(sql); if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ RecordSet rs = db.getRecordSet(); try { rs.setQuery(sql); while (rs.moveNext()) { result.add(new Email(rs)); } } finally { rs.dispose(); } return result; } public Address selectAddressByJobIdAndJobTypeAndPerNo( String jobId, String jobType, String perNo) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.PARTNER_NUMBER + " = '" + perNo + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Address result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug(DbConstants.Address.JOB_NUMBER + " = " + jobId //$NON-NLS-1$ + " AND " + DbConstants.Address.JOB_TYPE + " = " //$NON-NLS-1$ //$NON-NLS-2$ + jobId + " AND " + DbConstants.Address.PARTNER_NUMBER //$NON-NLS-1$ + " = " + perNo + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Address(rs); } } finally { rs.dispose(); } return result; } public Email selectEmailByJobIdAndJobTypeAndPerNo( String jobId, String jobType, String perNo) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Email.EMAIL //$NON-NLS-1$ + " WHERE " + DbConstants.Email.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Email.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Email.PARTNER_NUMBER + " = '" + perNo + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Email result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug(DbConstants.Email.JOB_NUMBER + " = " + jobId //$NON-NLS-1$ + " AND " + DbConstants.Email.JOB_TYPE + " = " //$NON-NLS-1$ //$NON-NLS-2$ + jobId + " AND " + DbConstants.Email.PARTNER_NUMBER //$NON-NLS-1$ + " = " + perNo + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Email(rs); } } finally { rs.dispose(); } return result; } public WorkType selectWorkTypeByJobTypeAndWorkTypeCode(JobType jobType, String workTypeCode) { RecordSet rs = db.getRecordSet(); String frm = ""; //$NON-NLS-1$ if (jobType.isREP() || jobType.isSAV()) frm = "04"; //$NON-NLS-1$ else if (jobType.isMON()) frm = "03"; //$NON-NLS-1$ String sql = "SELECT * FROM " + DbConstants.WorkType.WORK_TYPE //$NON-NLS-1$ + " WHERE " + DbConstants.WorkType.GROUP + " ='" + frm + "'" + " AND " + DbConstants.WorkType.CODE + " ='" + workTypeCode + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); WorkType result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new WorkType(rs); } } finally { rs.dispose(); } return result; } public List selectWorkTypeListByJobType(JobType jobType) { RecordSet rs = db.getRecordSet(); List result = new ArrayList(); String frm = ""; //$NON-NLS-1$ if (jobType.isREP() || jobType.isSAV()) frm = "04"; //$NON-NLS-1$ else if (jobType.isMON()) frm = "03"; //$NON-NLS-1$ String sql = "SELECT * FROM " + DbConstants.WorkType.WORK_TYPE //$NON-NLS-1$ + " WHERE " + DbConstants.WorkType.GROUP + " ='" + frm + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new WorkType(rs)); } } finally { rs.dispose(); } return result; } public List selectStateOfInstallation() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.StateOfInstallation.STATE_OF_INSTALLATION; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new StateOfInstallation(rs)); } } finally { rs.dispose(); } return result; } public List selectNextIntervention() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.NextIntervention.NEXT_INVENTION; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new NextIntervention(rs)); } } finally { rs.dispose(); } return result; } public ErrorCode selectErrorCodeByFc( String fc) { RecordSet rs = db.getRecordSet(); ErrorCode result = null; String sql = "SELECT * FROM " + DbConstants.ErrorCode.ERROR_CODE + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.ErrorCode.CODE + " ='" + fc + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result = new ErrorCode(rs); } } finally { rs.dispose(); } return result; } public List selectErrorCodeList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ErrorCode.ERROR_CODE //$NON-NLS-1$ + " ORDER BY " + DbConstants.ErrorCode.CODE; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ErrorCode(rs)); } } finally { rs.dispose(); } return result; } public List selectShortMessageListbyPerNo( int pernr) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.ShortMessage.RECEIVED_TIME + " DESC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ShortMessage(rs)); } } finally { rs.dispose(); } return result; } public ShortMessage selectShortMessageByPerNoAndTdName( int pernr, String tdName) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ShortMessage.MESSAGE_KEY + " ='" + tdName + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); ShortMessage result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ShortMessage(rs); } } finally { rs.dispose(); } return result; } public List selectInternalWorkTypeList() { RecordSet rs = db.getRecordSet(); List result = new ArrayList(); String sql = "SELECT * FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new InternalWorkType(rs)); } } finally { rs.dispose(); } return result; } public InternalWorkType selectInternalWorkTypeByWorkTypeCode(String workTypeCode) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE //$NON-NLS-1$ + " WHERE " + DbConstants.InternalWorkType.CODE + " ='" + workTypeCode + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); InternalWorkType result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new InternalWorkType(rs); } } finally { rs.dispose(); } return result; } public List selectServiceRefusedList() { RecordSet rs = db.getRecordSet(); List result = new ArrayList(); String sql = "SELECT * FROM " + DbConstants.ServiceRefused.SERVICE_REFUSED; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ServiceRefused(rs)); } } finally { rs.dispose(); } return result; } public void updateShortMessage( ShortMessage shortMessage) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.ShortMessage.SHORT_MESSAGE) .in(DbConstants.ShortMessage.SUBJECT, shortMessage.getSubject()) .in(DbConstants.ShortMessage.CONFIRM, shortMessage.getConfirm()) .in(DbConstants.ShortMessage.MESSAGE, shortMessage.getMessage()) .in(DbConstants.ShortMessage.STATUS, shortMessage.getStatus()) .in(DbConstants.ShortMessage.RECEIVED_DATE, shortMessage.getReceiveDate()) .in(DbConstants.ShortMessage.RECEIVED_TIME, shortMessage.getReceiveTime()) + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " = '" + shortMessage.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ShortMessage.MESSAGE_KEY + " = '" + shortMessage.getMessageKey() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void updateVariousExpenses(VariousExpenses variousExpenses) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.VariousExpenses.VARIOUS_EXPENSES) .in(DbConstants.VariousExpenses.PERSONAL_NUMBER, variousExpenses.getPersonalNumber()) .in(DbConstants.VariousExpenses.DATE, variousExpenses.getDate().getTime()) .in(DbConstants.VariousExpenses.IDX, variousExpenses.getVariousExpensesId()) .in(DbConstants.VariousExpenses.AMOUNT, variousExpenses.getAmount()) .in(DbConstants.VariousExpenses.EXPENSES_CODE, variousExpenses.getExpensesCode()) + " WHERE " + DbConstants.VariousExpenses.PERSONAL_NUMBER + " = '" + variousExpenses.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenses.DATE + " ='" + variousExpenses.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenses.IDX + " ='" + variousExpenses.getVariousExpensesId() + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public void updateVariousExpenseFile(VariousExpenseFile variousExpenseFile) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE) .in(DbConstants.VariousExpenseFile.PERSONAL_NUMBER, variousExpenseFile.getPersonalNumber()) .in(DbConstants.VariousExpenseFile.DATE, variousExpenseFile.getDate().getTime()) .in(DbConstants.VariousExpenseFile.IDX, variousExpenseFile.getVariousExpensesFileId()) .in(DbConstants.VariousExpenseFile.DESCRIPTION, variousExpenseFile.getDescription()) .in(DbConstants.VariousExpenseFile.SIGN_PIC_AT, variousExpenseFile.getSignpicAt()) .in(DbConstants.VariousExpenseFile.FORM_TYPE, variousExpenseFile.getFormType().getCode()) + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " = '" + variousExpenseFile.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenseFile.DATE + " ='" + variousExpenseFile.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenseFile.IDX + " ='" + variousExpenseFile.getVariousExpensesFileId() + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ db.executeSql(sqlStmt); } public ReportMessage selectReportMessageByMsgc( String msgc) { ReportMessage result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMessage.REPORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMessage.CODE + " = '" + msgc + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ReportMessage(rs); } } finally { rs.dispose(); } return result; } public JobMonText selectReportMONMessageByMsgcAndLangu( String msgc, String langu) { JobMonText result = null; // TODO "ZKDMOBMONTXT" missing "Language" from server. langu=""; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMonText.JOB_MON_TEXT //$NON-NLS-1$ + " WHERE " + DbConstants.JobMonText.CODE + " = '" + msgc + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobMonText.LANGUAGE + " = '" + langu + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobMonText(rs); } } finally { rs.dispose(); } return result; } public List selectReportMessage() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMessage.REPORT_MESSAGE; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMessage(rs)); } } finally { rs.dispose(); } return result; } public List selectJobMonMessageByLangu( String langu) { List result = new ArrayList(); // TODO "ZKDMOBMONTXT" missing "Language" from server. langu =""; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMonText.JOB_MON_TEXT//$NON-NLS-1$ + " WHERE " + DbConstants.JobMonText.LANGUAGE + " = '" + langu + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobMonText.CODE + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMonText(rs)); } } finally { rs.dispose(); } return result; } // public Incident selectIncidentByZiff( String strc, String ziff, String langu) { // Incident result = null; // // RecordSet rs = db.getRecordSet(); // // String sql = "SELECT * FROM " + DbConstants.Incident.Incident //$NON-NLS-1$ // + " WHERE " + DbConstants.Incident.ErrorCode + " ='" + strc //$NON-NLS-1$ //$NON-NLS-2$ // + "'" + " AND " + DbConstants.Incident.ZIFF + " ='" + ziff //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // + "'" + " AND " + DbConstants.Incident.Language + " ='" + langu //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // + "'"; //$NON-NLS-1$ // // if (log.isDebugEnabled()) // log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ // // rs.setQuery(sql); // // try { // while (rs.moveNext()) { // result = new Incident(rs); // } // } finally { // rs.dispose(); // } // return result; // } public Incident selectIncidentByFCT( String errorCode, String fct) { Incident result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Incident.INCIDENT //$NON-NLS-1$ + " WHERE " + DbConstants.Incident.CODE + " ='" + errorCode //$NON-NLS-1$ //$NON-NLS-2$ + "'" + " AND " + DbConstants.Incident.FCT + " ='" + fct //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "'"; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result = new Incident(rs); } } finally { rs.dispose(); } return result; } public List selectIncidentList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Incident.INCIDENT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Incident(rs)); } } finally { rs.dispose(); } return result; } public List selectHistoryList(String mldnr, String auart) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.History.HISTORY //$NON-NLS-1$ + " WHERE " + DbConstants.History.JOB_NUMBER + " = '" + mldnr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.History.JOB_TYPE + " = '" + auart + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new History(rs)); } } finally { rs.dispose(); } return result; } public List selectCheckList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Checklist.CHECK_LIST; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Checklist(rs)); } } finally { rs.dispose(); } return result; } public List selectProgress() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Progress.PROGRESS; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Progress(rs)); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ public List selectPersonList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Person.PERSON; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Person(rs)); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectExpensesList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Expenses(rs)); } } finally { rs.dispose(); } return result; } public List selectOrderMaterialList(Order order) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.OrderMaterial.ORDER_DATE + " ='" + order.getCreateDate().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new OrderMaterial(rs)); } } finally { rs.dispose(); } return result; } /** * @param von * @param pernr * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private TimeSheet selectActiveTimeSheetByFromDate(Date von, int pernr) { RecordSet rs = db.getRecordSet(); Date earlyMorning = DateTimeUtil.getDate(von).getTime(); Date lateNight = DateTimeUtil.getLateNight(von).getTime(); String sql = "SELECT * FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = " + pernr //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.IDX + " = " + //$NON-NLS-1$ //$NON-NLS-2$ "(SELECT MAX(" + DbConstants.TimeSheet.IDX + ") FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = '" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); TimeSheet result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new TimeSheet(rs); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private JobReportTime selectActiveJobReportTime() { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE ( rowid " + " = (SELECT MAX(rowid) FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + ")) " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " OR (" + DbConstants.JobReportTime.STOP_TIME + " ='" + DateUtils.getInitialDateTime().getTime() + "'" + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } else { /** * in case that there is some record has not been stopped yet * but it is not the latest record this will select the opened * entry instead of the latest record */ while (rs.moveNext()) { JobReportTime jobReportTime = new JobReportTime(rs); if (jobReportTime.getStopTime().equals(DateUtils.getInitialDateTime())) { result = jobReportTime; } } } } finally { rs.dispose(); } return result; } /** * @param guid Report ID * @return Last entry of the report time sheet. */ public JobReportTime selectLatestJobReportTimeByGUID(String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.START_TIME + " = " //$NON-NLS-1$ //$NON-NLS-2$ + "(SELECT MAX(" + DbConstants.JobReportTime.START_TIME + ") " + //$NON-NLS-1$ //$NON-NLS-2$ " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + //$NON-NLS-1$ " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } } finally { rs.dispose(); } return result; } public int selectNextIDXFromJobReportTimeByGUID(String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.JobReportTime.IDX + " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " = " //$NON-NLS-1$ //$NON-NLS-2$ + "(SELECT MAX(" + DbConstants.JobReportTime.IDX + ") " + //$NON-NLS-1$ //$NON-NLS-2$ " FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME + //$NON-NLS-1$ " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); int result = 1; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = rs.getInt(DbConstants.JobReportTime.IDX) + 1; } } finally { rs.dispose(); } return result; } /** * @param von * @param pernr * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectTimeSheetListByFromDate(Date von, int pernr) { List result = new ArrayList(); Date earlyMorning = DateTimeUtil.getDate(von).getTime(); Date lateNight = DateTimeUtil.getLateNight(von).getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new TimeSheet(rs)); } } finally { rs.dispose(); } return result; } /** * @param datum * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private Expenses selectExpenses(Date datum) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.DATE + " = '" + datum.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Expenses result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Expenses(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } /** * Searches the last entered value for the operation hour counter. * @param datum date form where the search is started into the past * @param pernr * @return Last available (not highest!) value of the operation hour counter (attribute BBIS) */ public Expenses selectLastAvailableBToDate(Date datum, int pernr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.DATE + " < " + datum.getTime() //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.Expenses.OPERATION_HOURS_UP_TO + " <> ''" //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.Expenses.DATE + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Expenses result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Expenses(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ rs.moveNext(); result = new Expenses(rs); } } finally { rs.dispose(); } return result; } public ReportMaterial selectMaxReportMaterial(String guid) { RecordSet rs = db.getRecordSet(); String sql = ("SELECT * FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = (SELECT MAX (" //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.ReportMaterial.IDX + ") FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + guid + "' )"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); ReportMaterial result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ReportMaterial(rs); } } finally { rs.dispose(); } return result; } public List selectReportMaterialList(String guid) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { ReportMaterial reportMaterial = new ReportMaterial(rs); if(!reportMaterial.isK14()){ Material part = selectMaterialByMatNo(reportMaterial.getSparePartNumber()); if (part != null) { reportMaterial.setProductName(part.getMaterialShortText()); } else { MaterialPerson materialPerson = selectMaterialPersonByMatNo(reportMaterial.getSparePartNumber()); if (materialPerson != null) { reportMaterial.setProductName(materialPerson.getMaterialShortText()); } } } result.add(reportMaterial); } } finally { rs.dispose(); } return result; } public List selectReportMaterialListByLimit(String guid, int limit) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String innerSql = "SELECT * FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.ReportMaterial.GUID + " = '" + guid + "'" + " ORDER BY " + DbConstants.ReportMaterial.IDX //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " DESC " + " LIMIT " + limit; //$NON-NLS-1$ //$NON-NLS-2$ String sql = "SELECT * FROM ( " + innerSql + " ) " + " ORDER BY " + DbConstants.ReportMaterial.IDX; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMaterial(rs)); } } finally { rs.dispose(); } return result; } public Job selectJobByGUID(String guid) { Job result = new Job(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Job.JOB + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.Job.CURRENT_REPORT_GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Job(rs); } } finally { rs.dispose(); } return result; } public List selectJobBySignGUID(String signguid) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT mob.* " //$NON-NLS-1$ + " FROM " + DbConstants.Job.JOB + " mob " //$NON-NLS-1$ //$NON-NLS-2$ + " JOIN " + DbConstants.Report.REPORT + " rep " //$NON-NLS-1$ //$NON-NLS-2$ + " ON mob." + DbConstants.Job.JOB_NUMBER + " = rep." + DbConstants.Report.JOB_NUMBER //$NON-NLS-1$ //$NON-NLS-2$ + " AND mob." + DbConstants.Job.JOB_TYPE + " = rep." + DbConstants.Report.JOB_TYPE //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE rep." + DbConstants.Report.SIGNATURE_GUID + " = '" + signguid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else { while (rs.moveNext()) { result.add(new Job(rs)); } } } finally { rs.dispose(); } return result; } public List selectReportListOfSignFiles() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT DISTINCT " + DbConstants.Report.SIGNATURE //$NON-NLS-1$ + " FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.SIGNATURE + " <> ''"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else { while (rs.moveNext()) { String signpic = rs.getString(DbConstants.Report.SIGNATURE); result.add(signpic); } } } finally { rs.dispose(); } return result; } public List selectReportListOfSignBundle() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.COLLECTIVELY + " <> ''" //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.Report.CREATE_DATE + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else { while (rs.moveNext()) { result.add(new Report(rs)); } } } finally { rs.dispose(); } return result; } public List selectMaterialPersonListByMatNoAndMatName( String matNr, String makTx) { List result = new ArrayList(); int pos = 0; while ((pos = makTx.indexOf('\'', pos)) != -1) { makTx = makTx.substring(0, pos) + '\'' + makTx.substring(pos++); pos++; } if (matNr.contains("'")) { matNr = matNr.replace("'", ""); } String cond = " OR "; if(matNr.isEmpty()) { cond = " AND "; } RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " //$NON-NLS-1$ + DbConstants.MaterialPerson.MATERIAL_PERSON + " WHERE " + DbConstants.MaterialPerson.TEXT + " LIKE '%" + makTx + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + cond + DbConstants.MaterialPerson.NUMBER + " LIKE '%" + matNr + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.MaterialPerson.TEXT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new MaterialPerson(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectMaterialListByMatNrAndMatName( String matNr, String makTx) { List result = new ArrayList(); int pos = 0; while ((pos = makTx.indexOf('\'', pos)) != -1) { makTx = makTx.substring(0, pos) + '\'' + makTx.substring(pos++); pos++; }if (matNr.contains("'")) { matNr = matNr.replace("'", ""); } String cond = " OR "; if(matNr.isEmpty()) { cond = " AND "; } RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Material.MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.Material.TEXT + " LIKE '%" + makTx + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + cond + DbConstants.Material.NUMBER + " LIKE '%" + matNr + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.Material.TEXT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Material(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public Material selectMaterialByMatNo( String matnr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Material.MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.Material.NUMBER + " = '" + matnr + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); Material result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Material(rs); } else { if (log.isDebugEnabled()) log.debug("multiple matnr/" + matnr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public MaterialPerson selectMaterialPersonByMatNo( String matnr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " //$NON-NLS-1$ + DbConstants.MaterialPerson.MATERIAL_PERSON + " WHERE " //$NON-NLS-1$ + DbConstants.MaterialPerson.NUMBER + " = '" + matnr + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); MaterialPerson result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new MaterialPerson(rs); } else { if (log.isDebugEnabled()) log.debug("multiple matnr/" + matnr + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } @Nullable public ServerJob selectServerJob(String jobNumber) { ServerJob result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ServerJob.SERVER_JOB //$NON-NLS-1$ + DbConstants.Where.WHERE_TEXT + " " + DbConstants.ServerJob.JOB_NUMBER + " ='" + jobNumber + "'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new ServerJob(rs); } else { log.warn(MessageFormat.format("multiple entries in table ServerJob for job number {0} found, jobNumber", new Object[] { jobNumber})); return null; } } finally { rs.dispose(); } return result; } public List selectServerJobList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ServerJob.SERVER_JOB //$NON-NLS-1$ + " ORDER BY " + DbConstants.ServerJob.MONTH_YEAR + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ServerJob(rs)); } } finally { rs.dispose(); } return result; } public List selectServerJobNotInJobList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ServerJob.SERVER_JOB + " c " //$NON-NLS-1$ //$NON-NLS-2$ + "WHERE NOT EXISTS (" //$NON-NLS-1$ + " SELECT * FROM " + DbConstants.Job.JOB + " j " //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + "c." + DbConstants.ServerJob.JOB_NUMBER + "=" + "j." + DbConstants.Job.JOB_NUMBER //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " AND " + "c." + DbConstants.ServerJob.JOB_TYPE + "=" + "j." + DbConstants.Job.JOB_TYPE //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + " )" //$NON-NLS-1$ + " ORDER BY " + "c." + DbConstants.ServerJob.MONTH_YEAR + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ServerJob(rs)); } } finally { rs.dispose(); } return result; } /** * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectJobMessageList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMessage.JOB_MESSAGE; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMessage(rs)); } } finally { rs.dispose(); } return result; } public List selectJobMessageListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobMessage.MESSAGE_ID; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMessage(rs)); } } finally { rs.dispose(); } return result; } public List selectReportMeasurementListByReport(Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + report.getGuId() + "'" // + " AND " + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ='" + report.getCommissionNumber() + "'" // + " AND " + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ='" + report.getPersonalNumber() + "'" + " ORDER BY " + DbConstants.ReportMeasurement.MEASURING_POINT; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMeasurement(rs)); } } finally { rs.dispose(); } return result; } public List selectReportMeasurementListByMeasuringPoint(Report report, String measuringPoint) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + report.getGuId() + "'" // + " AND " + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ='" + report.getCommissionNumber() + "'" // + " AND " + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ='" + report.getPersonalNumber() + "'" + " AND " + DbConstants.ReportMeasurement.MEASURING_POINT + " ='" + measuringPoint + "'" + " ORDER BY ROWID"; //$NON-NLS-1$ // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReportMeasurement(rs)); } } finally { rs.dispose(); } return result; } public int selectNextMeasurementFromReportMeasurement(Report report, String measuringPoint) { RecordSet rs = db.getRecordSet(); String sql = "select MAX(CAST( " + DbConstants.ReportMeasurement.MEASUREMENT + " AS INT)) AS " + DbConstants.ReportMeasurement.MEASUREMENT + " FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + report.getGuId() + "'" + " AND " + DbConstants.ReportMeasurement.MEASURING_POINT + " ='" + measuringPoint + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); int result = 1; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = rs.getInt(DbConstants.ReportMeasurement.MEASUREMENT) + 1; } } finally { rs.dispose(); } return result; } public List selectVariousExpenses(Date date, int perNo) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VariousExpenses.VARIOUS_EXPENSES + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " =" + perNo + "" + " AND " + DbConstants.VariousExpenseFile.DATE + "='" + date.getTime() + "'" ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new VariousExpenses(rs)); } } finally { rs.dispose(); } return result; } public VariousExpenseFile selectVariousExpensesFile(Date date, int perNo, String id) { VariousExpenseFile result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " =" + perNo + "" + " AND " + DbConstants.VariousExpenseFile.DATE + "='" + date.getTime() + "'" + " AND " + DbConstants.VariousExpenseFile.IDX + "='" + id + "'" + " ORDER BY " + DbConstants.VariousExpenseFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new VariousExpenseFile(rs); } } finally { rs.dispose(); } return result; } public JobMessage selectJobMessageListByreportAndMsgId( Report report, String msgId) { JobMessage result = null; if( report != null && msgId != null) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobMessage.MESSAGE_ID + "='" + msgId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobMessage.MESSAGE_ID; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobMessage(rs); } } finally { rs.dispose(); } } return result; } public List selectReportJobFileListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectReportJobFileDocumentListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectReportJobFileImageListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" + " AND " + DbConstants.JobFile.TYPE + " ='I'" + " ORDER BY " + DbConstants.JobFile.IDX; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectFormImageListByReport( Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" + " AND " + DbConstants.JobFile.TYPE + " ='G'" + " ORDER BY " + DbConstants.JobFile.IDX; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public JobFile selectFormImageByGuidAndFileName(String guid, String fileName) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'" + " AND " + DbConstants.JobFile.IDX + " ='" + fileName + "'" + " AND " + DbConstants.JobFile.TYPE + " ='G'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); JobFile result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobFile(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ rs.moveNext(); result = new JobFile(rs); } } finally { rs.dispose(); } return result; } public Map> selectDocumentListByReport( Report report) { Map> result = new HashMap>(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " ORDER BY " + DbConstants.JobFile.FORM_DESC; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { String formDesc = ""; while (rs.moveNext()) { JobFile jobFile = new JobFile(rs); if (!formDesc.isEmpty() && formDesc.equalsIgnoreCase(jobFile.getFormDesc())) { result.get(formDesc).add(jobFile); } else { formDesc = jobFile.getFormDesc(); List files = new ArrayList(); files.add(jobFile); result.put(formDesc, files); } } } finally { rs.dispose(); } return result; } public List selectDocumentFileListByReport( Report report, String formDesc) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " AND " + DbConstants.JobFile.SIGN_PIC_AT + " <>''" + " AND " + DbConstants.JobFile.FORM_DESC + " ='" + formDesc + "'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectDocumentFileNoFormListByReportAndDormDesc( Report report, String formDesc) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'" + " AND " + DbConstants.JobFile.SIGN_PIC_AT + " =''" + " AND " + DbConstants.JobFile.FORM_DESC + " ='" + formDesc + "'" + " ORDER BY " + DbConstants.JobFile.IDX; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFile(rs)); } } finally { rs.dispose(); } return result; } public List selectAbsencesNotificationList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION + " WHERE " + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " =" + selectActiveUser().getPersonalNumber() + "" + " ORDER BY " + DbConstants.AbsenceNotification.DATE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { AbsenceNotification absenceNotification = new AbsenceNotification(rs); Calendar absencesDeleteExpiredDate = DateTimeUtil.getDate(absenceNotification.getAbsenceDate()); absencesDeleteExpiredDate.add(Calendar.DAY_OF_YEAR, CommonConstants.PERMISSION_REQUEST_CODE); if (DateTimeUtil.getToday().after(absencesDeleteExpiredDate)) { log.info("Absences older than " + CommonConstants.PERMISSION_REQUEST_CODE + " days -> delete."); deleteAbsenceNotification(absenceNotification); } else { result.add(absenceNotification); } } } finally { rs.dispose(); } return result; } public List selectFormList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Form.FORM + " ORDER BY " + DbConstants.Form.ID; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { Form form = new Form(rs); result.add(form); } } finally { rs.dispose(); } return result; } public List selectValidFormList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); // Form Modernisierung Schiebet�re GDS status F valid from 28/02/2023 07:00 valid to 31/12/9999 07:00 // Form Testformular 1 status F valid from 21/09/2022 07:00 valid to 31/12/9999 07:00 Date date = new Date(); String sql = "SELECT * FROM " + DbConstants.Form.FORM + " WHERE " + DbConstants.Form.STATUS + " ='F'" + " AND '" + date.getTime() + "' >= " + DbConstants.Form.VALID_FROM + " AND '" + date.getTime() + "' <= " + DbConstants.Form.VALID_TO + " ORDER BY " + DbConstants.Form.ID; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { Form form = new Form(rs); result.add(form); } } finally { rs.dispose(); } return result; } public Form selectFormByIdAndVersion(String formId, int version) { Form result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Form.FORM + " WHERE " + DbConstants.Form.ID + " ='" + formId + "'" + " AND " + DbConstants.Form.VERSION + " =" + version; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); } else if (rs.getCount() == 1) { rs.moveNext(); result = new Form(rs); } else { log.error("multiple Form in table FORM found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectFormItemListByFormId(String formId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormItem.FORMITEM + " WHERE " + DbConstants.FormItem.FORM_ID + " ='" + formId + "'" + " ORDER BY " + DbConstants.FormItem.FORM_VERSION + ", " + DbConstants.FormItem.SEQUENCE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormItem formItem = new FormItem(rs); result.add(formItem); } } finally { rs.dispose(); } return result; } public List selectFormItemListByFormIdAndFormVersion(String formId, int formVersion) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormItem.FORMITEM + " WHERE " + DbConstants.FormItem.FORM_ID + " ='" + formId + "'" + " AND " + DbConstants.FormItem.FORM_VERSION + " =" + formVersion + " ORDER BY " + DbConstants.FormItem.FORM_VERSION + ", " + DbConstants.FormItem.SEQUENCE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormItem formItem = new FormItem(rs); result.add(formItem); } } finally { rs.dispose(); } return result; } public List selectDependencyListByFormIdFormVersionAndFormItemId(String formId, int formVersion, String formItemId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormDependency.FORMDEPENDENCY + " WHERE " + DbConstants.FormDependency.FORM_ID + " ='" + formId + "'" + " AND " + DbConstants.FormDependency.FORM_VERSION + " =" + formVersion + "" + " AND " + DbConstants.FormDependency.FORM_ITEM_ID + " ='" + formItemId + "'" + " ORDER BY " + DbConstants.FormDependency.FORM_VERSION; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormDependency dependency = new FormDependency(rs); result.add(dependency); log.info("FormDependency --> FormId :" + dependency.getFormId() + " FormVersion :" + dependency.getFormVersion() + " FormItemId :" + dependency.getFormItemId() + " Dependency :" + dependency.getDependency() + " CheckboxFormItemId :" + dependency.getCheckBoxFormItemId() + " ValueListId :" + dependency.getValueListId() + " ValueId :" + dependency.getValueId() ); } } finally { rs.dispose(); } return result; } public List selectValueListsByValueListId(String valueListId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormValueList.FORMVALUELIST + " WHERE " + DbConstants.FormValueList.VALUE_LIST_ID + " ='" + valueListId + "'" + " ORDER BY " + DbConstants.FormValueList.VALUE_LIST_ID; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormValueList formValueList = new FormValueList(rs); result.add(formValueList); } } finally { rs.dispose(); } return result; } public FormValueList selectFormValueListByValueListId(String valueListId, String ValueId) { FormValueList result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormValueList.FORMVALUELIST + " WHERE " + DbConstants.FormValueList.VALUE_LIST_ID + " ='" + valueListId + "'" + " AND " + DbConstants.FormValueList.VALUE_ID + " ='" + ValueId + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); } else if (rs.getCount() == 1) { rs.moveNext(); result = new FormValueList(rs); } else { log.error("multiple ValueList in table FORMVALUELIST found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public void getFormInstanceList(String guid) { List formInstances = selectFormInstanceListByGuid(guid); Map> formMap = new HashMap>(); for (FormInstance formInstance : formInstances) { if (formMap.containsKey(formInstance.getFormId())) { formMap.get(formInstance.getFormId()).add(formInstance); } else { List newList = new ArrayList(); newList.add(formInstance); formMap.put(formInstance.getFormId(), newList); } } } public List selectFormInstanceListByGuid(String guid) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'" + " ORDER BY " + DbConstants.FormInstance.FORM_VERSION; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormInstance formInstance = new FormInstance(rs); result.add(formInstance); } } finally { rs.dispose(); } return result; } public List selectFormInstanceListByGuidAndFormId(String guid, String formId) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'" + " AND " + DbConstants.FormInstance.FORM_ID + " ='" + formId + "'" + " ORDER BY " + DbConstants.FormInstance.FORM_VERSION; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { FormInstance formInstance = new FormInstance(rs); result.add(formInstance); } } finally { rs.dispose(); } return result; } public FormInstance selectFormInstanceByGuidFormIdAndFormItemId(String guid, String formId, String formItemId) { FormInstance result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'" + " AND " + DbConstants.FormInstance.FORM_ID + " ='" + formId + "'" + " AND " + DbConstants.FormInstance.FORM_ITEM_ID + " ='" + formItemId + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); } else if (rs.getCount() == 1) { rs.moveNext(); result = new FormInstance(rs); } else { log.error("multiple Form in table FORMINSTANCE found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public int countUnsavedAddresses() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.CHANGE_FLAG + " ='X'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int countUnsavedReport() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.REPORT_STATUS + " = 0"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int countNotConfirmedSHortMSG() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.CONFIRM + " ='X'" //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.ShortMessage.STATUS + " != '3'"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int cntJobs_InArbeit() { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + DbConstants.Job.STATUS + " = '" + JobStatus.IN_PROGRESS + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } private Person selectActiveUser() { Person result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Person.PERSON; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Person(rs); } else { log.error("multiple users in table ZKDMOBMA found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectReportListByJobIdAndJobType(String kobId, String jobType) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.JOB_NUMBER + " ='" + kobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " ='" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.Report.IDX + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Report(rs)); } } finally { rs.dispose(); } return result; } /** * @param table * @param column * @param criteria * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private int selectMax( String table, String column, String criteria) { RecordSet rs = db.getRecordSet(); String sql = "SELECT MAX(" + column + ") FROM " + table; //$NON-NLS-1$ //$NON-NLS-2$ if (!"".equalsIgnoreCase(criteria)) { //$NON-NLS-1$ sql = sql + " " + criteria; //$NON-NLS-1$ } if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); int result = 0; try { rs.moveNext(); result = rs.getInt(0); } finally { rs.dispose(); } return result; } public JobReportTime selectJobReportTimeByGuid( String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " >= (" //$NON-NLS-1$ //$NON-NLS-2$ + " SELECT MAX(" + DbConstants.JobReportTime.IDX + ") FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "' )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } } finally { rs.dispose(); } return result; } public List selectJobReportTimeListByReport(Report report) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReportTime(rs)); } } finally { rs.dispose(); } return result; } public JobReportTime selectPlayingJobReportTimeByReport(Report report) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + report.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.STOP_TIME + " = '0'" //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobReportTime result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobReportTime(rs); } } finally { rs.dispose(); } return result; } public List selectJobWithOpenTimesheet() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT j.* FROM " //$NON-NLS-1$ + DbConstants.Job.JOB + " j, " //$NON-NLS-1$ + DbConstants.JobReportTime.JOB_REPORT_TIME + " t " //$NON-NLS-1$ + " WHERE j." + DbConstants.Job.CURRENT_REPORT_GUID + " = t." + DbConstants.JobReportTime.GUID //$NON-NLS-1$ //$NON-NLS-2$ + " AND t." + DbConstants.JobReportTime.STOP_TIME + " = '" + DateUtils.getInitialDateTime().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Job(rs)); } } finally { rs.dispose(); } return result; } /** * @param guid * @param datum * @return * @deprecated */ @Deprecated @SuppressWarnings("unused") private List selectJobReportTimeList(String guid, Date datum) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (!datum.equals(DateUtils.getInitialDateTime())) { sql += " AND " + DbConstants.JobReportTime.DATE + " = '" + datum.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } sql += " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReportTime(rs)); } } finally { rs.dispose(); } return result; } public Employee selectEmployeeByPerNr( int perNo) { Employee result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Employee.EMPLOYEE //$NON-NLS-1$ + " WHERE " + DbConstants.Employee.PERSONAL_NUMBER + " = " + perNo + ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Employee(rs); } else { log.error("multiple person in table ZKDSMOBMA found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectEmployeeList(String criteria) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Employee.EMPLOYEE; //$NON-NLS-1$ //$NON-NLS-2$ if (criteria.length() > 0) { sql += " AND " + DbConstants.Employee.LAST_NAME + " LIKE '" + criteria + "%'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } sql += " ORDER BY " + DbConstants.Employee.LAST_NAME; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Employee(rs)); } } finally { rs.dispose(); } return result; } public List selectEmployeeList(Person person, String criteria) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Employee.EMPLOYEE //$NON-NLS-1$ + " WHERE " + DbConstants.Employee.PERSONAL_NUMBER + " != " + person.getPersonalNumber(); //$NON-NLS-1$ //$NON-NLS-2$ if (criteria.length() > 0) { sql += " AND " + DbConstants.Employee.LAST_NAME + " LIKE '" + criteria + "%'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } sql += " ORDER BY " + DbConstants.Employee.LAST_NAME; //$NON-NLS-1$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Employee(rs)); } } finally { rs.dispose(); } return result; } public List selectJobReportTimeListByDate(Date date) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.DATE + " = '" + date.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.JobReportTime.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReportTime(rs)); } } finally { rs.dispose(); } return result; } public Drive selectDriveByText(String text) { Drive result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Drive.DRIVE //$NON-NLS-1$ + " WHERE " + DbConstants.Drive.TEXT + " = '" + text + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Drive(rs); } } finally { rs.dispose(); } return result; } public List selectDriveList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Drive.DRIVE; //$NON-NLS-1$; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Drive(rs)); } } finally { rs.dispose(); } return result; } public List selectOrderListByPerNo( int perNr) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Order.ORDER //$NON-NLS-1$ + " WHERE " + DbConstants.Order.PERSONAL_NUMBER + " = " + perNr //$NON-NLS-1$ //$NON-NLS-2$ + " ORDER BY " + DbConstants.Order.CREATED_DATE + " DESC"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Order(rs)); } } finally { rs.dispose(); } return result; } public List selectInvoiceList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Invoice.INVOICE; //$NON-NLS-1$; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Invoice(rs)); } } finally { rs.dispose(); } return result; } public List selectBillingTypeListByJobType(JobType jobType) { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Billing.BILLING //$NON-NLS-1$ + " WHERE " + DbConstants.Billing.JOB_TYPE + " = '" + jobType.getCode() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " OR " + DbConstants.Billing.JOB_TYPE + " = ''" + " ORDER BY " + DbConstants.Billing.CODE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Billing(rs)); } } finally { rs.dispose(); } return result; } public Billing selectBillingTypeByJobTypeAndCode(JobType jobType, String code) { Billing result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Billing.BILLING //$NON-NLS-1$ + " WHERE " + DbConstants.Billing.JOB_TYPE + " = '" + jobType.getCode() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Billing.CODE + " = '" + code + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Billing(rs); } } finally { rs.dispose(); } return result; } public List selectCalendarDatesOlderThan(Date date) throws ApplicationException { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.CalendarTimeSheet.DATE + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " < '" + date.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.STATUS + " IN ('" + CalendarStatus.INITIAL + "', '" + CalendarStatus.SENT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { Date calDate = rs.getDate(DbConstants.CalendarTimeSheet.DATE); result.add(calDate); } } finally { rs.dispose(); } return result; } public CalendarTimeSheet loadCalendar(Date date, int pernr) { CalendarTimeSheet calendar = selectCalendarTimeSheet(date, pernr); calendar.setExpense(selectExpenses(date, pernr)); calendar.setTimeSheets(selectTimeSheetList(date, pernr)); return calendar; } public boolean saveCALENDAR(CalendarTimeSheet calendar) { if (calendar.getStatus().isINITIAL()) return insertCalendarTimeSheet(calendar); else return updateCalendarTimeSheet(calendar); } private CalendarTimeSheet selectCalendarTimeSheet(Date date, int pernr) throws ApplicationException { // Make sure that date is a date value and not a time value! // if(!DateTimeUtil.isDate(date)) { // throw new ApplicationException(Messages.getString("loadCALENDARObjectWithDatetime") + date + ")"); //$NON-NLS-1$ //$NON-NLS-2$ // } CalendarTimeSheet result = new CalendarTimeSheet(date, pernr); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " = '" + date.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.moveNext()) { result = new CalendarTimeSheet(rs); } } finally { rs.dispose(); } return result; } public List selectReasonList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Reason.REASON //$NON-NLS-1$ + " ORDER BY " + DbConstants.Reason.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Reason(rs)); } } finally { rs.dispose(); } return result; } public List selectJobDeleteReasonList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobReturnReason.JOB_RETURN_REASON //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobReturnReason.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobReturnReason(rs)); } } finally { rs.dispose(); } return result; } public List selectJobMonTextList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobMonText.JOB_MON_TEXT //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobMonText.TEXT + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobMonText(rs)); } } finally { rs.dispose(); } return result; } public List selectJobFormDescList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobFormDesc.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobFormDesc(rs)); } } finally { rs.dispose(); } return result; } public JobFormDesc selectJobFormDescByFormDesc(String formDesc) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC //$NON-NLS-1$ + " WHERE " + DbConstants.JobFormDesc.CODE + " = '" + formDesc + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobFormDesc result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobFormDesc(rs); } else { log.warn(MessageFormat.format("multiple entries in table " + DbConstants.JobFormDesc.CODE + " for formDesc {0} found", new Object[] { formDesc})); return null; } } finally { rs.dispose(); } return result; } public List selectJobNoFormList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobNoForm.JOB_NO_FORM //$NON-NLS-1$ + " ORDER BY " + DbConstants.JobNoForm.CODE + " ASC"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new JobNoForm(rs)); } } finally { rs.dispose(); } return result; } public JobNoForm selectJobNoFormByNoForm(String noForm) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.JobNoForm.JOB_NO_FORM //$NON-NLS-1$ + " WHERE " + DbConstants.JobNoForm.CODE + " = '" + noForm + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); JobNoForm result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new JobNoForm(rs); } else { log.warn(MessageFormat.format("multiple entries in table " + DbConstants.JobNoForm.CODE + " for noForm {0} found", new Object[] { noForm})); return null; } } finally { rs.dispose(); } return result; } public List selectAbsenceTypeList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.AbsenceType.ABSENCE_TYPE; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new AbsenceType(rs)); } } finally { rs.dispose(); } return result; } public List selectReceiptOfGoodsList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new ReceiptOfGoods(rs)); } } finally { rs.dispose(); } return result; } public AbsenceType selectAbsenceType(String code) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.AbsenceType.ABSENCE_TYPE + " WHERE " + DbConstants.AbsenceType.ABWGRND + " = '" + code + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); AbsenceType result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new AbsenceType(rs); } else { log.warn(MessageFormat.format("multiple entries in table " + DbConstants.AbsenceType.ABWGRND + " for noForm {0} found", new Object[] { code})); return null; } } finally { rs.dispose(); } return result; } private boolean insertCalendarTimeSheet(CalendarTimeSheet calendarTimeSheet) throws ApplicationException { // Make shure that date is a date value and not a time value! if(!DateTimeUtil.isDate(calendarTimeSheet.getDate())) { throw new ApplicationException(Messages.getString("saveCALENDARObjectWithDatetime") + calendarTimeSheet.getDate() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); try { DBSqlHelper sql = new DBSqlHelper(db); calendarTimeSheet.setStatus(CalendarStatus.SAVED); String sqlStmt = sql.INSERT(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET) .in(DbConstants.CalendarTimeSheet.DATE, calendarTimeSheet.getDate()) .in(DbConstants.CalendarTimeSheet.DATE_STRING, calendarTimeSheet.getDateString()) .in(DbConstants.CalendarTimeSheet.PERSONAL_NUMBER, calendarTimeSheet.getPersonalNumber()) .in(DbConstants.CalendarTimeSheet.STATUS, calendarTimeSheet.getStatus().getCode()) .toString(); int result = db.executeSql(sqlStmt); if (log.isDebugEnabled()) log.debug("Number of inserted records:'" + result + "' (SQL Statemant:/" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ insertReplaceExpenses(calendarTimeSheet.getExpense()); deleteAllTimeSheetByDate(calendarTimeSheet.getDate()); TreeSet timesheets = calendarTimeSheet.getTimeSheets(); Iterator itr = timesheets.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = itr.next(); insertTimeSheet(timeSheet); } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e); db.rollback(); } // termination with errors return false; } private boolean updateCalendarTimeSheet(CalendarTimeSheet calendar) { boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); DBSqlHelper sql = new DBSqlHelper(db); try { db.executeSql(sql.UPDATE(DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET) .in(DbConstants.CalendarTimeSheet.DATE, calendar.getDate()) .in(DbConstants.CalendarTimeSheet.DATE_STRING, calendar.getDateString()) .in(DbConstants.CalendarTimeSheet.PERSONAL_NUMBER, calendar.getPersonalNumber()) .in(DbConstants.CalendarTimeSheet.STATUS, calendar.getStatus().getCode()) + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " = " + calendar.getDate().getTime()); //$NON-NLS-1$ //$NON-NLS-2$ Expenses expenses = calendar.getExpense(); insertReplaceExpenses(expenses); deleteAllTimeSheetByDate(calendar.getDate()); TreeSet timesheets = calendar.getTimeSheets(); Iterator itr = timesheets.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = itr.next(); insertTimeSheet(timeSheet); } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e); db.rollback(); } // termination with errors return false; } public boolean deleteCalendarTimeSheet(CalendarTimeSheet calendar) { boolean pendingTransactionUsed = false; if (db.isTransactionPending()) pendingTransactionUsed = true; else db.startTransaction(); try { Expenses expenses = calendar.getExpense(); deleteExpenses(expenses); deleteAllTimeSheetByDate(calendar.getDate()); int cnt = db.executeSql("DELETE FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " = '" + calendar.getDate().getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.PERSONAL_NUMBER + " = '" + calendar.getPersonalNumber() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug(cnt + " CALENDAR Record(s) deleted for date " + calendar.getDateString() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e); db.rollback(); } // termination with errors return false; } /** * Finds the oldest open (status != sent) time sheet in the database. * @param pernr * @return The date of the oldest time sheet which has not been sent. Time * sheets younger than 3 days are are ignored. If no open time sheets * can be found, the current day (time: 00:00:00.000) is returned. */ public Date selectOldestUnsavedCalendarDate(int pernr) { Calendar today = DateTimeUtil.getToday(); // If no older CALENDAR can be found, return the current day Date result = today.getTime(); today.add(Calendar.DAY_OF_YEAR, -3); Date threeDaysAgo = today.getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.CalendarTimeSheet.DATE //$NON-NLS-1$ + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " < '" + threeDaysAgo.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.STATUS + " <> '" + CalendarStatus.SENT + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.CalendarTimeSheet.DATE + " ASC" //$NON-NLS-1$ //$NON-NLS-2$ ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() > 0) { rs.moveNext(); result = rs.getDate(DbConstants.CalendarTimeSheet.DATE); } } finally { rs.dispose(); } return result; } public int countUnsavedCalendar(int pernr) { int result = 0; Date yesterday = DateTimeUtil.getYesterday().getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT COUNT(*)" + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.CalendarTimeSheet.DATE + " < '" + yesterday.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.CalendarTimeSheet.STATUS + " <> '" + CalendarStatus.SENT + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() > 0) { rs.moveNext(); result = rs.getInt(0); } } finally { rs.dispose(); } return result; } private Expenses selectExpenses(Date date, int perNo) { Expenses result = new Expenses(date, perNo); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.DATE + " = '" + date.getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Expenses(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } private TreeSet selectTimeSheetList(Date date, int perNo) { TreeSet result = new TreeSet(); Date earlyMorning = DateTimeUtil.getDate(date).getTime(); Date lateNight = DateTimeUtil.getLateNight(date).getTime(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + perNo + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.TimeSheet.START_TIME + " ASC "; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new TimeSheet(rs)); } } finally { rs.dispose(); } return result; } public List selectVehicleInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { VehicleInventory inventoryStock = new VehicleInventory(rs); result.add(inventoryStock); } } finally { rs.dispose(); } return result; } public VehicleInventory selectVehicleInventoryByMatNr(String matNr) { VehicleInventory result = null; RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY + " WHERE " + DbConstants.VehicleInventory.MATERIAL_NUMBER + " = '" + matNr + "'" + " AND " + DbConstants.VehicleInventory.STORAGE_LOCATION + " = '" + getUser().getWarehouseNumber() + "'"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new VehicleInventory(rs); } else if (rs.getCount() > 1) { if (log.isDebugEnabled()) log.debug("multiple records"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } public List selectVehicleInventoryListByMatNrAndMatName( String matNr, String makTx) { List result = new ArrayList(); int pos = 0; while ((pos = makTx.indexOf('\'', pos)) != -1) { makTx = makTx.substring(0, pos) + '\'' + makTx.substring(pos++); pos++; } String cond = " OR "; if(matNr.isEmpty()) { cond = " AND "; } RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY //$NON-NLS-1$ + " WHERE " + DbConstants.VehicleInventory.MATERIAL_NAME + " LIKE '%" + makTx + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + cond + DbConstants.VehicleInventory.MATERIAL_NUMBER + " LIKE '%" + matNr + "%'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " ORDER BY " + DbConstants.VehicleInventory.MATERIAL_NAME; //$NON-NLS-1$ if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new VehicleInventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY // + " WHERE " + DbConstants.Inventory.PERSONAL_NUMBER + " = " + getUser().getPersonalNumber() ; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectNotExternalInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE + " <> '" + Warehouse.EXTERNAL + "'" + " AND " + DbConstants.Inventory.NAME + " <> ''"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectExternalInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE + " = '" + Warehouse.EXTERNAL + "'" + " AND " + DbConstants.Inventory.NAME + " <> ''"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public List selectNotMainInventoryList() { List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE + " <> '" + Warehouse.MAIN + "'" + " AND " + DbConstants.Inventory.NAME + " <> ''"; if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { result.add(new Inventory(rs)); } } finally { rs.dispose(); } log.info("size /" + result.size() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } public Inventory selectInventoryByPersonalNrAndWarehouseNr() { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.WAREHOUSE_NUMBER + " = '" + getUser().getWarehouseNumber() + "'" + " AND " + DbConstants.Inventory.PERSONAL_NUMBER + " = " + getUser().getPersonalNumber() ; rs.setQuery(sql); log.info("sql /" + sql + "/"); Inventory result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new Inventory(rs); } else { if (log.isDebugEnabled()) log.debug("multiple " + DbConstants.Inventory.PERSONAL_NUMBER +"/" + getUser().getPersonalNumber() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public DeliveryList selectArticleByMatnr(String orderNr, String matnr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.DeliveryList.DELIVERY_LIST + " WHERE " + DbConstants.DeliveryList.TO + " = '" + getUser().getWarehouseNumber() + "'" + " AND " + DbConstants.DeliveryList.ORDER_NUMBER + " = '" + orderNr + "'" + " AND " + DbConstants.DeliveryList.MATERIAL_NUMBER + " = '" + matnr + "'" + " AND " + DbConstants.DeliveryList.PERSONAL_NUMBER + " = " + getUser().getPersonalNumber() ; rs.setQuery(sql); log.info("sql /" + sql + "/"); DeliveryList result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new DeliveryList(rs); } else { if (log.isDebugEnabled()) log.debug("multiple " + DbConstants.DeliveryList.PERSONAL_NUMBER +"/" + getUser().getPersonalNumber() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public List selectArticleList(boolean isOpen) { //Open ZKDMOBFZGDELVRY.KNZDLVRY = O //Transit ZKDMOBFZGDELVRY.KNZDLVRY = T, G List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.DeliveryList.DELIVERY_LIST + " WHERE " + DbConstants.DeliveryList.TO + " = '" + getUser().getWarehouseNumber() + "'" + " AND (" + (isOpen ? DbConstants.DeliveryList.STATUS + " = 'O'" : (DbConstants.DeliveryList.STATUS + " = 'T'" + " OR " + DbConstants.DeliveryList.STATUS + " = 'G'")) + ") ORDER BY " + DbConstants.DeliveryList.DATE + " DESC, " + DbConstants.DeliveryList.MATERIAL_NAME; // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { DeliveryList article = new DeliveryList(rs); result.add(article); } } finally { rs.dispose(); } return result; } public List selectOutgoingArticleList() { //Receipt ZKDMOBFZGDELVRY.LGORT_TO = ZKDMOBMA.LGORT from user (ZKDMOBA.PERNR = active user) //isBooked ZKDMOBFZGDELVRY.LGORT_FROM = ZKDMOBMA.LGORT from user (ZKDMOBA.PERNR = active user) List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.DeliveryList.DELIVERY_LIST + " WHERE " + DbConstants.DeliveryList.FROM + " = '" + getUser().getWarehouseNumber() + "'" + " ORDER BY " + DbConstants.DeliveryList.DATE + " DESC, " + DbConstants.DeliveryList.MATERIAL_NAME; // if (log.isDebugEnabled()) log.info("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { while (rs.moveNext()) { DeliveryList article = new DeliveryList(rs); result.add(article); } } finally { rs.dispose(); } return result; } public MaterialMovement selectMaterialMovement(String guid) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT //$NON-NLS-1$ + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + guid + "'"; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); MaterialMovement result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new MaterialMovement(rs); } else { if (log.isDebugEnabled()) log.debug("multiple guid/" + guid + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public MaterialMovement selectMaterialMovement( String guid, int pernr) { RecordSet rs = db.getRecordSet(); String sql = "SELECT * FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT //$NON-NLS-1$ + " WHERE " + DbConstants.MaterialMovement.GUID + " = '" + guid + "'" + (pernr == -1? "" : " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " = " + pernr); if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); MaterialMovement result = null; try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); result = new MaterialMovement(rs); } else { if (log.isDebugEnabled()) log.debug("multiple guid/" + guid + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { rs.dispose(); } return result; } public void deleteNewUser(int newUserPernr) { db.executeSql("DELETE FROM " + DbConstants.Person.PERSON //$NON-NLS-1$ + " WHERE " + DbConstants.Person.PERSONAL_NUMBER + " = " + newUserPernr); //$NON-NLS-1$ //$NON-NLS-2$ } public void deleteOldUser(Person oldUser) { deleteOldUser(oldUser.getPersonalNumber()); } public void deleteOldUser(int oldPernr) { mUser = null; // trigger reload of user on next request db.executeSql("DELETE FROM " + DbConstants.Person.PERSON //$NON-NLS-1$ + " WHERE " + DbConstants.Person.PERSONAL_NUMBER + " = " //$NON-NLS-1$ //$NON-NLS-2$ + oldPernr); } public void deleteAllJob() { db.executeSql("DELETE FROM " + DbConstants.Job.JOB); //$NON-NLS-1$ } public void deleteAllAddress() { db.executeSql("DELETE FROM " + DbConstants.Address.ADDRESS); //$NON-NLS-1$ } public void deleteAllEmail() { db.executeSql("DELETE FROM " + DbConstants.Email.EMAIL); //$NON-NLS-1$ } public void deleteAllHistory() { db.executeSql("DELETE FROM " + DbConstants.History.HISTORY); //$NON-NLS-1$ } public void deleteAllReport() { db.executeSql("DELETE FROM " + DbConstants.Report.REPORT); //$NON-NLS-1$ } public void deleteAllJobMessage() { db.executeSql("DELETE FROM " + DbConstants.JobMessage.JOB_MESSAGE); //$NON-NLS-1$ } public void deleteAllReportMaterial() { db.executeSql("DELETE FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL); //$NON-NLS-1$ } public void deleteAllJobReportTime() { db.executeSql("DELETE FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME); //$NON-NLS-1$ } public void deleteAllTimeSheet() { db.executeSql("DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET); //$NON-NLS-1$ } private void deleteAllTimeSheetByDate(Date date) { Date earlyMorning = DateTimeUtil.getDate(date).getTime(); Date lateNight = DateTimeUtil.getLateNight(date).getTime(); int cnt = db.executeSql("DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.START_TIME + " >='" + earlyMorning.getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.START_TIME + " <='" + lateNight.getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("Number of deleted ZKDMATIME Records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } public void deleteAllExpenses() { db.executeSql("DELETE FROM " + DbConstants.Expenses.EXPENSES); //$NON-NLS-1$ } public void deleteAllOrderMaterial() { db.executeSql("DELETE FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL); //$NON-NLS-1$ } public void deleteAllOrder() { db.executeSql("DELETE FROM " + DbConstants.Order.ORDER); //$NON-NLS-1$ } public void deleteAllShortMessage() { db.executeSql("DELETE FROM " + DbConstants.ShortMessage.SHORT_MESSAGE); //$NON-NLS-1$ } public void deleteAllWorkTypeT() { db.executeSql("DELETE FROM " + DbConstants.WorkType.WORK_TYPE); //$NON-NLS-1$ } public void deleteAllErrorCode() { db.executeSql("DELETE FROM " + DbConstants.ErrorCode.ERROR_CODE); //$NON-NLS-1$ } public void deleteAllMaterial() { db.executeSql("DELETE FROM " + DbConstants.Material.MATERIAL); //$NON-NLS-1$ } public void deleteAllEmployee() { db.executeSql("DELETE FROM " + DbConstants.Employee.EMPLOYEE); //$NON-NLS-1$ } public void deleteAllMaterialOfPerson() { db.executeSql("DELETE FROM " //$NON-NLS-1$ + DbConstants.MaterialPerson.MATERIAL_PERSON); } public void deleteAllPerson() { db.executeSql("DELETE FROM " + DbConstants.Person.PERSON); //$NON-NLS-1$ } public void deleteAllServerJob() { db.executeSql("DELETE FROM " + DbConstants.ServerJob.SERVER_JOB); //$NON-NLS-1$ } public void deleteAllJobFile() { db.executeSql("DELETE FROM " + DbConstants.JobFile.JOB_FILE); //$NON-NLS-1$ } public void deleteAllReason() { db.executeSql("DELETE FROM " + DbConstants.Reason.REASON); //$NON-NLS-1$ } public void deleteAllJobReason() { db.executeSql("DELETE FROM " + DbConstants.JobReturnReason.JOB_RETURN_REASON); //$NON-NLS-1$ } public void deleteAllJobMonText() { db.executeSql("DELETE FROM " + DbConstants.JobMonText.JOB_MON_TEXT); //$NON-NLS-1$ } public void deleteAllIncident() { db.executeSql("DELETE FROM " + DbConstants.Incident.INCIDENT); //$NON-NLS-1$ } public void deleteAllJobFormDesc() { db.executeSql("DELETE FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC); //$NON-NLS-1$ } public void deleteAllJobNoForm() { db.executeSql("DELETE FROM " + DbConstants.JobNoForm.JOB_NO_FORM); //$NON-NLS-1$ } public void deleteAllReportMessage() { db.executeSql("DELETE FROM " + DbConstants.ReportMessage.REPORT_MESSAGE); //$NON-NLS-1$ } public void deleteAllDrive() { db.executeSql("DELETE FROM " + DbConstants.Drive.DRIVE); //$NON-NLS-1$ } public void deleteAllBilling() { db.executeSql("DELETE FROM " + DbConstants.Billing.BILLING); //$NON-NLS-1$ } public void deleteAllInvoice() { db.executeSql("DELETE FROM " + DbConstants.Invoice.INVOICE); //$NON-NLS-1$ } public void deleteAllInternalWorkType() { db.executeSql("DELETE FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE); //$NON-NLS-1$ } public void deleteAllAbsenceType() { db.executeSql("DELETE FROM " + DbConstants.AbsenceType.ABSENCE_TYPE); //$NON-NLS-1$ } public void deleteAllServiceRefused() { db.executeSql("DELETE FROM " + DbConstants.ServiceRefused.SERVICE_REFUSED); //$NON-NLS-1$ } public void deleteAllChecklist() { db.executeSql("DELETE FROM " + DbConstants.Checklist.CHECK_LIST); //$NON-NLS-1$ } public void deleteAllProgress() { db.executeSql("DELETE FROM " + DbConstants.Progress.PROGRESS); //$NON-NLS-1$ } public void deleteFormMetadata() { FORM.delete(db); FORMITEM.delete(db); FORMDEPENDENCY.delete(db); FORMVALUELIST.delete(db); } public void deleteAllStateOfInstallation() { db.executeSql("DELETE FROM " + DbConstants.StateOfInstallation.STATE_OF_INSTALLATION); //$NON-NLS-1$ } public void deleteAllNextIntervention() { db.executeSql("DELETE FROM " + DbConstants.NextIntervention.NEXT_INVENTION); //$NON-NLS-1$ } public void deleteAllInventoryStock() { db.executeSql("DELETE FROM " + DbConstants.VehicleInventory.VEHICLE_INVENTORY); //$NON-NLS-1$ } public void deleteAllInventory() { db.executeSql("DELETE FROM " + DbConstants.Inventory.INVENTORY); //$NON-NLS-1$ } public void deleteAllReceiptOfGoods() { db.executeSql("DELETE FROM " + DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS); //$NON-NLS-1$ } public void deleteAllDeliveryList() { db.executeSql("DELETE FROM " + DbConstants.DeliveryList.DELIVERY_LIST); //$NON-NLS-1$ } public void deleteAllFormInstance() { db.executeSql("DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE); //$NON-NLS-1$ } public int deleteFormInstancesWithoutReport() { String sqlStmt = "DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE //$NON-NLS-1$ + " WHERE NOT EXISTS (" //$NON-NLS-1$ + "SELECT 1 FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.REPORT + "." + DbConstants.Report.GUID //$NON-NLS-1$ + " = " + DbConstants.FormInstance.FORMINSTANCE + "." + DbConstants.FormInstance.GUID //$NON-NLS-1$ + ")"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } /** * L�scht den ganzen Auftrag inkl. aller dazugeh�rigen Datens�tzen aus der Datenbank. * @param app * @param job */ public boolean deleteJob( Job job) { boolean pendingTransactionUsed = startTransaction(db); try{ String sqlStmt = "DELETE FROM " + DbConstants.Job.JOB //$NON-NLS-1$ + " WHERE " + "MLDNR = '" + job.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + "AUART = '" + job.getJobType() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ int cnt = db.executeSql(sqlStmt); if (log.isInfoEnabled()) { log.info("Number of deleted ZKDMOB Records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } // address // cnt = deleteZKDMOBADRByMLDNRAndAUART(job.getMLDNR_OrderNumber(), job.getAUART().getCode()); // history deleteHistoryByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); List reportList = selectReportListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); // report time without existing report deleteJobReportTimeByGUID(job.getCurrentReportGuId(this)); for (int i = 0; i < reportList.size(); i++) { Report report = (Report) reportList.get(i); // report msg deleteJobMessage(report.getGuId()); // report time deleteJobReportTimeByGUID(report.getGuId()); // report parts deleteReportMaterialByGUID(report.getGuId()); // report files deleteReportFileByGUID(report.getGuId()); // form instance deleteReportFormInstanceByGUID(report.getGuId()); // report deleteReport(report); } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e.getMessage()); if (!pendingTransactionUsed) db.rollback(); else throw e; } return false; } public boolean deleteCompleteReport(Report report) { boolean pendingTransactionUsed = startTransaction(db); try{ // report time without existing report deleteJobReportTimeByGUID(report.getGuId()); // report deleteReport(report); // report parts deleteReportMaterialByGUID(report.getGuId()); // report msg deleteJobMessage(report.getGuId()); // delete images deleteReportImage(report.getGuId()); // delete documents deleteReportDocument(report.getGuId()); // delete Measurements deleteReportMeasurement(report.getGuId()); // delete form instance deleteReportFormInstanceByGUID(report.getGuId()); // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return true; } catch (DBException e) { log.error(e.getMessage()); if (!pendingTransactionUsed) db.rollback(); else throw e; } return false; } /** * @param expenses */ private void deleteExpenses( Expenses expenses) { String sql = "DELETE FROM " + DbConstants.Expenses.EXPENSES //$NON-NLS-1$ + " WHERE " + DbConstants.Expenses.PERSONAL_NUMBER + " = '" + expenses.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Expenses.DATE + " = '" + expenses.getDate().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ int cnt = db.executeSql(sql); if (log.isDebugEnabled()) log.debug("Number of deleted ZKDMATIME Records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } private int deleteHistoryByJobIdAndJobType( String jobId, String jobType) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.History.HISTORY //$NON-NLS-1$ + " WHERE " + DbConstants.History.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.History.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ; return executeDataManipulationStmt(sqlStmt); } private int deleteJobReportTimeByGUID( String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobReportTime.JOB_REPORT_TIME //$NON-NLS-1$ + " WHERE " + DbConstants.JobReportTime.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } public void deleteMaterialPerson(MaterialPerson materialPerson) { db.executeSql("DELETE FROM " + DbConstants.MaterialPerson.MATERIAL_PERSON //$NON-NLS-1$ + " WHERE " + DbConstants.MaterialPerson.NUMBER + " = '" + materialPerson.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.MaterialPerson.TEXT + " = '" + materialPerson.getMaterialShortText() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private int deleteJobMessage(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobMessage.JOB_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.JobMessage.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportImage(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " <>'F'"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportDocument(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.TYPE + " ='F'"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportMeasurement(String guid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + guid + "'"; //$NON-NLS-1$ return executeDataManipulationStmt(sqlStmt); } public int deleteFormInstanceByGuidAndFormId( String guid, String formid) throws DBException { String sqlStmt = "DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE + " WHERE " + DbConstants.FormInstance.GUID + " = '" + guid + "'" + " AND " + DbConstants.FormInstance.FORM_ID + " = '" + formid + "'" ; return executeDataManipulationStmt(sqlStmt); } /** * @param part * @deprecated */ @Deprecated @SuppressWarnings("unused") private void deleteMaterial(Material part) { db.executeSql("DELETE FROM " + DbConstants.Material.MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.Material.NUMBER + " = '" + part.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Material.TEXT + " = '" + part.getMaterialShortText() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void deleteReportMaterial(ReportMaterial reportMaterial) { db.executeSql("DELETE FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + reportMaterial.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = " + reportMaterial.getIdx()); //$NON-NLS-1$ //$NON-NLS-2$ } private int deleteReportMaterialByGUID(String guid) { String sqlStmt = "DELETE FROM " + DbConstants.ReportMaterial.REPORT_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.ReportMaterial.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportFileByGUID(String guid) { String sqlStmt = "DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } private int deleteReportFormInstanceByGUID(String guid) { String sqlStmt = "DELETE FROM " + DbConstants.FormInstance.FORMINSTANCE //$NON-NLS-1$ + " WHERE " + DbConstants.FormInstance.GUID + " ='" + guid + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } /** * @param jobid * @param jobType * @deprecated */ @Deprecated @SuppressWarnings("unused") private void deleteReportByJobidAndJobType( String jobid, String jobType) { db.executeSql("DELETE FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.JOB_NUMBER + " = '" + jobid + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " = '" + jobType + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private int deleteReport(Report report) { String sqlStmt = "DELETE FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.JOB_NUMBER + " = '" + report.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " = '" + report.getJobType() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.GUID + " = '" + report.getGuId() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return executeDataManipulationStmt(sqlStmt); } public void deleteReportByGUID(String guid) { db.executeSql("DELETE FROM " + DbConstants.Report.REPORT //$NON-NLS-1$ + " WHERE " + DbConstants.Report.GUID + " = '" + guid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * @param timeSheets * @deprecated */ @Deprecated @SuppressWarnings("unused") private void deleteTimeSheetList(List timeSheets) { for (int i = 0; i < timeSheets.size(); i++) { deleteTimeSheet((TimeSheet) timeSheets.get(i)); } } private void deleteTimeSheet(TimeSheet timeSheet) { db.executeSql("DELETE FROM " + DbConstants.TimeSheet.TIME_SHEET //$NON-NLS-1$ + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = '" + timeSheet.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.IDX + " = '" + timeSheet.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.DATE + " = '" + timeSheet.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void deleteOrder(Order order) { db.executeSql("DELETE FROM " + DbConstants.Order.ORDER //$NON-NLS-1$ + " WHERE " + DbConstants.Order.IDX + " = " + order.getIdx() + "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } public void deleteOrderMaterial(OrderMaterial orderMaterial) { String sql = "DELETE FROM " + DbConstants.OrderMaterial.ORDER_MATERIAL //$NON-NLS-1$ + " WHERE " + DbConstants.OrderMaterial.PERSONAL_NUMBER + " = " + orderMaterial.getPersonalNumber() + "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.NUMBER + " ='" + orderMaterial.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.DATE + " ='" + orderMaterial.getDate().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ db.executeSql(sql); } public void deleteShortMessage(ShortMessage shortMessage) { db.executeSql("DELETE FROM " + DbConstants.ShortMessage.SHORT_MESSAGE //$NON-NLS-1$ + " WHERE " + DbConstants.ShortMessage.PERSONAL_NUMBER + " ='" + shortMessage.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ShortMessage.MESSAGE_KEY + " ='" + shortMessage.getMessageKey() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void deleteJobFile(JobFile jobFile) { db.executeSql("DELETE FROM " + DbConstants.JobFile.JOB_FILE //$NON-NLS-1$ + " WHERE " + DbConstants.JobFile.IDX + " ='" + jobFile.getJobFileId() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // remove image data from memory after delete (lazy load; MIG-988) jobFile.setSignPicAt(null); } public void deleteReportMeasurement(ReportMeasurement reportMeasurement) { String sql = "DELETE FROM " + DbConstants.ReportMeasurement.REPORT_MEASUREMENT + " WHERE " + DbConstants.ReportMeasurement.GUID + " ='" + reportMeasurement.getGuId() + "'" + " AND " + DbConstants.ReportMeasurement.COMMISSION_NUMBER + " ='" + reportMeasurement.getCommissionNumber() + "'" + " AND " + DbConstants.ReportMeasurement.PERSONAL_NUMBER + " ='" + reportMeasurement.getPersonalNumber() + "'" + " AND " + DbConstants.ReportMeasurement.MEASURING_POINT + " ='" + reportMeasurement.getMeasurementPoint() + "'" + " AND " + DbConstants.ReportMeasurement.MEASUREMENT + " ='" + reportMeasurement.getMeasurement() + "'"; db.executeSql(sql ); log.info(sql); } public void deleteVariousExpense(VariousExpenses variousExpenses) { String sql = "DELETE FROM " + DbConstants.VariousExpenses.VARIOUS_EXPENSES + " WHERE " + DbConstants.VariousExpenses.PERSONAL_NUMBER + " ='" + variousExpenses.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenses.DATE + " ='" + variousExpenses.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenses.IDX + " ='" + variousExpenses.getVariousExpensesId() + "'"; db.executeSql(sql ); log.info(sql); } public void deleteVariousExpenseFile(VariousExpenseFile variousExpenseFile) { String sql = "DELETE FROM " + DbConstants.VariousExpenseFile.VARIOUS_EXPENSE_FILE + " WHERE " + DbConstants.VariousExpenseFile.PERSONAL_NUMBER + " ='" + variousExpenseFile.getPersonalNumber() + "'" + " AND " + DbConstants.VariousExpenseFile.DATE + " ='" + variousExpenseFile.getDate().getTime() + "'" + " AND " + DbConstants.VariousExpenseFile.IDX + " ='" + variousExpenseFile.getVariousExpensesFileId() + "'"; db.executeSql(sql ); log.info(sql); } public void deleteAbsenceNotification(AbsenceNotification absenceNotification) { db.executeSql("DELETE FROM " + DbConstants.AbsenceNotification.ABSENCE_NOTIFICATION + " WHERE " + DbConstants.AbsenceNotification.GUID + " ='" + absenceNotification.getGuId() + "'" + " AND " + DbConstants.AbsenceNotification.PERSONAL_NUMBER + " ='" + absenceNotification.getPersonalNumber() + "'" + " AND " + DbConstants.AbsenceNotification.DATE + " = '" + absenceNotification.getAbsenceDate().getTime() + "'"); } public void deleteMaterialMovement(MaterialMovement materialMovement) { db.executeSql("DELETE FROM " + DbConstants.MaterialMovement.MATRIAL_MOVEMENT + " WHERE " + DbConstants.MaterialMovement.GUID + " ='" + materialMovement.getGuid() + "'" + " AND " + DbConstants.MaterialMovement.PERSONAL_NUMBER + " ='" + materialMovement.getPersonalNumber() + "'"); } public void updateReport(Report report) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.UPDATE(DbConstants.Report.REPORT) .in(DbConstants.Report.COMMISSION_NUMBER, report.getCommissionNumber()) .in(DbConstants.Report.CHECK_LIST, report.getChecklist()) .in(DbConstants.Report.ORDER_NUMBER, report.getOrderNumber()) .in(DbConstants.Report.FINAL_REPAIR, report.getFinalRepair()) .in(DbConstants.Report.CREATE_DATE, report.getCreateDate()) .in(DbConstants.Report.ERROR_FLAG_1, report.getErrorFlag1()) .in(DbConstants.Report.ERROR_FLAG_2, report.getErrorFlag2()) .in(DbConstants.Report.ERROR_FLAG_3, report.getErrorFlag3()) .in(DbConstants.Report.SYSTEM_ERROR, report.getSystemError()) .in(DbConstants.Report.ERROR_ID_1, report.getErrorId1()) .in(DbConstants.Report.ERROR_ID_2, report.getErrorId2()) .in(DbConstants.Report.ERROR_ID_3, report.getErrorId3()) .in(DbConstants.Report.ERROR_H_1, report.getErrorH1()) .in(DbConstants.Report.ERROR_H_2, report.getErrorH2()) .in(DbConstants.Report.ERROR_H_3, report.getErrorH3()) .in(DbConstants.Report.REASONING, report.getReasoning()) .in(DbConstants.Report.DISTANCE, report.getDistance()) .in(DbConstants.Report.PERSONAL_NUMBER, report.getPersonalNumber()) .in(DbConstants.Report.SIGNATURE_GUID,report.getSignatureGuId()) .in(DbConstants.Report.CUSTOMER_SUPPORT, report.getCustomerSupport()) .in(DbConstants.Report.CUSTOMRE_SUPPORT_TEXT,report.getCustomerSupportText()) .in(DbConstants.Report.REPORT_STATUS,report.getReportStatus().getCode()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_1, report.getServicePlanMonth1()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_2, report.getServicePlanMonth2()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_3, report.getServicePlanMonth3()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_4, report.getServicePlanMonth4()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_5, report.getServicePlanMonth5()) .in(DbConstants.Report.SERVICE_PLAN_MENTH_6, report.getServicePlanMonth6()) .in(DbConstants.Report.MONTH_YEAR, report.getMonthYear()) .in(DbConstants.Report.SAFETY_REPORT, report.getSafetyReport()) .in(DbConstants.Report.SIGNATURE_FLAG, report.getSignatureFlag()) .in(DbConstants.Report.SIGNATURE_INFO, report.getSignatureInfo()) .in(DbConstants.Report.SIGNATURE, report.getSignature()) .in(DbConstants.Report.EXPENSES, report.getExpenses()) .in(DbConstants.Report.INCIDENT_AB, report.getIncidentAB()) .in(DbConstants.Report.PARTICAL_REPAIR, report.getPartialRepair()) .in(DbConstants.Report.BILLING, report.getBilling()) .in(DbConstants.Report.WORK_TYPE, report.getWorkType()) .in(DbConstants.Report.NO_MATERIAL, report.getNoMaterial()) .in(DbConstants.Report.CYCLE_OF_INSTALLATION, report.getCycleOfInstallation()) .in(DbConstants.Report.NO_FORM1, report.getNoForm1()) .in(DbConstants.Report.NO_FORM2, report.getNoForm2()) .in(DbConstants.Report.NO_FORM3, report.getNoForm3()) .in(DbConstants.Report.SERVICE_REFUSED, report.getServiceRefused()) .in(DbConstants.Report.OPEN_PENDING, report.getOpenPending()) .in(DbConstants.Report.GOVERNMENT_REPORT, report.getGovernmentReport()) .in(DbConstants.Report.CHECKLIST_STATE, report.getChecklistState()) .in(DbConstants.Report.CHECKLIST_SIA, report.getChecklistSIA()) .in(DbConstants.Report.CHECKLIST_READY, report.getChecklistReady()) .in(DbConstants.Report.CHECKLIST_INSTRUCTION, report.getChecklistInstruction()) .in(DbConstants.Report.CHECKLIST_VKF, report.getChecklistVKF()) .in(DbConstants.Report.CHECKLIST_TEST, report.getChecklistTest()) .in(DbConstants.Report.SIGNATURE_NAME, report.getSignatureName()) .in(DbConstants.Report.MON_STK, report.getMonStk()) + " WHERE " + DbConstants.Report.IDX + " = " + report.getIdx() + "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_NUMBER + " = '" + report.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.JOB_TYPE + " = '" + report.getJobType() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Report.GUID + " = '" + report.getGuId() + "'"; db.executeSql(sqlStmt); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isInfoEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ } public void updateJobMessage(JobMessage jobMessage) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobMessage.JOB_MESSAGE) .in(DbConstants.JobMessage.MESSAGE_CODE, jobMessage.getMessageCode()) .in(DbConstants.JobMessage.TEXT_1, jobMessage.getMessageCodeText()) .in(DbConstants.JobMessage.TEXT_2, jobMessage.geText()) .in(DbConstants.JobMessage.MoreText, jobMessage.getMoreText()) + " WHERE " + DbConstants.JobMessage.GUID + " = '" + jobMessage.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobMessage.MESSAGE_ID + " = '" + jobMessage.getMessageId() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void updateJobFile(JobFile jobFile) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobFile.JOB_FILE) .in(DbConstants.JobFile.IDX, jobFile.getJobFileId()) .in(DbConstants.JobFile.GUID, jobFile.getGuid()) .in(DbConstants.JobFile.JOB_NUMBER, jobFile.getJobNumber()) .in(DbConstants.JobFile.JOB_TYPE, jobFile.getJobType().getCode()) .in(DbConstants.JobFile.TYPE, jobFile.getType()) .in(DbConstants.JobFile.DESCRIPTION, jobFile.getDescription()) .in(DbConstants.JobFile.SIGN_PIC_AT, jobFile.getSignpicAt()) .in(DbConstants.JobFile.FORM_TYPE, jobFile.getFormType().getCode()) .in(DbConstants.JobFile.FORM_DESC, jobFile.getFormDesc()) .in(DbConstants.JobFile.SENT_DATE, jobFile.getSentDate()) + " WHERE " + DbConstants.JobFile.GUID + " = '" + jobFile.getGuid() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobFile.IDX + " = '" + jobFile.getJobFileId() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // remove image data from memory after update (lazy load; MIG-988) jobFile.setSignPicAt(null); } private String getSqlUpdateJob(Job job) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = (sql.UPDATE(DbConstants.Job.JOB) .in(DbConstants.Job.CURRENT_REPORT_GUID,job.getCurrentReportGuId(this)) .in(DbConstants.Job.PERSONAL_NUMBER,job.getPersonalNumber()) .in(DbConstants.Job.STATUS,job.getStatus().getCode()) .in(DbConstants.Job.PRIORITY,job.getPriority()) .in(DbConstants.Job.JOB_FORWARD,job.getJobForward()) .in(DbConstants.Job.COMMISSION_NUMBER,job.getCommissionNumber()) .in(DbConstants.Job.STAFF_NAME, job.getStaffName()) .in(DbConstants.Job.STAFF_PHONE, job.getStaffPhoneNumber()) .in(DbConstants.Job.APPOINTMENT_DATE, job.getAppointmentDate()) .in(DbConstants.Job.ACTIVE_DATE, job.getActiveJobDate()) .in(DbConstants.Job.JOB_RESCHEDULE_DATE, job.getJobRescheduleDate()) .in(DbConstants.Job.JOB_RESCHEDULE_TIME, job.getJobRescheduleTime()) .in(DbConstants.Job.WEEK, job.getWeek()) .in(DbConstants.Job.FIX, job.getFix()) .in(DbConstants.Job.APPOINTMENT, job.getAppointment()) .in(DbConstants.Job.ORDER_NUMBER, job.getOrderNumber()) .in(DbConstants.Job.PARTNER_OF_INSTALL_ADDRESS_ID, job.getPartnerOfInstallAddressId()) .in(DbConstants.Job.CUSTOMER_SERVICE_ADDRESS_ID, job.getKdnServiceAddressId()) .in(DbConstants.Job.CUSTOMER_ADDRESS_ID, job.getCustomerAddressId()) .in(DbConstants.Job.PARTNER_ADDRESS_ID, job.getPartnerAddressId()) .in(DbConstants.Job.OBJECT_ADDRESS_ID, job.getObjectAddressId()) .in(DbConstants.Job.OWNER_ADDRESS_ID, job.getOwnerAddressId()) .in(DbConstants.Job.NEW_JOB_DATE, job.getNewJobDate()) .in(DbConstants.Job.ERROR_ID, job.getErrorId()) .in(DbConstants.Job.CALL_SERVICE_FLAG, job.getCallServiceFlag()) .in(DbConstants.Job.MAINTENANCE_CONTRACT_TYPE, job.getMaintenanceContractType()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_1, job.getServicePlanMonth1()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_2, job.getServicePlanMonth2()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_3, job.getServicePlanMonth3()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_4, job.getServicePlanMonth4()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_5, job.getServicePlanMonth5()) .in(DbConstants.Job.SERVICE_PLAN_MONTH_6, job.getServicePlanMonth6()) .in(DbConstants.Job.SERVICE_OPEN, job.getServiceOpen()) .in(DbConstants.Job.CONTACT_NAME, job.getContactName()) .in(DbConstants.Job.CONTACT_PHONE, job.getContactPhoneNumber()) .in(DbConstants.Job.TECHNICAL_NAME, job.getTechnicalName()) .in(DbConstants.Job.TECHNICAL_PHONE, job.getTechnicalPhoneNumber()) .in(DbConstants.Job.SELLER_NAME, job.getSellerName()) .in(DbConstants.Job.SELLER_PHONE, job.getSellerPhoneNumber()) .in(DbConstants.Job.STATUS_EDIT, job.getStatusEdit()) .in(DbConstants.Job.DRIVER_TYPE, job.getDriveType()) .in(DbConstants.Job.DRIVER_TYPE_UPD, job.isDriveTypeUpdated() ? "X" : "") //$NON-NLS-1$ //$NON-NLS-2$ .in(DbConstants.Job.DEFAULT_TIME, job.getDefaultTime()) .in(DbConstants.Job.DESCRIPTION, job.getInformation()) .in(DbConstants.Job.INFORMATION, job.getDescription()) .in(DbConstants.Job.CYCLE_OF_INSTALLATIN_FLAG, job.getCycleOfInstallationFlag()) .in(DbConstants.Job.FORM_DESC_1, job.getFormDesc1()) .in(DbConstants.Job.FORM_DESC_2, job.getFormDesc2()) .in(DbConstants.Job.FORM_DESC_3, job.getFormDesc3()) .in(DbConstants.Job.SERVICE_REFUSED_FLAG, job.getServiceRefusedFlag()) .in(DbConstants.Job.LINK, job.getLink()) .in(DbConstants.Job.GUARANTEE, job.getGuarantee()) .in(DbConstants.Job.MORE_INFORMARION_FLAG, job.getMoreInformationsFlag()) + " WHERE " + DbConstants.Job.JOB_NUMBER + " = '" + job.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Job.JOB_TYPE + " = '" + job.getJobType() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info("sql /" + sqlStmt + "/"); return sqlStmt; } /** * Updates the job, addresses and reports with the new KomNr * @param job The job, where the KomNr needs to be updated * @param comNo The new KomNr */ public void updateJobByComNo(Job job, String comNo) { if (!job.getCommissionNumber().equalsIgnoreCase(comNo)) { job.setCommissionNumber(comNo); updateJob(job); updateAddressComNo(job.getJobNumber(), job.getJobType().getCode(), comNo); if (!job.getCurrentReport().getReportStatus().isInitial()) { job.getCurrentReport().setCommissionNumber(comNo); updateReport(job.getCurrentReport()); } updateReportMaterialComNo(job.getCurrentReportGuId(this), comNo); } } public void updateJob(Job job) { Iterator
itr = job.getAddresses().values().iterator(); while (itr.hasNext()) { Address address = itr.next(); updateAddress(address); } db.executeSql(getSqlUpdateJob(job)); } public int updateAddress(Address address) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = (sql.UPDATE(DbConstants.Address.ADDRESS) .in(DbConstants.Address.JOB_TYPE, address.getJobType().getCode()) .in(DbConstants.Address.CITY, address.getCity()) .in(DbConstants.Address.TYPE, address.getType()) .in(DbConstants.Address.EMAIL, address.getEmail()) .in(DbConstants.Address.FAX, address.getFaxNumber()) .in(DbConstants.Address.CUSTOMER_NUMBER, address.getCustomerNumber()) .in(DbConstants.Address.JOB_NUMBER, address.getJobNumber()) .in(DbConstants.Address.NAME1, address.getName1()) .in(DbConstants.Address.NAME2, address.getName2()) .in(DbConstants.Address.NAME3, address.getName3()) .in(DbConstants.Address.LOCATION, address.getLocation()) .in(DbConstants.Address.PARTNER_NUMBER, address.getPartnerNummer()) .in(DbConstants.Address.PASTAL_CODE, address.getPostalCode()) .in(DbConstants.Address.STREET, address.getStreet()) .in(DbConstants.Address.PHONE_1, address.getTelNumber1()) .in(DbConstants.Address.PHONE_2, address.getTelNumber2()) .in(DbConstants.Address.TITLE, address.getTitle()) .in(DbConstants.Address.CHANGE_FLAG, address.getChangeFlag()) .in(DbConstants.Address.COMMISSION_NUMBER, address.getCommissionNumber()) .in(DbConstants.Address.DIRTY_FLAG, address.getDirtyFlag()) + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + address.getJobNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + address.getJobType() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.PARTNER_NUMBER + " = '" + address.getPartnerNummer() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isInfoEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ int cnt = db.executeSql(sqlStmt); if (log.isInfoEnabled()) log.info("Number of affected records:'" + cnt + "'"); //$NON-NLS-1$ //$NON-NLS-2$ return cnt; } public void updateAddressComNo(String jobId, String jobType, String newComNo) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Address.ADDRESS) .in(DbConstants.Address.COMMISSION_NUMBER, newComNo) + " WHERE " + DbConstants.Address.JOB_NUMBER + " = '" + jobId + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.Address.JOB_TYPE + " = '" + jobType + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } /** * @param timeSheet * @param newIdx * @deprecated */ @Deprecated @SuppressWarnings("unused") private void updateTimeSheetIdx(TimeSheet timeSheet, int newIdx) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.TimeSheet.TIME_SHEET) .in(DbConstants.TimeSheet.IDX, newIdx) + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = " + timeSheet.getPersonalNumber() //$NON-NLS-1$ //$NON-NLS-2$ + " AND " + DbConstants.TimeSheet.IDX + " = '" + timeSheet.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.DATE + " ='" + timeSheet.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * @param jobReportTime * @param newIdx * @deprecated */ @Deprecated @SuppressWarnings("unused") private void updateJobReportTimeIdx( JobReportTime jobReportTime, int newIdx) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobReportTime.JOB_REPORT_TIME) .in(DbConstants.JobReportTime.IDX, newIdx) + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + jobReportTime.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " = '" + jobReportTime.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.DATE + " = '" + jobReportTime.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /** * @param jobReportTime * @deprecated */ @Deprecated @SuppressWarnings("unused") private void updateJobReportTime( JobReportTime jobReportTime) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.JobReportTime.JOB_REPORT_TIME) .in(DbConstants.JobReportTime.START_TIME, jobReportTime.getStartTime()) .in(DbConstants.JobReportTime.STOP_TIME, jobReportTime.getStopTime()) .in(DbConstants.JobReportTime.WORK_TYPE_CODE, jobReportTime.getWorkTypeCode()) + " WHERE " + DbConstants.JobReportTime.GUID + " = '" + jobReportTime.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.IDX + " = '" + jobReportTime.getIdx() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.JobReportTime.DATE + " = '" + jobReportTime.getDate().getTime() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void updateUser(Person person) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Person.PERSON).in( DbConstants.Person.WAREHOUSE_NUMBER, person.getWarehouseNumber()).in( DbConstants.Person.COMMISSION_NUMBER_FORMAT, person.getCommunicationNumberFormat()).in( DbConstants.Person.EXPENSES_ACTIVE, person.getExpensesActive()).in( DbConstants.Person.PROFILE_TEXT, person.getProfileText()) + " WHERE " + DbConstants.Person.PERSONAL_NUMBER + " = " + person.getPersonalNumber()); } public void switchUser(Person person) { DBSqlHelper sql = new DBSqlHelper(db); String sqlStmt = sql.INSERT(DbConstants.Person.PERSON).in( DbConstants.Person.PERSONAL_NUMBER, person.getPersonalNumber()).in( DbConstants.Person.LAST_NAME, person.getLastName()).in( DbConstants.Person.FIRST_NAME, person.getFirstName()).in( DbConstants.Person.INITIAL, person.getInitial()).in( DbConstants.Person.PERSONAL_NUMBER_DEPUTY, person.getPersonalNumberDeputy()).in( DbConstants.Person.PHONE, person.getPhoneNumber()).in( DbConstants.Person.NUM01, person.getNUM01()).in( DbConstants.Person.SALES_OFFICE, person.getSalesOffice()).in( DbConstants.Person.ABSENT_FROM, person.getAbsentFrom()).in( DbConstants.Person.ABSENT_TO, person.getAbsentTo()).in( DbConstants.Person.LANGUAGE, person.getLanguage()).in( DbConstants.Person.DEVICE_ID, person.getDeviceId()).in( DbConstants.Person.PASSWORD, person.getPassword()).in( DbConstants.Person.REFRESH_FLAG, person.getRefreshFlag()).in( DbConstants.Person.WAREHOUSE_NUMBER, person.getWarehouseNumber()).in( DbConstants.Person.COMMISSION_NUMBER_FORMAT, person.getCommunicationNumberFormat()).in( DbConstants.Person.EXPENSES_ACTIVE, person.getExpensesActive()).in( DbConstants.Person.PROFILE_TEXT, person.getProfileText()) .toString(); db.executeSql(sqlStmt); } public void updateReportMaterialIdx(ReportMaterial reportMaterial, int newIdx) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.ReportMaterial.REPORT_MATERIAL) .in(DbConstants.ReportMaterial.IDX, newIdx) + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + reportMaterial.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = " + reportMaterial.getIdx()); //$NON-NLS-1$ //$NON-NLS-2$ } public void updateReportMaterial(ReportMaterial reportMaterial) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.ReportMaterial.REPORT_MATERIAL).in( DbConstants.ReportMaterial.PERSONAL_NUMBER, reportMaterial.getPersonalNumber()).in( DbConstants.ReportMaterial.COMMISSION_NUMBER, reportMaterial.getCommissionNumber()).in( DbConstants.ReportMaterial.AMOUNT, reportMaterial.getAmount()).in( DbConstants.ReportMaterial.DELIVERY, reportMaterial.getDelivery()).in( DbConstants.ReportMaterial.EXPRESS_DELIVERY, reportMaterial.getExpressDelivery()).in( DbConstants.ReportMaterial.ACCOUNT_CODE, reportMaterial.getAccountCode()).in( DbConstants.ReportMaterial.UNIT, reportMaterial.getUnit()).in( DbConstants.ReportMaterial.NAME, reportMaterial.getProductName()).in( DbConstants.ReportMaterial.PRICE, reportMaterial.getPrice()).in( DbConstants.ReportMaterial.BARCODE, reportMaterial.getBarcode()).in( DbConstants.ReportMaterial.K14, reportMaterial.getK14()).in( DbConstants.ReportMaterial.EXPLANATION_TEXT, reportMaterial.getExplanationText()).in( DbConstants.ReportMaterial.OTHER_TYPE_FLAG, reportMaterial.getOtherTypeFlag()) + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + reportMaterial.getGuId() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.ReportMaterial.IDX + " = " + reportMaterial.getIdx() //$NON-NLS-1$ //$NON-NLS-2$ ); } public void updateArticleEntryCount(String guid, String entryCount) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.DeliveryList.DELIVERY_LIST) .in(DbConstants.DeliveryList.ENTRY_COUNT, entryCount) + " WHERE " + DbConstants.DeliveryList.GUID + " = '" + guid + "'" ); } public void updateArticleEntryCount(String orderNr, String matnr, String entryCount) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.DeliveryList.DELIVERY_LIST) .in(DbConstants.DeliveryList.ENTRY_COUNT, entryCount) + " WHERE " + DbConstants.DeliveryList.TO + " = '" + getUser().getWarehouseNumber() + "'" + " AND " + DbConstants.DeliveryList.ORDER_NUMBER + " = '" + orderNr + "'" + " AND " + DbConstants.DeliveryList.MATERIAL_NUMBER + " = '" + matnr + "'" ); } public void updateReportMaterialComNo(String guid, String newConNo) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.ReportMaterial.REPORT_MATERIAL) .in(DbConstants.ReportMaterial.COMMISSION_NUMBER, newConNo) + " WHERE " + DbConstants.ReportMaterial.GUID + " = '" + guid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void updateOrder(Order order) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Order.ORDER).in( DbConstants.Order.STATUS, order.getStatus()).in( DbConstants.Order.ANZ, order.getANZ()).in( DbConstants.Order.CREATED_DATE, order.getCreateDate()).in( DbConstants.Order.SENT_DATE, order.getSentDate()) + " WHERE " + DbConstants.TimeSheet.PERSONAL_NUMBER + " = '" + order.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.TimeSheet.IDX + " = " + order.getIdx()); //$NON-NLS-1$ //$NON-NLS-2$ } public void updateOrderMaterial(OrderMaterial orderMaterial) { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.OrderMaterial.ORDER_MATERIAL) .in(DbConstants.OrderMaterial.AMOUNT, orderMaterial.getAmount()) .in(DbConstants.OrderMaterial.UNIT, orderMaterial.getUnit()) .in(DbConstants.OrderMaterial.EXPRESS_FLAG, orderMaterial.getExpressFlag()) + " WHERE " + DbConstants.OrderMaterial.PERSONAL_NUMBER + " = '" + orderMaterial.getPersonalNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.NUMBER + " = '" + orderMaterial.getMaterialNumber() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND " + DbConstants.OrderMaterial.DATE + " = '" + orderMaterial.getDate().getTime() + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } public int cntJobid( String jobId) { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT " + DbConstants.Job.JOB_NUMBER + " FROM " + DbConstants.Job.JOB //$NON-NLS-1$ //$NON-NLS-2$ + " WHERE " + DbConstants.Job.JOB_NUMBER + " = '" + jobId + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public int cntPerNo( String perNo) { int result = 0; RecordSet rs = db.getRecordSet(); String sql = "SELECT " //$NON-NLS-1$ + DbConstants.Address.JOB_NUMBER + ", " //$NON-NLS-1$ + DbConstants.Address.JOB_TYPE + ", " //$NON-NLS-1$ + DbConstants.Address.PARTNER_NUMBER + " FROM " + DbConstants.Address.ADDRESS //$NON-NLS-1$ + " WHERE " + DbConstants.Address.PARTNER_NUMBER + " = '" + perNo + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { result = rs.getCount(); } finally { rs.dispose(); } return result; } public void updateRefreshFlag() { DBSqlHelper sql = new DBSqlHelper(db); db.executeSql(sql.UPDATE(DbConstants.Employee.EMPLOYEE).in(DbConstants.Employee.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.WorkType.WORK_TYPE).in(DbConstants.WorkType.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.ErrorCode.ERROR_CODE).in(DbConstants.ErrorCode.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Material.MATERIAL).in(DbConstants.Material.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Reason.REASON).in(DbConstants.Reason.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobReturnReason.JOB_RETURN_REASON).in(DbConstants.JobReturnReason.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobMonText.JOB_MON_TEXT).in(DbConstants.JobMonText.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.InternalWorkType.INTERNAL_WORK_TYPE).in(DbConstants.InternalWorkType.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Incident.INCIDENT).in(DbConstants.Incident.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobFormDesc.JOB_FORM_DESC).in(DbConstants.JobFormDesc.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.JobNoForm.JOB_NO_FORM).in(DbConstants.JobNoForm.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Invoice.INVOICE).in(DbConstants.Invoice.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.AbsenceType.ABSENCE_TYPE).in(DbConstants.AbsenceType.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.ServiceRefused.SERVICE_REFUSED).in(DbConstants.ServiceRefused.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Checklist.CHECK_LIST).in(DbConstants.Checklist.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Progress.PROGRESS).in(DbConstants.Progress.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.StateOfInstallation.STATE_OF_INSTALLATION).in(DbConstants.StateOfInstallation.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.NextIntervention.NEXT_INVENTION).in(DbConstants.NextIntervention.REFRESH_FLAG, " ").toString()); db.executeSql(sql.UPDATE(DbConstants.Inventory.INVENTORY).in(DbConstants.Inventory.REFRESH_FLAG, " ").toString()); } public void deleteAllWorkTypeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.WorkType.WORK_TYPE + " WHERE " + DbConstants.WorkType.REFRESH_FLAG + " = ' '"); } public void deleteAllErrorCodeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.ErrorCode.ERROR_CODE + " WHERE " + DbConstants.ErrorCode.REFRESH_FLAG + " = ' '"); } public void deleteAllMaterialNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Material.MATERIAL + " WHERE " + DbConstants.Material.REFRESH_FLAG + " = ' '"); } public void deleteAllEmployeeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Employee.EMPLOYEE + " WHERE " + DbConstants.Employee.REFRESH_FLAG + " = ' '"); } public void deleteAllReasonNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Reason.REASON + " WHERE " + DbConstants.Reason.REFRESH_FLAG + " = ' '"); } public void deleteAllJobDeleteReasonNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobReturnReason.JOB_RETURN_REASON + " WHERE " + DbConstants.JobReturnReason.REFRESH_FLAG + " = ' '"); } public void deleteAllJobMonTextNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobMonText.JOB_MON_TEXT + " WHERE " + DbConstants.JobMonText.REFRESH_FLAG + " = ' '"); } public void deleteAllIncIdentNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Incident.INCIDENT + " WHERE " + DbConstants.Incident.REFRESH_FLAG + " = ' '"); } public void deleteAllJobFormDescNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobFormDesc.JOB_FORM_DESC + " WHERE " + DbConstants.Incident.REFRESH_FLAG + " = ' '"); } public void deleteAllJobNoFormNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.JobNoForm.JOB_NO_FORM + " WHERE " + DbConstants.Incident.REFRESH_FLAG + " = ' '"); } public void deleteAllInvoiceNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Invoice.INVOICE + " WHERE " + DbConstants.Invoice.REFRESH_FLAG + " = ' '"); } public void deleteAllInternalWorkTypeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.InternalWorkType.INTERNAL_WORK_TYPE + " WHERE " + DbConstants.InternalWorkType.REFRESH_FLAG + " = ' '"); } public void deleteAllAbsenceTypeNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.AbsenceType.ABSENCE_TYPE + " WHERE " + DbConstants.AbsenceType.REFRESH_FLAG + " = ' '"); } public void deleteAllServiceRefusedNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.ServiceRefused.SERVICE_REFUSED + " WHERE " + DbConstants.ServiceRefused.REFRESH_FLAG + " = ' '"); } public void deleteAllChecklistNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Checklist.CHECK_LIST + " WHERE " + DbConstants.Checklist.REFRESH_FLAG + " = ' '"); } public void deleteAllProgresstNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Progress.PROGRESS + " WHERE " + DbConstants.Progress.REFRESH_FLAG + " = ' '"); } public void deleteAllStateOfInstallationNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.StateOfInstallation.STATE_OF_INSTALLATION + " WHERE " + DbConstants.StateOfInstallation.REFRESH_FLAG + " = ' '"); } public void deleteAllNextInterventionNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.NextIntervention.NEXT_INVENTION + " WHERE " + DbConstants.NextIntervention.REFRESH_FLAG + " = ' '"); } public void deleteAllInventoryNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.Inventory.INVENTORY + " WHERE " + DbConstants.Inventory.REFRESH_FLAG + " = ' '"); } public void deleteAllReceiptOfGoodsNonRefreshed() { db.executeSql("DELETE FROM " + DbConstants.ReceiptOfGoods.RECEIPT_OF_GOODS + " WHERE " + DbConstants.ReceiptOfGoods.REFRESH_FLAG + " = ' '"); } public List selectCalendarDateWithRunningTimeCapturing(int pernr) { // Date result = null; List result = new ArrayList(); RecordSet rs = db.getRecordSet(); String sql = "SELECT c." + DbConstants.CalendarTimeSheet.DATE //$NON-NLS-1$ + " FROM " + DbConstants.CalendarTimeSheet.CALENDAR_TIME_SHEET + " c, " //$NON-NLS-1$ //$NON-NLS-2$ + DbConstants.TimeSheet.TIME_SHEET + " t " //$NON-NLS-1$ + " WHERE t." + DbConstants.TimeSheet.START_TIME + " >= c." + DbConstants.CalendarTimeSheet.DATE //$NON-NLS-1$ //$NON-NLS-2$ + " AND t." + DbConstants.TimeSheet.START_TIME + " < c." + DbConstants.CalendarTimeSheet.DATE + " + 86400000 " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND t." + DbConstants.TimeSheet.PERSONAL_NUMBER + " ='" + pernr + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + " AND t." + DbConstants.TimeSheet.STOP_TIME + " ='" + DateUtils.getInitialDateTime().getTime() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); //$NON-NLS-1$ //$NON-NLS-2$ rs.setQuery(sql); try { if (rs.getCount() == 0) { if (log.isDebugEnabled()) log.debug("/" + sql + "/ not found"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (rs.getCount() == 1) { rs.moveNext(); Date date = rs.getDate(DbConstants.CalendarTimeSheet.DATE); result.add(date); } else { while (rs.moveNext()) { Date date = rs.getDate(DbConstants.CalendarTimeSheet.DATE); result.add(date); } log.error("Multiple CALENDAR objects with running time capturing found!"); //$NON-NLS-1$ } } finally { rs.dispose(); } return result; } private boolean startTransaction(DBSession session) { if (session.isTransactionPending()) return true; else { session.startTransaction(); return false; } } private int executeDataManipulationStmt(String sqlStmt) throws DBException { int result = -1; boolean pendingTransactionUsed = startTransaction(db); try{ if (log.isInfoEnabled()) log.info("sql /" + sqlStmt + "/"); //$NON-NLS-1$ //$NON-NLS-2$ result = db.executeSql(sqlStmt); if (log.isInfoEnabled()) { log.info("Number of affected records:'" + result + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } // only commit the transaction if it's shelf started! if (!pendingTransactionUsed) db.commit(); // successful termination return result; } catch (DBException e) { log.error(e.getMessage()); if (!pendingTransactionUsed) db.rollback(); else throw e; } // termination with errors return result; } private String setDefaultLanguage(String language) { String result = language; if (StringUtil.isEmpty(result)) { result = "D"; //$NON-NLS-1$ } return result; } } package ch.mfiles.kaba.kolibri.timesheet.util; public class CalendarScrollTrigger { public static final int NONE = 0; public static final int PREVIOUS = 1; public static final int NEXT = 2; private static final int VISIBLE_THRESHOLD = 1; private static final int PREVIOUS_PREFETCH_THRESHOLD = 3; private static final int NEXT_PREFETCH_THRESHOLD = 10; private static final int UNKNOWN_POSITION = -1; private int lastFirstVisibleItem = UNKNOWN_POSITION; private boolean userScrolling = false; private boolean suppressUntilIdle = false; private int consumedTriggersUntilIdle = NONE; private int suppressedTriggersUntilIdle = NONE; public static int getTrigger(int firstVisibleItem, int visibleItemCount, int totalItemCount, boolean userScrolling, boolean loadRunning) { if (loadRunning || !userScrolling || visibleItemCount <= 0 || totalItemCount <= visibleItemCount) { return NONE; } if (firstVisibleItem <= VISIBLE_THRESHOLD) { return PREVIOUS; } if ((firstVisibleItem + visibleItemCount) >= totalItemCount) { return NEXT; } return NONE; } public void onScrollStateChanged(boolean userScrolling) { if (!userScrolling) { this.userScrolling = false; this.suppressUntilIdle = false; this.consumedTriggersUntilIdle = NONE; this.suppressedTriggersUntilIdle = NONE; this.lastFirstVisibleItem = UNKNOWN_POSITION; return; } if (!this.userScrolling) { this.consumedTriggersUntilIdle = NONE; this.suppressedTriggersUntilIdle = NONE; this.lastFirstVisibleItem = UNKNOWN_POSITION; } this.userScrolling = true; } public void suppressUntilIdle() { this.suppressUntilIdle = true; this.consumedTriggersUntilIdle = PREVIOUS | NEXT; } public void suppressTriggerUntilIdle(int trigger) { if (!isLoadTrigger(trigger)) { return; } this.suppressedTriggersUntilIdle |= trigger; this.consumedTriggersUntilIdle |= trigger; } public int getTrigger(int firstVisibleItem, int visibleItemCount, int totalItemCount, boolean loadRunning) { if (loadRunning || !userScrolling || suppressUntilIdle || visibleItemCount <= 0 || totalItemCount <= visibleItemCount) { rememberPosition(firstVisibleItem); return NONE; } if (lastFirstVisibleItem == UNKNOWN_POSITION) { rememberPosition(firstVisibleItem); return NONE; } int previousFirstVisibleItem = lastFirstVisibleItem; rememberPosition(firstVisibleItem); if (firstVisibleItem < previousFirstVisibleItem && firstVisibleItem <= PREVIOUS_PREFETCH_THRESHOLD) { return consumeTrigger(PREVIOUS); } if (firstVisibleItem > previousFirstVisibleItem && (firstVisibleItem + visibleItemCount) >= totalItemCount - NEXT_PREFETCH_THRESHOLD) { return consumeTrigger(NEXT); } return NONE; } public int getOverScrollTrigger(int firstVisibleItem, int lastVisibleItem, int totalItemCount, boolean loadRunning) { if (loadRunning || suppressUntilIdle || totalItemCount <= 0) { return NONE; } boolean topVisible = firstVisibleItem <= 0; boolean bottomVisible = lastVisibleItem >= totalItemCount - 1; if (topVisible && bottomVisible) { return NONE; } if (topVisible) { return consumeTrigger(PREVIOUS); } if (bottomVisible) { return consumeTrigger(NEXT); } return NONE; } private int consumeTrigger(int trigger) { if (isTriggerSuppressed(trigger)) { return NONE; } consumedTriggersUntilIdle |= trigger; return trigger; } private boolean isTriggerSuppressed(int trigger) { return (consumedTriggersUntilIdle & trigger) != 0 || (suppressedTriggersUntilIdle & trigger) != 0; } private boolean isLoadTrigger(int trigger) { return trigger == PREVIOUS || trigger == NEXT; } private void rememberPosition(int firstVisibleItem) { lastFirstVisibleItem = firstVisibleItem; } } package ch.mfiles.kaba.kolibri.timesheet.util; import junit.framework.TestCase; public class CalendarScrollTriggerTest extends TestCase { public CalendarScrollTriggerTest(String name) { super(name); } public void testStaticTriggerKeepsExistingBottomBehavior() { assertEquals(CalendarScrollTrigger.PREVIOUS, CalendarScrollTrigger.getTrigger(0, 10, 35, true, false)); } public void testStaticTriggerDoesNotTriggerWhileListIsPositionedProgrammatically() { assertEquals(CalendarScrollTrigger.NONE, CalendarScrollTrigger.getTrigger(0, 10, 35, false, false)); } public void testStaticTriggerKeepsExistingNextBehavior() { assertEquals(CalendarScrollTrigger.NEXT, CalendarScrollTrigger.getTrigger(25, 10, 35, true, false)); } public void testDoesNotTriggerNextMonthBeforeLastItemIsVisible() { assertEquals(CalendarScrollTrigger.NONE, CalendarScrollTrigger.getTrigger(24, 10, 35, true, false)); } public void testDoesNotTriggerWhileLoadIsRunning() { assertEquals(CalendarScrollTrigger.NONE, CalendarScrollTrigger.getTrigger(0, 10, 35, true, true)); } public void testStatefulTriggerWaitsUntilScrollDirectionIsKnown() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(25, 10, 35, false)); assertEquals(CalendarScrollTrigger.NEXT, trigger.getTrigger(26, 9, 35, false)); } public void testStatefulTriggerDoesNotTriggerPreviousWhenProgrammaticPositionLandsNearTop() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.suppressUntilIdle(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(0, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(1, 10, 35, false)); } public void testStatefulTriggerRearmsAfterIdleAndNewGesture() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.suppressUntilIdle(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(0, 10, 35, false)); trigger.onScrollStateChanged(false); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(2, 10, 35, false)); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getTrigger(1, 10, 35, false)); } public void testStatefulTriggerAllowsOnlyOneLoadPerGesture() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(14, 10, 35, false)); assertEquals(CalendarScrollTrigger.NEXT, trigger.getTrigger(15, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(26, 9, 35, false)); } public void testStatefulTriggerRequiresMatchingScrollDirection() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(0, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(1, 10, 35, false)); } public void testOverscrollAtBottomTriggersNextWithoutNeedingDirectionChange() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.NEXT, trigger.getOverScrollTrigger(25, 34, 35, false)); } public void testOverscrollAtTopTriggersPrevious() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getOverScrollTrigger(0, 9, 35, false)); } public void testOverscrollAllowsOnlyOneLoadPerGesture() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.NEXT, trigger.getOverScrollTrigger(25, 34, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getOverScrollTrigger(25, 34, 35, false)); } public void testOverscrollDoesNotTriggerWhenWholeListIsVisible() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.NONE, trigger.getOverScrollTrigger(0, 34, 35, false)); } public void testStatefulTriggerPrefetchesNextBeforeListEnd() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(14, 10, 35, false)); assertEquals(CalendarScrollTrigger.NEXT, trigger.getTrigger(15, 10, 35, false)); } public void testStatefulTriggerDoesNotPrefetchNextBeforeThreshold() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(13, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(14, 10, 35, false)); } public void testStatefulTriggerPrefetchesPreviousBeforeListStart() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(4, 10, 35, false)); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getTrigger(3, 10, 35, false)); } public void testStatefulTriggerDoesNotPrefetchPreviousBeforeThreshold() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(5, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(4, 10, 35, false)); } public void testOppositeOverscrollDirectionCanTriggerBeforeIdle() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getOverScrollTrigger(0, 9, 35, false)); trigger.suppressTriggerUntilIdle(CalendarScrollTrigger.PREVIOUS); assertEquals(CalendarScrollTrigger.NEXT, trigger.getOverScrollTrigger(25, 34, 35, false)); } } package ch.mfiles.kaba.kolibri.timesheet.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.InternalWorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenses; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.ExpenseMaskEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.ViewPageAdapter; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.ExpenseMaskWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.VehicleMaskWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kaba.kolibri.timesheet.forms.VariousExpensesImageNewEditForm.VariousExpenseFileNewEditFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class TimeSheetDetailForm extends SuperForm implements OnItemSelectedListener, OnCheckedChangeListener { private static Log log = LogFactory.getLog(TimeSheetDetailForm.class); private TimeUtil timeUtil; private CalendarTimeSheet calendar; private Date selectedDate; private RelativeLayout mainView; private ActionCtrl deleteAction; private ActionCtrl addAction; private TabLayout tabLayout; private int pageSelected = 0; /* * Daily routine section */ private TimeListWidget dailyRoutineListWidget; private List timeList; /* * Expense section */ private AppCompatCheckBox noExpensesCheckBox; private ExpenseMaskEditText dailyExpensesEditText; private ExpenseMaskEditText pikettExpensesEditText; private MDSpinner reasonForVariousExpensesValue; private MDEditText freeTextEditText; private ExpenseMaskEditText variousExpensesEditText; private MDEditText deductionEditText; private ExpenseMaskEditText deductionAmountEditText; private MDRadioButton timeRadioButton; private MDRadioButton expensesRadioButton; private MDEditText vehicleFromEditText; private MDEditText vehicleToEditText; /* * Various Expenses section */ private ImageListWidget variousExpenseListWidget; private List variousExpenseList; private LinearLayout emptyMessageView; private ActionUtil utilButton; public void reloadCalendar() { this.calendar = app.dbutil.loadCalendar(selectedDate, app.dbutil.getUser().getPersonalNumber()); } @Override public void onFormCall(Object argument) { if (argument instanceof TimeSheetDetailFormArgument) { TimeSheetDetailFormArgument formArgument = (TimeSheetDetailFormArgument) argument; pageSelected = formArgument.getTabSelected(); selectedDate = formArgument.getDate(); isServiceApp = formArgument.isServiceApp(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); timeUtil = new TimeUtil(app, app.dbutil, this); utilButton = new ActionUtil(app); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideSoftInputFromWindow(); onBackPressed(); } }); deleteAction = addActionCtrl(false, true, 1, "actionDelete"); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setVisible(false); addAction = addActionCtrl(false, true, 1, "actionAdd"); //$NON-NLS-1$ addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setVisible(false); addAction.setEnabled(false); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.addView(mainView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); reloadCalendar(); if(calendar.isValid() && !calendar.getStatus().isSENT()) { setSendButtonEnabled(true); } else { setSendButtonEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); } if (calendar != null) { setFormTitle(DateTimeUtil.showDayOfWeek(calendar.getDate()) + ", " + DateTimeUtil.showDate(calendar.getDate())); //$NON-NLS-1$ } else { setFormTitle(DateTimeUtil.showDayOfWeek(selectedDate) + ", " + DateTimeUtil.showDate(selectedDate)); //$NON-NLS-1$ } if (mainView.getChildCount() > 0) { mainView.removeAllViewsInLayout(); mainView.invalidate(); } View contentView = createTabContentView(context); mainView.addView(contentView); tabLayout.getTabAt(pageSelected).select(); view.invalidate(); loadDailyRoutine(); loadExpense(); // loadVariousExpenses(); Person user = app.dbutil.getUser(); boolean editableCalendar = !calendar.getStatus().isSENT(); boolean editableExpenses = user.getExpensesActive() && editableCalendar && canSaveExpenseForDate(selectedDate, DateTimeUtil.getToday().getTime()); setEnabledControls(editableCalendar); setExpenseControlsEnabled(editableExpenses); if (!user.getExpensesActive()) { noExpensesCheckBox.setChecked(true); vehicleFromEditText.setRequired(false); vehicleToEditText.setRequired(false); } return null; } private void setEnabledControls(boolean enabled) { if(enabled) { deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); if(selectedDate.after(DateTimeUtil.getToday().getTime())) { addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setEnabled(false); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); setSendButtonEnabled(false); enabled = false; } else { addAction.setEnabled(true); addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setEnabled(true); setSendButtonEnabled(true); } } else { deleteAction.setEnabled(false); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); setSendButtonEnabled(false); } } private void setExpenseControlsEnabled(boolean enabled) { noExpensesCheckBox.setEnabled(enabled); setExpenseEnable(enabled); vehicleFromEditText.setEnabled(enabled); vehicleToEditText.setEnabled(enabled); } @Override public ApplicationEvent onBackPressed() { if (isEditedExpense()) { if (validateExpense()) { leaveToCalendarOverview(); } else { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(TimeSheetMessages.getString("ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } else { leaveToCalendarOverview(); } return null; } }, false); } } else { leaveToCalendarOverview(); } return null; } private void leaveToCalendarOverview() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(CalendarOverviewForm.class, new CalendarOverviewForm.CalendarOverviewFormArgument(calendar, isServiceApp)); } }, false); } private boolean validateExpense() { boolean result = true; clearErrorMessages(); if (!noExpensesCheckBox.isChecked()) { if (!timeRadioButton.isChecked() && !expensesRadioButton.isChecked()) { timeRadioButton.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } } if (dailyExpensesEditText.isFocused()) { dailyExpensesEditText.clearFocus(); } if (pikettExpensesEditText.isFocused()) { pikettExpensesEditText.clearFocus(); } if (variousExpensesEditText.isFocused()) { variousExpensesEditText.clearFocus(); } if (deductionAmountEditText.isFocused()) { deductionAmountEditText.clearFocus(); } if (vehicleFromEditText.isFocused()) { vehicleFromEditText.clearFocus(); } if (vehicleToEditText.isFocused()) { vehicleToEditText.clearFocus(); } if(!result) { pageSelected = 1; tabLayout.getTabAt(pageSelected).select(); view.invalidate(); } else { saveExpense(); } return result; } /** * Handles on click event for delete calendar. * * @return */ public ApplicationEvent actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteAllRecords"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } app.dbutil.deleteCalendarTimeSheet(calendar); return appman.getActiveApplication().leaveToForm(CalendarOverviewForm.class, new CalendarOverviewForm.CalendarOverviewFormArgument(calendar, isServiceApp)); } }; return null; } /** * Handles on click event for add action. * * @return */ public ApplicationEvent actionAdd() { if (pageSelected == 2) { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, null); } else { if (isEditedExpense() && !validateExpense()) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(TimeSheetMessages.getString("ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } else { return appman.getActiveApplication().leaveToForm(TimeSheetForm.class, new TimeSheetForm.TimeSheetFormArgument(calendar, null)); } } }, false); } else { return appman.getActiveApplication().leaveToForm(TimeSheetForm.class, new TimeSheetForm.TimeSheetFormArgument(calendar, null)); } } return null; } private void leaveToImageNewEditForm(final Bitmap bitmap) { if(bitmap == null) return; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(VariousExpensesImageNewEditForm.class, new VariousExpenseFileNewEditFormArguments(selectedDate, bitmap, null)); } }, false); } /** * Handles on click event for send. * * @return */ @Override public ApplicationEvent onSendPressed() { setSendButtonEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); if (calendar !=null && calendar.getStatus().isSENT()) { app.showMessage(TimeSheetMessages.getString("timesheetAlreadySent")); //$NON-NLS-1$ log.error(TimeSheetMessages.getString("timesheetAlreadySent")); return null; } boolean isExpenseValid = true; if (!noExpensesCheckBox.isChecked()) { if (StringUtil.isEmpty(dailyExpensesEditText.getText().toString())) { dailyExpensesEditText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ isExpenseValid = false; } } if (vehicleFromEditText.isRequired() && StringUtil.isEmpty(vehicleFromEditText.getText().toString())) { vehicleFromEditText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ isExpenseValid = false; } if (vehicleToEditText.isRequired() && StringUtil.isEmpty(vehicleToEditText.getText().toString())) { vehicleToEditText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ isExpenseValid = false; } if (!isExpenseValid) { app.showWarningMessageBox(TimeSheetMessages.getString("cannotTransmissonToServerThereIsUnsavedPersonalTimeData"), new RunOnUIThread() { @Override public void runOnUIThread() { setSendButtonEnabled(true); pageSelected = 1; tabLayout.getTabAt(pageSelected).select(); } }); return null; } if (isEditedExpense()) { if (validateExpense()) { reloadCalendar(); log.info("is Expense valid " + calendar.getExpense().validate().isValid()); log.info("is TimeSheets valid " + !calendar.getTimeSheets().isEmpty()); } } sendCalendar(); return null; } private void sendCalendar() { log.info("is Calendar valid " + calendar.isValid()); if (calendar.isValid()) { new AsyncTask(this) { private CalendarTimeSheet sendCalendar; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { sendCalendar = app.sendTimeSheet(calendar); return null; } @Override protected void runOnUIThread() { if (sendCalendar !=null && sendCalendar.getStatus().isSENT()) { app.showMessage(TimeSheetMessages.getString("timesheetSent")); //$NON-NLS-1$ setSendButtonEnabled(false); reloadCalendar(); loadDailyRoutine(); setEnabledControls(!calendar.getStatus().isSENT()); setExpenseControlsEnabled(false); } else { setSendButtonEnabled(true); } } }; } else { String errorMessage = TimeSheetMessages.getString("cannotTransmissonToServerThereIsUnsavedPersonalTimeData"); if(validateExpense() && calendar.getTimeSheets().isEmpty()) { errorMessage = TimeSheetMessages.getString("NoTimeSheet"); pageSelected = 0; tabLayout.getTabAt(pageSelected).select(); } app.showWarningMessageBox(errorMessage, new RunOnUIThread() { @Override public void runOnUIThread() { setSendButtonEnabled(true); } }); } } private View createTabContentView(Context context) { if (pageSelected != 1) { contextMenuActionState(true); } // create vertical linear view to hold TabLayout and ViewPager LinearLayout contentView = new LinearLayout(context); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentView.setOrientation(LinearLayout.VERTICAL); // create TabLayout tabLayout = new TabLayout(context); LinearLayout.LayoutParams tabLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); tabLayout.setLayoutParams(tabLayoutParams); tabLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); tabLayout.setTabTextColors(LayoutUtils.DEFAULT_TAB_TEXT_COLOR, LayoutUtils.DEFAULT_TAB_SELECTED_TEXT_COLOR); tabLayout.setSelectedTabIndicatorColor(LayoutUtils.DEFAULT_HIGHLIGHT); contentView.addView(tabLayout); // create 2 simple pages and add them to a page adapter ViewPageAdapter pagerAdapter = new ViewPageAdapter(); // info personal time tab pagerAdapter.addPage(TimeSheetMessages.getString("personalTime"), getDailyRoutineContent()); //$NON-NLS-1$ // address expense tab pagerAdapter.addPage(TimeSheetMessages.getString("expense"), getExpenseContent()); // address expense tab // pagerAdapter.addPage(TimeSheetMessages.getString("variousExpenses"), getVariousExpensesContent()); //$NON-NLS-1$ // ViewPager for PageAdapter ViewPager viewPager = new ViewPager(context); viewPager.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentView.addView(viewPager); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { // reloadCalendar(); if (position == 1) { // personal time contextMenuActionState(false); // loadExpense(); pageSelected = 1; } else { pageSelected = position++; contextMenuActionState(true); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Auto-generated method stub } @Override public void onPageScrollStateChanged(int state) { // Auto-generated method stub } }); viewPager.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { app.showMessage("onFocusChange " + v.getTag() + " focus " + hasFocus); } }); // link TabLayout to ViewPager tabLayout.setupWithViewPager(viewPager); return contentView; } private View getDailyRoutineContent() { RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); dailyRoutineListWidget = new TimeListWidget(context); dailyRoutineListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); dailyRoutineListWidget.setDividerHeight(1); dailyRoutineListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(dailyRoutineListWidget); return mainFormView; } private void loadDailyRoutine() { dailyRoutineListWidget.clean(); if (calendar != null) { ArrayList items = new ArrayList(); timeList = new ArrayList(calendar.getTimeSheets()); for (final TimeSheet timeSheet : timeList) { final TimeListWidgetItem item = new TimeListWidgetItem(); if (calendar.getStatus().isSENT()) { item.setTextColor(LayoutUtils.DEFAULT_LIGHT_GRAY); } else { item.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); } InternalWorkType internalWorkType = app.dbutil.selectInternalWorkTypeByWorkTypeCode(timeSheet.getWorkTypeCode()); item.setTitleText(internalWorkType == null ? "":internalWorkType.getText()); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { item.setBackgroundColor(LayoutUtils.DEFAULT_ORANGE); item.setStringLine1(TimeSheetMessages.getString("timeIsRumming")); //$NON-NLS-1$ item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.STOP_TIME, CommonConstants.Images.IMAGE_DPI))); item.setButtonImageTag(CommonConstants.Mode.PLAYING); } else { if (calendar.getStatus().isSENT()) { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); } item.setStringLine1(DateTimeUtil.showTime(timeSheet.getStartTime()) + " - " + DateTimeUtil.showTime(timeSheet.getStopTime()) + " " + TimeSheetMessages.getString("clock")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ item.setButtonImageTag(CommonConstants.Mode.STOP); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton) { if (calendar.getStatus().isSENT()) { return; } if (CommonConstants.Mode.STOP.equals(v.getTag())) { deleteDailyRoutineAction(timeSheet); } else { timeUtil.stopWorkTimeCapturing(new RunOnUIThread() { @Override public void runOnUIThread() { // reload calendar from database reloadCalendar(); loadDailyRoutine(); } }); } } } }); item.setDateTitle(DateTimeUtil.showDayOfMonth(calendar.getDate())); item.setDateText(DateTimeUtil.showDayOfWeek(calendar.getDate())); items.add(item); dailyRoutineListWidget.setOnItemClickListener(createOnItemClickListener(timeList)); } dailyRoutineListWidget.addItems(items); } } private OnItemClickListener createOnItemClickListener(final List timeList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { final TimeSheet timeSheet = timeList.get(position); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetForm.class, new TimeSheetForm.TimeSheetFormArgument(calendar, timeSheet)); } }, false); } }; } private void deleteDailyRoutineAction(final TimeSheet timeSheet) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteRecord"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } // number the timesheet entries consecutively in chronological // order TreeSet timeSheets = new TreeSet(timeList); Iterator itr = timeSheets.iterator(); int idx = 0; while (itr.hasNext()) { TimeSheet temp = itr.next(); if (temp.getPersonalNumber() == timeSheet.getPersonalNumber() && temp.getStartTime().compareTo(timeSheet.getStartTime()) == 0) { itr.remove(); } else { temp.setIdx(idx); idx++; } } // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(timeSheets); // Save hole CALENDAR Object to the database app.dbutil.saveCALENDAR(calendar); return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); loadDailyRoutine(); } }; } private View getExpenseContent() { RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); // No Expenses noExpensesCheckBox = CommonUtilForm.getCheckBox(context, TimeSheetMessages.getString("noExpenses")); //$NON-NLS-1$ noExpensesCheckBox.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton paramCompoundButton, boolean paramBoolean) { if (paramBoolean) { setExpenseEnable(false); dailyExpensesEditText.getText().clear(); pikettExpensesEditText.getText().clear(); variousExpensesEditText.getText().clear(); deductionEditText.getText().clear(); deductionAmountEditText.getText().clear(); paramCompoundButton.setChecked(paramBoolean); dailyExpensesEditText.clearError(); timeRadioButton.clearError(); } else { setExpenseEnable(true); loadExpense(); paramCompoundButton.setChecked(paramBoolean); } } }); contentLinearLayout.addView(noExpensesCheckBox); LinearLayout dailyLinearLayout = new LinearLayout(context); dailyLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams dailyLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); dailyLinearLayoutParams.gravity = Gravity.CENTER; dailyLinearLayoutParams.width = LayoutParams.MATCH_PARENT; dailyLinearLayoutParams.weight = 1; dailyLinearLayout.setLayoutParams(dailyLinearLayoutParams); dailyExpensesEditText = ExpenseMaskEditText.createDefaultEditText(dailyLinearLayout, TimeSheetMessages.getString("dailyExpense"), true); //$NON-NLS-1$ LinearLayout.LayoutParams dailyExpensesLayoutParams = new LinearLayout.LayoutParams(0, 0); dailyExpensesLayoutParams.gravity = Gravity.CENTER; dailyExpensesLayoutParams.width = 0; dailyExpensesLayoutParams.height = LayoutParams.MATCH_PARENT; dailyExpensesLayoutParams.weight = 0.3f; dailyExpensesEditText.getParentTextInputLayout().setLayoutParams(dailyExpensesLayoutParams); // Pikett Expenses pikettExpensesEditText = ExpenseMaskEditText.createDefaultEditText(dailyLinearLayout, TimeSheetMessages.getString("pikettExpenses"), false); //$NON-NLS-1$ LinearLayout.LayoutParams pikettExpensesLayoutParams = new LinearLayout.LayoutParams(0, 0); pikettExpensesLayoutParams.gravity = Gravity.CENTER; pikettExpensesLayoutParams.width = 0; pikettExpensesLayoutParams.height = LayoutParams.MATCH_PARENT; pikettExpensesLayoutParams.weight = 0.3f; pikettExpensesEditText.getParentTextInputLayout().setLayoutParams(pikettExpensesLayoutParams); contentLinearLayout.addView(dailyLinearLayout); // Misc Expense reasonForVariousExpensesValue = MDSpinner.createDefaultSpinner(contentLinearLayout, TimeSheetMessages.getString("miscExpense"), false); //$NON-NLS-1$ reasonForVariousExpensesValue.setTag("MISC_EXPENSE"); //$NON-NLS-1$ reasonForVariousExpensesValue.setOnItemSelectedListener(this); LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) reasonForVariousExpensesValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); reasonForVariousExpensesValue.getUnderline().setLayoutParams(underlineLinearLayout); // Misc Display freeTextEditText = MDEditText.createDefaultEditText(contentLinearLayout, "", InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ freeTextEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY_FIVE) }); // Various expenses variousExpensesEditText = ExpenseMaskEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("Amount"), false); //$NON-NLS-1$ // Deduction deductionEditText = MDEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("deduction"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ deductionEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY_FIVE) }); // Deduction Amount deductionAmountEditText = ExpenseMaskEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("Amount"), false); //$NON-NLS-1$ LinearLayout compensationLinearLayout = new LinearLayout(context); compensationLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams compensationLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); compensationLinearLayoutParams.gravity = Gravity.LEFT; compensationLinearLayoutParams.width = LayoutParams.MATCH_PARENT; compensationLinearLayoutParams.weight = 0.7f; compensationLinearLayoutParams.topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; compensationLinearLayoutParams.bottomMargin = LayoutUtils.DEFAULT_MAX_MARGIN; compensationLinearLayout.setLayoutParams(compensationLinearLayoutParams); // Compensation TextView compensationTextView = CommonUtilForm.getTextView(context, TimeSheetMessages.getString("compensation")); //$NON-NLS-1$ LinearLayout.LayoutParams compensationTextViewLayoutParams = new LinearLayout.LayoutParams(0, 0); compensationTextViewLayoutParams.gravity = Gravity.LEFT; compensationTextViewLayoutParams.width = 0; compensationTextViewLayoutParams.height = LayoutParams.MATCH_PARENT; compensationTextViewLayoutParams.weight = 0.3f; compensationTextView.setLayoutParams(compensationTextViewLayoutParams); compensationLinearLayout.addView(compensationTextView); timeRadioButton = MDRadioButton.createDefaultRadioButton(compensationLinearLayout, TimeSheetMessages.getString("time")); //$NON-NLS-1$ timeRadioButton.setTag("TIME"); //$NON-NLS-1$ timeRadioButton.setOnCheckedChangeListener(this); timeRadioButton.setEnabled(false); LinearLayout.LayoutParams timeRadioButtonLayoutParams = new LinearLayout.LayoutParams(0, 0); timeRadioButtonLayoutParams.gravity = Gravity.LEFT; timeRadioButtonLayoutParams.width = 0; timeRadioButtonLayoutParams.height = LayoutParams.MATCH_PARENT; timeRadioButtonLayoutParams.weight = 0.2f; ((LinearLayout) timeRadioButton.getParent()).setLayoutParams(timeRadioButtonLayoutParams); expensesRadioButton = MDRadioButton.createDefaultRadioButton(compensationLinearLayout, TimeSheetMessages.getString("expense")); //$NON-NLS-1$ expensesRadioButton.setTag("EXPENSE"); //$NON-NLS-1$ expensesRadioButton.setOnCheckedChangeListener(this); expensesRadioButton.setEnabled(false); LinearLayout.LayoutParams expensesRadioButtonLayoutParams = new LinearLayout.LayoutParams(0, 0); expensesRadioButtonLayoutParams.gravity = Gravity.LEFT; expensesRadioButtonLayoutParams.width = 0; expensesRadioButtonLayoutParams.height = LayoutParams.MATCH_PARENT; expensesRadioButtonLayoutParams.weight = 0.2f; ((LinearLayout) expensesRadioButton.getParent()).setLayoutParams(expensesRadioButtonLayoutParams); compensationLinearLayout.setVisibility(View.GONE); contentLinearLayout.addView(compensationLinearLayout); // Vehicle Kilometers TextView vehicleKilometerTextView = CommonUtilForm.getTextView(context, TimeSheetMessages.getString("vehicleKilometers")); //$NON-NLS-1$ contentLinearLayout.addView(vehicleKilometerTextView); LinearLayout vehicleLinearLayout = new LinearLayout(context); vehicleLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams vehicleLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); vehicleLinearLayoutParams.gravity = Gravity.CENTER; vehicleLinearLayoutParams.width = LayoutParams.MATCH_PARENT; vehicleLinearLayoutParams.weight = 1; vehicleLinearLayout.setLayoutParams(vehicleLinearLayoutParams); // Vehicle Kilometers From vehicleFromEditText = MDEditText.createDefaultEditText(vehicleLinearLayout, TimeSheetMessages.getString("from"), InputType.TYPE_NUMBER_FLAG_DECIMAL, true); //$NON-NLS-1$ vehicleFromEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.NINE) }); vehicleFromEditText.addTextChangedListener(new VehicleMaskWatcher(vehicleFromEditText)); LinearLayout.LayoutParams vehicleFromLayoutParams = new LinearLayout.LayoutParams(0, 0); vehicleFromLayoutParams.gravity = Gravity.LEFT; vehicleFromLayoutParams.width = 0; vehicleFromLayoutParams.height = LayoutParams.MATCH_PARENT; vehicleFromLayoutParams.weight = 0.3f; vehicleFromEditText.getParentTextInputLayout().setLayoutParams(vehicleFromLayoutParams); // Vehicle Kilometers To vehicleToEditText = MDEditText.createDefaultEditText(vehicleLinearLayout, TimeSheetMessages.getString("to"), InputType.TYPE_NUMBER_FLAG_DECIMAL, true); //$NON-NLS-1$ vehicleToEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.NINE) }); vehicleToEditText.addTextChangedListener(new VehicleMaskWatcher(vehicleToEditText)); LinearLayout.LayoutParams vehicleToLayoutParams = new LinearLayout.LayoutParams(0, 0); vehicleToLayoutParams.gravity = Gravity.LEFT; vehicleToLayoutParams.width = 0; vehicleToLayoutParams.height = LayoutParams.MATCH_PARENT; vehicleToLayoutParams.weight = 0.3f; vehicleToEditText.getParentTextInputLayout().setLayoutParams(vehicleToLayoutParams); contentLinearLayout.addView(vehicleLinearLayout); relativeLayout.addView(contentLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(relativeLayout); return scrollView; } private void loadExpense() { // resetExpense(); fillExpenseCombo(); // if (!calendar.getTimeSheets().isEmpty()) { expensesRadioButton.setChecked(true); Expenses expenses = calendar.getExpense(); log.info("DailyExpenses :" + expenses.getDailyExpenses() + "\nNoExpenses :" + expenses.getNoExpenses() + "\nExpensesDescription :" + expenses.getExpensesDescription() + "\nPikettExpenses :" + expenses.getPikettExpenses() + "\nVariousExpenses :" + expenses.getVariousExpenses() + "\nDeduction :" + expenses.getDeduction() + "\nDeductionDescription :" + expenses.getDeductionDescription() + "\nOperatingHoursOf :" + expenses.getOperatingHoursOf() + "\nOperatingHoursUpTo :" + expenses.getOperatingHoursUpTo() + "\nOperatingHoursTotal :" + expenses.getOperatingHoursTotal() + "\nCompensation :" + expenses.getCompensation()); log.info("is Initial " + expenses.isInitial()); if (expenses.isInitial()) { if (!calendar.getTimeSheets().isEmpty()) { Expenses lastExpens = app.dbutil.selectLastAvailableBToDate(calendar.getDate(), app.dbutil.getUser().getPersonalNumber()); if (lastExpens != null) { calendar.getExpense().setOperatingHoursOf(lastExpens.getOperatingHoursUpTo()); vehicleFromEditText.setText(lastExpens.getOperatingHoursUpTo()); } } } else { noExpensesCheckBox.setChecked(expenses.isNoExpenses()); dailyExpensesEditText.setText(expenses.getDailyExpenses()); pikettExpensesEditText.setText(expenses.getPikettExpenses()); // If SPNSTXT is empty: No 'Diverese Spesen' exist if (expenses.getExpensesDescription().equalsIgnoreCase("")) { //$NON-NLS-1$ reasonForVariousExpensesValue.setSelection(0); } // If SPNSTXT is part of the combobox stings: A value of the combobox was selected a no free text was used else if (app.enumUtil.variousExpensEnum.containsValue(expenses.getExpensesDescription())) { reasonForVariousExpensesValue.setSelectionByName(expenses.getExpensesDescription()); } // If SPNSTXT is not part of the combobox stings: A free text was entered and the combobox contains the entry "01 Diverses.." else { reasonForVariousExpensesValue.setSelectionById("01"); } variousExpensesEditText.setText(expenses.getVariousExpenses()); deductionEditText.setText(expenses.getDeductionDescription()); deductionAmountEditText.setText(expenses.getDeduction()); if (expenses.isCompensation()) expensesRadioButton.setChecked(true); else timeRadioButton.setChecked(true); if (expenses.getOperatingHoursTotal().length() > 0) { vehicleFromEditText.setText(""); //$NON-NLS-1$ vehicleToEditText.setText(""); //$NON-NLS-1$ } else { vehicleFromEditText.setText(expenses.getOperatingHoursOf()); vehicleToEditText.setText(expenses.getOperatingHoursUpTo()); } } // } else { // noExpensesCheckBox.setChecked(false); // } } private void resetExpense() { noExpensesCheckBox.setChecked(false); dailyExpensesEditText.getText().clear(); pikettExpensesEditText.getText().clear(); reasonForVariousExpensesValue.setSelection(0); freeTextEditText.getText().clear(); variousExpensesEditText.getText().clear(); deductionEditText.getText().clear(); deductionAmountEditText.getText().clear(); vehicleFromEditText.getText().clear(); vehicleToEditText.getText().clear(); } private View getVariousExpensesContent() { RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); variousExpenseListWidget = new ImageListWidget(context); variousExpenseListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); variousExpenseListWidget.setDividerHeight(1); variousExpenseListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, Messages.getString("noDocumentsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); mainFormView.addView(variousExpenseListWidget); mainFormView.addView(emptyMessageView); return mainFormView; } private void loadVariousExpenses() { variousExpenseListWidget.clean(); if (calendar != null) { ArrayList items = new ArrayList(); variousExpenseList = app.dbutil.selectVariousExpenses(calendar.getDate(), app.dbutil.getUser().getPersonalNumber()); if(variousExpenseList.isEmpty()) { view.addView(emptyMessageView); emptyMessageView.setVisibility(View.VISIBLE); } else { emptyMessageView.setVisibility(View.GONE); } for (int i = 0; i < variousExpenseList.size(); i++) { final VariousExpenses variousExpenses = variousExpenseList.get(i); final ImageListWidgetItem item = new ImageListWidgetItem(); variousExpenses.setVariousExpensesFile(app.dbutil.selectVariousExpensesFile(calendar.getDate(), app.dbutil.getUser().getPersonalNumber(), variousExpenses.getVariousExpensesId())); DecimalFormat df = new DecimalFormat("###.00", new DecimalFormatSymbols(new Locale("en", "US"))); item.setDescription(app.enumUtil.variousExpensEnum.get(variousExpenses.getExpensesCode())); item.setImageBitmap(variousExpenses.getVariousExpensesFile().getSignPicBitmap()); if (!variousExpenses.getAmount().isEmpty()) { item.setType(df.format(Double.parseDouble(variousExpenses.getAmount()))); } items.add(item); variousExpenseListWidget.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { VariousExpenses variousExpenses = variousExpenseList.get(position); return appman.getActiveApplication().leaveToForm(VariousExpensesImageNewEditForm.class, new VariousExpenseFileNewEditFormArguments(selectedDate, variousExpenses.getVariousExpensesFile().getSignPicBitmap(), variousExpenses)); } }, false); } }); } variousExpenseListWidget.addItems(items); } } @Override public void onFormReset() { super.onFormReset(); resetExpense(); } @Override protected void clearErrorMessages() { super.clearErrorMessages(); dailyExpensesEditText.clearError(); pikettExpensesEditText.clearError(); reasonForVariousExpensesValue.clearError(); freeTextEditText.clearError(); variousExpensesEditText.clearError(); deductionEditText.clearError(); deductionAmountEditText.clearError(); timeRadioButton.clearError(); expensesRadioButton.clearError(); vehicleFromEditText.clearError(); vehicleToEditText.clearError(); } private void fillExpenseCombo() { List miscExpenseValueList = new ArrayList(); Iterator itr = app.enumUtil.variousExpensEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); miscExpenseValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } reasonForVariousExpensesValue.setContents(miscExpenseValueList); } private void setExpenseEnable(boolean enabled) { dailyExpensesEditText.setEnabled(enabled); pikettExpensesEditText.setEnabled(enabled); reasonForVariousExpensesValue.setEnabled(enabled); freeTextEditText.setEnabled(enabled); variousExpensesEditText.setEnabled(enabled); deductionEditText.setEnabled(enabled); deductionAmountEditText.setEnabled(enabled); // timeRadioButton.setEnabled(enabled); // expensesRadioButton.setEnabled(enabled); } public void saveExpense() { if(calendar.getStatus().isSENT()) { return; } if (!canSaveExpenseForDate(calendar.getDate(), DateTimeUtil.getToday().getTime())) { return; } Expenses expenses = calendar.getExpense(); expenses.setNoExpenses(noExpensesCheckBox.isChecked()); expenses.setDate(calendar.getDate()); expenses.setExpensesDate(calendar.getDate()); expenses.setDailyExpenses(getExpenseCurrencyValue(dailyExpensesEditText.getValue())); expenses.setPikettExpenses(getExpenseCurrencyValue(pikettExpensesEditText.getValue())); // Bug 1401 - hardcode ZKDMAEXPNS:SPNSKEY to value CHF expenses.setExpensesKey("CHF"); //$NON-NLS-1$ log.info(" VariousExpenses " + variousExpensesEditText.getValue()); expenses.setVariousExpenses(getExpenseCurrencyValue(variousExpensesEditText.getValue())); String spnstxt = ""; //$NON-NLS-1$ // Default string 00 "Bitte w�hlen.." must not be stored if (!reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ // Only entry 01 "Diverses.." allows to enter an additional // text, otherwise the Combobox string is stored if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase("01")) //$NON-NLS-1$ spnstxt = freeTextEditText.getText().toString(); else spnstxt = reasonForVariousExpensesValue.getSelectedName(); } expenses.setExpensesDescription(spnstxt); expenses.setDeductionDescription(deductionEditText.getText().toString()); expenses.setDeduction(getExpenseCurrencyValue(deductionAmountEditText.getValue())); expenses.setOperatingHoursOf(vehicleFromEditText.getText().toString()); expenses.setOperatingHoursUpTo(vehicleToEditText.getText().toString()); log.info("DailyExpenses " + expenses.getDailyExpenses() + " PikettExpenses " + expenses.getPikettExpenses() + " VariousExpenses " + expenses.getVariousExpenses() + " Deduction " + expenses.getDeduction() + " OperatingHoursOf " + expenses.getOperatingHoursOf() + " OperatingHoursUpTo " + expenses.getOperatingHoursUpTo()); expenses.setExpenseCompensation(); log.info("Compensation " + expenses.getCompensation()); boolean successfull = app.dbutil.saveCALENDAR(calendar); if (!successfull) { app.showMessageBox(TimeSheetMessages.getString("expenseSheetCouldNotBeSaved"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ } // Reload data from database reloadCalendar(); } static boolean canSaveExpenseForDate(Date selectedDate, Date today) { if (selectedDate == null || today == null) { return false; } return !DateTimeUtil.getDate(selectedDate).getTime().after(DateTimeUtil.getDate(today).getTime()); } static String getExpenseCurrencyValue(String value) { if (StringUtil.isEmpty(value)) { return ""; //$NON-NLS-1$ } char decimalSeparator = value.indexOf(',') >= 0 && value.indexOf('.') < 0 ? ',' : '.'; String result = removeInvalidCurrencyCharacters(value, decimalSeparator); return containsDigit(result) ? result : ""; //$NON-NLS-1$ } private static String removeInvalidCurrencyCharacters(String value, char decimalSeparator) { StringBuilder result = new StringBuilder(); boolean hasDecimalSeparator = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isDigit(c)) { result.append(c); } else if (c == decimalSeparator && !hasDecimalSeparator) { result.append(c); hasDecimalSeparator = true; } } return result.toString(); } private static boolean containsDigit(String value) { for (int i = 0; i < value.length(); i++) { if (Character.isDigit(value.charAt(i))) { return true; } } return false; } private boolean isEditedExpense() { boolean result = false; Expenses expenses = calendar.getExpense(); if (noExpensesCheckBox.isChecked() != expenses.isNoExpenses()) { result = true; } if (!vehicleFromEditText.getText().toString().equalsIgnoreCase(expenses.getOperatingHoursOf())) { result = true; } if (!vehicleToEditText.getText().toString().equalsIgnoreCase(expenses.getOperatingHoursUpTo())) { result = true; } if (!noExpensesCheckBox.isChecked()) { if (!dailyExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getDailyExpenses())) { result = true; } if (!pikettExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getPikettExpenses())) { result = true; } // 00: Bitte w�hlen.. if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ if (!variousExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getVariousExpenses())) { result = true; } } // 01: Diverses.. else if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase("01")) { //$NON-NLS-1$ if (!freeTextEditText.getText().toString().equals(expenses.getExpensesDescription())) { result = true; } } // others else { if (!reasonForVariousExpensesValue.getSelectedName().equalsIgnoreCase(expenses.getExpensesDescription())) { result = true; } } if (!variousExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getVariousExpenses())) { result = true; } if (!deductionEditText.getText().toString().equalsIgnoreCase(expenses.getDeductionDescription())) { result = true; } if (!deductionAmountEditText.getText().toString().equalsIgnoreCase(expenses.getDeduction())) { result = true; } } return result; } private void contextMenuActionState(boolean state) { deleteAction.setVisible(state); deleteAction.setValidate(state); addAction.setVisible(state); addAction.setValidate(state); } public static class TimeSheetDetailFormArgument { private int tabSelected; private Date selectedDate; private boolean isServiceApp; public int getTabSelected() { return tabSelected; } protected TimeSheetDetailFormArgument() { } public TimeSheetDetailFormArgument(Date selectedDate, int tabSelect, boolean isServiceApp) { this.tabSelected = tabSelect; this.selectedDate = selectedDate; this.isServiceApp = isServiceApp; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public Date getDate() { return this.selectedDate; } public boolean isServiceApp() { return this.isServiceApp; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { timeRadioButton.clearError(); if ("TIME".equals(buttonView.getTag().toString()) && timeRadioButton.isChecked()) { //$NON-NLS-1$ expensesRadioButton.setChecked(false); } if ("EXPENSE".equals(buttonView.getTag().toString()) && expensesRadioButton.isChecked()) { //$NON-NLS-1$ timeRadioButton.setChecked(false); } } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("MISC_EXPENSE".equals(parent.getTag())) { //$NON-NLS-1$ freeTextEditText.setEnabled(false); freeTextEditText.setText(""); variousExpensesEditText.setText(""); if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ // Code 00 ("Please Select"): no selection was made so far -> disable text for "Diverse Spesen" and value field } else if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase("01")) { //$NON-NLS-1$ // Code 01 ("Diverse.."): -> enable text for "Diverse Spesen" and value field freeTextEditText.setEnabled(true); freeTextEditText.setText(calendar.getExpense().getExpensesDescription()); variousExpensesEditText.setText(calendar.getExpense().getVariousExpenses()); } else { // All other codes: -> disable text but enable value filed freeTextEditText.setText(""); //$NON-NLS-1$ variousExpensesEditText.setText(calendar.getExpense().getVariousExpenses()); } } else { validateExpense(); } } @Override public void onNothingSelected(AdapterView paramAdapterView) { // Auto-generated method stub } }
package ch.mfiles.kaba.kolibri.timesheet.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.DatePicker; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ListWidget.OverScrollListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarDateRange; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarDateSelection; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarListWindow; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarMonthHeaderPolicy; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarScrollTrigger; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarTimeSheetCache; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarToolbarTitleText; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; @SuppressWarnings("unused") public class CalendarOverviewForm extends SuperForm { protected static Log log = LogFactory.getLog(CalendarOverviewForm.class); private static final int MAX_CALENDAR_ITEMS = 124; public static TimeSheetApplication app; private Context context; private TimeListWidget listWidget; private ProgressBar loadMoreProgressView; private RelativeLayout mainFormView; private LinearLayout emptyMessageView; private TextView calendarValue; private Date dateSelected = new Date(); private TimeUtil timeUtil; private CalendarTimeSheet mCalendar; private CalendarTimeSheet selectedCalendar; private List calendarList = new ArrayList(); private CalendarTimeSheetCache calendarCache; private CalendarScrollTrigger calendarScrollTrigger = new CalendarScrollTrigger(); private CalendarToolbarTitleText calendarTitleText = new CalendarToolbarTitleText(); private volatile boolean preloadCalendarRunning = false; public void onFormCall(Object argument) { if (argument instanceof CalendarOverviewFormArgument) { mCalendar = ((CalendarOverviewFormArgument) argument).getCALENDAR(); isServiceApp = ((CalendarOverviewFormArgument) argument).isServiceApp(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(TimeSheetMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; timeUtil = new TimeUtil(app, app.dbutil, this); // hide runtime menu items setRuntimeMenuHidden(true); FrameLayout calendarTitleLayout = new FrameLayout(context); LinearLayout.LayoutParams titleLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); titleLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), LayoutUtils.convertDpToPixel(context, -8), 0, 0); calendarTitleLayout.setLayoutParams(titleLayoutParams); calendarValue = new TextView(context); calendarValue.setTextColor(LayoutUtils.DEFAULT_WHITE); calendarValue.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); calendarValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); calendarValue.setSingleLine(); FrameLayout.LayoutParams titleTextLayoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); titleTextLayoutParams.gravity = Gravity.CENTER_VERTICAL; calendarTitleLayout.addView(calendarValue, titleTextLayoutParams); TextView dropdownIndicator = new TextView(context); dropdownIndicator.setText("\u25BE"); dropdownIndicator.setTextColor(LayoutUtils.DEFAULT_WHITE); dropdownIndicator.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); dropdownIndicator.setSingleLine(); FrameLayout.LayoutParams dropdownLayoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); dropdownLayoutParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; calendarTitleLayout.addView(dropdownIndicator, dropdownLayoutParams); OnTouchListener showDatePickerListener = new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { if (paramMotionEvent.getAction() == MotionEvent.ACTION_UP) { createDatePickerDialog(getPickerDate()).show(); } return true; } }; calendarTitleLayout.setOnTouchListener(showDatePickerListener); calendarValue.setOnTouchListener(showDatePickerListener); dropdownIndicator.setOnTouchListener(showDatePickerListener); Toolbar toolbar = getToolbar(); toolbar.addView(calendarTitleLayout); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); saveButton.setVisible(false); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget = new TimeListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); //0xAARRGGBB listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget.setOnOverScrollListener(new OverScrollListener() { @Override public void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { if(clampedY) { int trigger = calendarScrollTrigger.getOverScrollTrigger(listWidget.getFirstVisiblePosition(), listWidget.getLastVisiblePosition(), listWidget.getCount(), loadMoreCalendarRunning); if (trigger == CalendarScrollTrigger.PREVIOUS) { loadMoreCalendar(true); return; } if (trigger == CalendarScrollTrigger.NEXT) { loadMoreCalendar(false); return; } } } }); listWidget.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { calendarScrollTrigger.onScrollStateChanged(scrollState != OnScrollListener.SCROLL_STATE_IDLE); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int trigger = calendarScrollTrigger.getTrigger(firstVisibleItem, visibleItemCount, totalItemCount, loadMoreCalendarRunning); if (trigger == CalendarScrollTrigger.PREVIOUS) { loadMoreCalendar(true); return; } if (trigger == CalendarScrollTrigger.NEXT) { loadMoreCalendar(false); return; } updateVisibleCalendarDate(firstVisibleItem, visibleItemCount); } }); ArrayList items = new ArrayList(); listWidget.addItems(items); mainFormView.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(emptyMessageView); loadMoreProgressView = new ProgressBar(context); loadMoreProgressView.setIndeterminate(true); RelativeLayout.LayoutParams loadMoreProgressParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); loadMoreProgressParams.addRule(RelativeLayout.CENTER_HORIZONTAL); loadMoreProgressParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); loadMoreProgressParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 16); loadMoreProgressView.setLayoutParams(loadMoreProgressParams); loadMoreProgressView.setVisibility(View.GONE); mainFormView.addView(loadMoreProgressView); linearLayout.addView(mainFormView); view.addView(linearLayout); return view; } private DatePickerDialog createDatePickerDialog(Date initialDate) { Calendar calendar = Calendar.getInstance(); calendar.setTime(initialDate); return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, monthOfYear); cal.set(Calendar.DAY_OF_MONTH, dayOfMonth); cal.set(Calendar.YEAR, year); // Load new calendar object from database mCalendar = app.dbutil.loadCalendar(cal.getTime(), app.dbutil.getUser().getPersonalNumber()); loadTable(); selectCalendar(mCalendar.getDate(), false); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } private Date getPickerDate() { Date visibleDate = mCalendar == null ? null : mCalendar.getDate(); Date selectedDate = selectedCalendar == null ? null : selectedCalendar.getDate(); return CalendarDateSelection.getPickerDate(visibleDate, selectedDate); } /** * This event is received every time the form is shown. This happens if the * form is called by the framework, another form or if reactivated from the * application's form stack. <p/> * * The application developer has to set all member variables (reset the * state of the form) at this point because the framework reuses the forms * (every form is instantiated exactly once during the lifetime of an * application) *

* * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(TimeSheetMessages.getString("calendar")); //$NON-NLS-1$ log.info("calendar " + mCalendar.getDateString()); loadTable(); Date visibleDate = CalendarDateSelection.getVisibleDate(mCalendar.getDate(), selectedCalendar == null ? null : selectedCalendar.getDate()); selectCalendar(visibleDate, false); List capturingDays = app.dbutil.selectCalendarDateWithRunningTimeCapturing(app.dbutil.getUser().getPersonalNumber()); if (!capturingDays.isEmpty()) { Calendar capturingDay = Calendar.getInstance(); capturingDay.setTime(capturingDays.get(0)); if(DateTimeUtil.getToday().get(Calendar.DAY_OF_YEAR) > capturingDay.get(Calendar.DAY_OF_YEAR) && DateTimeUtil.getToday().get(Calendar.YEAR) == capturingDay.get(Calendar.YEAR)) { // stopTime timeUtil.stopWorkTimeCapturing(new RunOnUIThread() { @Override public void runOnUIThread() { // start time timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { loadTable(); } }); } }); } } return null; } private volatile int currentDayPosition; private volatile int selectedDayPosition; /** * UI independent part of table loading... */ private ArrayList loadTableItems() { calendarList.clear(); currentDayPosition = -1; selectedDayPosition = -1; List monthCalendars = getCalendarCache().getMonthItems(mCalendar.getDate()); calendarList.addAll(monthCalendars); return createTableItems(monthCalendars, 0, true); } private ArrayList createTableItems(List calendars, int startIndex, boolean updateSelectionPositions) { int index = startIndex; Date previousDate = startIndex > 0 && startIndex - 1 < calendarList.size() ? calendarList.get(startIndex - 1).getDate() : null; ArrayList items = new ArrayList(); Iterator itr = calendars.iterator(); while (itr.hasNext()) { final CalendarTimeSheet calendar = (CalendarTimeSheet) itr.next(); Calendar date = Calendar.getInstance(); date.setTime(calendar.getDate()); final TimeListWidgetItem item = new TimeListWidgetItem(); if (CalendarMonthHeaderPolicy.shouldShowHeader(calendar.getDate(), previousDate, index)) { item.setHeader(DateTimeUtil.showMonthNameYear(date.getTime())); } previousDate = calendar.getDate(); // status // Colours of line depends on the status of the timesheet itself: // grey = sent // red = validation error // black / orange = active / current date item.setTextColor(getStyleByCalendar(calendar)); String hours = "0.00"; //$NON-NLS-1$ String expns = "0.00"; //$NON-NLS-1$ String opHrs = ""; //$NON-NLS-1$ if (!calendar.getStatus().isINITIAL()) { if (calendar.getDate().after(DateTimeUtil.getToday().getTime())) { calendar.setStatus(CalendarStatus.INITIAL); app.dbutil.deleteCalendarTimeSheet(calendar); } else { hours = getWorkingHours(calendar.getTimeSheets()); expns = getExpens(calendar.getExpense()); opHrs = getOperatingHours(calendar.getExpense()); item.setTitleText(TimeSheetMessages.getString("time") + " " + hours + " Std."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String line1 = TimeSheetMessages.getString("expense") + ": " + expns; //$NON-NLS-1$ //$NON-NLS-2$ item.setStringLine1(line1); } } else { // hours = TimeSheetMessages.getString("timeIsRunning"); } if(DateTimeUtil.getToday().get(Calendar.DAY_OF_YEAR) == date.get(Calendar.DAY_OF_YEAR) && DateTimeUtil.getToday().get(Calendar.YEAR) == date.get(Calendar.YEAR)) { //current date = orange if (updateSelectionPositions) { currentDayPosition = index; } item.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); item.setBackgroundColor(LayoutUtils.DEFAULT_ORANGE); if(calendar.isTimeCapturing()){ item.setTitleText(TimeSheetMessages.getString("startingTime") + ": " + DateTimeUtil.showTime(calendar.getStartTimeCapturing())); //$NON-NLS-1$ item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.STOP_TIME, CommonConstants.Images.IMAGE_DPI))); } else { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.START_TIME, CommonConstants.Images.IMAGE_DPI))); } if(calendar.getStatus().isSENT()) { item.setTextColor(LayoutUtils.DEFAULT_DARK_GRAY); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.START_TIME_DISABLED, CommonConstants.Images.IMAGE_DPI))); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton) { if(calendar.isTimeCapturing()){ // stopTime timeUtil.stopWorkTimeCapturing(new RunOnUIThread() { @Override public void runOnUIThread() { loadTable(); } }); } else { // start time timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { loadTable(); } }); } } } }); } else { Calendar selectedCal = Calendar.getInstance(); selectedCal.setTime(mCalendar.getDate()); if(selectedCal.get(Calendar.DAY_OF_YEAR) == date.get(Calendar.DAY_OF_YEAR) && selectedCal.get(Calendar.YEAR) == date.get(Calendar.YEAR)) { if (updateSelectionPositions) { selectedDayPosition = index; } } selectedCal.setTime(calendar.getDate()); if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { item.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); if(calendar.getStatus().isSENT()) { item.setTextColor(LayoutUtils.DEFAULT_DARK_GRAY); } } } item.setDateTitle(DateTimeUtil.showDayOfMonth(calendar.getDate())); item.setDateText(DateTimeUtil.showDayOfWeek(calendar.getDate())); items.add(item); index ++; } return items; } /** * UI part of table loading... * @param items */ private void loadTableDataListWidget(ArrayList items) { listWidget.clean(); listWidget.setOnItemClickListener(createOnItemClickListener()); listWidget.addItems(items); if(currentDayPosition>-1) { listWidget.setSelection(currentDayPosition -3); } if(selectedDayPosition>-1) { listWidget.setSelection(selectedDayPosition); } } private void loadTable() { resetCalendarCache(); ArrayList items = loadTableItems(); loadTableDataListWidget(items); preloadAdjacentCalendars(mCalendar.getDate()); } private volatile boolean loadMoreCalendarRunning = false; private void loadMoreCalendar(final boolean isLoadPrevious) { // Problem: the refresh trigger is called multiple times during a // single overscroll gesture, so stop processing events until the // reload has finished if (loadMoreCalendarRunning) return; loadMoreCalendarRunning = true; setLoadMoreProgressVisible(true); final int firstVisibleBeforeLoad = listWidget.getFirstVisiblePosition(); final int firstVisibleTopBeforeLoad = listWidget.getChildCount() > 0 ? listWidget.getChildAt(0).getTop() : 0; final Date boundaryDate = isLoadPrevious ? calendarList.get(0).getDate() : calendarList.get(calendarList.size() - 1).getDate(); final int appendStartIndex = calendarList.size(); new AsyncTask(this) { private volatile List loadedCalendars; private volatile ArrayList items; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (calendarList.isEmpty()) { return null; } CalendarDateRange.Range range = isLoadPrevious ? CalendarDateRange.previousBefore(boundaryDate) : CalendarDateRange.nextAfter(boundaryDate); loadedCalendars = getCalendarCache().getRangeItems(range.getStartDate(), range.getEndDate()); items = createTableItems(loadedCalendars, isLoadPrevious ? 0 : appendStartIndex, false); return null; } @Override protected void runOnUIThread() { if (loadedCalendars == null || loadedCalendars.isEmpty() || items == null || items.isEmpty()) { loadMoreCalendarRunning = false; setLoadMoreProgressVisible(false); return; } calendarScrollTrigger.suppressTriggerUntilIdle( isLoadPrevious ? CalendarScrollTrigger.PREVIOUS : CalendarScrollTrigger.NEXT); if (isLoadPrevious) { calendarList.addAll(0, loadedCalendars); listWidget.getItems().addAll(0, items); int anchorPosition = firstVisibleBeforeLoad + items.size(); trimCalendarItems(true); updateCalendarHeaders(); listWidget.getAdapter().notifyDataSetChanged(); listWidget.setSelectionFromTop(anchorPosition, firstVisibleTopBeforeLoad); } else { calendarList.addAll(loadedCalendars); listWidget.getItems().addAll(items); int removedFromStart = trimCalendarItems(false); updateCalendarHeaders(); listWidget.getAdapter().notifyDataSetChanged(); if (removedFromStart > 0) { listWidget.setSelectionFromTop( CalendarListWindow.getPositionAfterStartTrim(firstVisibleBeforeLoad, removedFromStart), firstVisibleTopBeforeLoad); } } loadMoreCalendarRunning = false; setLoadMoreProgressVisible(false); } }; } private int trimCalendarItems(boolean removeFromEnd) { int trimCount = CalendarListWindow.getTrimCount(calendarList.size(), MAX_CALENDAR_ITEMS); if (trimCount <= 0) { return 0; } if (removeFromEnd) { int fromIndex = calendarList.size() - trimCount; calendarList.subList(fromIndex, calendarList.size()).clear(); listWidget.getItems().subList(fromIndex, listWidget.getItems().size()).clear(); return 0; } calendarList.subList(0, trimCount).clear(); listWidget.getItems().subList(0, trimCount).clear(); return trimCount; } private void updateCalendarHeaders() { int itemCount = Math.min(calendarList.size(), listWidget.getItems().size()); Date previousDate = null; for (int i = 0; i < itemCount; i++) { CalendarTimeSheet calendar = calendarList.get(i); if (CalendarMonthHeaderPolicy.shouldShowHeader(calendar.getDate(), previousDate, i)) { listWidget.getItems().get(i).setHeader(DateTimeUtil.showMonthNameYear(calendar.getDate())); } else { listWidget.getItems().get(i).setHeader(null); } previousDate = calendar.getDate(); } } private void setLoadMoreProgressVisible(boolean visible) { if (loadMoreProgressView != null) { loadMoreProgressView.setVisibility(visible ? View.VISIBLE : View.GONE); } } private CalendarTimeSheetCache getCalendarCache() { if (calendarCache == null) { calendarCache = new CalendarTimeSheetCache(new CalendarTimeSheetCache.Loader() { @Override public CalendarTimeSheet loadCalendar(Date date, int personalNumber) { return app.dbutil.loadCalendar(date, personalNumber); } }, app.dbutil.getUser().getPersonalNumber()); } return calendarCache; } private void resetCalendarCache() { getCalendarCache().clear(); } private void preloadAdjacentCalendars(final Date focusDate) { if (preloadCalendarRunning) { return; } preloadCalendarRunning = true; final CalendarTimeSheetCache cache = getCalendarCache(); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { cache.preloadAdjacentMonths(focusDate); return null; } @Override protected void runOnUIThread() { preloadCalendarRunning = false; } }; } private void selectCalendar(Date date) { selectCalendar(date, true); } private void selectCalendar(Date date, boolean smoothScroll) { selectedCalendar = null; for (int i = 0; i < calendarList.size(); i++) { if(CalendarDateSelection.isSameCalendarDay(date, calendarList.get(i).getDate())) { Calendar nextCal = Calendar.getInstance(); nextCal.setTime(calendarList.get(i).getDate()); setDate(nextCal.get(Calendar.YEAR), nextCal.get(Calendar.MONTH), nextCal.get(Calendar.DAY_OF_MONTH)); selectedCalendar = calendarList.get(i); calendarScrollTrigger.suppressUntilIdle(); if (smoothScroll) { listWidget.smoothScrollToPosition(i); } else { listWidget.setSelectionFromTop(i, 0); } return; } } } private void updateVisibleCalendarDate(int firstVisibleItem, int visibleItemCount) { if (calendarList.isEmpty() || firstVisibleItem < 0 || visibleItemCount <= 0) { return; } int visiblePosition = CalendarListWindow.getToolbarTitlePosition(firstVisibleItem, calendarList.size()); CalendarTimeSheet visibleCalendar = calendarList.get(visiblePosition); Calendar nextCal = Calendar.getInstance(); nextCal.setTime(visibleCalendar.getDate()); mCalendar = visibleCalendar; setDate(nextCal.get(Calendar.YEAR), nextCal.get(Calendar.MONTH), nextCal.get(Calendar.DAY_OF_MONTH)); } private OnItemClickListener createOnItemClickListener() { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { selectedCalendar = calendarList.get(position); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(selectedCalendar.getDate(), 0, isServiceApp)); } }, false); } }; } private void setDate(int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); String date = calendarTitleText.updateVisibleMonthTitle(calendar.getTime()); if (date == null) { return; } calendarValue.setText(date); } @Override public ApplicationEvent onBackPressed() { if (isServiceApp) { return appman.leaveToApplication(CommonConstants.Application.SERVICE_APP, null); } else { return appman.exitApplication(); } } private String getOperatingHours(Expenses expense) { String opHrs = ""; //$NON-NLS-1$ if (!expense.isInitial()) { if (StringUtil.isNotEmpty(expense.getOperatingHoursTotal())) { opHrs = expense.getOperatingHoursTotal(); } else if (!(StringUtil.isEmpty(expense.getOperatingHoursOf()) || StringUtil.isEmpty(expense.getOperatingHoursUpTo()))) { Locale locale = Locale.ENGLISH; if (expense.getOperatingHoursOf().contains(",")) { locale = Locale.GERMAN; } try { float vonFloatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(expense.getOperatingHoursOf()))); float bisFloatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(expense.getOperatingHoursUpTo()))); DecimalFormat formater = new DecimalFormat("###.0", new DecimalFormatSymbols(locale)); opHrs = formater.format(bisFloatValue - vonFloatValue); } catch (NumberFormatException e) { opHrs = "--"; } catch (ParseException e) { opHrs = "--"; } } else { opHrs = "--"; //$NON-NLS-1$ } } else { opHrs = "--"; //$NON-NLS-1$ } return opHrs; } private String getExpens(Expenses expense) { String expns = ""; //$NON-NLS-1$ if (!expense.isInitial()) { if (expense.isNoExpenses()) expns = TimeSheetMessages.getString("non"); //$NON-NLS-1$ else { float tgspsn = 0; float divspsn = 0; float pikett = 0; float abzg = 0; Locale locale = Locale.ENGLISH; if (expense.getDailyExpenses().contains(",")) { locale = Locale.GERMAN; } tgspsn = getFloatValue(expense.getDailyExpenses()); divspsn = getFloatValue(expense.getVariousExpenses()); // divspsn = getFloatValue(expense.getVariousExpenses()); pikett = getFloatValue(expense.getPikettExpenses()); abzg = getFloatValue(expense.getDeduction()); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("##0.00", symbols); format.setMaximumFractionDigits(2); expns = format.format(tgspsn + divspsn + pikett - abzg); } } else { expns = "--"; //$NON-NLS-1$ } try { Double.parseDouble(expns); } catch (NumberFormatException e) { expns = "00.00"; //$NON-NLS-1$ } return expns; } private float getFloatValue(String value) { try { Locale locale = Locale.ENGLISH; if (value.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(value))); return floatValue; } catch (NumberFormatException e) { return 0; } catch (ParseException e) { return 0; } } private String getWorkingHours(TreeSet timeSheets) { long totalTime = 0; Iterator itr = timeSheets.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = (TimeSheet) itr.next(); if (timeSheet.validate().isValid()) totalTime += DateTimeUtil.getTimeDifference(timeSheet.getStopTime(), timeSheet.getStartTime()); // totalTime += zkdmatime.getStopTime().getTime() - zkdmatime.getStartTime().getTime(); } return DateTimeUtil.showTime(totalTime); } private int getStyleByCalendar(CalendarTimeSheet calendar) { int result = LayoutUtils.DEFAULT_TEXT_COLOR; if (calendar.getStatus().isINITIAL() || calendar.getStatus().isSAVED()) result = LayoutUtils.DEFAULT_TEXT_COLOR; else if (calendar.getStatus().isSENT()) result = LayoutUtils.DEFAULT_LIGHT_GRAY; else if (!calendar.isValid()) result = LayoutUtils.DEFAULT_ERROR_COLOR; return result; } public static class CalendarOverviewFormArgument { private CalendarTimeSheet calendar; private boolean isServiceApp; protected CalendarOverviewFormArgument() { } public CalendarOverviewFormArgument(CalendarTimeSheet calendar, boolean isServiceApp) { this.calendar = calendar; this.isServiceApp = isServiceApp; } public CalendarTimeSheet getCALENDAR() { return this.calendar; } public boolean isServiceApp() { return this.isServiceApp; } } }
    service/AndroidManifest.xml:       service/application.dtd:       service/application.xml:  
    service/build.gradle.kts:   plugins { id("ch.mfiles.kolibri-application") } dependencies { implementation(project(":common")) }     service/build.xml:       service/i18n/ch/mfiles/kaba/kolibri/service/messages.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) AtLeastXImagesNecessary = At least {0} images necessary BluetoothIsNotTurnOn = Bluetooth isn't turned on CHF = CHF CannotCreateOrder = Cannot create order. CannotSaveDocAlreadyExist = Cannot save, {0} already exist. Checklist = Checklist IBS ChecklistInstructionText = The installation was handed over to the operator, instructions were given and an operator manual was handed over. ChecklistReadyText = According to the order, the installation is complete and ready for operation. ChecklistSIAText = The installation corresponds in all parts to SIA 343 (DIN 18650) and Tornorm no. SN 12453. ChecklistStateText = All assembled elements of the installation are in perfect condition and show no signs of damage (paint, glass, etc.). ChecklistTestText = Fire and security functions connected and tested. ChecklistVKFText = Instruction is given to the operator. If not, the operator manual on the installation. The VKF documentation is sent to the client. Client = Client ClientNumber = Client No. Contact = Contact Customer = Customer DeleteMeasurement = Delete measurement? DeleteReport = Delete report? DiscardMeasurement = Discard measurement? DoYouReallyWantToDeleteTheCompleteReport = Do you really want to delete the complete report? \nReport time, material, signature et cetera will be deleted too. Document = Document DocumentReqired = Document {0} required. DocumentsWillBeLost = Documents will be lost, are you sure that you want to continue? Done = Done E = E editInstallationType = Edit installation type EstateManagement = Estate Management GoodsReceipt = Goods Receipt GoodsIssue = Goods issue Goodwill = Goodwill Guarantee = Guarantee GuaranteeTitle = Guarantee GuaranteeMaterial = Guarantee ImageReqired = Image {0} required. Important = Important JobFinishedSendReport = Job finished? Send Report? K14Material = K-Material MeasurementComplete = Measurement: Complete. MeasurementInComplete = Measurement incomplete MeasurementMaximum = At maximum {0} measurements possible NoPhoneNumber = No phone number Object = Object Odered = Odered OrderNo = Order No. OverwriteAnExistingMeasurement = The recorded data are discarded and a new measurement is started. Continue? Owner = Owner Partner = Partner Planed = Planed PleaseEnterATime = Please enter a time Receiver = Receiver ReleaseDevice = Release device RescheduleJob = Reschedule job SAVResponsible = SAV responsible SAV = SAV Service = Service Signature = Signature TheCapturedDataWillBeDeleted = The captured data will be deleted. Continue? VC = VC WrongFormatXX-XXXX-XXX/XX = Wrong format(XX-XXXX-XXX/XX) YouAreSingingNReport = You are signing {0} reports. aborted = aborted... absenceList = Absence Notification absenceNotification = Absence Notification absenceType = Absence type absences = Absences accept = Accept active = Active add = Add addition = Addition additionalDelivery = Additional delivery address = Address addressDoesNotExist = {0}-address does not exist addresses = Addresses agregatedSignature = Agregated signature allowedTime = Allowed time amount = Amount appointment = Appointment AppointmentDate = AppointmentDate: appointmentDefined = Appointment defined areYouSureThatYouWantToDeleteRecord = Are you sure that you want to delete this record? areYouSureWantToDeleteRecord = Are you sure that you want to delete this record? articleScan = Article Scan articleName = Article name articleNotINInventory = Artikel not in Inventory! articleNumber = Article number artNo = Art. No. back = Back backOffice = Back office bemHistory = Bem. / History billing = Billing camera = Camera cancel = Cancel captured = Captured caseHandler = Case handler change = Change changeAddress = Change address changesWillBeLost = Changes will be lost, are you sure that you want to continue? charging = Charging checkCycles = Check cycles checkList = Checklist IBS ChooseForm = Choose Form city = City clear = Clear clock = O'clock collectiveSignature = Collective Signature codeReturnDelivery = Code return delivery commNo = Comm. No. commNoCheck = Comm. No.-Check commNotCorrect = Comm. not correct? commissionNumber = Commission number commissionNumberNotCorrectWillSaveEmptyString = Commission number not correct (0XXXXXX-XX)\nand will save empty String. completed = Completed configurations = Configurations confirm = Confirm confirmation = Confirmation consequentialRepair = Consequential repair coordinateAppointment = Coordinate appointment! correct = Correct correctCommissionNumber = Correct commission number correctInstallationType = Correct Installation type costumerRemark = Costumer remark costumerReport = Costumer report costumerService = Costumer service createJob = Create job createREPJob = Create REP-Job customizeYourInfo = Customize your info cycleOfInstallation = Number of cycles date = Date dateFrom = Date from dateTo = Date to delete = Delete deleteCompleteReport = DELETE COMPLETE REPORT deliverDate = Deliver date delivered = Delivered deliveredArticles = Delivered articles department = Department description = Description designation = Designation deviceMirroring = Device mirroring discardForm = Discard form? distance = Distance distancesBetween0To999kmAreAppropriate = Distances between 0 to 999km are appropriate doYouReallyWantToDeleteXShortMessagesAtOnce = Do you really want to delete {0} short messages at once? doYouReallyWantToLoadXjobsAtOnce = Do you really want to load {0} jobs at once? doYouWantToDeleteJob = Do you want to delete job? doYouWantToDeleteThisSignature = Do you want to delete this signature? doYouWantToGetOrder = Do you want to get Order (MLDNR :{0}) done = Done download = Download downloadOrder = Download order downloadOrder(SAP) = Download order(SAP) drive = Drive duplicatedMaterialNumber = There is MaterialNumber {0} duplicated {1} can not insert. duration = Stock editReport = Edit report editingInstallationType = Editing installation type email = Email employee = Employee employees = Employees endRepair = End Repair enteredValueIsInTheFuturePleaseEnterValidTime = The entered value is in the future! Please enter a valid time. enterprise = Enterprise erase = Erase error = Error errorCode = Error code errorMessages = Error messages: ers = Ers existingEntriesFromCannotAddEntryOn = Existing entries from {0}, can not add entry on {1} exists = Exists exit = Exit exitServiceApplication = Exit service application expenses = Expenses explanationForReturn = Explanation for return external = External failure = Failure fax = Fax fileDeleted = File Deleted. finalRepair = Final repair finalized = Finalized finished = Finished firstName = First name followup = Follow-up forward = Forward from = From FormReqired = From {0} required. Forms = Forms fromImventory = From Inventory gilgenCommonApplicationIsNotInstalled = The Gilgen Common application is not installed! The Gilgen Service cannot run. gilgenMaterialApplicationIsNotInstalled = The Material application is not installed! gilgenTimesheetApplicationIsNotInstalled = The Timesheet application is not installed! governmentReport = report callout charged at cost history = History hours = Hours hrs = Hrs. image = Image images = Images inProgress = In progress incidentA = Incident A incidentB = Incident B incomingArticle = Incoming Article incomingArticleTitle = Incoming Article incomingArticleWithoutListEntry = Post incoming article info = Info information = Information insertFixedMasterDataFile = Insert fixed-master-data(File) insertingMasterData = Inserting MasterData... installGilgenCommonApplicationFirst = Install the Gilgen Common application first. Continue installation and restart Kolibri. installationError = Installation error installationState = State of installation internal = Internal interventionType = Type of next intervention invalid = Invalid invalidBarcodeGuarantee = Invalid Barcode guarantee invalidCommissionNumber = Invalid commission number invalidJobNumber = Invalid job number invalidKomNo = Invalid KomNo inventoryInformations = Inventory informations inventoryName = Inventory name inventoryNumber = Inventory number inventoryStock = Inventory Stock job = Job job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = The selected Job couldn't be deleted. Please send back open reports or working time jobDeleted = Job deleted jobDetails = Job details jobEdit = Job edit jobInfo = Job info jobList = Job list jobNumber = Job number jobState = job state jobTime = Job Time jobsSelected = {0} / {1} jobs selected lastName = Last name link = Link listIsEmptyNoTimeEntryToDelete = List is empty, no time entry to delete listOfEmployees = List of employees location = Location maintenance = Maintenance maintenanceCode = Maintenance code maintenanceDone = Maintenance done maintenanceMonths = Maintenance months maintenancePlanned = Maintenance planned masterDataSuccessfullyRefreshed = Master data successfully refreshed material = Material materialApp = Material App materialName = Material name materialNumber = Material number materialWasDeleted = Material was deleted. materialWithThisNameAlreadyExists = Material with this name already exists materialWithThisNumberAlreadyExists = Material with this number already exists. maximumOfCheckdBoxesIs6 = Maximum of checked boxes is 6 Measurement = Measurement messageToChef = Message to chef messageToCostumer = Message to costumer messageToKDZ = Message to KDZ messages = Messages month = Month moreInformations = More Informations mtDone = Mt. done mtPlanned = Mt. planned name = Name nameOfInventory = Inventory new = New newInventory = New inventory newJob = New job newReport = New report newTimeEntryConfictsWithExistingOne = New time entry conficts with existing one: {0} - {1} next = Next nextReport = Next report no = No noAbsencesRecorded = No Absences recorded noAppointmentKnown = No appointment known noArticleFound = No article found. noChecklistPresent = No checklist present, report cannot be sent. noDataAvailable = No data available noDataForOrderTypePleaseRefreshMasterdata = No data for order type, please refresh masterdata. noDocumentPresent = No document present, report cannot be sent: noEmployeeSelected = No employee selected. noFormDescImagePresent = No document/image {0} present noFormDescPresent = No document {0} present noImagesEntriesReportCannotBeSent = No images entries, report cannot be sent. noFormsRecorded = No forms recorded noImagesRecorded = No images recorded noJobAvailable = No job available. noJobSelected = No job selected! noMaterialPresent = No Material present, report cannot be sent. noMaterialRecorded = No material recorded noMaterialused = No material used. noMessagesRecorded = No messages recorded noNumberToDialPleaseSelectJob. = No number to dial. Please select a job. noReasonSelected = No reason selected noRecordsAvailable = No records available noReport = no report noReportAvailable = No report available noReportRecorded = No report recorded noShortMessageAvailable = No short message available. noSignature = No signature noSignatureCaptured = No signature captured noSignaturePresent = No signature present, report cannot be sent. noSignatureReasonSaved = No signature: Reason saved. notAdded = not added noTimeEntrySelected = No time entry selected noTimesRecorded = No times recorded noTimesheetEntriesReportCannotBeSent = No timesheet entries, report cannot be sent. normalMaterial = Normal material notEdit = Not edited notImplementedYet = Not implemented yet. notPossible = Not possible notRecorded = Not recorded notSend = Not send noVonoviaFormPresent = No Vonovia Form present, report cannot be sent. number = Number of = of ok = OK onCall = On-call open = Open openMaintenance = Open maintenance openPending = Open pending orderDate = Order date orderedArticles = Ordered Articles orderNo = Order number orderPosition = Order position orderType = Order type otherTypeOfMaterial = Other type of material outgoingArticle = Outgoing article outgoingArticles = Outgoing articles outgoingArticlesList = List of outgoing articles partialRepair = Partial repair partiallySend = Partially sent pdfFiles = PDF files person = Person personalNumber = Personal number phone = Phone planned = Planned plannedJob = Planned Job pleaseCompleteTheReport = Please complete the report pleaseEnterValidDate = Please enter a valid date pleaseEnterValidTime = Please enter a valid time pleaseSelectValidTime = Please select a valid time previous = Previous previousReport = Previous report price = Price priority = Priority progress = Fortschritt projectLeader = Project leader reason = Reason reasonForDelete = Reason for delete reasongIncomingArticle = Reasong incoming article reasonReturnDelivery = Reason return delivery receipt = Receipt receive = Receive receivedFrom = Received from refreshMasterData = Refresh master data refreshMasterData(SAP) = Refresh master data refreshingMasterData = Refreshing MasterData... refreshingMasterDataFailed = Refreshing Master data failed! refreshingStock = Refreshing stock releaseDevice = Release device remarks = Remarks report = Report report(s) = report(s) reportAbsence = Report absence reportCannotBeSent = Report cannot be sent. reportData = Report data reportMessageToCustomer = Job type {0} must have a report message to client. reportView = Report view reports = Reports reschedule = Reschedule rideToSideNotCharged = Ride to side not charged salesPerson = Sales person savc = SAVC save = Save savingNotPossible = Saving not possible scan = Scan search = Search searchJob = Search job searchOrder(SAP) = Search order (SAP) secondVisitNeeded = Second visit needed securityReport = Security report securityReportCreated = Security report created securityReportFilledIn = Security report filled in selectOneOrMoreJobs = Select one or more jobs. selectOneOrMoreShortMessages = Select one or more short messages. send = Sent sendAbsenceNotification = Do you want to report this absence? Messages cannot be processed after they have been sent. sendReport = Send report? sendReportTo = Send report to sendingReport = Sending report sent = sent sentDate = Sent servicePerformed = Service performed serviceRefused = Service refused shortMessage = Short message shortMessages = Short messages showPlannedJobDialogText = The job is planned in future and will be displayed in filter "planned" after confirming. signatureAlreadySaved = Signature already saved signatureBelongsToJobsDoYouWanToDeleteIt = The signature belongs to {0} jobs. Do you want to delete it? signatureBundle = Signature bundle signatureCanNotBeLoadedFromFile = Signature can not be loaded from file signatureCannotBeChanged = Signature can not be changed anymore because at least on report from the group has been already sent signatureDeleted = Signature deleted. signatureSaved = Signature saved spareParts = Spare parts spareparts = Spare parts start = Start startGilgenService = Start Gilgen Service state = State status = Status stock = Stock stop = Stop street = Street streetOrNumber = Street/Number summaryTotal = Gesamtsumme synchronizingOrders = Synchronizing orders tel1 = Tel. 1 tel2 = Tel. 2 telWColon = Tel.: template = template TheFormIsDiscardedContinue = The form is discarded. Continue? theSelectedMessageAreDeleted = The selected message(s) are deleted. TheSelectedItemIsNotInStockContinue = The selected item is not in stock. Continue? TheSelectedArticleIsNotInMasterdata = The selected article isn't available in masterdata. Please contact support. thereAreTimeStampsWithoutWorkType = There are time stamps without work type. Please change. time = Time timeFrom = Time from timeNotStopped = Time not stopped timeSheet = TimeSheet timeStopped = Time stopped timeTo = Time to times = Times timesBelongToDifferentDays = Times belong to different days. timesheetApp = Timesheet App title = Title to = To tooManyMeasurements = Too many measurements available at one measuring point total = Total transit = Transit typeOfJob = Type of job typeOfMaterial = Type of material typeOfWork = Type of work unit = Unit unknown = Unknown userList = User list UserName = User-Name valid = Valid valid_guarantee_label = This system has a valid guarantee label. Please make a case decision. vehicleInventory = Vehicle Inventory warning = Warning! way = Way week = Week workType = Work type wrongComm = Wrong commission number wrongFormArgument = Wrong form argument class found in form year = Year yes = Yes youAreSigning = You are signing youCanSelectMaximumOf30Jobs = You can select a maximum of 30 jobs. zip = ZIP zipCity = ZIP / City     service/i18n/ch/mfiles/kaba/kolibri/service/messages_fr.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AppointmentDate = D\u00E9lai: AtLeastXImagesNecessary = Au moins {0} images n\u00E9cessaires BluetoothIsNotTurnOn = Bluetooth n'est pas activ\u00E9. CHF = CHF CannotCreateOrder = Commande ne peut pas \u00EAtre cr\u00E9\u00E9e. CannotSaveDocAlreadyExist = Ne peut pas \u00EAtre sauvegard\u00E9, {0} existe d\u00E9j\u00E0 Checklist = Checklist IBS ChecklistInstructionText = L\u2019instruction de l\u2019exploitant a \u00E8t\u00E8 effectu\u00E8e / Si non, le manuel d\u2019exploitation est d\u00E8pos\u00E8 sur l\u2019installation. La documentation AEAI sera envoy\u00E8e au client. ChecklistReadyText = L\u2019installation est compl\u00E8te et op\u00E8rationnelle conform\u00E8ment au contrat ChecklistSIAText = L'installation avec tous les \u00E8l\u00E8ments correspond aux directives de la SIA 343/214, SN EN16005:2012. .ainsi que les normes de porte No. SN EN 12453:2017. ChecklistStateText = Tous les \u00E9l\u00E9ments de l'installation sont en parfait \u00E9tat et n'ont pas de dommage (couleur, verre, etc.). ChecklistTestText = Fonctions coupe-feu et de protection de la valeur raccord\u00Ees et test\u00E8es. ChecklistVKFText = L\u2019exploitant a \u00E9t\u00E9 instruit. Sinon: manuel pour l\u2019op\u00E9rateur sur l\u2019installation. La documentation AEAI sera envoy\u00E9e au commettant. ChooseForm = Formularauswahl Client = Client ClientNumber = No. de Client Contact = Contact Customer = Entrepreneur DeleteMeasurement = Efface le mesure? DeleteReport = Effacer rapport? DiscardMeasurement = Annuler le mesure? DoYouReallyWantToDeleteTheCompleteReport = Voulez-vous vraiment effacer le rapport complet?\nTemps de rapport saisis, mat\u00E9riel, signature etc. seront \u00E9galement effac\u00E9s. Document = Document DocumentReqired = Document {0} requis. DocumentsWillBeLost = Des documents sont supprim\u00E9s, voulez-vous continuer? Done = Achev\u00E9 E = E editInstallationType = Modifier le type d'installation EstateManagement = Administration FormReqired = Formulare {0} requis. Forms = Formulare GoodsIssue = Sortie de marchandises GoodsReceipt = La r\u00E9ception des marchandises Goodwill = \u00C0 bien plaire Guarantee = Livraison retour GuaranteeMaterial = Livraison retour GuaranteeTitle = Livraison retour ImageReqired = Image {0} requis. Important = Important JobFinishedSendReport = La commande est termin\u00E9e? Envoyer le rapport? K14Material = Mat\u00E9riel K Measurement = Mesure MeasurementComplete = Mesure: Saisie. MeasurementInComplete = Mesure incompl\u00E8te MeasurementMaximum = Au maximum {0} mesures possible. NoPhoneNumber = Pas de no. de t\u00E9l\u00E9phone Object = Objet Odered = Command\u00E9 OrderNo = No. de commande OverwriteAnExistingMeasurement = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es et une nouvelle mesure est lanc\u00E9e. Continuer? Owner = Propri\u00E9taire Partner = Partner Planed = Planifi\u00E9 PleaseEnterATime = Veuillez enregistrer le temps Receiver = Destinataire de marchandise ReleaseDevice = Partager un appareil RescheduleJob = Replanifier l'ordre SAV = SAV SAVResponsible = Responsable SAV Service = Service Signature = Signature TheCapturedDataWillBeDeleted = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es. Continuer? TheFormIsDiscardedContinue = Das Formular wird verworfen. Fortfahren? TheSelectedArticleIsNotInMasterdata = L'article s\u00E9lectionn\u00E9 n'est pas dans les donn\u00EEs de base. Veuillez contacter l'assistance. TheSelectedItemIsNotInStockContinue = L'article s\u00E9lectionn\u00E9 n'est pas en stock. Continuer? UserName = MA-Name VC = VC WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). YouAreSingingNReport = Vous signez {0} rapports. aborted = annul\u00E9\u2026 absenceList = Message d'absence absenceNotification = Saisire l'absence absenceType = D\u00E9but de l'absence absences = Absences accept = Accepter active = Active add = Ajouter addition = Compl\u00E9ment additionalDelivery = Livraison ult\u00E9rieure address = Adresse addressDoesNotExist = Pas trouv\u00E9 l'adresse {0}. addresses = Adresses agregatedSignature = Signature collective allowedTime = Temps pr\u00E9vu amount = Quantit\u00E9 appointment = D\u00E9lai appointmentDefined = D\u00E9lai fixe areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? areYouSureWantToDeleteRecord = Effacer l'enregistrement? artNo = No. d'article articleName = Artikelbezeichnung articleNotINInventory = Article pas en stock ! articleNumber = num\u00E9ro d'article articleScan = Nom de l'article back = Retour backOffice = Vente interne bemHistory = Remarque / Historique billing = Facturation camera = Camera cancel = Annuler captured = Saisie caseHandler = Responsable de projet change = Changement changeAddress = Changement d'adresse changesWillBeLost = Les changements sont rejett\u00E9s, continuer? charging = Facturation checkCycles = Cycles checkList = Check-list IBS city = Lieu clear = Remettre clock = Regarder codeReturnDelivery = Livraison de retour de code collectiveSignature = Signature collective commNo = No. de comm. commNoCheck = V\u00E9rifiez No. de Commission commNotCorrect = No. de commission pas correcte? commissionNumber = No. de commission commissionNumberNotCorrectWillSaveEmptyString = Num\u00E9ro de commission incorrect (0XXXXXX-XX) completed = Compl\u00E9t\u00E9 configurations = Configurations confirm = Confirmer confirmation = Confirmation consequentialRepair = R\u00E9paration successive coordinateAppointment = Convenir le d\u00E9lai! correct = Correct correctCommissionNumber = Corrigez le num\u00E9ro de commission. correctInstallationType = Correcte d'installation costumerRemark = Remarque clients costumerReport = Rapport clients costumerService = SAV createJob = Cr\u00E9er un ordre createREPJob = Cr\u00E9er job REP customizeYourInfo = Personnalisez votre informations. cycleOfInstallation = Num\u00E9ro de cycle date = Date dateFrom = Date de dateTo = Date \u00E0 delete = Effacer deleteCompleteReport = EFFACER RAPPORT ENTIER deliverDate = la date de livraison delivered = Position livr\u00E9e deliveredArticles = Livr\u00E9 department = D\u00E9pt. description = Description designation = Designation deviceMirroring = Appareil lib\u00E9r\u00E9 discardForm = Formular verwerfen? distance = Distance distancesBetween0To999kmAreAppropriate = Les distances entre 0 e 999km sont permises. doYouReallyWantToDeleteXShortMessagesAtOnce = Voulez-vous vraiment supprimer {0} Flashes d'informations \u00E0 la fois? doYouReallyWantToLoadXjobsAtOnce = Voulez-vous vraiment charger {0} emplois \u00E0 la fois? doYouWantToDeleteJob = Effacer la commande? doYouWantToDeleteThisSignature = Voulez-vous vraiment effacer la signature? doYouWantToGetOrder = T\u00E9l\u00E9charger la commande (MLDNR :{0})? done = Termin\u00E9 download = T\u00E9l\u00E9charger downloadOrder = T\u00E9l\u00E9charger la commande downloadOrder(SAP) = T\u00E9l\u00E9charger la commande (SAP) drive = Type entrainment duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. duration = Dur\u00E9e editReport = Editer le rapport editingInstallationType = Modifier le type d'investissement email = Email employee = Employ\u00E9(e) employees = Employ\u00E9s endRepair = R\u00E9paration finale enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enterprise = Entreprise erase = Effacer error = Erreur errorCode = Code erreur errorMessages = Rapports de non-conformit\u00E9: ers = Rechange existingEntriesFromCannotAddEntryOn = Impossible pour {1} d''ajouter les enregistrements existants de {0} exists = Existant exit = Quitter exitServiceApplication = Quitter expenses = Frais explanationForReturn = Raison pour le renvoi (de mat\u00E9riel) external = Au client failure = D\u00E9faillance fax = Fax fileDeleted = Fichier supprim\u00E9. finalRepair = Raison du retour de livraison finalized = Fini finished = Termin\u00E9 firstName = Pr\u00E9nom followup = R\u00E9p. suivant forward = Transf\u00E9rer from = De fromImventory = En stock gilgenCommonApplicationIsNotInstalled = L'application commune n'est pas install\u00E9e. C'est la raison pourquoi l'application service ne peut pas \u00E9tre d\u00E9marr\u00E9e. gilgenMaterialApplicationIsNotInstalled = L'application mat\u00E9riel n'est pas install\u00E9e! gilgenTimesheetApplicationIsNotInstalled = L'application Timesheet n'est pas install\u00E9e! governmentReport = Rapport des travaux en r\u00E9gie history = Historique hours = Heures hrs = Hrs. image = Image images = Images inProgress = En courant incidentA = D\u00E9faillance A incidentB = D\u00E9faillance B incomingArticle = La r\u00E9ception des marchandises incomingArticleTitle = La r\u00E9ception des marchandises incomingArticleWithoutListEntry = R\u00E9server l'entr\u00E9e info = Info information = Information insertFixedMasterDataFile = Charger les donn\u00E9es de base (fichier) insertingMasterData = Ins\u00E9rer les donn\u00E9es de base ... installGilgenCommonApplicationFirst = S.v.p. installer premi\u00E9rement l'application commune de suite continuer l'installation et red\u00E9marrer Kolibri. installationError = Erreur d'installation installationState = \u00E9tat de fonctionnement internal = Interne interventionType = processus de suivi invalid = Incorrect invalidBarcodeGuarantee = Code-barre invalide invalidCommissionNumber = No. de commission invalide invalidJobNumber = No. de commande invalide invalidKomNo = No. de commission incorrect inventoryInformations = Informations boursi\u00E9res inventoryName = Nom du camp inventoryNumber = Num\u00E9ro d'entrep\u00F4t inventoryStock = Action job = Commande job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = Impossible d'effacer la commande s\u00E9lectionn\u00E9e. S.v.p. transmettre les rapports ouverts et temps. jobDeleted = Commande effac\u00E9e jobDetails = D\u00E9tails d'ordre jobEdit = Modification de rapport jobInfo = Info Job jobList = Liste Job jobNumber = Num\u00E9ro de commande jobState = \u00C9tat de commande jobTime = Temps de commande jobsSelected = {0} / {1} jobs s\u00E9lectionn\u00E9 lastName = Nom de famille link = Link listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible d'effacer le temps listOfEmployees = Liste des employ\u00E9s location = Installation maintenance = Service maintenanceCode = Code SAV maintenanceDone = Service ex\u00E9cut\u00E9 maintenanceMonths = Mois de service maintenancePlanned = SAV pr\u00E9vu masterDataSuccessfullyRefreshed = Donn\u00E9es de base actualis\u00E9es avec succ\u00E9s material = Mat\u00E9riel materialApp = App. Mat\u00E9riel materialName = D\u00E9signation d'article materialNumber = Num\u00E9ro d'article materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. maximumOfCheckdBoxesIs6 = Maximum de choix: 6 messageToChef = Message sup\u00E9rieur messageToCostumer = Message client messageToKDZ = Message KDZ messages = Communications month = Mois moreInformations = Erw. Komm. mtDone = SAV fini mtPlanned = SAV pr\u00E9vu name = D\u00E9signation nameOfInventory = Camp new = Nouveau newInventory = Nouvel entrep\u00F4t newJob = Nouvel ordre newReport = Nouveau rapport newTimeEntryConfictsWithExistingOne = Nouveau enregistrement en collision avec l''enregistrement existant: {0} - {1} next = Continuer nextReport = Prochain rapport no = No noAbsencesRecorded = Aucune absences enregistr\u00E9e noAppointmentKnown = Pas de d\u00E9lai noArticleFound = Aucun article trouv\u00E9. noChecklistPresent = Manque la checklist, impossible de transmettre le rapport. noDataAvailable = Pas de donn\u00E9es disponibles noDataForOrderTypePleaseRefreshMasterdata = Pas de donn\u00E9es pour le type de commande, s.v.p. actualiser les donn\u00E9es de base. noDocumentPresent = Aucun document disponible, le rapport ne peut \u00EAtre envoy\u00E9 noEmployeeSelected = Aucun employ\u00E9 s\u00E9lectionn\u00E9. noFormDescImagePresent = document/image {0} n'existe pas. noFormDescPresent = Document {0} n'existe pas. noFormsRecorded = Aucun formulare enregistr\u00E9 noImagesEntriesReportCannotBeSent = Aucun image saisis, impossible de transmettre le rapport. noImagesRecorded = Aucun image enregistr\u00E9 noJobAvailable = Aucun travail disponible. noJobSelected = Aucune commande s\u00E9lectionn\u00E9! noMaterialPresent = Manque la mat\u00E9riel , impossible de transmettre le rapport. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMaterialused = Aucun mat\u00E9riel utilis\u00E9. noMessagesRecorded = Aucun message enregistr\u00E9 noNumberToDialPleaseSelectJob. = Impossible de choisir. Veuillez s\u00E9lectionner une c noReasonSelected = Aucune justification n'est choisie noRecordsAvailable = Aucun temps saisie noReport = Aucun rapport noReportAvailable = Aucun rapport saisie noReportRecorded = Aucun rapport enregistr\u00E9 noShortMessageAvailable = Aucun message court disponible. noSignature = Aucune signature noSignatureCaptured = Aucune signature n'est saisie noSignaturePresent = Manque la signature, impossible de transmettre le rapport. noSignatureReasonSaved = Pas de signature: Basic d\u00E9tect\u00E9. noTimeEntrySelected = Aucun enregistrement n'est saisi noTimesRecorded = Aucune heure enregistr\u00E9e noTimesheetEntriesReportCannotBeSent = Aucun temps saisis, impossible de transmettre le rapport. noVonoviaFormPresent = Manque la Vonovia formulare, impossible de transmettre le rapport. normalMaterial = Mat\u00E9riel standard notAdded = no registrado notEdit = Pas \u00E9dit\u00E9 notImplementedYet = Pas encore impl\u00E9ment\u00E9. notPossible = Impossible notRecorded = Non enregistr\u00E9 notSend = Pas envoy\u00E9(e) number = Nombre of = de ok = OK onCall = Piquet open = Ouvert openMaintenance = SAV ouvert openPending = Affaire en suspens orderDate = Date de commande orderNo = No de commande orderPosition = Article de commande orderType = Type de commande orderedArticles = En attente otherTypeOfMaterial = Mat\u00E9riau diff\u00E9rent\u0009\u0009 outgoingArticle = Sortie de marchandises\u0009\u0009 outgoingArticles = Sortie de marchandises outgoingArticlesList = Action partialRepair = R\u00E9paration partielle partiallySend = Partiellement envoy\u00E9(e) pdfFiles = PDF person = Responsable personalNumber = Num\u00E9ro personnel phone = T\u00E9l\u00E9phone planned = Pr\u00E9vu plannedJob = Travail pr\u00E9vu pleaseCompleteTheReport = Remplissez le rapport, s.v.p. pleaseEnterValidDate = Veuillez enregistrer un temps date pleaseEnterValidTime = Veuillez enregistrer un temps valide pleaseSelectValidTime = Veuillez s\u00E9lectionner une heure valide previous = Pr\u00E9c\u00E9dente previousReport = Rapport pr\u00E9c\u00E9dent price = Prix priority = Priorit\u00E9 progress = Progress projectLeader = Chef de projet reason = Raison reasonForDelete = Raison d'effacer reasonReturnDelivery = Raison du retour de livraison reasongIncomingArticle = Justification de la r\u00E9ception des marchandises receipt = Entr\u00E9e receive = T\u00E9l\u00E9charger receivedFrom = Re\u00E7u de refreshMasterData = Actualiser les donn\u00E9es de base refreshMasterData(SAP) = Actualiser les donn\u00E9es de base refreshingMasterData = Actualiser les donn\u00E9es de base ... refreshingMasterDataFailed = Actualisation des donn\u00E9es de base \u00E9chou\u00E9e! refreshingStock = Mise \u00E0 jour du stock releaseDevice = Partager un appareil remarks = Remarques report = Rapport report(s) = Rapport(s) de travai reportAbsence = D\u00E9poser l'absence reportCannotBeSent = Impossible de transmettre le rapport. reportData = Donn\u00E9es du rapport reportMessageToCustomer = Les commandes {0} doivent contenir un message du rapport destin\u00E9 au client. reportView = Vue du rapport reports = Rapports reschedule = Reprogrammer rideToSideNotCharged = Aucun d\u00E9placement ne sera factur\u00E9. salesPerson = Technico-commercial savc = Code de SAV save = Sauvegarder savingNotPossible = Impossible de m\u00E9moriser scan = Balayage search = Recherche searchJob = Recherche Job searchOrder(SAP) = Chercher la commande (SAP) secondVisitNeeded = 2\u00E8me utilisation n\u00E9cessaire. securityReport = Rapport de s\u00E9curit\u00E9 securityReportCreated = Rapport de s\u00E9curit\u00E9 \u00E9tabli securityReportFilledIn = Rapport de s\u00E9curit\u00E9 \u00E9tabli selectOneOrMoreJobs = S\u00E9lectionnez un ou plusieurs ordres. selectOneOrMoreShortMessages = S\u00E9lectionnez un ou plusieurs messages courts. send = Envoy\u00E9(e) sendAbsenceNotification = D\u00E9sirez-vous annoncer cette absence? Apr\u00E8s avoir envoy\u00E9 les messages, il n'est plus possible de les \u00E9diter. sendReport = Envoyer le rapport? sendReportTo = Envoyer le rapport \u00E0 sendingReport = Envoyer le rappor sent = envoy\u00E9 sentDate = Envoy\u00E9(e) servicePerformed = Accompli serviceRefused = Refus\u00E9 shortMessage = Flash d'information shortMessages = Flash d'informations showPlannedJobDialogText = L'ordre a une date d\u2019intervention planifi\u00E9e et est affich\u00E9 dans le filtre "Planifi\u00E9" apr\u00E8s confirmation. signatureAlreadySaved = Signature d\u00E9j\u00E0 m\u00E9moris\u00E9e signatureBelongsToJobsDoYouWanToDeleteIt = La signature collective appartient \u00E0 des commandes {0}. Effacer ? signatureBundle = Signature collective signatureCanNotBeLoadedFromFile = Impossible de charger la signature par le fichier. signatureCannotBeChanged = Impossible de modifier la signature collective, car au min. un rapport de la groupe a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9. signatureDeleted = Signature supprim\u00E9. signatureSaved = Signature m\u00E9moris\u00E9e spareParts = Pi\u00E8ces de rechange spareparts = Pi\u00E8ces de rechange start = D\u00E9marrage startGilgenService = D\u00E9marrage Gilgen Service state = \u00C9tat status = \u00C9tat stock = Nombre stop = Arr\u00E9t street = Rue streetOrNumber = Rue/No. summaryTotal = Somme totale synchronizingOrders = Synchroniser les ordres tel1 = T\u00E9l. 1 tel2 = T\u00E9l. 2 telWColon = T\u00E9l.: template = Soumission theSelectedMessageAreDeleted = Les messages s\u00E9lectionn\u00E9s sont supprim\u00E9s. thereAreTimeStampsWithoutWorkType = Il y a encore de temps sans mode de travail, s.v.p corriger. time = Temps timeFrom = \u00E0 timeNotStopped = Le temps n'est pas arr\u00E9t\u00E9 timeSheet = Saisie du temps timeStopped = Le temps est arr\u00E9t\u00E9 timeTo = jusqu'\u00E0 times = Temps timesBelongToDifferentDays = Les temps font partie de diff\u00E9rents jours. timesheetApp = Timesheet App title = Titre to = de tooManyMeasurements = Trop de mesurages disponibles en un seuil point de mesurage. total = Total transit = Transit typeOfJob = Type de commande typeOfMaterial = Type de mat\u00E9riel typeOfWork = Type de travail unit = Unit\u00E9 unknown = Inconnu userList = Liste d'employ\u00E9s valid = Correct valid_guarantee_label = Cette installation poss\u00E8de une identification de garantie valable. Veuillez s.v.p. prendre une d\u00E9cision. vehicleInventory = Entrep\u00F4t de v\u00E8hicules warning = Avertissement! way = Mani\u00E8re week = Semaine workType = Mode de travail wrongComm = Mauvais no. de comm. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect year = Ann\u00E9e yes = Oui youAreSigning = Vous signez youCanSelectMaximumOf30Jobs = Vous pouvez s\u00E9lectionner un maximum de 30 emplois. zip = NPA zipCity = NPA / Lieu     service/i18n/ch/mfiles/kaba/kolibri/service/messages_it.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface AppointmentDate = D\u00E9lai: AtLeastXImagesNecessary = Sono necessarie almeno {0} immagini BluetoothIsNotTurnOn = Bluetooth n'est pas activ\u00E9. CHF = CHF CannotCreateOrder = Commande ne peut pas \u00EAtre cr\u00E9\u00E9e. CannotSaveDocAlreadyExist = Ne peut pas \u00EAtre sauvegard\u00E9, {0} existe d\u00E9j\u00E0 Checklist = Checklist IBS ChecklistInstructionText = Le syst\u00E8me a \u00E9t\u00E9 remis \u00E0 l\u2019exploitant qui a re\u00E7u les instructions ainsi qu\u2019un manuel pour l\u2019op\u00E9rateur. ChecklistReadyText = Le syst\u00E8me est complet selon la commande et pr\u00EAt au fonctionnement. ChecklistSIAText = L'installation est conforme \u00E0 la norme SIA 343 (DIN 18650) ainsi que la norme de portes et portails No SN 12453. ChecklistStateText = Tous les \u00E9l\u00E9ments mont\u00E9s de l'installation sont en parfait \u00E9tat et ne repr\u00E9senten aucun dommage (couleur, verre, etc.). ChecklistTestText = L\u2019exploitant a \u00E9t\u00E9 instruit. Sinon: manuel pour l\u2019op\u00E9rateur sur l\u2019installation. La documentation AEAI sera envoy\u00E9e au commettant. ChecklistVKFText = L\u2019exploitant a \u00E9t\u00E9 instruit. Sinon: manuel pour l\u2019op\u00E9rateur sur l\u2019installation. La documentation AEAI sera envoy\u00E9e au commettant. ChooseForm = Formularauswahl Client = Client ClientNumber = no. de Client Contact = Contact Customer = Entrepreneur DeleteMeasurement = Efface le mesure? DeleteReport = Effacer rapport? DiscardMeasurement = Annuler le mesure? DoYouReallyWantToDeleteTheCompleteReport = Voulez-vous vraiment effacer le rapport complet?\nTemps de rapport saisis, mat\u00E9riel, signature etc. seront \u00E9galement effac\u00E9s. Document = Document DocumentReqired = Document {0} requis. DocumentsWillBeLost = Des documents sont supprim\u00E9s, voulez-vous continuer? Done = Achev\u00E9 E = E editInstallationType = Modifica tipo di impianto EstateManagement = Administration FormReqired = Formular {0} requis. Forms = Formulare GoodsIssue = Uscita merci GoodsReceipt = Ricevuta Merci Goodwill = \u00C0 bien plaire Guarantee = Livraison retour GuaranteeMaterial = Livraison Mat\u00E9riel GuaranteeTitle = Livraison retour ImageReqired = Image {0} requis. Important = Important JobFinishedSendReport = La commande est termin\u00E9e? Envoyer le rapport? K14Material = Mat\u00E9riel K Measurement = Mesure MeasurementComplete = Mesure: Saisie. MeasurementInComplete = Mesure incompl\u00E8te MeasurementMaximum = Au maximum 3 mesures possible. NoPhoneNumber = Pas de no. de t\u00E9l\u00E9phone Object = Objet Odered = Ordinato OrderNo = No. de commande OverwriteAnExistingMeasurement = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es et une nouvelle mesure est lanc\u00E9e. Continuer? Owner = Propri\u00E9taire Partner = Partner Planed = Planifi\u00E9 PleaseEnterATime = Veuillez enregistrer le temps Receiver = Destinataire de marchandise ReleaseDevice = Partager un appareil RescheduleJob = Replanifier l'ordre SAV = SAV SAVResponsible = Responsable SAV Service = Service Signature = Signature TheCapturedDataWillBeDeleted = Les donn\u00E9es enregistr\u00E9es sont effac\u00E9es. Continuer? TheFormIsDiscardedContinue = Das Formular wird verworfen. Fortfahren? TheSelectedArticleIsNotInMasterdata = L'articolo s\u00E9lectionn\u00E9s non esiste nei dati anagrafici. Si prega di contattare l'assistenza. TheSelectedItemIsNotInStockContinue = L'articolo s\u00E9lectionn\u00E9s non \u00E9 disponibile. Continua? UserName = MA-Name VC = VC WrongFormatXX-XXXX-XXX/XX = Format incorrect (XX-XXXX-XXX/XX). YouAreSingingNReport = Vous signez {0} rapports. aborted = annul\u00E9\u2026 absenceList = Message d'absence absenceNotification = Saisire l'absence absenceType = D\u00E9but de l'absence absences = Absences accept = Accepter active = Active add = Ajouter addition = Compl\u00E9ment additionalDelivery = Retour address = Adresse addressDoesNotExist = Pas trouv\u00E9 l'adresse {0}. addresses = Adresses agregatedSignature = Signature collective allowedTime = Temps pr\u00E9vu amount = Quantit\u00E9 appointment = D\u00E9lai appointmentDefined = D\u00E9lai fixe areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? areYouSureWantToDeleteRecord = Effacer l'enregistrement? artNo = No. d'article articleName = Nome dell'elemento articleNotINInventory = Articolo non in stock! articleNumber = codice articolo articleScan = Scansione dell'article back = Retour backOffice = Vente interne bemHistory = Remarque / Historique billing = Facturation camera = Camera cancel = Annuler captured = Saisie caseHandler = Responsable de projet change = Changement changeAddress = Changement d'adresse changesWillBeLost = Les changements sont rejett\u00E9s, continuer? charging = Facturation checkCycles = Cycles checkList = Check-list IBS city = Lieu clear = Remettre clock = Regarder codeReturnDelivery = Consegna del reso con codice collectiveSignature = Signature collective commNo = No. de comm. commNoCheck = V\u00E9rifiez No. de Commission commNotCorrect = No. de commission pas correcte? commissionNumber = No. de commission commissionNumberNotCorrectWillSaveEmptyString = Num\u00E9ro de commission incorrect (0XXXXXX-XX) completed = Compl\u00E9t\u00E9 configurations = Configurations confirm = Confirmer confirmation = Confirmation consequentialRepair = R\u00E9paration successive coordinateAppointment = Convenir le d\u00E9lai! correct = Correct correctCommissionNumber = Corrigez le num\u00E9ro de commission. correctInstallationType = Correcte d'installation costumerRemark = Remarque clients costumerReport = Rapport clients costumerService = SAV createJob = Cr\u00E9er un ordre createREPJob = Cr\u00E9er job REP customizeYourInfo = Personnalisez votre informations. cycleOfInstallation = Num\u00E9ro de cycle date = Date dateFrom = Date de dateTo = Date \u00E0 delete = Effacer deleteCompleteReport = EFFACER RAPPORT ENTIER deliverDate = data di consegna delivered = Posizione consegnata deliveredArticles = Consegnato department = D\u00E9pt. description = Description designation = Designation deviceMirroring = Appareil lib\u00E9r\u00E9 discardForm = Formular verwerfen? distance = Distance distancesBetween0To999kmAreAppropriate = Les distances entre 0 e 999km sont permises. doYouReallyWantToDeleteXShortMessagesAtOnce = Voulez-vous vraiment supprimer {0} Flashes d'informations \u00E0 la fois? doYouReallyWantToLoadXjobsAtOnce = Voulez-vous vraiment charger {0} emplois \u00E0 la fois? doYouWantToDeleteJob = Effacer la commande? doYouWantToDeleteThisSignature = Voulez-vous vraiment effacer la signature? doYouWantToGetOrder = T\u00E9l\u00E9charger la commande (MLDNR :{0})? done = Termin\u00E9 download = T\u00E9l\u00E9charger downloadOrder = T\u00E9l\u00E9charger la commande downloadOrder(SAP) = T\u00E9l\u00E9charger la commande (SAP) drive = Type entrainment duplicatedMaterialNumber = Article {0} d\u00E9j\u00E0 extistant {1} impossible d'ajouter. duration = Durata editReport = Editer le rapport editingInstallationType = Modifica il tipo di investimento email = Email employee = Employ\u00E9(e) employees = Employ\u00E9s endRepair = R\u00E9paration finale enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enterprise = Entreprise erase = Effacer error = Erreur errorCode = Code erreur errorMessages = Rapports de non-conformit\u00E9: ers = Rechange existingEntriesFromCannotAddEntryOn = Impossible pour {1} d''ajouter les enregistrements existants de {0} exists = Existant exit = Quitter exitServiceApplication = Quitter expenses = Frais explanationForReturn = Grund R\u00FCcklieferung external = Au client failure = D\u00E9faillance fax = Fax fileDeleted = Fichier supprim\u00E9. finalRepair = Raison du retour de livraison finalized = Fini finished = Termin\u00E9 firstName = Pr\u00E9nom followup = R\u00E9p. suivant forward = Transf\u00E9rer from = De fromImventory = Da magazzino gilgenCommonApplicationIsNotInstalled = L'application commune n'est pas install\u00E9e. C'est la raison pourquoi l'application service ne peut pas \u00E9tre d\u00E9marr\u00E9e. gilgenMaterialApplicationIsNotInstalled = L'application mat\u00E9riel n'est pas install\u00E9e! gilgenTimesheetApplicationIsNotInstalled = L'application Timesheet n'est pas install\u00E9e! governmentReport = Rapport des travaux en r\u00E9gie history = Historique hours = Heures hrs = Hrs. image = Image images = Images inProgress = En courant incidentA = D\u00E9faillance A incidentB = D\u00E9faillance B incomingArticle = Ricevuta Merci incomingArticleTitle = Ricevuta Merci incomingArticleWithoutListEntry = Prenota l'ingresso info = Info information = Information insertFixedMasterDataFile = Charger les donn\u00E9es de base (fichier) insertingMasterData = Ins\u00E9rer les donn\u00E9es de base ... installGilgenCommonApplicationFirst = S.v.p. installer premi\u00E9rement l'application commune de suite continuer l'installation et red\u00E9marrer Kolibri. installationError = Erreur d'installation installationState = condizione operativa internal = Interne interventionType = processo di follow-up invalid = Incorrect invalidBarcodeGuarantee = Code-barre invalide invalidCommissionNumber = No. de commission invalide invalidJobNumber = No. de commande invalide invalidKomNo = No. de commission incorrect inventoryInformations = Informazioni sulle scorte inventoryName = Nome del campo inventoryNumber = Numero di magazzino inventoryStock = Azione job = Commande job\# = Job # jobCannotBeDeletedPleaseSendBackOpenReports = Impossible d'effacer la commande s\u00E9lectionn\u00E9e. S.v.p. transmettre les rapports ouverts et temps. jobDeleted = Commande effac\u00E9e jobDetails = D\u00E9tails d'ordre jobEdit = Modification de rapport jobInfo = Info Job jobList = Liste Job jobNumber = Num\u00E9ro de commande jobState = \u00C9tat de commande jobTime = Temps de commande jobsSelected = {0} / {1} jobs s\u00E9lectionn\u00E9 lastName = Nom de famille link = Link listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible d'effacer le temps listOfEmployees = Liste des employ\u00E9s location = Installation maintenance = Service maintenanceCode = Code SAV maintenanceDone = Service ex\u00E9cut\u00E9 maintenanceMonths = Mois de service maintenancePlanned = SAV pr\u00E9vu masterDataSuccessfullyRefreshed = Donn\u00E9es de base actualis\u00E9es avec succ\u00E9s material = Mat\u00E9riel materialApp = App. Mat\u00E9riel materialName = D\u00E9signation d'article materialNumber = Num\u00E9ro d'article materialWasDeleted = \u00C9l\u00E9ment a \u00E9t\u00E9 supprim\u00E9. materialWithThisNameAlreadyExists = Mat\u00E9riel avec ce nom existe d\u00E9j\u00E0. materialWithThisNumberAlreadyExists = Mat\u00E9riel avec ce num\u00E9ro existe d\u00E9j\u00E0. maximumOfCheckdBoxesIs6 = Maximum de choix: 6 messageToChef = Message sup\u00E9rieur messageToCostumer = Message client messageToKDZ = Message KDZ messages = Communications month = Mois moreInformations = Erw. Komm. mtDone = SAV fini mtPlanned = SAV pr\u00E9vu name = D\u00E9signation nameOfInventory = Campo new = Nouveau newInventory = Nuovo magazzino newJob = Nouvel ordre newReport = Nouveau rapport newTimeEntryConfictsWithExistingOne = Nouveau enregistrement en collision avec l''enregistrement existant: {0} - {1} next = Continuer nextReport = Prochain rapport no = Nombre noAbsencesRecorded = Aucune absences enregistr\u00E9e noAppointmentKnown = Pas de d\u00E9lai noArticleFound = Nessun articolo trovato. noChecklistPresent = Manque la checklist, impossible de transmettre le rapport. noDataAvailable = Pas de donn\u00E9es disponibles noDataForOrderTypePleaseRefreshMasterdata = Pas de donn\u00E9es pour le type de commande, s.v.p. actualiser les donn\u00E9es de base. noDocumentPresent = Aucun document disponible, le rapport ne peut \u00EAtre envoy\u00E9 noEmployeeSelected = Aucun employ\u00E9 s\u00E9lectionn\u00E9. noFormDescImagePresent = document/image {0} n'existe pas. noFormDescPresent = Document {0} n'existe pas. noFormsRecorded = Aucune formulare enregistr\u00E9 noImagesEntriesReportCannotBeSent = Aucun image saisis, impossible de transmettre le rapport. noImagesRecorded = Aucun image enregistr\u00E9 noJobAvailable = Aucun travail disponible. noJobSelected = Aucune commande s\u00E9lectionn\u00E9! noMaterialPresent = Manque la mat\u00E9riel , impossible de transmettre le rapport. noMaterialRecorded = Aucun mat\u00E9riel enregistr\u00E9 noMaterialused = Aucun mat\u00E9riel utilis\u00E9. noMessagesRecorded = Aucun message enregistr\u00E9 noNumberToDialPleaseSelectJob. = Impossible de choisir. Veuillez s\u00E9lectionner une c noReasonSelected = Aucune justification n'est choisie noRecordsAvailable = Aucun temps saisie noReport = Aucun rapport noReportAvailable = Aucun rapport saisie noReportRecorded = Aucun rapport enregistr\u00E9 noShortMessageAvailable = Aucun message court disponible. noSignature = Aucune signature noSignatureCaptured = Aucune signature n'est saisie noSignaturePresent = Manque la signature, impossible de transmettre le rapport. noSignatureReasonSaved = Pas de signature: Basic d\u00E9tect\u00E9. noTimeEntrySelected = Aucun enregistrement n'est saisi noTimesRecorded = Aucune heure enregistr\u00E9e noTimesheetEntriesReportCannotBeSent = Aucun temps saisis, impossible de transmettre le rapport. noVonoviaFormPresent = Manque la formulare Vonovia, impossible de transmettre le rapport. normalMaterial = Mat\u00E9riel standard notAdded = non registrato notEdit = Pas \u00E9dit\u00E9 notImplementedYet = Pas encore impl\u00E9ment\u00E9. notPossible = Impossible notRecorded = Non enregistr\u00E9 notSend = Pas envoy\u00E9(e) number = Nombre of = de ok = OK onCall = Piquet open = Ouvert openMaintenance = SAV ouvert openPending = Affaire en suspens orderDate = Date de commande orderNo = No de commande orderPosition = Articolo dell'ordine orderType = Type de commande orderedArticles = In attesa di otherTypeOfMaterial = Material ungleich\u0009\u0009\u0009 outgoingArticle = Uscita merci\u0009\u0009 outgoingArticles = Uscita merci outgoingArticlesList = Azione partialRepair = R\u00E9paration partielle partiallySend = Partiellement envoy\u00E9(e) pdfFiles = PDF person = Responsable personalNumber = Num\u00E9ro personnel phone = T\u00E9l\u00E9phone planned = Pr\u00E9vu plannedJob = Travail pr\u00E9vu pleaseCompleteTheReport = Remplissez le rapport, s.v.p. pleaseEnterValidDate = Veuillez enregistrer un temps date pleaseEnterValidTime = Veuillez enregistrer un temps valide pleaseSelectValidTime = Veuillez s\u00E9lectionner une heure valide previous = Pr\u00E9c\u00E9dente previousReport = Rapport pr\u00E9c\u00E9dent price = Prix priority = Priorit\u00E9 progress = Progress projectLeader = Chef de projet reason = Raison reasonForDelete = Raison d'effacer reasonReturnDelivery = Motivo della restituzione reasongIncomingArticle = Giustificazione del ricevimento della merce receipt = Entr\u00E9e receive = T\u00E9l\u00E9charger receivedFrom = Re\u00E7u de refreshMasterData = Actualiser les donn\u00E9es de base refreshMasterData(SAP) = Actualiser les donn\u00E9es de base refreshingMasterData = Actualiser les donn\u00E9es de base ... refreshingMasterDataFailed = Actualisation des donn\u00E9es de base \u00E9chou\u00E9e! refreshingStock = Mise \u00E0 jour du stock releaseDevice = Partager un appareil remarks = Remarques report = Rapport report(s) = Rapport(s) de travai reportAbsence = D\u00E9poser l'absence reportCannotBeSent = Impossible de transmettre le rapport. reportData = Donn\u00E9es du rapport reportMessageToCustomer = Les commandes {0} doivent contenir un message du rapport destin\u00E9 au client. reportView = Vue du rapport reports = Rapports reschedule = Reprogrammer rideToSideNotCharged = Aucun d\u00E9placement ne sera factur\u00E9. salesPerson = Technico-commercial savc = Code de SAV save = Sauvegarder savingNotPossible = Impossible de m\u00E9moriser scan = Balayage search = Recherche searchJob = Recherche Job searchOrder(SAP) = Chercher la commande (SAP) secondVisitNeeded = 2\u00E8me utilisation n\u00E9cessaire. securityReport = Rapport de s\u00E9curit\u00E9 securityReportCreated = Rapport de s\u00E9curit\u00E9 \u00E9tabli securityReportFilledIn = Rapport de s\u00E9curit\u00E9 \u00E9tabli selectOneOrMoreJobs = S\u00E9lectionnez un ou plusieurs ordres. selectOneOrMoreShortMessages = S\u00E9lectionnez un ou plusieurs messages courts. send = Envoy\u00E9(e) sendAbsenceNotification = D\u00E9sirez-vous annoncer cette absence? Apr\u00E8s avoir envoy\u00E9 les messages, il n'est plus possible de les \u00E9diter. sendReport = Envoyer le rapport? sendReportTo = Envoyer le rapport \u00E0 sendingReport = Envoyer le rappor sent = envoy\u00E9 sentDate = Envoy\u00E9(e) servicePerformed = Accompli serviceRefused = Refus\u00E9 shortMessage = Flash d'information shortMessages = Flash d'informations showPlannedJobDialogText = L'ordre a une date d\u2019intervention planifi\u00E9e et est affich\u00E9 dans le filtre "Planifi\u00E9" apr\u00E8s confirmation. signatureAlreadySaved = Signature d\u00E9j\u00E0 m\u00E9moris\u00E9e signatureBelongsToJobsDoYouWanToDeleteIt = La signature collective appartient \u00E0 des commandes {0}. Effacer ? signatureBundle = Signature collective signatureCanNotBeLoadedFromFile = Impossible de charger la signature par le fichier. signatureCannotBeChanged = Impossible de modifier la signature collective, car au min. un rapport de la groupe a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9. signatureDeleted = Signature supprim\u00E9. signatureSaved = Signature m\u00E9moris\u00E9e spareParts = Pi\u00E8ces de rechange spareparts = Pi\u00E8ces de rechange start = D\u00E9marrage startGilgenService = D\u00E9marrage Gilgen Service state = \u00C9tat status = \u00C9tat stock = Nombre stop = Arr\u00E9t street = Rue streetOrNumber = Rue/No. summaryTotal = Totale synchronizingOrders = Synchroniser les ordres tel1 = T\u00E9l. 1 tel2 = T\u00E9l. 2 telWColon = T\u00E9l.: template = Soumission theSelectedMessageAreDeleted = Les messages s\u00E9lectionn\u00E9s sont supprim\u00E9s. thereAreTimeStampsWithoutWorkType = Il y a encore de temps sans mode de travail, s.v.p corriger. time = Temps timeFrom = \u00E0 timeNotStopped = Le temps n'est pas arr\u00E9t\u00E9 timeSheet = Saisie du temps timeStopped = Le temps est arr\u00E9t\u00E9 timeTo = jusqu'\u00E0 times = Temps timesBelongToDifferentDays = Les temps font partie de diff\u00E9rents jours. timesheetApp = Timesheet App title = Titre to = de tooManyMeasurements = Trop de mesurages disponibles en un seuil point de mesurage. total = Total transit = Transit typeOfJob = Type de commande typeOfMaterial = Type de mat\u00E9riel typeOfWork = Type de travail unit = Unit\u00E9 unknown = Inconnu userList = Liste d'employ\u00E9s valid = Correct valid_guarantee_label = Cette installation poss\u00E8de une identification de garantie valable. Veuillez s.v.p. prendre une d\u00E9cision. vehicleInventory = Magazzino veicoli warning = Avertissement! way = Mani\u00E8re week = Semaine workType = Mode de travail wrongComm = Mauvais no. de comm. wrongFormArgument = Param\u00E8tre de remise de la forme incorrect year = Ann\u00E9e yes = Oui youAreSigning = Vous signez youCanSelectMaximumOf30Jobs = Vous pouvez s\u00E9lectionner un maximum de 30 emplois. zip = NPA zipCity = NPA / Lieu     service/i18n/ch/mfiles/kaba/kolibri/service/ServiceMessages.java:   package ch.mfiles.kaba.kolibri.service; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class ServiceMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.service.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private ServiceMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static String getString(Locale locale, String key) { try { ResourceBundle resourceBundleLocale = ResourceBundle .getBundle(BUNDLE_NAME, locale); return resourceBundleLocale.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }     service/project.properties:   # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23     service/report.html:  
Kontakt Anrufen
Gruppe
Telefon-Nr.
Firma
Name Vorname
Name Vorname
Firma
Gruppe
Telefon-Nr.
    service/sonar.xml:       service/src/ch/mfiles/kaba/kolibri/service/forms/AbsenceNotificationListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceNotification; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceType; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class AbsenceNotificationListForm extends SuperForm { private static Log log = LogFactory.getLog(AbsenceNotificationListForm.class); protected Job job; private Toolbar toolbar; protected DetailListWidget listWidget; private ActionCtrl addButton; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { // if (argument != null) { // if (argument instanceof AbsenceNotificationListFormArguments) { // AbsenceNotificationListFormArguments formArguments = (AbsenceNotificationListFormArguments) argument; // job = formArguments.getJob(); // } else { // log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ // throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ // } // } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new DetailListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noAbsencesRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("absences")); //$NON-NLS-1$ loadImageAttachmentsList(); return null; } private void loadImageAttachmentsList() { listWidget.clean(); List absenceNotificationList = app.dbutil.selectAbsencesNotificationList(); view.removeAllViews(); if(absenceNotificationList.isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); for (AbsenceNotification absenceNotification : absenceNotificationList) { final DetailListWidgetItem item = new DetailListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); String title = "-"; String line1 = "-"; String line2 = ""; AbsenceType absenceType = app.dbutil.selectAbsenceType(absenceNotification.getAbsenceType()); if (absenceType != null && !absenceType.getAbsenceType().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { title = absenceType.getText(); } line1 = DateTimeUtil.showDate(absenceNotification.getDateFrom()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(absenceNotification.getTimeFrom()) + " to " //$NON-NLS-1$ + DateTimeUtil.showDate(absenceNotification.getDateTo()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(absenceNotification.getTimeTo()); line2 = absenceNotification.getText(); item.setTitleText(title); item.setStringLine1(line1); item.setStringLine2(line2); items.add(item); } listWidget.setOnItemClickListener(createOnItemClickListener(absenceNotificationList)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List absenceNotificationList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { app.injectAndLeaveToForm(AbsenceNotificationNewEditForm.class, new AbsenceNotificationNewEditForm.AbsenceNotificationNewEditFormArguments(absenceNotificationList.get(position))); //$NON-NLS-1$ } }; } protected ApplicationEvent onAddPressed() { return app.leaveToForm(AbsenceNotificationNewEditForm.class, new AbsenceNotificationNewEditForm.AbsenceNotificationNewEditFormArguments(null)); } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/AbsenceNotificationNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.content.DialogInterface.OnDismissListener; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceNotification; import ch.mfiles.kaba.kolibri.common.businessobjects.AbsenceType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; public class AbsenceNotificationNewEditForm extends DialogForm { private static Log log = LogFactory.getLog(AbsenceNotificationNewEditForm.class); // initialized by the kolibri framework... public static ServiceApplication app; protected ActionCtrl sendButton; private AbsenceNotification absenceNotification; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil actionUtil; private MDSpinner absenceTypeValue; private MDSpinner dateFromValue; private TimeEditText fromText; private MDSpinner dateToValue; private TimeEditText toText; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.EIGHTY_TWO; private Button deleteButton; private boolean isExistTime; private String defaultTime = "00:00"; @Override public void onFormCall(Object argument) { if (argument instanceof AbsenceNotificationNewEditFormArguments) { AbsenceNotificationNewEditFormArguments formArguments = (AbsenceNotificationNewEditFormArguments) argument; absenceNotification = formArguments.getAbsenceNotification(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; actionUtil = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); sendButton = addActionCtrl(false, true, 2, "onSendPressed"); //$NON-NLS-1$ sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout fromLinearLayout = new LinearLayout(context); fromLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; fromLinearLayout.setLayoutParams(leftIconLinearLayoutParams); final LinearLayout formDateLinearLayout = new LinearLayout(context); formDateLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams formDateValueParams = new LinearLayout.LayoutParams(0, 0); formDateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; formDateValueParams.width = 0; formDateValueParams.height = LayoutParams.MATCH_PARENT; formDateValueParams.weight = 0.5f; formDateLinearLayout.setLayoutParams(formDateValueParams); // date dateFromValue = MDSpinner.createDefaultSpinner(formDateLinearLayout, ServiceMessages.getString("dateFrom"), true); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) dateFromValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateFromValue.getUnderline().setLayoutParams(underlineLinearLayout); fromLinearLayout.addView(formDateLinearLayout); dateFromValue.setFocusable(false); dateFromValue.setFocusableInTouchMode(false); dateFromValue.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { showDatePickerDialog(dateFromValue); return true; } }); fromText = TimeEditText.createDefaultEditText(fromLinearLayout,ServiceMessages.getString("timeFrom"), true); //$NON-NLS-1$ LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; fromText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); contentLinearLayout.addView(fromLinearLayout); LinearLayout toLinearLayout = new LinearLayout(context); toLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams toLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); toLinearLayoutParams.gravity = Gravity.CENTER; toLinearLayoutParams.width = LayoutParams.MATCH_PARENT; toLinearLayoutParams.weight = 1; toLinearLayout.setLayoutParams(toLinearLayoutParams); final LinearLayout toDateLinearLayout = new LinearLayout(context); toDateLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams toDateValueParams = new LinearLayout.LayoutParams(0, 0); toDateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; toDateValueParams.width = 0; toDateValueParams.height = LayoutParams.MATCH_PARENT; toDateValueParams.weight = 0.5f; toDateLinearLayout.setLayoutParams(toDateValueParams); // date dateToValue = MDSpinner.createDefaultSpinner(toDateLinearLayout, ServiceMessages.getString("dateTo"), true); //$NON-NLS-1$ dateToValue.setTag("DATUM"); //$NON-NLS-1$ LinearLayout.LayoutParams dateToLinearLayout = (LinearLayout.LayoutParams) dateToValue.getUnderline().getLayoutParams(); dateToLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateToValue.getUnderline().setLayoutParams(dateToLinearLayout); toLinearLayout.addView(toDateLinearLayout); dateToValue.setFocusable(false); dateToValue.setFocusableInTouchMode(false); dateToValue.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { showDatePickerDialog(dateToValue); return true; } }); toText = TimeEditText.createDefaultEditText(toLinearLayout, ServiceMessages.getString("timeTo"), true); //$NON-NLS-1$ toText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); LinearLayout.LayoutParams toInputLayoutParams = new LinearLayout.LayoutParams(0, 0); toInputLayoutParams.gravity = Gravity.CENTER; toInputLayoutParams.width = 0; toInputLayoutParams.height = LayoutParams.MATCH_PARENT; toInputLayoutParams.weight = 0.5f; toText.getParentTextInputLayout().setLayoutParams(toInputLayoutParams); contentLinearLayout.addView(toLinearLayout); LinearLayout absenceTypeLinearLayout = new LinearLayout(context); absenceTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); absenceTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // work type absenceTypeValue = MDSpinner.createDefaultSpinner(absenceTypeLinearLayout, ServiceMessages.getString("absenceType"), true); //$NON-NLS-1$ absenceTypeValue.setTag("ARBEITSART"); //$NON-NLS-1$ absenceTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (position != 0) absenceTypeValue.clearError(); } }); contentLinearLayout.addView(absenceTypeLinearLayout); messages = MDEditText.createDefaultEditText(contentLinearLayout, "description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } private void showDatePickerDialog(final MDSpinner dateValue) { Calendar calendar = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDate(dateValue, year, monthOfYear, dayOfMonth); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.setButton(android.content.DialogInterface.BUTTON_NEGATIVE, ServiceMessages.getString("cancel"), new android.content.DialogInterface.OnClickListener() { //$NON-NLS-1$ @Override public void onClick(android.content.DialogInterface dialog, int which) { if (which == android.content.DialogInterface.BUTTON_NEGATIVE) { dateValue.setEnabled(true); dialog.dismiss(); } } }); datePickerDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(android.content.DialogInterface dialog) { dateValue.setEnabled(true); } }); datePickerDialog.show(); dateValue.setEnabled(false); } private void setDate(MDSpinner dateValue, int year, int monthOfYear, int dayOfMonth) { Calendar calendar = DateTimeUtil.getToday(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); List dateTypeValueList = new ArrayList(); String date = DateTimeUtil.showDate(calendar.getTime()); dateTypeValueList.add(new CustomSpinnerItem(date, date)); dateValue.setContents(dateTypeValueList); // if (absenceNotification == null) { dateValue.setEnabled(true); // } } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("absenceNotification")); //$NON-NLS-1$ resetView(); List absenceTypeValueList = new ArrayList(); List absenceTypes = app.dbutil.selectAbsenceTypeList(); for (AbsenceType absenceType : absenceTypes) { absenceTypeValueList.add(new CustomSpinnerItem((String) absenceType.getAbsenceType(), (String) absenceType.getText())); } absenceTypeValue.setContents(absenceTypeValueList); messages.getText().clear(); Calendar calendar = Calendar.getInstance(); if (absenceNotification == null) { setEnabled(true); setDate(dateFromValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); setDate(dateToValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } else { calendar.setTime(absenceNotification.getDateFrom()); setDate(dateFromValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(absenceNotification.getDateTo()); setDate(dateToValue, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); setEnabled(false); fromText.setText(DateTimeUtil.showTimeGMT(absenceNotification.getTimeFrom())); fromText.clearFocus(); toText.setText(DateTimeUtil.showTimeGMT(absenceNotification.getTimeTo())); toText.clearFocus(); absenceTypeValue.setSelectionById(absenceNotification.getAbsenceType()); messages.setText(absenceNotification.getText()); } return null; } private void setEnabled(boolean enabled) { sendButton.setEnabled(enabled); Images sendImage = ImagesUtil.Images.SEND_DISABLED_WHITE; if (enabled) { sendImage = ImagesUtil.Images.SEND_WHITE; } sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(sendImage, CommonConstants.Images.IMAGE_DPI))); dateFromValue.setEnabled(enabled); fromText.setEnabled(enabled); dateToValue.setEnabled(enabled); toText.setEnabled(enabled); absenceTypeValue.setEnabled(enabled); messages.setEnabled(enabled); } private void resetView() { absenceTypeValue.clearError(); absenceTypeValue.setSelection(0); dateFromValue.clearError(); fromText.clearError(); fromText.getText().clear(); dateToValue.clearError(); toText.clearError(); toText.getText().clear(); messages.clearError(); messages.getText().clear(); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(AbsenceNotificationListForm.class); } public ApplicationEvent onSendPressed() { boolean error = false; final Date dateFrom = DateTimeUtil.parseDateFromddMMyyyy(dateFromValue.getSelectedName()); final Date timeFrom = DateTimeUtil.parseDateFromHHmm(fromText.getText().toString(), dateFrom); final Date dateTo = DateTimeUtil.parseDateFromddMMyyyy(dateToValue.getSelectedName()); final Date timeTo = DateTimeUtil.parseDateFromHHmm(toText.getText().toString(), dateTo); if (dateFrom == null) { dateFromValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); error = true; } if (dateTo == null) { dateToValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); error = true; } if (timeFrom == null) { fromText.setError(ServiceMessages.getString("pleaseEnterValidTime")); error = true; } if (timeTo == null) { toText.setError(ServiceMessages.getString("pleaseEnterValidTime")); error = true; } if (dateTo.before(dateFrom)) { dateToValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); error = true; } if (timeTo != null && ((timeFrom != null && timeTo.before(timeFrom)) || timeTo.before(dateFrom))) { toText.setError(ServiceMessages.getString("pleaseEnterValidTime")); error = true; } if(absenceTypeValue.isRequired() && absenceTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { absenceTypeValue.setError(Messages.getString("pleaseSelectValue")); error = true; } if (error) { return null; } KeyboardUtil.closeKeyboard(appman, getView()); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("sendAbsenceNotification"), ServiceMessages.getString("reportAbsence"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } AbsenceNotification absenceNotification = new AbsenceNotification(); try { GuidGenerator guidGenerator = new GuidGenerator(); absenceNotification.setGuid(guidGenerator.generate()); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } absenceNotification.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); absenceNotification.setAbsenceDate(DateTimeUtil.getNow().getTime()); absenceNotification.setDateFrom(dateFrom); absenceNotification.setTimeFrom(timeFrom); absenceNotification.setDateTo(dateTo); absenceNotification.setTimeTo(timeTo); absenceNotification.setAbsenceType(absenceTypeValue.getSelectedId()); absenceNotification.setText(messages.getText().toString()); app.dbutil.insertAbsenceNotification(absenceNotification); new RemoteTransactionHandler().runSaveAbsence(absenceNotification.getAbsenceDate(), absenceNotification.getPersonalNumber(), absenceNotification.getGuId()); return app.leaveToForm(AbsenceNotificationListForm.class); } }, false); return null; } public static class AbsenceNotificationNewEditFormArguments { private AbsenceNotification absenceNotification; public AbsenceNotificationNewEditFormArguments(AbsenceNotification absenceNotification) { this.absenceNotification = absenceNotification; } public AbsenceNotification getAbsenceNotification() { return absenceNotification; } public void setAbsenceNotification(AbsenceNotification absenceNotification) { this.absenceNotification = absenceNotification; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/AddressEditSuperForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ui.LayoutInflater; public class AddressEditSuperForm extends SuperForm implements TextWatcher { private static Log log = LogFactory.getLog(AddressEditSuperForm.class); protected Job job; protected LinearLayout linearLayout; protected LinearLayout emailLinearLayout; protected MDEditText location; protected MDEditText street; protected MDEditText zip; protected MDEditText city; protected MDEditText tel1; protected MDEditText tel2; protected MDEditText fax; protected MDEditText email; protected List emailTextList; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArguments = (JobDetailFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); // Location location = MDEditText.createDefaultEditText(linearLayout, Messages.getString("location"),InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ location.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); // Str./No. street = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("street"),InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ street.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.SIXTY)}); // ZIP zip = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("zip"),InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ zip.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE)}); // City city = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("city"),InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ city.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); // Tel. 1 tel1 = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("tel1"),InputType.TYPE_CLASS_PHONE, false, this); //$NON-NLS-1$ tel1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY)}); // Tel. 2 tel2 = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("tel2"),InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ tel2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY)}); // Fax fax = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("fax"),InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ fax.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY)}); // Email email = MDEditText.createDefaultEditText(linearLayout, ServiceMessages.getString("email"),InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS, false); //$NON-NLS-1$ email.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus && !isEmailValid(email)) { email.setSelected(true); app.showWarningMessageBox(CommonConstants.Regex.EMAIL_VALIDATION_MSG); } } }); emailLinearLayout = new LinearLayout(context); emailLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); emailLinearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(emailLinearLayout); return view; } public void generateEmailContete(int emailSize) { emailTextList.clear(); emailLinearLayout.removeAllViews(); for (int i = 0; i < emailSize; i++) { MDEditText emailText = MDEditText.createDefaultEditText(emailLinearLayout, ServiceMessages.getString("email") + " " + (i+2) ,InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS, false); //$NON-NLS-1$ emailText.setEnabled(false); emailTextList.add(emailText); } } @Override public ApplicationEvent onFormShow() { super.onFormShow(); emailTextList = new ArrayList(); loadData(); return null; } /** * Loads data. */ public void loadData() { //Loads data. } @Override public void onFormReset() { super.onFormReset(); location.getText().clear(); street.getText().clear(); zip.getText().clear(); city.getText().clear(); tel1.getText().clear(); tel2.getText().clear(); fax.getText().clear(); email.getText().clear(); emailTextList.clear(); } @Override public ApplicationEvent onBackPressed() { return appman.getActiveApplication().leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 1)); } @Override protected boolean isValid() { boolean result = true; String errorMessage = Messages.getString("pleaseProvideValue"); //$NON-NLS-1$ if (street.isRequired() && street.getText().toString().trim().isEmpty()) { street.setError(errorMessage); result = false; } if (zip.isRequired() && zip.getText().toString().trim().isEmpty()) { zip.setError(errorMessage); result = false; } if (city.isRequired() && city.getText().toString().trim().isEmpty()) { city.setError(errorMessage); result = false; } if (tel1.isRequired() && tel1.getText().toString().trim().isEmpty()) { tel1.setError(errorMessage); result = false; } if (!email.getText().toString().trim().isEmpty() && !isEmailValid(email)) { result = false; } for (MDEditText editText : emailTextList) { editText.getText().clear(); if (!editText.getText().toString().trim().isEmpty() && !isEmailValid(editText)) { result = false; } } // success return result; } private boolean isEmailValid(MDEditText email) { if (!email.getText().toString().trim().isEmpty()) { Pattern pattern = Pattern.compile(CommonConstants.Regex.EMAIL_VALIDATOR); Matcher matcher = pattern.matcher(email.getText().toString()); if(!matcher.matches()) { email.setError(CommonConstants.Regex.EMAIL_VALIDATION_MSG); return false; } } return true; } @Override public void afterTextChanged(Editable s) { // Do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(street.hasFocus()) street.clearError(); if(zip.hasFocus()) zip.clearError(); if(city.hasFocus()) city.clearError(); if(tel1.hasFocus()) tel1.clearError(); } @Override public void clearErrorMessages() { super.clearErrorMessages(); street.clearError(); zip.clearError(); city.clearError(); tel1.clearError(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ArticleDetailForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.types.DeliveryStatus; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ArticleListForm.ArticleListFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ArticleDetailForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(ArticleDetailForm.class); public static ServiceApplication app; // don't make this CommonApplication public LinearLayout contentLinearLayout; public MDEditText orderNumberEditText; public MDEditText orderPositionEditText; public AmountEditText amountEditText; public MDEditText unitEditText; public MDEditText stockEditText; public MDEditText priceEditText; public MDEditText deliverDateEditText; public MDEditText deliverEditText; private Article article; private DeliveryList deliveryList; private MaterialMovement materialMovement; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleDetailFormArguments) { ArticleDetailFormArguments formArguments = (ArticleDetailFormArguments) argument; deliveryList = formArguments.getArticle(); materialMovement = formArguments.getMaterialMovement(); article = new Article(formArguments.getMaterialMovement(), formArguments.getArticle()); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); getToolbar().setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } else { loadMaterialsList(numberEditText.getText().toString()); // if(searchView.isMaterialSelected() && selectedMaterial != null || selectedMaterialPerson != null) { //// hideSoftInputFromWindow(); // // } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); } else { nameEditText.clearError(); } } }); contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout orderLinearLayout = new LinearLayout(context); orderLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); orderLinearLayout.setOrientation(LinearLayout.HORIZONTAL); orderNumberEditText = MDEditText.createDefaultEditText(orderLinearLayout, ServiceMessages.getString("orderNo"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ orderNumberEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout.LayoutParams orderNumberInputLayoutParams = new LinearLayout.LayoutParams(0, 0); orderNumberInputLayoutParams.gravity = Gravity.CENTER; orderNumberInputLayoutParams.width = 0; orderNumberInputLayoutParams.height = LayoutParams.MATCH_PARENT; orderNumberInputLayoutParams.weight = 0.3f; orderNumberEditText.getParentTextInputLayout().setLayoutParams(orderNumberInputLayoutParams); orderPositionEditText = MDEditText.createDefaultEditText(orderLinearLayout, ServiceMessages.getString("orderPosition"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ orderPositionEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout.LayoutParams orderPositionInputLayoutParams = new LinearLayout.LayoutParams(0, 0); orderPositionInputLayoutParams.gravity = Gravity.CENTER; orderPositionInputLayoutParams.width = 0; orderPositionInputLayoutParams.height = LayoutParams.MATCH_PARENT; orderPositionInputLayoutParams.weight = 0.3f; orderPositionEditText.getParentTextInputLayout().setLayoutParams(orderPositionInputLayoutParams); contentLinearLayout.addView(orderLinearLayout); LinearLayout detailLinearLayout = new LinearLayout(context); detailLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); detailLinearLayout.setOrientation(LinearLayout.HORIZONTAL); amountEditText = AmountEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("amount"), true); //$NON-NLS-1$ amountEditText.setTag("AMOUNT"); //$NON-NLS-1$ amountEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SEVEN) }); LinearLayout.LayoutParams amountInputLayoutParams = new LinearLayout.LayoutParams(0, 0); amountInputLayoutParams.gravity = Gravity.CENTER; amountInputLayoutParams.width = 0; amountInputLayoutParams.height = LayoutParams.MATCH_PARENT; amountInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(amountInputLayoutParams); // Unit unitEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("unit"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ unitEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); unitEditText.setTag("UNIT"); //$NON-NLS-1$ unitEditText.setEnabled(false); LinearLayout.LayoutParams unitInputLayoutParams = new LinearLayout.LayoutParams(0, 0); unitInputLayoutParams.gravity = Gravity.LEFT; unitInputLayoutParams.width = 0; unitInputLayoutParams.height = LayoutParams.MATCH_PARENT; unitInputLayoutParams.weight = 0.2f; unitEditText.getParentTextInputLayout().setLayoutParams(unitInputLayoutParams); stockEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("duration"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ stockEditText.setTag("STOCK"); //$NON-NLS-1$ stockEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); stockEditText.setEnabled(false); LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.LEFT; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; stockEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); priceEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("price"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ priceEditText.setTag("PRICE"); //$NON-NLS-1$ priceEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT) }); priceEditText.setEnabled(false); priceEditText.setDirectionRight(true); LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); priceInputLayoutParams.gravity = Gravity.CENTER; priceInputLayoutParams.width = 0; priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; priceInputLayoutParams.weight = 0.2f; priceEditText.getParentTextInputLayout().setLayoutParams(priceInputLayoutParams); contentLinearLayout.addView(detailLinearLayout); LinearLayout deliverLinearLayout = new LinearLayout(context); deliverLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deliverLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deliverDateEditText = MDEditText.createDefaultEditText(deliverLinearLayout, ServiceMessages.getString("deliverDate"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ deliverDateEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.ELEVEN) }); LinearLayout.LayoutParams deliverDateInputLayoutParams = new LinearLayout.LayoutParams(0, 0); deliverDateInputLayoutParams.gravity = Gravity.CENTER; deliverDateInputLayoutParams.width = 0; deliverDateInputLayoutParams.height = LayoutParams.MATCH_PARENT; deliverDateInputLayoutParams.weight = 0.15f; deliverDateEditText.getParentTextInputLayout().setLayoutParams(deliverDateInputLayoutParams); deliverEditText = MDEditText.createDefaultEditText(deliverLinearLayout, ServiceMessages.getString("delivered"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, true); //$NON-NLS-1$ deliverEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SEVEN) }); LinearLayout.LayoutParams deliverInputLayoutParams = new LinearLayout.LayoutParams(0, 0); deliverInputLayoutParams.gravity = Gravity.CENTER; deliverInputLayoutParams.width = 0; deliverInputLayoutParams.height = LayoutParams.MATCH_PARENT; deliverInputLayoutParams.weight = 0.15f; deliverEditText.getParentTextInputLayout().setLayoutParams(deliverInputLayoutParams); contentLinearLayout.addView(deliverLinearLayout); addContentLinearLayout(contentLinearLayout); nameEditText.setEnabled(false); numberEditText.setEnabled(false); orderNumberEditText.setEnabled(false); orderPositionEditText.setEnabled(false); amountEditText.setEnabled(false); deliverDateEditText.setEnabled(false); searchView.setVisibility(View.INVISIBLE); // searchView.setOnSearchClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // saveButton.setVisible(false); // } // }); // searchView.setOnCloseListener(new OnCloseListener() { // // @Override // public boolean onClose() { // saveButton.setVisible(true); // return false; // } // }); saveButton.setTitle(ServiceMessages.getString("save")); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); resetView(); setShowScanNumber(false); if (deliveryList != null) { // Article list setEnableSaveButton(false); // amountEditText.setEnabled(true); // Active: Only if ZKDMOBFZGDELVRY.LGORT_TO = and, if delivered, ZKDMOBFZGDELVRY.KNZDLVRY = T, G log.info("delivery to " + article.getTo() + " deliver status " + article.getStatus().getCode()); if (article.getTo().equalsIgnoreCase(app.dbutil.getUser().getWarehouseNumber()) && (article.getStatus().isPART_DELIVERED() || article.getStatus().isDELIVERED())) { setEnableSaveButton(true); } } else { // push message //Active and shown: Only if ZKDMOBFZGMBEW.GUID = if(article.getGuid().isEmpty()) { getToolbar().setNavigationIcon(getBitmanDrawable(app.imagesUtil.getImage(Images.BACK_WHITE_DISABLED, CommonConstants.Images.IMAGE_DPI))); } else { getToolbar().setNavigationIcon(getBitmanDrawable(app.imagesUtil.getImage(Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI))); } } setFormTitle(ServiceMessages.getString("incomingArticleTitle")); nameEditText.setRequired(false); numberEditText.setRequired(false); nameEditText.getParentTextInputLayout().setHint(ServiceMessages.getString("articleName")); numberEditText.getParentTextInputLayout().setHint(ServiceMessages.getString("articleNumber")); deliverEditText.setRequired(false); deliverEditText.setEnabled(false); log.info("article from " + article.getWarehouse() + " status " + article.getStatus().getCode()); if (article.getWarehouse().equalsIgnoreCase("HLG") && !article.getStatus().isINITIAL()) { //Active: Only if ZKDMOBFZGDELVRY.LGKNZ = HLG and ZKDMOBFZGDELVRY.KNZDLVRY = O, T or G deliverEditText.setEnabled(true); deliverEditText.setRequired(true); } log.info("article OrderNumber " + article.getOrderNumber()); log.info("article Position " + article.getOrderPosition()); nameEditText.setText(article.getMaterialName()); numberEditText.setText(article.getMaterialNumber()); orderNumberEditText.setText(article.getOrderNumber()); orderPositionEditText.setText(article.getOrderPosition() + ""); log.info("EntryCount " + article.getEntryCount()); amountEditText.setText(article.getEntryCount()); unitEditText.setText(article.getEntryUnit()); VehicleInventory vehicleInventory = app.dbutil.selectVehicleInventoryByMatNr(article.getMaterialNumber()); stockEditText.setText(vehicleInventory == null ? "":vehicleInventory.getStockOfMaterial()); deliverDateEditText.setText(DateTimeUtil.showDate(article.getDate())); deliverEditText.setText(article.getEntryCount()); deliverEditText.setEnabled(true); Material material = app.dbutil.selectMaterialByMatNo(article.getMaterialNumber()); if (material != null) { priceEditText.setText(material.getNewPrice()); } return null; } @Override protected void resetView() { super.resetView(); orderNumberEditText.clearError(); orderNumberEditText.getText().clear(); orderPositionEditText.clearError(); orderPositionEditText.getText().clear(); priceEditText.clearError(); amountEditText.clearError(); stockEditText.clearError(); unitEditText.clearError(); priceEditText.getText().clear(); amountEditText.getText().clear(); stockEditText.getText().clear(); unitEditText.getText().clear(); deliverEditText.clearError(); deliverEditText.getText().clear(); } @Override public ApplicationEvent onBackPressed() { if(deliveryList == null) { return null; } return app.leaveToForm(ArticleListForm.class); } @Override protected ApplicationEvent onSavePressed() { KeyboardUtil.closeKeyboard(appman, getView()); if (isValid()) { onSave(); } return null; } protected boolean isValid() { boolean result = true; return result; } @Override protected boolean onSave() { setEnableSaveButton(false); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (materialMovement == null) { materialMovement = new MaterialMovement(); materialMovement.setGuid(article.getGuid()); materialMovement.setOrderNumber(article.getOrderNumber()); materialMovement.setOrderPosition(article.getOrderPosition()); } int pernr = app.dbutil.getUser().getPersonalNumber(); materialMovement.setPersonalNumber(pernr); materialMovement.setPersonalNumberConfirmed(pernr); materialMovement.setMaterialNumber(numberEditText.getText().toString()); materialMovement.setEntryUnit(unitEditText.getText().toString()); materialMovement.setEntryCount(deliverEditText.getText().toString()); if(new RemoteTransactionHandler().runConfirmMaterialMoveMent(materialMovement)) { if(new RemoteTransactionHandler().runGetDeliveryList(pernr, monitor)) { // has been deleted after confirm } } return null; } @Override protected void runOnUIThread() { // need to wait until transaction success (data in table delayed) DeliveryList selectedArticle = app.dbutil.selectArticleByMatnr(article.getOrderNumber(), article.getMaterialNumber()); if (selectedArticle != null && !selectedArticle.getEntryCount().equalsIgnoreCase(materialMovement.getEntryCount())) { selectedArticle.setEntryCount(materialMovement.getEntryCount()); app.dbutil.updateArticleEntryCount(selectedArticle.getOrderNumber(), selectedArticle.getMaterialNumber(), selectedArticle.getEntryCount()); } app.injectAndLeaveToForm(ArticleListForm.class, new ArticleListFormArgument()); } }; return false; } public static class ArticleDetailFormArguments { private DeliveryList article; private MaterialMovement materialMovement; public ArticleDetailFormArguments(DeliveryList article) { this.article = article; } public ArticleDetailFormArguments(MaterialMovement materialMovement) { this.materialMovement = materialMovement; } public DeliveryList getArticle() { return this.article; } public MaterialMovement getMaterialMovement() { return this.materialMovement; } } private class Article { private MaterialMovement materialMovement; private DeliveryList deliveryList; private Material material; Article(MaterialMovement materialMovement, DeliveryList deliveryList) { this.materialMovement = materialMovement; this.deliveryList = deliveryList; if (materialMovement != null) { material = app.dbutil.selectMaterialByMatNo(materialMovement.getMaterialNumber()); } } public String getGuid() { return materialMovement != null ? materialMovement.getGuid():deliveryList.getGuid(); } public String getOrderNumber() { return materialMovement != null ? materialMovement.getOrderNumber():deliveryList.getOrderNumber(); } public int getOrderPosition() { return materialMovement != null ? materialMovement.getOrderPosition() : deliveryList.getOrderPosition(); } public int getPersonalNumber() { return materialMovement != null ? materialMovement.getPersonalNumber():deliveryList.getPersonalNumber(); } public String getMaterialNumber() { return materialMovement != null ? materialMovement.getMaterialNumber():deliveryList.getMaterialNumber(); } public String getMaterialName() { return materialMovement != null ? material.getMaterialShortText():deliveryList.getMaterialName(); } public String getFrom() { return materialMovement != null ? materialMovement.getFrom():deliveryList.getFrom(); } public String getTo() { return materialMovement != null ? materialMovement.getTo():deliveryList.getTo(); } public Date getDate() { return materialMovement != null ? new Date():deliveryList.getDate(); } public String getEntryCount() { return materialMovement != null ? materialMovement.getEntryCount():deliveryList.getEntryCount(); } public String getEntryUnit() { return materialMovement != null ? materialMovement.getEntryUnit():deliveryList.getEntryUnit(); } public DeliveryStatus getStatus() { return materialMovement != null ? new DeliveryStatus():deliveryList.getStatus(); } public String getWarehouse() { return materialMovement != null ? "":deliveryList.getWarehouse(); } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ArticleIncomningForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.ReceiptOfGoods; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDAutoComplete; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ArticleIncomningForm extends ArticleSearchForm { private static Log log = LogFactory.getLog(ArticleIncomningForm.class); public static ServiceApplication app; public MDSpinner reasonValue; public MDAutoComplete fromInventoryAutoComplete; private Material selectedMaterial; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleIncomingFormFormArguments) { ArticleIncomingFormFormArguments formArguments = (ArticleIncomingFormFormArguments) argument; } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); reasonValue = MDSpinner.createDefaultSpinner(contentLinearLayout, ServiceMessages.getString("reasongIncomingArticle"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { reasonValue.clearError(); } }); fromInventoryAutoComplete = MDAutoComplete.createDefaultAutoCompleteText(contentLinearLayout, ServiceMessages.getString("fromImventory"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true); fromInventoryAutoComplete.setTag("INVENTORY"); //$NON-NLS-1$ return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("incomingArticleWithoutListEntry")); loadData(); return null; } @Override public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(queryText, queryText); for (Material matPart : materialList) { searchView.getSuggessionItemList().add(new SuggessionItem(matPart.getMaterialNumber(), matPart.getMaterialShortText())); } stockEditText.setText("0"); if (materialList.size() > 0 && materialList.size() == 1) { // Exactly found an article from the StammMat if (materialList.size() == 1) { selectedMaterial = materialList.get(0); } } if (selectedMaterial != null) { unitEditText.setText(selectedMaterial.getUnit()); List vehicleInventories = app.dbutil.selectVehicleInventoryListByMatNrAndMatName(selectedMaterial.getMaterialNumber(), selectedMaterial.getMaterialShortText()); if (vehicleInventories.size() > 0) { VehicleInventory vehicleInventory = vehicleInventories.get(0); stockEditText.setText(vehicleInventory.getStockOfMaterial()); } priceEditText.setText(selectedMaterial.getNewPrice()); // sizeEditText.setText(selectedMaterial.getSize()); // expressCheckBox.setChecked(false); saveButton.setVisible(true); } } @Override protected void loadData() { super.loadData(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); fillResonCombo(); fillInventoryCombo(); } private void fillResonCombo() { List receiptOfGoodValueList = new ArrayList(); List receiptOfGoods = app.dbutil.selectReceiptOfGoodsList(); for (ReceiptOfGoods receiptOfGood : receiptOfGoods) { receiptOfGoodValueList.add(new CustomSpinnerItem((String) receiptOfGood.getCode(), receiptOfGood.getText())); } reasonValue.setContents(receiptOfGoodValueList); } private void fillInventoryCombo() { List receiptOfGoodValueList = new ArrayList(); List inventoryList = app.dbutil.selectExternalInventoryList(); for (Inventory inventory : inventoryList) { receiptOfGoodValueList.add(new CustomSpinnerItem((String) inventory.getWarehouseNumber(), inventory.getName())); } fromInventoryAutoComplete.setContents(receiptOfGoodValueList); } @Override protected void resetView() { super.resetView(); reasonValue.setSelection(0); reasonValue.clearError(); fromInventoryAutoComplete.setSelection(0); fromInventoryAutoComplete.clearError(); } protected boolean isValid() { boolean result = super.isValid(); String errorMessage = Messages.getString("pleaseProvideValue"); if (reasonValue.isRequired() && reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { reasonValue.setError(errorMessage); result = false; } log.info("inventory " + fromInventoryAutoComplete.getSelectedId()); if (fromInventoryAutoComplete.isRequired() && (fromInventoryAutoComplete.getEditableText().toString().isEmpty() || fromInventoryAutoComplete.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) || fromInventoryAutoComplete.getSelectedId().equalsIgnoreCase("0000"))) { fromInventoryAutoComplete.setError(errorMessage); result = false; } return result; } @Override protected boolean onSave() { super.onSave(); materialMovement.setReceiptOfGoods(reasonValue.getSelectedId()); materialMovement.setFrom(fromInventoryAutoComplete.getSelectedId()); materialMovement.setTo(app.dbutil.getUser().getWarehouseNumber()); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(new RemoteTransactionHandler().runSaveMaterialMoveMent(materialMovement)) { } return onBackPressed(); } }; return false; } public static class ArticleIncomingFormFormArguments { public ArticleIncomingFormFormArguments() { } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ArticleListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnCloseListener; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.RelativeLayout.LayoutParams; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ArticleDetailForm.ArticleDetailFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ArticleListForm extends SuperForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(ArticleListForm.class); private SearchView searchView; private TextView inventoryNameText; private String queryText = ""; private ActionCtrl outgoingAction; private ActionCtrl searchAction; private ActionCtrl contextMenuAction; private RelativeLayout mainView; protected DefaultListWidget listWidget; private LinearLayout emptyMessageView; private AHBottomNavigation bottomNavigation; private int bottomNavigationTabSelected; private Inventory inventory; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleListFormArgument) { ArticleListFormArgument formArgument = (ArticleListFormArgument) argument; } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create SearchView searchView = new SearchView(context); searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END)); searchView.setOnQueryTextListener(this); searchView.setOnCloseListener(new OnCloseListener() { @Override public boolean onClose() { closeSearchView(); return false; } }); // toolbar.addView(searchView); // hide runtime menu items setRuntimeMenuHidden(true); // checkout article action outgoingAction = addActionCtrl(false, true, 0, "actionOutgoing"); //$NON-NLS-1$ outgoingAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SHOPPING_CART_WHITE, CommonConstants.Images.IMAGE_DPI))); // create search action searchAction = addActionCtrl(false, true, 0, "actionSearch"); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); contextMenuAction = addActionCtrl(false, true, 0, "actionCcontextMenu"); //$NON-NLS-1$ contextMenuAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.MENU_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); // contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout inventoryNameLayout = new LinearLayout(context); inventoryNameLayout.setOrientation(LinearLayout.VERTICAL); inventoryNameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); inventoryNameLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); inventoryNameText = CommonUtilForm.getTextView(context, ""); inventoryNameText.setTextColor(Color.WHITE); inventoryNameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); inventoryNameText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; textViewParams.bottomMargin = LayoutUtils.DEFAULT_MAX_MARGIN; inventoryNameText.setLayoutParams(textViewParams); inventoryNameLayout.addView(inventoryNameText); contentLinearLayout.addView(inventoryNameLayout); RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget = new DefaultListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); LinearLayout.LayoutParams noDataTextViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); noDataTextViewParams.gravity = Gravity.CENTER; noDataTextViewParams.topMargin = 20; textView.setLayoutParams(noDataTextViewParams); emptyMessageView.addView(textView); mainFormView.addView(emptyMessageView); contentLinearLayout.addView(mainFormView); mainView.addView(contentLinearLayout); mainView.addView(createBottomNavigation(context)); mainView.addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { boolean widthChanged = (right - left) != (oldRight - oldLeft); if (widthChanged) { // width has changed } boolean heightChanged = (bottom - top) != (oldBottom - oldTop); if (heightChanged) { // height has changed loadTable(); } } }); view.addView(mainView); return view; } private View createBottomNavigation(Context context) { bottomNavigation = new AHBottomNavigation(context); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); bottomNavigation.setLayoutParams(params); // Create items AHBottomNavigationItem item1 = new AHBottomNavigationItem(ServiceMessages.getString("transit") , getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.TRUCK_WHITE, CommonConstants.Images.IMAGE_DPI))); AHBottomNavigationItem item3 = new AHBottomNavigationItem(ServiceMessages.getString("open") , getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DONE_WHITE, CommonConstants.Images.IMAGE_DPI))); // Add items bottomNavigation.addItem(item1); // bottomNavigation.addItem(item2); bottomNavigation.addItem(item3); // Change colors bottomNavigation.setAccentColor(Color.parseColor("#00796B")); //$NON-NLS-1$ bottomNavigation.setInactiveColor(Color.parseColor("#757575")); //$NON-NLS-1$ // Manage titles bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW); // Set listener bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() { @Override public boolean onTabSelected(final int position, boolean wasSelected) { bottomNavigationTabSelected = position; loadTable(); return true; } }); return bottomNavigation; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("vehicleInventory")); closeSearchView(); inventory = app.dbutil.selectInventoryByPersonalNrAndWarehouseNr(); inventoryNameText.setText(ServiceMessages.getString("nameOfInventory") + " " + (inventory == null? "-":inventory.getName())); inventoryNameText.setText(ServiceMessages.getString("nameOfInventory") + " " + (inventory == null? "-":inventory.getName() + " - " + ServiceMessages.getString("incomingArticle"))); bottomNavigation.refresh(); bottomNavigation.setCurrentItem(0); app.messageUtil.showContinueMessage(); // need to wait until transaction success (data in table delayed) new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { loadTable(); } }; return null; } private void closeSearchView() { getToolbar().removeView(searchView); hideSoftInputFromWindow(); setVisibleAction(true); queryText = ""; } private void loadTable() { // bottom navigation selected // bottomNavigationTabSelected // bottomNavigation: 0 -> Transit , 1 -> Open List articleList = app.dbutil.selectArticleList(bottomNavigationTabSelected == 1); int listWidgetHeight = view.getHeight() - inventoryNameText.getHeight() - bottomNavigation.getHeight(); if(listWidget.getHeight() > 0 && listWidget.getHeight() != listWidgetHeight) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, listWidgetHeight); listWidget.setLayoutParams(params); } ((RelativeLayout.LayoutParams) listWidget.getLayoutParams()).height -= ((LinearLayout.LayoutParams) inventoryNameText.getLayoutParams()).topMargin; ((RelativeLayout.LayoutParams) listWidget.getLayoutParams()).height -= ((LinearLayout.LayoutParams) inventoryNameText.getLayoutParams()).bottomMargin; listWidget.clean(); ArrayList items = new ArrayList(); // if (articleList.isEmpty()) { // DeliveryList deliveryList = new DeliveryList(); // deliveryList.setGuid("7F000001018E2B1A192467BF0BEA31B6"); // deliveryList.setWarehouse("AAA"); // deliveryList.setMaterialNumber("45-0645-327"); // deliveryList.setMaterialName("Antrieb DBX"); // deliveryList.setEntryCount("3.000"); // deliveryList.setEntryUnit("STK"); // deliveryList.setStatus("O"); // articleList.add(deliveryList); // // DeliveryList deliveryList2 = new DeliveryList(); // deliveryList2.setGuid("7F000001018E2B1A192467BF0BEA75B6"); // deliveryList2.setWarehouse("AAA"); // deliveryList2.setMaterialNumber("45-0645-867"); // deliveryList2.setMaterialName("Antrieb DHX"); // deliveryList2.setEntryCount("4.000"); // deliveryList2.setEntryUnit("STK"); // deliveryList2.setStatus("T"); // articleList.add(deliveryList2); // // DeliveryList deliveryList3 = new DeliveryList(); // deliveryList3.setGuid("7F000001018E2B1A192467BF0BE8431B6"); // deliveryList3.setWarehouse("AAA"); // deliveryList3.setMaterialNumber("45-07545-327"); // deliveryList3.setMaterialName("Antrieb SBX"); // deliveryList3.setEntryCount("1.000"); // deliveryList3.setEntryUnit("STK"); // deliveryList3.setStatus("G"); // articleList.add(deliveryList3); // // DeliveryList deliveryList4 = new DeliveryList(); // deliveryList4.setGuid("7F000001018E2B1A642467BF0BE8431B6"); // deliveryList4.setWarehouse("AAA"); // deliveryList4.setMaterialNumber("45-0t545-327"); // deliveryList4.setMaterialName("Bedix SBX"); // deliveryList4.setEntryCount("1.000"); // deliveryList4.setEntryUnit("STK"); // articleList.add(deliveryList4); // // DeliveryList deliveryList5 = new DeliveryList(); // deliveryList5.setGuid("7F000001018E2B1A642467GF0BE8431B6"); // deliveryList5.setWarehouse("AAA"); // deliveryList5.setMaterialNumber("45-0t945-727"); // deliveryList5.setMaterialName("Bedix SBX"); // deliveryList5.setEntryCount("1.000"); // deliveryList5.setEntryUnit("STK"); // articleList.add(deliveryList5); // // DeliveryList deliveryList6 = new DeliveryList(); // deliveryList6.setGuid("7F00000101VD2B1A192467BF0BE8431B6"); // deliveryList6.setWarehouse("AAA"); // deliveryList6.setMaterialNumber("45-07345-367"); // deliveryList6.setMaterialName("Antrieb SBX"); // deliveryList6.setEntryCount("1.000"); // deliveryList6.setEntryUnit("STK"); // deliveryList6.setStatus("G"); // articleList.add(deliveryList6); // // // DeliveryList deliveryList7 = new DeliveryList(); // deliveryList7.setGuid("7F000001018E2B1A38246FDF0BEA75B6"); // deliveryList7.setWarehouse("AAA"); // deliveryList7.setMaterialNumber("45-0645-867"); // deliveryList7.setMaterialName("Antrieb DHX"); // deliveryList7.setEntryCount("4.000"); // deliveryList7.setEntryUnit("STK"); // deliveryList7.setStatus("T"); // articleList.add(deliveryList7); // // DeliveryList deliveryList8 = new DeliveryList(); // deliveryList8.setGuid("7F00000101742B1A195667BF0BE8431B6"); // deliveryList8.setWarehouse("AAA"); // deliveryList8.setMaterialNumber("45-06545-387"); // deliveryList8.setMaterialName("Antrieb SBX"); // deliveryList8.setEntryCount("1.000"); // deliveryList8.setEntryUnit("STK"); // deliveryList8.setStatus("G"); // articleList.add(deliveryList8); // // DeliveryList deliveryList9 = new DeliveryList(); // deliveryList9.setGuid("7F03064101742B1A295668BF0BE8431B6"); // deliveryList9.setWarehouse("AAA"); // deliveryList9.setMaterialNumber("45-36515-387"); // deliveryList9.setMaterialName("Antrieb SBX"); // deliveryList9.setEntryCount("1.000"); // deliveryList9.setEntryUnit("STK"); // deliveryList9.setStatus("G"); // articleList.add(deliveryList9); // } for (DeliveryList article : articleList) { final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setData(article); item.setStatusColor(article.getStatusColor()); // item.setStatusType(msg.getConfirmedMsg()); item.isShowCheckBox(false); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(article.getMaterialName()); item.setStringLine1(ServiceMessages.getString("materialNumber") + ": " + article.getMaterialNumber()); // ZKDMOBFZGDELVRY.ENTRY_UOM> item.setStringLine2(ServiceMessages.getString("orderedArticles") + ": " + article.getEntryCount() + " " + article.getEntryUnit() ); items.add(item); } if (items.isEmpty()) { emptyMessageView.setVisibility(View.VISIBLE); } else { emptyMessageView.setVisibility(View.GONE); listWidget.setOnItemClickListener(createOnItemClickListener()); listWidget.addItems(items); } if (searchView.getVisibility() == View.VISIBLE) { filter(queryText); } } private OnItemClickListener createOnItemClickListener() { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { DeliveryList deliveryListClicked = (DeliveryList) ((DefaultListWidgetItem) listWidget.getAdapter().getItem(position)).getData(); app.injectAndLeaveToForm(ArticleDetailForm.class, new ArticleDetailFormArguments(deliveryListClicked)); } }; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } @Override public boolean onQueryTextSubmit(String queryText) { filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { filter(queryText); return true; } private void filter(String queryText) { this.queryText = queryText; if (searchView.getVisibility() == View.VISIBLE) { listWidget.getAdapter().getFilter().filter(queryText); } } private void setVisibleAction(boolean visible) { outgoingAction.setVisible(visible); contextMenuAction.setVisible(visible); searchAction.setVisible(visible); searchView.setVisibility(visible ? View.INVISIBLE:View.VISIBLE); } protected ApplicationEvent actionOutgoing() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { Person crrentUser = app.dbutil.getUser(); new RemoteTransactionHandler().runGetInventryStock(crrentUser.getPersonalNumber(), crrentUser.getWarehouseNumber(), crrentUser.getLanguage()); return app.leaveToForm(ArticleOutgoingForm.class); } }; return null; } protected ApplicationEvent actionSearch() { KeyboardUtil.closeKeyboard(appman, getView()); getToolbar().addView(searchView); // hide menu setVisibleAction(false); searchView.setIconified(false); return null; } protected ApplicationEvent actionCcontextMenu() { PopupMenu popupMenu = new PopupMenu(context, getToolbar()); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); addPopupMenuItem(popupMenu, ServiceConstants.Index.ONE, ServiceMessages.getString("articleScan"), ImagesUtil.Images.CAMERA_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.TWO, ServiceMessages.getString("incomingArticle"), ImagesUtil.Images.SHOPPING_CART_ADD_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.THREE, ServiceMessages.getString("outgoingArticlesList"), ImagesUtil.Images.SHOPPING_CART_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.FOUR, ServiceMessages.getString("inventoryStock"), ImagesUtil.Images.TRUCK_BLACK); addPopupMenuItem(popupMenu, ServiceConstants.Index.FIVE, ServiceMessages.getString("inventoryInformations"), ImagesUtil.Images.INFO); //forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem); return true; } }); popupMenu.show(); return null; } private void handleMenuItemClicked(final MenuItem menuItem) { new AsyncTask(this) { private String barcode; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (menuItem.getItemId() == ServiceConstants.Index.ONE) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(ArticleListForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } else if (menuItem.getItemId() == ServiceConstants.Index.TWO) { // Nav to Incoming article without list entry return app.leaveToForm(ArticleIncomningForm.class); } else if (menuItem.getItemId() == ServiceConstants.Index.THREE) { // Nav to List of outgoing articles (booked) return app.leaveToForm(ArticleOutgoingListForm.class); } else if (menuItem.getItemId() == ServiceConstants.Index.FOUR) { // Nav to Inventory Stock return app.leaveToForm(InventoryStockForm.class); } else if (menuItem.getItemId() == ServiceConstants.Index.FIVE) { // Nav to Inventory informations return app.leaveToForm(InventoryInformationsForm.class, new InventoryInformationsForm.FormArguments(new Inventory())); } return null; } @Override public void runOnUIThread() { if (menuItem.getItemId() == ServiceConstants.Index.ONE) { if (barcode != null && !barcode.isEmpty()) { actionSearch(); System.out.println("barcode " + barcode); String matNoQuery = StringUtil.getMaterialNoFromScan(barcode.trim()); System.out.println("matNoQuery " + matNoQuery); searchView.setQuery(matNoQuery, true); } } return; } }; } private void addPopupMenuItem(PopupMenu popupMenu, int index, String label, Images image) { popupMenu.getMenu() .add(Menu.NONE, index, Menu.NONE, label) .setIcon(getBitmanDrawable(app.imagesUtil.getImage(image, CommonConstants.Images.IMAGE_DPI))); } public static class ArticleListFormArgument { private int tabSelected; private Date selectedDate; public int getTabSelected() { return tabSelected; } protected ArticleListFormArgument() { } public ArticleListFormArgument(Date selectedDate, int tabSelect) { this.tabSelected = tabSelect; this.selectedDate = selectedDate; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public Date getDate() { return this.selectedDate; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ArticleOutgoingForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDAutoComplete; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ArticleOutgoingForm extends ArticleSearchForm { private static Log log = LogFactory.getLog(ArticleOutgoingForm.class); public static ServiceApplication app; public MDAutoComplete inventoryAutoComplete; public MDEditText codeReturnInventoryEditText; public MDEditText reasonReturnDeliveryEditText; private VehicleInventory selectedVehicleInventory; private DeliveryList deliveryList; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleOutgoingFormArguments) { ArticleOutgoingFormArguments formArguments = (ArticleOutgoingFormArguments) argument; deliveryList = formArguments.getDeliveryList(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && !searchView.getQueryHint().toString().equalsIgnoreCase(Messages.getString("search"))) { searchView.setQueryHint(Messages.getString("search")); } } }); inventoryAutoComplete = MDAutoComplete.createDefaultAutoCompleteText(contentLinearLayout, ServiceMessages.getString("newInventory"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true); inventoryAutoComplete.setTag("INVENTORY"); //$NON-NLS-1$ LinearLayout codeReturnInventoryLinearLayout = new LinearLayout(context); codeReturnInventoryLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams codeReturnInventoryLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); codeReturnInventoryLinearLayoutParams.gravity = Gravity.CENTER; codeReturnInventoryLinearLayoutParams.width = LayoutParams.MATCH_PARENT; codeReturnInventoryLinearLayoutParams.height = LayoutParams.MATCH_PARENT; codeReturnInventoryLinearLayoutParams.weight = 1; codeReturnInventoryLinearLayout.setLayoutParams(codeReturnInventoryLinearLayoutParams); codeReturnInventoryEditText = MDEditText.createDefaultEditText(codeReturnInventoryLinearLayout, ServiceMessages.getString("codeReturnDelivery"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ codeReturnInventoryEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); LinearLayout.LayoutParams codeReturnInventoryLayoutParams = new LinearLayout.LayoutParams(0, 0); codeReturnInventoryLayoutParams.gravity = Gravity.CENTER; codeReturnInventoryLayoutParams.width = 0; codeReturnInventoryLayoutParams.height = LayoutParams.MATCH_PARENT; codeReturnInventoryLayoutParams.weight = 0.9f; codeReturnInventoryEditText.getParentTextInputLayout().setLayoutParams(codeReturnInventoryLayoutParams); codeReturnInventoryEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { codeReturnInventoryEditText.clearError(); if (codeReturnInventoryEditText.getText().toString().isEmpty()) { reasonReturnDeliveryEditText.setRequired(false); reasonReturnDeliveryEditText.clearError(); } else { reasonReturnDeliveryEditText.setRequired(true); } } }); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.1f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { private String barcode = ""; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { if (!barcode.isEmpty()) { codeReturnInventoryEditText.setInputType(InputType.TYPE_CLASS_TEXT); codeReturnInventoryEditText.setText(barcode); codeReturnInventoryEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } } }; } }); cameraLinearLayout.addView(gridImageView); codeReturnInventoryLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(codeReturnInventoryLinearLayout); reasonReturnDeliveryEditText = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("reasonReturnDelivery"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ reasonReturnDeliveryEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY) }); reasonReturnDeliveryEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { reasonReturnDeliveryEditText.clearError(); } }); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("outgoingArticle")); searchView.setIconified(true); if (deliveryList != null) { searchView.setVisibility(View.INVISIBLE); loadMaterialsList(deliveryList.getMaterialNumber()); if (selectedVehicleInventory == null) { nameEditText.setText(deliveryList.getMaterialName()); numberEditText.setText(deliveryList.getMaterialNumber()); unitEditText.setText(deliveryList.getEntryUnit()); stockEditText.setText(deliveryList.getEntryCount()); Material material = app.dbutil.selectMaterialByMatNo(deliveryList.getMaterialNumber()); priceEditText.setText(material==null? "":material.getNewPrice()); inventoryAutoComplete.setSelectionById(deliveryList.getTo()); saveButton.setVisible(true); // nameEditText.setTag(deliveryList.getMaterialName()); // numberEditText.setTag(deliveryList.getMaterialNumber()); // // unitEditText.setText(deliveryList.getEntryUnit()); // stockEditText.setText(deliveryList.getEntryCount()); // Material material = app.dbutil.selectMaterialByMatNo(deliveryList.getMaterialNumber()); // // priceEditText.setText(material==null? "":material.getNewPrice()); // saveButton.setVisible(true); } } else { searchView.setVisibility(View.VISIBLE); } return null; } @Override public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List vehicleInventoryList = app.dbutil.selectVehicleInventoryListByMatNrAndMatName(queryText, queryText); for (VehicleInventory vehicleInventory : vehicleInventoryList) { searchView.getSuggessionItemList().add(new SuggessionItem(vehicleInventory.getMaterialNumber(), vehicleInventory.getMaterialName())); } if (vehicleInventoryList.size() > 0 && vehicleInventoryList.size() == 1) { // Exactly found an article from the StammMat if (vehicleInventoryList.size() == 1) { selectedVehicleInventory = vehicleInventoryList.get(0); } } if (selectedVehicleInventory != null) { if (nameEditText.getText().toString().isEmpty()) { nameEditText.setText(selectedVehicleInventory.getMaterialName()); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(selectedVehicleInventory.getMaterialNumber()); } unitEditText.setText(selectedVehicleInventory.getUnit()); stockEditText.setText(selectedVehicleInventory.getStockOfMaterial()); saveButton.setVisible(true); //article is in the inventory (ZKDMOBFZLGSYNC and/or ZKDMOBDELVRYLIST) but NOT in the masterdata (ZDKMOBMAT). Material material = app.dbutil.selectMaterialByMatNo(selectedVehicleInventory.getMaterialNumber()); if (material == null) { searchView.setQueryHint(ServiceMessages.getString("noArticleFound")); app.showMessage(ServiceMessages.getString("noArticleFound")); app.messageUtil.showContinueMessage(); } else { priceEditText.setText(material.getNewPrice()); } } } @Override protected void loadData() { super.loadData(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); fillInventoryCombo(); reasonReturnDeliveryEditText.setRequired(!codeReturnInventoryEditText.getText().toString().isEmpty()); } private void fillInventoryCombo() { List receiptOfGoodValueList = new ArrayList(); List inventoryList = app.dbutil.selectNotExternalInventoryList(); for (Inventory inventory : inventoryList) { receiptOfGoodValueList.add(new CustomSpinnerItem((String) inventory.getWarehouseNumber(), inventory.getName())); } inventoryAutoComplete.setContents(receiptOfGoodValueList); } @Override protected void resetView() { super.resetView(); log.info("resetView "); inventoryAutoComplete.setSelection(0); inventoryAutoComplete.clearError(); codeReturnInventoryEditText.clearError(); codeReturnInventoryEditText.getText().clear(); reasonReturnDeliveryEditText.clearError(); reasonReturnDeliveryEditText.getText().clear(); } protected boolean isValid() { boolean result = super.isValid(); String errorMessage = Messages.getString("pleaseProvideValue"); if (isMatrialNumberWrongFormat()) { result = false; } if (reasonReturnDeliveryEditText.isRequired() && reasonReturnDeliveryEditText.getText().toString().isEmpty()) { reasonReturnDeliveryEditText.setError(errorMessage); result = false; } log.info("inventory " + inventoryAutoComplete.getSelectedId()); if (inventoryAutoComplete.isRequired() && (inventoryAutoComplete.getEditableText().toString().isEmpty() || inventoryAutoComplete.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) || inventoryAutoComplete.getSelectedId().equalsIgnoreCase("0000"))) { inventoryAutoComplete.setError(errorMessage); result = false; } return result; } @Override public ApplicationEvent onBackPressed() { // clear deliveryList = null; selectedVehicleInventory = null; return super.onBackPressed(); } @Override protected boolean onSave() { super.onSave(); materialMovement.setTo(inventoryAutoComplete.getSelectedId()); materialMovement.setBarcode(codeReturnInventoryEditText.getText().toString()); materialMovement.setBarcodeText(reasonReturnDeliveryEditText.getText().toString()); new AsyncTask(this) { private Material material = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (selectedVehicleInventory == null) { //Check, if the chosen article is existing in table ZKDMOBFZLGSYNC (article name and article number): if (app.showMessageBox(ServiceMessages.getString("TheSelectedItemIsNotInStockContinue"), ServiceMessages.getString("articleNotINInventory"), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } } else { //If an selected article is not in masterdata, show a different dialog: // "Artikel nicht in Stammdaten vorhanden. Bitte Support kontaktieren" with the only option "OK". material = app.dbutil.selectMaterialByMatNo(numberEditText.getText().toString()); if (material == null) { if (app.showMessageBox(ServiceMessages.getString("TheSelectedArticleIsNotInMasterdata"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { selectedVehicleInventory = null; return null; } } } if(new RemoteTransactionHandler().runSaveMaterialMoveMent(materialMovement)) { } return onBackPressed(); } @Override public void runOnUIThread() { if (material == null) { resetView(); } return; } }; return false; } public static class ArticleOutgoingFormArguments { private DeliveryList deliveryList; public ArticleOutgoingFormArguments() { } public ArticleOutgoingFormArguments(DeliveryList deliveryList) { this.deliveryList = deliveryList; } public DeliveryList getDeliveryList() { return this.deliveryList; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ArticleOutgoingListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.DeliveryList; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class ArticleOutgoingListForm extends SuperForm { private static Log log = LogFactory.getLog(ArticleOutgoingListForm.class); private TextView inventoryNameText; private RelativeLayout mainView; protected DefaultListWidget listWidget; private LinearLayout emptyMessageView; private Inventory inventory; @Override public void onFormCall(Object argument) { if (argument instanceof ArticleListFormArgument) { ArticleListFormArgument formArgument = (ArticleListFormArgument) argument; } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // toolbar.addView(searchView); // hide runtime menu items setRuntimeMenuHidden(true); // set invisible save button saveButton.setVisible(false); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); // contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout inventoryNameLayout = new LinearLayout(context); inventoryNameLayout.setOrientation(LinearLayout.VERTICAL); inventoryNameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); inventoryNameLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); inventoryNameText = CommonUtilForm.getTextView(context, ""); inventoryNameText.setTextColor(Color.WHITE); inventoryNameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); inventoryNameText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; textViewParams.bottomMargin = LayoutUtils.DEFAULT_MAX_MARGIN; inventoryNameText.setLayoutParams(textViewParams); inventoryNameLayout.addView(inventoryNameText); contentLinearLayout.addView(inventoryNameLayout); RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget = new DefaultListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); LinearLayout.LayoutParams noDataTextViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); noDataTextViewParams.gravity = Gravity.CENTER; noDataTextViewParams.topMargin = 20; textView.setLayoutParams(noDataTextViewParams); emptyMessageView.addView(textView); mainFormView.addView(emptyMessageView); contentLinearLayout.addView(mainFormView); mainView.addView(contentLinearLayout); mainView.addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { boolean widthChanged = (right - left) != (oldRight - oldLeft); if (widthChanged) { // width has changed } boolean heightChanged = (bottom - top) != (oldBottom - oldTop); if (heightChanged) { // height has changed loadTable(); } } }); view.addView(mainView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("vehicleInventory")); inventory = app.dbutil.selectInventoryByPersonalNrAndWarehouseNr(); inventoryNameText.setText(ServiceMessages.getString("nameOfInventory") + " " + (inventory == null? "-":inventory.getName() + " - " + ServiceMessages.getString("outgoingArticles"))); loadTable(); return null; } private void loadTable() { List articleList = app.dbutil.selectOutgoingArticleList(); listWidget.clean(); ArrayList items = new ArrayList(); // if (articleList.isEmpty()) { // DeliveryList deliveryList = new DeliveryList(); // deliveryList.setGuid("7F000001018E2B1A192467BF0BEA31B6"); // deliveryList.setWarehouse("AAA"); // deliveryList.setMaterialNumber("45-0645-327"); // deliveryList.setMaterialName("Antrieb DBX"); // deliveryList.setEntryCount("3.000"); // deliveryList.setEntryUnit("STK"); // deliveryList.setStatus("O"); // articleList.add(deliveryList); // // DeliveryList deliveryList2 = new DeliveryList(); // deliveryList2.setGuid("7F000001018E2B1A192467BF0BEA75B6"); // deliveryList2.setWarehouse("AAA"); // deliveryList2.setMaterialNumber("45-0548-117"); // deliveryList2.setMaterialName("Antrieb DHX"); // deliveryList2.setEntryCount("4.000"); // deliveryList2.setEntryUnit("STK"); // deliveryList2.setStatus("T"); // articleList.add(deliveryList2); // // DeliveryList deliveryList3 = new DeliveryList(); // deliveryList3.setGuid("7F000001018E2B1A192467BF0BE8431B6"); // deliveryList3.setWarehouse("AAA"); // deliveryList3.setMaterialNumber("45-0755-327"); // deliveryList3.setMaterialName("Antrieb SBX"); // deliveryList3.setEntryCount("1.000"); // deliveryList3.setEntryUnit("STK"); // deliveryList3.setStatus("G"); // articleList.add(deliveryList3); // // DeliveryList deliveryList4 = new DeliveryList(); // deliveryList4.setGuid("7F000001018E2B1A642467BF0BE8431B6"); // deliveryList4.setWarehouse("AAA"); // deliveryList4.setMaterialNumber("45-0345-327"); // deliveryList4.setMaterialName("Bedix SBX"); // deliveryList4.setEntryCount("1.000"); // deliveryList4.setEntryUnit("STK"); // articleList.add(deliveryList4); // } for (DeliveryList article : articleList) { final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setData(article); item.setStatusColor(article.getStatusColor()); // item.setStatusType(msg.getConfirmedMsg()); item.isShowCheckBox(false); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(article.getMaterialName()); item.setStringLine1(ServiceMessages.getString("materialNumber") + ": " + article.getMaterialNumber()); // ZKDMOBFZGDELVRY.ENTRY_UOM> item.setStringLine2(ServiceMessages.getString("deliveredArticles") + ": " + article.getEntryCount() + " " + article.getEntryUnit() ); items.add(item); } if (items.isEmpty()) { emptyMessageView.setVisibility(View.VISIBLE); } else { emptyMessageView.setVisibility(View.GONE); // listWidget.setOnItemClickListener(createOnItemClickListener()); listWidget.addItems(items); } } // private OnItemClickListener createOnItemClickListener() { // return new OnItemClickListener() { // // @Override // public void onItemClick(AdapterView parent, View view, final int position, final long id) { // DeliveryList deliveryListClicked = (DeliveryList) ((DefaultListWidgetItem) listWidget.getAdapter().getItem(position)).getData(); // app.injectAndLeaveToForm(ArticleOutgoingForm.class, new ArticleOutgoingFormArguments(deliveryListClicked)); // } // }; // } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ArticleListForm.class); } public static class ArticleListFormArgument { private int tabSelected; private Date selectedDate; public int getTabSelected() { return tabSelected; } protected ArticleListFormArgument() { } public ArticleListFormArgument(Date selectedDate, int tabSelect) { this.tabSelected = tabSelect; this.selectedDate = selectedDate; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public Date getDate() { return this.selectedDate; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ArticleSearchForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.SearchView.OnCloseListener; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ArticleSearchForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(ArticleSearchForm.class); public static ServiceApplication app; // don't make this CommonApplication public LinearLayout contentLinearLayout; public AmountEditText amountEditText; public MDEditText unitEditText; public MDEditText stockEditText; public MDEditText priceEditText; public MaterialMovement materialMovement; @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } else { loadMaterialsList(numberEditText.getText().toString()); // if(searchView.isMaterialSelected() && selectedMaterial != null || selectedMaterialPerson != null) { //// hideSoftInputFromWindow(); // // } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); } else { nameEditText.clearError(); } } }); contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout detailLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); detailLinearLayout.setOrientation(LinearLayout.HORIZONTAL); amountEditText = AmountEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("amount"), true); //$NON-NLS-1$ LinearLayout.LayoutParams amountInputLayoutParams = new LinearLayout.LayoutParams(0, 0); amountInputLayoutParams.gravity = Gravity.CENTER; amountInputLayoutParams.width = 0; amountInputLayoutParams.height = LayoutParams.MATCH_PARENT; amountInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(amountInputLayoutParams); // Unit unitEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("unit"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ unitEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); unitEditText.setTag("UNIT"); //$NON-NLS-1$ unitEditText.setEnabled(false); LinearLayout.LayoutParams unitInputLayoutParams = new LinearLayout.LayoutParams(0, 0); unitInputLayoutParams.gravity = Gravity.LEFT; unitInputLayoutParams.width = 0; unitInputLayoutParams.height = LayoutParams.MATCH_PARENT; unitInputLayoutParams.weight = 0.2f; unitEditText.getParentTextInputLayout().setLayoutParams(unitInputLayoutParams); stockEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("duration"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ stockEditText.setTag("STOCK"); //$NON-NLS-1$ stockEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); stockEditText.setEnabled(false); LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.LEFT; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; stockEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); priceEditText = MDEditText.createDefaultEditText(detailLinearLayout, ServiceMessages.getString("price"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ priceEditText.setTag("PRICE"); //$NON-NLS-1$ priceEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT) }); priceEditText.setEnabled(false); priceEditText.setDirectionRight(true); LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); priceInputLayoutParams.gravity = Gravity.CENTER; priceInputLayoutParams.width = 0; priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; priceInputLayoutParams.weight = 0.2f; priceEditText.getParentTextInputLayout().setLayoutParams(priceInputLayoutParams); contentLinearLayout.addView(detailLinearLayout); addContentLinearLayout(contentLinearLayout); searchView.setOnSearchClickListener(new OnClickListener() { @Override public void onClick(View v) { saveButton.setVisible(false); } }); searchView.setOnCloseListener(new OnCloseListener() { @Override public boolean onClose() { saveButton.setVisible(true); return false; } }); saveButton.setTitle(ServiceMessages.getString("save")); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); resetView(); setShowScanNumber(true); return null; } @Override protected void loadData() { super.loadData(); } @Override protected void resetView() { super.resetView(); priceEditText.clearError(); amountEditText.clearError(); stockEditText.clearError(); priceEditText.getText().clear(); amountEditText.getText().clear(); stockEditText.getText().clear(); unitEditText.setSelection(0); unitEditText.clearError(); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ArticleListForm.class); } @Override protected ApplicationEvent onSavePressed() { KeyboardUtil.closeKeyboard(appman, getView()); if (isValid()) { onSave(); } return null; } protected boolean isValid() { boolean result = true; String errorMessage = Messages.getString("pleaseProvideValue"); if (nameEditText.isRequired() && nameEditText.getText().toString().isEmpty()) { nameEditText.setError(errorMessage); result = false; } if (numberEditText.isRequired() && numberEditText.getText().toString().isEmpty()) { numberEditText.setError(errorMessage); result = false; } if (amountEditText.isRequired() && amountEditText.getText().toString().isEmpty()) { amountEditText.setError(errorMessage); result = false; } return result; } @Override protected boolean onSave() { materialMovement = new MaterialMovement(); Person user = app.dbutil.getUser(); int pernr = user.getPersonalNumber(); GuidGenerator generator = new GuidGenerator(); try { materialMovement.setGuid(generator.generate()); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } materialMovement.setPersonalNumber(pernr); materialMovement.setPersonalNumberConfirmed(pernr); materialMovement.setFrom(user.getWarehouseNumber()); materialMovement.setMaterialNumber(numberEditText.getText().toString()); materialMovement.setEntryCount(amountEditText.getText().toString()); materialMovement.setEntryUnit(unitEditText.getText().toString()); return false; } }     service/src/ch/mfiles/kaba/kolibri/service/forms/EmployeeListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobListForm.JobListFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The Employee List Form Class. * * @author nop (02-03-2017) * * @see "[MIG-49] implement of "Mitarbeiterliste" (list of employees)" */ public class EmployeeListForm extends SuperForm implements OnQueryTextListener{ private static Log log = LogFactory.getLog(EmployeeListForm.class); protected Job job; protected DetailListWidget listWidget; @Override public void onFormCall(Object argument) { if (argument instanceof JobListFormArguments) { JobListFormArguments formArguments = (JobListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); listWidget = new DetailListWidget(context); // Search View SearchView searchView = new SearchView(context); searchView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); searchView.setQueryHint(Messages.getString("search")); //$NON-NLS-1$ searchView.setFocusable(true); searchView.setFocusableInTouchMode(true); searchView.setBackgroundColor(LayoutUtils.DEFAULT_SEARCH_COLOR); searchView.setOnQueryTextListener(this); contentLinearLayout.addView(searchView); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); contentLinearLayout.addView(listWidget); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("listOfEmployees")); //$NON-NLS-1$ listWidget.clean(); final List employeeList = app.dbutil.selectEmployeeList(app.dbutil.getUser(), ""); //$NON-NLS-1$ ArrayList items = new ArrayList(); for (int i = 0; i < employeeList.size(); i++) { final Employee employee = employeeList.get(i); final DetailListWidgetItem item = new DetailListWidgetItem(); log.info("emp " + employee.getFirstName() + employee.getSpecificFunction()); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); String specificFunction = ""; if (!employee.getSpecificFunction().getText().isEmpty()) { specificFunction = " (" + employee.getSpecificFunction().getText() + ")"; } item.setTitleText(employee.getLastName() + " " + employee.getFirstName() + specificFunction); //$NON-NLS-1$ item.setStringLine1(ServiceMessages.getString("telWColon") + employee.getPhoneNumber()); //$NON-NLS-1$ item.setStringLine2(ServiceMessages.getString("personalNumber") + ":" + employee.getPersonalNumber()); //$NON-NLS-1$ //$NON-NLS-2$ item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton && employee.getPhoneNumber() != null) { String phoneNumber = employee.getPhoneNumber().replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } }); items.add(item); } listWidget.addItems(items); return null; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } }     service/src/ch/mfiles/kaba/kolibri/service/forms/InventoryInformationsForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class InventoryInformationsForm extends SuperForm { private static Log log = LogFactory.getLog(InventoryInformationsForm.class); private MDEditText name; private MDEditText number; private MDEditText user; private MDEditText personalNumber; private Inventory inventory; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.inventory = formArguments.getInventory(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ArticleListForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); name = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("inventoryName"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); // name.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); number = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("inventoryNumber"), //$NON-NLS-1$ InputType.TYPE_TEXT_VARIATION_PERSON_NAME , false); // number.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SIXTY) }); user = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("UserName"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); // user.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); personalNumber = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("personalNumber"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER , false); personalNumber.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT) }); ScrollView scroll = new ScrollView(context); scroll.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scroll.addView(contentLinearLayout); relativeLayout.addView(scroll); view = new LinearLayout(context); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("inventoryInformations")); //$NON-NLS-1$ inventory = app.dbutil.selectInventoryByPersonalNrAndWarehouseNr(); name.setText(inventory == null? "-":inventory.getName()); number.setText(inventory == null? "-":inventory.getWarehouseNumber()); Person crrentUser = app.dbutil.getUser(); user.setText(crrentUser.getFirstName() + " " + crrentUser.getLastName()); personalNumber.setText(crrentUser.getPersonalNumber() + ""); setEnable(false); return null; } private void setEnable(boolean enabled) { name.setEnabled(enabled); number.setEnabled(enabled); user.setEnabled(enabled); personalNumber.setEnabled(enabled); } public static class FormArguments { private Inventory inventory; public FormArguments(Inventory inventory) { this.inventory = inventory; } public Inventory getInventory() { return inventory; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/InventoryStockForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnCloseListener; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Inventory; import ch.mfiles.kaba.kolibri.common.businessobjects.VehicleInventory; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.types.Warehouse; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class InventoryStockForm extends SuperForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(InventoryStockForm.class); protected Job job; private SearchView searchView; private ActionCtrl refreshAction; private ActionCtrl scanAction; private ActionCtrl searchAction; protected DetailListWidget listWidget; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set navigation image and listener Image backImage = ImagesUtil.getInstance(app).getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); // create SearchView searchView = new SearchView(context); searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END)); searchView.setOnQueryTextListener(this); searchView.setOnCloseListener(new OnCloseListener() { @Override public boolean onClose() { getToolbar().removeView(searchView); setVisibleAction(true); return false; } }); // toolbar.addView(searchView); // hide runtime menu items setRuntimeMenuHidden(true); // create refresh action refreshAction = addActionCtrl(false, true, 0, "actionRefresh"); //$NON-NLS-1$ // refreshAction.setTitle(ServiceMessages.getString("refresh")); //$NON-NLS-1$ refreshAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.UPDATE_WHITE, CommonConstants.Images.IMAGE_DPI))); // create scan action scanAction = addActionCtrl(false, true, 0, "actionScan"); //$NON-NLS-1$ // scanAction.setTitle(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); // create search action searchAction = addActionCtrl(false, true, 0, "actionSearch"); //$NON-NLS-1$ // searchAction.setTitle(ServiceMessages.getString("search")); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); setVisibleAction(true); listWidget = new DetailListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); // set invisible save button saveButton.setVisible(false); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("inventoryStock")); actionRefresh(); return null; } private void loadInventoryStockList() { listWidget.clean(); List inventoryStockList = app.dbutil.selectVehicleInventoryList(); view.removeAllViews(); if(inventoryStockList.isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); for (VehicleInventory inventoryStock : inventoryStockList) { final DetailListWidgetItem item = new DetailListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(inventoryStock.getMaterialName()); item.setStringLine1(ServiceMessages.getString("materialNumber") + ": " + inventoryStock.getMaterialNumber()); item.setStringLine2("Bestand: " + inventoryStock.getStockOfMaterial() + " " + inventoryStock.getUnit()); items.add(item); } // listWidget.setOnItemClickListener(createOnItemClickListener(inventoryStockList)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List inventoryStockList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { VehicleInventory inventoryStock = inventoryStockList.get(position); //TODO remove for test only Inventory inventory = new Inventory(); inventory.setWarehouseNumber("0102152"); inventory.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); inventory.setName(inventoryStock.getMaterialName()); inventory.setWarehouse(new Warehouse()); inventory.setRefreshFlag(""); app.injectAndLeaveToForm(InventoryInformationsForm.class, new InventoryInformationsForm.FormArguments(inventory)); } }; } protected ApplicationEvent onAddPressed() { return null; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.leaveToForm(ArticleListForm.class); } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } private void setVisibleAction(boolean visible) { searchAction.setVisible(visible); refreshAction.setVisible(visible); scanAction.setVisible(visible); searchView.setVisibility(visible ? View.INVISIBLE:View.VISIBLE); } protected ApplicationEvent actionRefresh() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { Person crrentUser = app.dbutil.getUser(); new RemoteTransactionHandler().runGetInventryStock(crrentUser.getPersonalNumber(), crrentUser.getWarehouseNumber(), crrentUser.getLanguage()); return null; } @Override protected void runOnUIThread() { loadInventoryStockList(); } }; return null; } protected ApplicationEvent actionScan() { new AsyncTask(this) { private String barcode; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(InventoryStockForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { app.showMessage(result.toString()); barcode = result.getContents(); log.info("scan result -> " + barcode); //$NON-NLS-1$ } return null; } }; return null; } protected ApplicationEvent actionSearch() { KeyboardUtil.closeKeyboard(appman, getView()); getToolbar().addView(searchView); // hide menu setVisibleAction(false); searchView.setIconified(false); return null; } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDeleteForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReturnReason; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class JobDeleteForm extends DialogForm { private static Log log = LogFactory.getLog(JobDeleteForm.class); // initialized by the kolibri framework... public static ServiceApplication app; private Job job; protected Context context; protected LinearLayout view; private ActionCtrl deleteButton; private MDSpinner reasonValue; @Override public void onFormCall(Object argument) { if (argument instanceof JobDeleteFormArguments) { JobDeleteFormArguments formArguments = (JobDeleteFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); saveButton.setVisible(false); deleteButton = addActionCtrl(false, true, 1, "onDeletePressed"); //$NON-NLS-1$ deleteButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // reason reasonValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { reasonValue.setError(null); reasonValue.clearError(); } @Override public void onNothingSelected(AdapterView arg0) { } }); contentLinearLayout.addView(workTypeLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("reasonForDelete")); //$NON-NLS-1$ List reasonValueList = new ArrayList(); List reasonList = app.dbutil.selectJobDeleteReasonList(); for (int i = 0; i < reasonList.size(); i++) { Reason reason = reasonList.get(i); reasonValueList.add(new CustomSpinnerItem(reason.getReasonText(), reason.getText(), reason.getText())); } reasonValue.setContents(reasonValueList); return null; } protected ApplicationEvent onDeletePressed() { if(reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { reasonValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ return null; } new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(app.showConfirmDeleteDialog()) { if (new RemoteTransactionHandler().updateStatus(db, job, JobStatus.DELETED, JobStatus.SAP_Deleted, reasonValue.getSelectedId())) { log.info("after updateStatus" + job.getStatus().toString()); log.info("after reloadSelectedJob" + job.getStatus().toString()); if (JobStatus.RECEIVED.equals(JobStatus.DELETED)) { // remove existing a new job notification new Notifications(app).removeNotification(CommonConstants.Notification.NEW_JOB); } } if (job.getStatus().isDeleted() && app.dbutil.deleteJob(job)) { app.showMessage(ServiceMessages.getString("jobDeleted"), true); //$NON-NLS-1$ } return onBackPressed(); } return null; } }; return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobListForm.class); } public static class JobDeleteFormArguments { private Job job; public JobDeleteFormArguments(Job zkdmob) { this.job = zkdmob; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailAddressEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.res.ColorStateList; import android.support.v7.widget.AppCompatRadioButton; import android.text.InputType; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The edit address form for job details. * * @author nop (23-02-2017) * * @see "[MIG-44] implement of "Adressen editieren"" */ public class JobDetailAddressEditForm extends AddressEditSuperForm implements OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(JobDetailAddressEditForm.class); protected Address address; private AppCompatRadioButton firmaRadioButton; private AppCompatRadioButton personRadioButton; private MDSpinner personTitleValue; private MDEditText personFirstName; private MDEditText personLastName; private MDEditText personAddition; private MDSpinner companyTitleValue; private MDEditText company; private MDEditText companyName; private MDEditText companyAddition; private List emailList; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailAddressForm.AddressFormArguments) { JobDetailAddressForm.AddressFormArguments formArguments = (JobDetailAddressForm.AddressFormArguments) argument; job = formArguments.getJob(); address = formArguments.getAddress(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroup.setPadding(10, 0, 10, 10); radioGroup.setOnCheckedChangeListener(this); radioGroup.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.addView(radioGroup); ColorStateList colorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_enabled } }, new int[] { LayoutUtils.DEFAULT_TEXT_COLOR }); firmaRadioButton = new AppCompatRadioButton(context); firmaRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 3f)); firmaRadioButton.setText(ServiceMessages.getString("enterprise")); //$NON-NLS-1$ firmaRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); firmaRadioButton.setSupportButtonTintList(colorStateList); firmaRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); firmaRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(firmaRadioButton); personRadioButton = new AppCompatRadioButton(context); personRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); personRadioButton.setText(ServiceMessages.getString("person")); //$NON-NLS-1$ personRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); personRadioButton.setSupportButtonTintList(colorStateList); personRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); personRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(personRadioButton); RelativeLayout formRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams formRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); formRelativeLayoutParams.topMargin = 10; formRelativeLayout.setLayoutParams(formRelativeLayoutParams); formRelativeLayout.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); // Title personTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ personTitleValue.setTag("PERSON_TITLE"); //$NON-NLS-1$ personTitleValue.setOnItemSelectedListener(this); linearLayout.addView(personTitleValue.getTopParent(), 0); personFirstName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("firstName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(personFirstName), 1); personLastName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("lastName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(personLastName), 2); personAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(personAddition), 3); // company company = MDEditText.createDefaultEditText(context, ServiceMessages.getString("enterprise"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(company), 0); companyAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(companyAddition), 1); // company title companyTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ companyTitleValue.setTag("COMPANY_TITLE"); //$NON-NLS-1$ companyTitleValue.setOnItemSelectedListener(this); linearLayout.addView(companyTitleValue.getTopParent(), 2); companyName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("name"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false, this); //$NON-NLS-1$ linearLayout.addView(MDEditText.getTextInputLayout(companyName), 3); ScrollView scrollView = new ScrollView(context); LinearLayout.LayoutParams scrollViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); scrollView.setLayoutParams(scrollViewParams); formRelativeLayout.addView(linearLayout); contentLinearLayout.addView(formRelativeLayout); scrollView.addView(contentLinearLayout); relativeLayout.addView(scrollView); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("changeAddress")); //$NON-NLS-1$ return null; } @Override public void loadData() { // title List valueList = new ArrayList<>(); Iterator itr = app.enumUtil.titelEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); valueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } emailList = app.dbutil.selectEmailListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); generateEmailContete(emailList.size()); personTitleValue.setContents(valueList); companyTitleValue.setContents(valueList); if (StringUtil.isNotEmpty(address.getTitle()) && !valueList.isEmpty()) { String title = app.enumUtil.titelEnum.get(address.getTitle()); personTitleValue.setSelectionByName(title); companyTitleValue.setSelectionByName(title); } else { personTitleValue.setSelection(0); companyTitleValue.setSelection(0); } personFirstName.setText(address.getName1()); personLastName.setText(address.getName2()); personAddition.setText(address.getName3()); company.setText(address.getName1()); companyName.setText(address.getName2()); companyAddition.setText(address.getName3()); location.setText(address.getLocation()); street.setText(address.getStreet()); zip.setText(address.getPostalCode()); city.setText(address.getCity()); tel1.setText(address.getTelNumber1()); tel2.setText(address.getTelNumber2()); fax.setText(address.getFaxNumber()); email.setText(address.getEmail()); for (int i = 0; i < emailTextList.size(); i++) { MDEditText emailEditText = emailTextList.get(i); emailEditText.setText(emailList.get(i).getEmail()); } if (address.isPrivate()) { personRadioButton.setChecked(true); } else { firmaRadioButton.setChecked(true); } } @Override public void onCheckedChanged(RadioGroup paramRadioGroup, int paramInt) { clearErrorMessages(); if (firmaRadioButton.isChecked()) { setPersonInfomation(false); setFimaInfomation(true); } else if (personRadioButton.isChecked()) { setPersonInfomation(true); setFimaInfomation(false); } } private void setFimaInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } company.setVisibility(visibility); companyAddition.setVisibility(visibility); companyTitleValue.getTopParent().setVisibility(visibility); companyName.setVisibility(visibility); } private void setPersonInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } personTitleValue.setRequired(isVisible); personTitleValue.getTopParent().setVisibility(visibility); personFirstName.setVisibility(visibility); personLastName.setVisibility(visibility); personAddition.setVisibility(visibility); } @Override protected boolean isValid() { boolean result = super.isValid(); String selectMessage = Messages.getString("pleaseSelectValue"); //$NON-NLS-1$ String provideMessage = Messages.getString("pleaseProvideValue"); //$NON-NLS-1$ if (firmaRadioButton.isChecked()) { if (companyTitleValue.isRequired() && companyTitleValue.getSelectedItemPosition() == 0) { companyTitleValue.setError(selectMessage); result = false; } if (company.isRequired() && "".equals(company.getText().toString().trim())) { //$NON-NLS-1$ company.setError(provideMessage); result = false; } if (companyName.isRequired() && "".equals(companyName.getText().toString().trim())) { //$NON-NLS-1$ companyName.setError(provideMessage); result = false; } } else { if (personTitleValue.isRequired() && personTitleValue.getSelectedItemPosition() == 0) { personTitleValue.setError(selectMessage); result = false; } if (personLastName.isRequired() && "".equals(personLastName.getText().toString().trim())) { //$NON-NLS-1$ personLastName.setError(provideMessage); result = false; } } return result; } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { String title = ""; //$NON-NLS-1$ // private address if (personRadioButton.isChecked()) { if (personTitleValue.getSelectedItemPosition() != 0) { title = personTitleValue.getSelectedId(); } address.setName1(personFirstName.getText().toString()); address.setName2(personLastName.getText().toString()); address.setName3(personAddition.getText().toString()); } else if (firmaRadioButton.isChecked()) { if (companyTitleValue.getSelectedItemPosition() != 0) { title = companyTitleValue.getSelectedId(); } address.setName1(company.getText().toString()); address.setName2(companyName.getText().toString()); address.setName3(companyAddition.getText().toString()); } address.setTitle(title); address.setLocation(location.getText().toString()); address.setStreet(street.getText().toString()); address.setPostalCode(zip.getText().toString()); address.setCity(city.getText().toString()); address.setTelNumber1(tel1.getText().toString()); address.setTelNumber2(tel2.getText().toString()); address.setFaxNumber(fax.getText().toString()); address.setEmail(email.getText().toString()); // address.setEmail2(email2.getText().toString()); // address.setEmail3(email3.getText().toString()); if (firmaRadioButton.isChecked()) { address.setPrivate(false); } else { address.setPrivate(true); } app.dbutil.updateAddress(address); new RemoteTransactionHandler().runSaveOrder(job, address); job.loadAddresses(app.dbutil); return onBackPressed(); } }; return true; } @Override public void onFormReset() { super.onFormReset(); personTitleValue.setSelection(0); personFirstName.getText().clear(); personLastName.getText().clear(); personAddition.getText().clear(); companyTitleValue.setSelection(0); company.getText().clear(); companyName.getText().clear(); companyAddition.getText().clear(); } @Override public void onNothingSelected(AdapterView arg0) { //Do nothing } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("PERSON_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ personTitleValue.clearError(); } else if ("COMPANY_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ companyTitleValue.clearError(); } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { super.onTextChanged(s, start, before, count); if (personLastName.hasFocus()) { personLastName.clearError(); } if (company.hasFocus()) { company.clearError(); } if (companyName.hasFocus()) { companyName.clearError(); } } @Override public void clearErrorMessages() { super.clearErrorMessages(); personTitleValue.clearError(); companyTitleValue.clearError(); personLastName.clearError(); company.clearError(); companyName.clearError(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailAddressForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.impl.android.ui.UIActivity; /** * The address form for job details. * * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public class JobDetailAddressForm extends GridLayoutForm { private static Log log = LogFactory.getLog(JobDetailAddressForm.class); private Job job; private RelativeLayout addressRelativeLayout; private LinearLayout cardLinearLayout; public JobDetailAddressForm(Context context, ServiceApplication app) { super(context, app); } /** * Gets view. * * @param job * @param title */ public View getView(Job job) { this.job = job; createLayoutAndContents(); return getParentView(addressRelativeLayout); } /** * Creates layout and contents. * * @param job * @param title */ public void createLayoutAndContents() { addressRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams addressRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); addressRelativeLayoutParams.setMargins(0, 0, 0, LayoutUtils.DEFAULT_MAX_MARGIN); addressRelativeLayout.setLayoutParams(addressRelativeLayoutParams); cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); // Address type "Object" (ZKDMOB.OBJNR) // // MON: // Address type "Contact" (ZKDMOB.PARAPNR) // Address type "Customer" (ZKDMOB.PARZSNR) // Address type "Receiver" (ZKDMOB.PARZANR) // // REP/SAV: // Address type "Partner" (ZKDMOB.PARAPNR) // Address type "Customer" (ZKDMOB.PARANMNR) // Address type "Owner" (ZKDMOB.PARZANR) // Address type "Estate Management" (ZKDMOB.PARZRNR) // Address type "Client" (ZKDMOB.PARZSNR) // OBJNR - ObjectAddress // PARAPNR - PartnerOfInstallAddress // PARZSNR - CustomerKdnErrorAddress // PARZANR - OwnerAddress // // PARAPNR - PartnerOfInstallAddress // PARANMNR - PartnerAddress // PARZANR - OwnerAddress // PARZRNR - KdnServiceAddress // PARZSNR - CustomerKdnErrorAddress log.info("Object -> OBJNR ->" + job.getObjectAddressId()); createAddressContents(ServiceMessages.getString("Object"), job.getObjectAddress()); //$NON-NLS-1$ if(job.getJobType().isMON()) { log.info("Contact -> PARAPNR ->" + job.getPartnerAddressId()); log.info("Customer -> PARZSNR ->" + job.getCustomerAddressId()); log.info("Receiver -> PARZANR ->" + job.getOwnerAddressId()); createAddressContents(ServiceMessages.getString("Contact"), job.getPartnerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Customer"), job.getCustomerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Receiver"), job.getOwnerAddress()); //$NON-NLS-1$ } else { log.info("Partner -> PARAPNR ->" + job.getPartnerOfInstallAddressId()); log.info("Customer -> PARANMNR ->" + job.getPartnerAddressId()); log.info("Owner -> PARZANR ->" + job.getOwnerAddressId()); log.info("EstateManagement -> PARZRNR ->" + job.getKdnServiceAddressId()); log.info("Client -> PARZSNR ->" + job.getCustomerAddressId()); createAddressContents(ServiceMessages.getString("Partner"), job.getPartnerOfInstallAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Customer"), job.getPartnerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Owner"), job.getOwnerAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("EstateManagement"), job.getKdnServiceAddress()); //$NON-NLS-1$ createAddressContents(ServiceMessages.getString("Client"), job.getCustomerAddress()); //$NON-NLS-1$ } addressRelativeLayout.addView(cardLinearLayout); } /** * Creates address contents. * * @param gridLayout * @param address */ private void createAddressContents(String titleText, Address address) { if(address.getJobNumber().isEmpty()) { // no address return; } GridLayout gridLayout = createGridLayout(titleText, job, address); // Client number createAddressTextView(gridLayout, ServiceMessages.getString("ClientNumber"), address.getCustomerNumber()); // Title String title = app.enumUtil.titelEnum.get(address.getTitle()) == null ? "" : app.enumUtil.titelEnum.get(address.getTitle()); //$NON-NLS-1$ createAddressTextView(gridLayout, ServiceMessages.getString("title"), title); //$NON-NLS-1$ // First name String firsrName = address.isPrivate() ? ServiceMessages.getString("firstName") : ServiceMessages.getString("enterprise"); //$NON-NLS-1$ //$NON-NLS-2$ createAddressTextView(gridLayout, firsrName, address.getName1()); // LastName String lastName = address.isPrivate() ? ServiceMessages.getString("lastName") : ServiceMessages.getString("name"); //$NON-NLS-1$ //$NON-NLS-2$ createAddressTextView(gridLayout, lastName, address.getName2()); // Addition createAddressTextView(gridLayout, ServiceMessages.getString("addition"), address.getName3()); //$NON-NLS-1$ // Location createAddressTextView(gridLayout, Messages.getString("location"), address.getLocation()); //$NON-NLS-1$ // Str./No. createAddressTextView(gridLayout, ServiceMessages.getString("street"), address.getStreet()); //$NON-NLS-1$ // ZIP createAddressTextView(gridLayout, ServiceMessages.getString("zip"), address.getPostalCode()); //$NON-NLS-1$ // City createAddressTextView(gridLayout, ServiceMessages.getString("city"), address.getCity()); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Tel. 1 createAddressTextView(gridLayout, ServiceMessages.getString("tel1"), address.getTelNumber1(), true); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Tel. 2 createAddressTextView(gridLayout, ServiceMessages.getString("tel2"), address.getTelNumber2(), true); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Fax createAddressTextView(gridLayout, ServiceMessages.getString("fax"), address.getFaxNumber()); //$NON-NLS-1$ // Empty line createAddressTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ // Email createAddressTextView(gridLayout, ServiceMessages.getString("email"), address.getEmail()); //$NON-NLS-1$ List emailList = app.dbutil.selectEmailListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); if (!emailList.isEmpty()) { for (int i = 0; i < emailList.size(); i++) { Email email = emailList.get(i); log.info("JobNumber " + email.getJobNumber() + " PartnerNummer " + email.getPartnerNummer() + " JobType " + email.getJobType().getCode() + " Email " + email.getEmail()); createAddressTextView(gridLayout, ServiceMessages.getString("email") + " " + (i+2), email.getEmail()); //$NON-NLS-1$ } } cardLinearLayout.addView(cardView); } /** * Creates address text view. * * @param gridLayout * @param key * @param value */ private void createAddressTextView(final GridLayout gridLayout, final String key, final String value) { createAddressTextView(gridLayout, key, value, false); } /** * Creates address text view. * * @param gridLayout * @param key * @param value * @param iconTypeName */ private void createAddressTextView(final GridLayout gridLayout, final String key, final String value, boolean isShowIcon) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.2f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.8f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(context); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(value); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(gridTextViewValue); if (isShowIcon) { ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); if (value != null && value.trim().length() > 0) { gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phoneNumber = value.replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } }); } else { gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE_DISABLED, CommonConstants.Images.IMAGE_DPI))); } gridRelativeLayout.addView(gridImageView); } gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } public static class AddressFormArguments { private Job job; private Address address; protected AddressFormArguments() { } protected AddressFormArguments(Job job) { } public AddressFormArguments(Job job, Address address) { this.job = job; this.address = address; } public Job getJob() { return job; } public Address getAddress() { return address; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.forms.widgets.ViewPageAdapter; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.OnTimeAction; import ch.mfiles.kaba.kolibri.service.forms.SignatureForm.Arguments; import ch.mfiles.kaba.kolibri.service.util.ReportUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class JobDetailForm extends SuperForm { private static Log log = LogFactory.getLog(JobDetailForm.class); private Job job; private JobReportTime selectedJobTime; private LinearLayout mainView; private JobDetailInfoForm infoForm; private JobDetailAddressForm addressForm; private JobDetailReportForm reportForm; private ActionCtrl jobEditActioni; private ActionCtrl informationsAction; private ActionCtrl commissionNumberAction; private ActionCtrl finalizedReportsAction; private ActionCtrl signatureAction; private ActionCtrl sendAction; private TabLayout tabLayout; private int pageSelected = 0; private Toolbar toolbar; public JobReportTime getSelectedJobtime() { return selectedJobTime; } public void setSelectedJobTime(JobReportTime jobTime) { selectedJobTime = jobTime; } public void setSelectedJob(Job job) { this.job = job; this.job.loadAddresses(app.dbutil); this.job.loadReports(app.dbutil); } public void reloadSelectedJob() { this.job = app.dbutil.selectJobByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); this.job.loadReports(app.dbutil); } @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArgument = (JobDetailFormArgument)argument; job = formArgument.getJob(); job.loadAddresses(app.dbutil); job.loadReports(app.dbutil); pageSelected = formArgument.getTabSelected(); }else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context The context to user for creating UI widgets. * @param inflater The inflater to use to inflate the application's layouts from XML resource ids. * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); setFormTitle(ServiceMessages.getString("jobDetails")); //$NON-NLS-1$ // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationContentDescription("Back"); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); /* create the "Job Edit" in context menu. * * @see "[MIG-46] implement of "create job"" */ jobEditActioni = addActionCtrl(false, false, 2, "onJobEdit"); //$NON-NLS-1$ jobEditActioni.setTitle(ServiceMessages.getString("customizeYourInfo")); //$NON-NLS-1$ jobEditActioni.setEnabled(false); // create the "Edit installation type" entry in the context menu. informationsAction = addActionCtrl(false, false, 2, "editInformations"); //$NON-NLS-1$ informationsAction.setTitle(ServiceMessages.getString("editInstallationType")); //$NON-NLS-1$ informationsAction.setEnabled(false); // create the "Kom-No." in context menu. commissionNumberAction = addActionCtrl(false, false, 2, "onCommissionNumber"); //$NON-NLS-1$ commissionNumberAction.setTitle(ServiceMessages.getString("wrongComm")); //$NON-NLS-1$ commissionNumberAction.setEnabled(false); finalizedReportsAction = addActionCtrl(false, true, 1, "onFinalizedReports"); //$NON-NLS-1$ finalizedReportsAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_FILE_BLACK, CommonConstants.Images.IMAGE_DPI))); finalizedReportsAction.setVisible(false); signatureAction = addActionCtrl(false, true, 1, "onSignature"); //$NON-NLS-1$ signatureAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_BLACK, CommonConstants.Images.IMAGE_DPI))); signatureAction.setVisible(false); sendAction = addActionCtrl(false, true, 1, "onSendingReport"); //$NON-NLS-1$ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setVisible(false); // set invisible save button saveButton.setVisible(false); mainView = new LinearLayout(context); mainView.setOrientation(LinearLayout.VERTICAL); mainView.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS())); LinearLayout.LayoutParams checkFinalizeLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); mainView.setLayoutParams(checkFinalizeLayoutParams); infoForm = new JobDetailInfoForm(context, app); addressForm = new JobDetailAddressForm(context, app); reportForm = new JobDetailReportForm(context, app); reportForm.setOnTimeActionListener(new OnTimeAction() { @Override public void runOnTimeAction() { changeActionSend(); pageSelected = 2; onFormShow(); } }); view.addView(mainView); return view; } /** * This event is received every time the form is shown. This happens if the * form is called by the framework, another form or if reactivated from the * application's form stack. <p/> * * The application developer has to set all member variables (reset the * state of the form) at this point because the framework reuses the forms * (every form is instantiated exactly once during the lifetime of an * application) *

* * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); app.messageUtil.showContinueMessage(); if (mainView.getChildCount() > 0) { mainView.removeAllViewsInLayout(); mainView.invalidate(); } toolbar.setEnabled(true); View contentView = createTabContentView(context); mainView.addView(contentView); tabLayout.getTabAt(pageSelected).select(); view.invalidate(); return null; } /** * Handles on click event for job edit. * * @return * * @see "[MIG-46] implement of "create job"" */ public ApplicationEvent onJobEdit() { pageSelected = 0; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { tabLayout.getTabAt(pageSelected).select(); ch.mfiles.kaba.kolibri.service.forms.JobEditForm.FormArguments formArguments = new JobEditForm.FormArguments(false, job.getCommissionNumber(), job, job.getObjectAddress(), job.getPartnerAddress()); return app.callForm(JobEditForm.class, formArguments); } }, false); return null; } public ApplicationEvent editInformations() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobDetailInfoInstallationTypeForm.class, new JobDetailForm.JobDetailFormArgument(job)); } }, false); return null; } /** * Handles on click event for commission number. * * @return * * @see "[MIG-43] implement of "Falsche Kommissionsnummer"" */ public ApplicationEvent onCommissionNumber() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobDetailInfoCommissionNumberForm.class, new JobDetailForm.JobDetailFormArgument(job)); } }, false); return null; } public ApplicationEvent onFinalizedReports() { pageSelected = 2; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { List jobList = new ArrayList(); jobList.add(job); return app.callForm(ReportSummaryForm.class, new Arguments(jobList, false)); } }, false); return null; } /** * Handles on click event for signature. * * @return */ public ApplicationEvent onSignature() { pageSelected = 2; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { List jobList = new ArrayList(); jobList.add(job); return appman.getActiveApplication().callForm(SignatureForm.class, new SignatureForm.Arguments(jobList, false)); } }, false); return null; } /** * Handles on click event for sending report. * * @return */ public ApplicationEvent onSendingReport() { sendAction.setEnabled(false); log.info("sending report PARANMNR " + job.getPartnerAddressId() + " PARAPNR " + job.getObjectAddressId()); log.info("address PARANMNR " + job.getPartnerAddress().getPartnerNummer() + " PARAPNR " + job.getObjectAddress().getPartnerNummer()); ReportUtil reportUtil = new ReportUtil(this, app); reportUtil.onSendingReport(job); changeActionSend(); return null; } protected void changeActionFinalizedReport() { JobStatus jobStatus = job.getStatus(); finalizedReportsAction.setVisible(true); finalizedReportsAction.setEnabled(false); finalizedReportsAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_FILE_DISABLED, CommonConstants.Images.IMAGE_DPI))); if (jobStatus.isPartlyDone() || jobStatus.isFinalized()) { finalizedReportsAction.setEnabled(true); finalizedReportsAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_FILE_BLACK, CommonConstants.Images.IMAGE_DPI))); } } /** * Displays "Signature" button (POS5) depending on * @param form * @param job */ protected void changeActionSignature() { JobStatus jobStatus = job.getStatus(); signatureAction.setVisible(true); signatureAction.setEnabled(false); signatureAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); if (jobStatus.isReceived() || jobStatus.isPartlyDone() || jobStatus.isInProgress()) { List jobs = getBundledJobList(job); if (!jobs.isEmpty()) { boolean enabled = true; // fill the report status into a HasSet HashSet reportStatusSet = new HashSet(); Iterator itr = jobs.iterator(); while (itr.hasNext()) { Report report = itr.next().getLatestReport(); reportStatusSet.add(report.getReportStatus().getCode()); } /* 1. if there is at least one report in initial state, signature button is disabled this is because a report can not be signed before it exists * 2. if all reports are sent signature button is disabled * */ if (reportStatusSet.contains(ReportStatus.INITIAL) || (reportStatusSet.contains(ReportStatus.RECEIVED) && reportStatusSet.size() == 1)) { enabled = false; } // ..in all other situations, signature button remains enabled if (enabled) { signatureAction.setEnabled(true); signatureAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_BLACK, CommonConstants.Images.IMAGE_DPI))); } } } signatureAction.setValidate(true); } protected List getBundledJobList(Job job) { List jobList = new ArrayList(); // reload report because they can be changed! job.loadReports(app.dbutil); String signguId = job.getLatestReport().getSignatureGuId(); // add only the current job to the list if it was not signed together with others if (StringUtil.isEmpty(signguId)) jobList.add(job); // load jobs which have been signed together else { jobList = new ArrayList(app.dbutil.selectJobBySignGUID(signguId)); Iterator itr = jobList.iterator(); while (itr.hasNext()) { Job bundledJob = itr.next(); bundledJob.loadReports(app.dbutil); } } return jobList; } /** * Displays "Send" button (POS4) depending on * @param job */ private void changeActionSend() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { Person currentUser = app.dbutil.getUser(); Report report = job.getCurrentReport(); sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(false); if (currentUser != null && !report.getReportStatus().isInitial()) { setSelectedJobTime(app.dbutil.selectJobReportTimeByGuid(job.getCurrentReportGuId(app.dbutil))); if (report.getReportStatus().isNew()){ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(true); if (getSelectedJobtime() != null && getSelectedJobtime().getStopTime().equals(new Date(0))) { sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(false); } } } sendAction.setValidate(true); return null; } }, false); } protected void changeActions() { changeActionSignature(); changeActionSend(); } private View createTabContentView(Context context) { if (pageSelected == 0) { contextMenuActionState(true); } signatureAction.setVisible(false); sendAction.setVisible(false); finalizedReportsAction.setVisible(false); // create vertical linear view to hold TabLayout and ViewPager LinearLayout contentView = new LinearLayout(context); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentView.setOrientation(LinearLayout.VERTICAL); // create TabLayout tabLayout = new TabLayout(context); LinearLayout.LayoutParams tabLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); tabLayout.setLayoutParams(tabLayoutParams); tabLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); tabLayout.setTabTextColors(LayoutUtils.DEFAULT_TAB_TEXT_COLOR, LayoutUtils.DEFAULT_TAB_SELECTED_TEXT_COLOR); tabLayout.setSelectedTabIndicatorColor(LayoutUtils.DEFAULT_HIGHLIGHT); contentView.addView(tabLayout); // create 3 simple pages and add them to a page adapter ViewPageAdapter pagerAdapter = new ViewPageAdapter(); // info content tab pagerAdapter.addPage(ServiceMessages.getString("jobInfo"), infoForm.getView(job, ServiceMessages.getString("information"))); //$NON-NLS-1$ //$NON-NLS-2$ // address content tab pagerAdapter.addPage(ServiceMessages.getString("addresses"), addressForm.getView(job)); //$NON-NLS-1$ // report content tab pagerAdapter.addPage(ServiceMessages.getString("report"), reportForm.getView(job)); //$NON-NLS-1$ // ViewPager for PageAdapter ViewPager viewPager = new ViewPager(context); viewPager.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentView.addView(viewPager); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { if (position == 0 ) { // info contextMenuActionState(true); } else { contextMenuActionState(false); } if (position == 1) { // Address // do nothings } if (position == 2) { // Report signatureAction.setVisible(true); changeActionFinalizedReport(); changeActionSignature(); job.getLatestReport().checkIfTimeStartOverOndDay(app.dbutil); sendAction.setVisible(true); finalizedReportsAction.setVisible(true); changeActionSend(); } else { signatureAction.setVisible(false); sendAction.setVisible(false); finalizedReportsAction.setVisible(false); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Auto-generated method stub } @Override public void onPageScrollStateChanged(int state) { // Auto-generated method stub } }); // link TabLayout to ViewPager tabLayout.setupWithViewPager(viewPager); return contentView; } @Override public ApplicationEvent onBackPressed() { if (toolbar.isEnabled()) { toolbar.setEnabled(false); return app.leaveToForm(JobListForm.class, null); } return null; } private void contextMenuActionState(boolean state) { jobEditActioni.setVisible(state); jobEditActioni.setValidate(state); commissionNumberAction.setVisible(state); commissionNumberAction.setValidate(state); informationsAction.setVisible(state); informationsAction.setValidate(state); if (state) { if (job.getJobType().isREP() && job.isLocalJob() && app.dbutil.getUser().getPersonalNumber() == job.getPersonalNumber()) { jobEditActioni.setEnabled(true); } else { jobEditActioni.setEnabled(false); } if (job.getJobType().isREP() && (job.getCurrentReport() == null || job.getCurrentReport().getReportStatus().isInitial())) { informationsAction.setEnabled(true); commissionNumberAction.setEnabled(true); } else { informationsAction.setEnabled(false); commissionNumberAction.setEnabled(false); } } } public static class JobDetailFormArgument { private Job job; private int tabSelected; public int getTabSelected() { return tabSelected; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } protected JobDetailFormArgument() { } public JobDetailFormArgument(Job job) { this.job = job; } public JobDetailFormArgument(Job job, int tabSelect) { this.job = job; this.tabSelected = tabSelect; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailHistoryForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.List; import android.content.Context; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.History; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; /** * The history form for job details. * * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public class JobDetailHistoryForm extends GridLayoutForm { public JobDetailHistoryForm(Context context, ServiceApplication app) { super(context, app); } /** * Sets view. * * @param job * @param targetLinearLayout */ public void setView(Job job, LinearLayout targetLinearLayout) { createBemerkungenLayoutAndContents(job, targetLinearLayout, ServiceMessages.getString("remarks")); //$NON-NLS-1$ createHistoryLayoutAndContents(job, targetLinearLayout, ServiceMessages.getString("history")); //$NON-NLS-1$ } /** * Creates bemerkungen layout and contents. * * @param job * @param targetLinearLayout * @param title */ private void createBemerkungenLayoutAndContents(Job job, LinearLayout targetLinearLayout, String title) { GridLayout gridLayout = createGridLayout(title); gridLayout.setColumnCount(1); if (!job.getStatus().isInitial()) { if (job.getDescription().length() > 0) { createHistoryTextView(gridLayout, job.getDescription()); } else { createHistoryTextView(gridLayout, "-"); //$NON-NLS-1$ } if (job.getInformation().length() > 0) { createHistoryTextView(gridLayout, job.getInformation()); } else { createHistoryTextView(gridLayout, "-"); //$NON-NLS-1$ } } else { createHistoryTextView(gridLayout, ServiceMessages.getString("noReportAvailable")); //$NON-NLS-1$ } targetLinearLayout.addView(cardView); } /** * Creates history layout and contents. * * @param job * @param targetLinearLayout * @param title */ private void createHistoryLayoutAndContents(Job job, LinearLayout targetLinearLayout, String title) { GridLayout gridLayout = createGridLayout(title); gridLayout.setColumnCount(1); if (!job.getStatus().isInitial()) { List historieList = app.dbutil.selectHistoryList(job.getJobNumber(), job.getJobType().getCode()); if (!historieList.isEmpty()) { for (int i = 0; i < historieList.size(); i++) { History zkdhist = historieList.get(i); if (zkdhist.getText().length() > 0) { createHistoryTextView(gridLayout, zkdhist.getText()); } else { createHistoryTextView(gridLayout, "-"); //$NON-NLS-1$ } } } } else { createHistoryTextView(gridLayout, ServiceMessages.getString("noReportAvailable")); //$NON-NLS-1$ } targetLinearLayout.addView(cardView); } /** * Creates history text view. * * @param gridLayout * @param text */ private void createHistoryTextView(GridLayout gridLayout, String text) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(text.replace("\\n", System.getProperty("line.separator"))); //$NON-NLS-1$ //$NON-NLS-2$ gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridLayout.addView(gridTextViewKey); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailInfoCommissionNumberForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The commission number form for job details. * * @author nop (27-02-2017) * * @see "[MIG-43] implement of "Falsche Kommissionsnummer"" */ public class JobDetailInfoCommissionNumberForm extends SuperForm{ private static Log log = LogFactory.getLog(JobDetailInfoCommissionNumberForm.class); protected Job job; private CommissionNumberLayout commissionNumberLayout; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArguments = (JobDetailFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, contentLinearLayout, true); //$NON-NLS-1$ commissionNumberLayout.getCommissionNumberText().setLabel(ServiceMessages.getString("correctCommissionNumber")); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("commNotCorrect")); //$NON-NLS-1$ commissionNumberLayout.setJobTypeAndFormat(job.getJobType(), app.dbutil.getUser().getCommunicationNumberFormat()); if (!job.getCommissionNumber().isEmpty()) { commissionNumberLayout.setText(job.getCommissionNumber()); } else { commissionNumberLayout.setText("0"); //$NON-NLS-1$ } return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job)); } @Override protected boolean isValid() { boolean result = true; if ("".equals(commissionNumberLayout.getCommissionNumber().trim())) { //$NON-NLS-1$ commissionNumberLayout.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ result = false; } else { result = commissionNumberLayout.getCommissionNumberText().isValid(); } return result; } @Override protected boolean onSave() { saveButton.setEnabled(false); new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { log.info("Comm no " + job.getCommissionNumber()); job.setCommissionNumber(commissionNumberLayout.getCommissionNumber()); log.info("New Comm no " + job.getCommissionNumber()); if(new RemoteTransactionHandler().runUpdateOrder(job, app.dbutil.getUser())) { job = app.dbutil.selectJobByJobIdAndJobType(job.getJobNumber(), job.getJobType().toString()); job.loadReports(app.dbutil); return onBackPressed(); } return null; } }; return true; } @Override public void onFormReset() { super.onFormReset(); commissionNumberLayout.clear(); saveButton.setEnabled(true); } @Override protected void clearErrorMessages() { super.clearErrorMessages(); commissionNumberLayout.clearError(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailInfoForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.regex.Pattern; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.GridLayout; import android.text.Html; import android.text.util.Linkify; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; /** * The info form for job details. * * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public class JobDetailInfoForm extends GridLayoutForm { private JobDetailHistoryForm historyForm; private RelativeLayout infoRelativeLayout; public JobDetailInfoForm(Context context, ServiceApplication app) { super(context, app); this.historyForm = new JobDetailHistoryForm(context, app); } /** * Gets view. * * @param job * @param title */ public View getView(Job job, String title) { createLayoutAndContents(job, title); return getParentView(infoRelativeLayout); } /** * Creates layout and contents. * * @param job * @param title */ public void createLayoutAndContents(Job job, String title) { createInfoLayoutAndContents(job, title); } /** * Creates info layout and contents. * * @param job * @param title */ private void createInfoLayoutAndContents(Job job, String title) { infoRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams infoRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); infoRelativeLayoutParams.setMargins(0, 0, 0, LayoutUtils.DEFAULT_MAX_MARGIN); infoRelativeLayout.setLayoutParams(infoRelativeLayoutParams); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); addImportantContents(job, linearLayout); if (job.getJobType().isMON()) { createMONInfoContents(job, createGridLayout(title)); } else { createREPSAVInfoContents(job, createGridLayout(title)); } ((LayoutParams) cardView.getLayoutParams()).topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; linearLayout.addView(cardView); // add history historyForm.setView(job, linearLayout); infoRelativeLayout.addView(linearLayout); } /** * Creates MON info contents. * * @param gridLayout * @param gridLayout */ private void createMONInfoContents(Job job, GridLayout gridLayout) { addJobStatus(job, gridLayout); addJobNumber(job, gridLayout); addAppointment(job, gridLayout); addLink(job, gridLayout); addBackOffice(job, gridLayout); addEmptyRow(gridLayout); addInstallationNo(job, gridLayout); addDriveUnit(job, gridLayout); addResponsible(job, gridLayout); addSalesperson(job, gridLayout); addAllowedTime(job, gridLayout); } /** * Creates REP/SAV info contents. * * @param gridLayout * @param gridLayout */ private void createREPSAVInfoContents(Job job, GridLayout gridLayout) { addJobStatus(job, gridLayout); addJobNumber(job, gridLayout); addJobPriority(job, gridLayout); addAppointment(job, gridLayout); addOnCallService(job, gridLayout); addLink(job, gridLayout); addBackOffice(job, gridLayout); addJobCreationDate(job, gridLayout); addEmptyRow(gridLayout); addInstallationNo(job, gridLayout); addDriveUnit(job, gridLayout); addErrorMsgCode(job, gridLayout); addEmptyRow(gridLayout); addCheckCycles(job, gridLayout); addDocumentRequired(job, gridLayout); addSAV(job, gridLayout); addEmptyRow(gridLayout); addResponsibleSAN(job, gridLayout); addMoreInformations(job, gridLayout); } private void createInfoTextView(GridLayout gridLayout, String key, TextView gridTextViewValue) { TextView gridTextViewKey = new TextView(gridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.4f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout gridRelativeLayout = new RelativeLayout(gridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.6f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(gridTextViewValue); gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } /** * Creates info text view. * * @param gridLayout * @param key * @param value */ private void createInfoTextView(GridLayout gridLayout, String key, String value) { TextView gridTextViewValue = createTextView(gridLayout); gridTextViewValue.setText(value); createInfoTextView(gridLayout, key, gridTextViewValue); } private void createLinkTextView(GridLayout gridLayout, String key, final String url) { TextView gridTextViewValue = createTextView(gridLayout); Pattern pattern = Pattern.compile(url); Linkify.addLinks(gridTextViewValue, pattern, "http://"); gridTextViewValue.setText(Html.fromHtml("http://"+url+"")); gridTextViewValue.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("googlechrome://navigate?url="+ url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); createInfoTextView(gridLayout, key, gridTextViewValue); } private TextView createTextView(GridLayout gridLayout) { TextView gridTextViewValue = new TextView(gridLayout.getContext()); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); return gridTextViewValue; } private void addJobStatus(Job job, GridLayout gridLayout) { String jobStatus = app.enumUtil.jobStatusNameEnum.get(job.getStatus().getCode()); if (job.getStatus().isForwarded()) { Employee employee = app.dbutil.selectEmployeeByPerNr(job.getJobForward()); if (employee != null) { jobStatus += " an " + employee.getLastName() + "" + employee.getFirstName(); //$NON-NLS-1$ //$NON-NLS-2$ } } createInfoTextView(gridLayout, ServiceMessages.getString("state"), jobStatus); //$NON-NLS-1$ } private void addJobNumber(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, Messages.getString("orderNo"), job.getJobType() + " " + StringUtil.removeAllLeadingZero(job.getJobNumber())); //$NON-NLS-1$ //$NON-NLS-2$ } private void addJobPriority(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("priority"), app.enumUtil.jobPriorityEnum.get(job.getPriority())); //$NON-NLS-1$ } private void addAppointment(Job job, GridLayout gridLayout) { // Ternim String atpointmentText = ServiceMessages.getString("appointment"); //$NON-NLS-1$ String appointmentLabel = atpointmentText; String appointmentValue = ServiceMessages.getString("noAppointmentKnown"); //$NON-NLS-1$ if (job.getWeek() == 0 && !job.isFixed()) { appointmentLabel = atpointmentText; appointmentValue = job.getAppointmentDateAsString(); } else if (job.getWeek() == 0 && job.isFixed()) { appointmentLabel = ServiceMessages.getString("appointmentDefined"); //$NON-NLS-1$ appointmentValue = job.getHtmlAppointmentDate(); } else if (job.getWeek() > 0) { appointmentLabel = atpointmentText; appointmentValue = ServiceMessages.getString("week") + Integer.toString(job.getWeek()); //$NON-NLS-1$ } createInfoTextView(gridLayout, appointmentLabel, appointmentValue); if (job.isAppointment()) { createInfoTextView(gridLayout, "", ServiceMessages.getString("coordinateAppointment")); //$NON-NLS-1$ //$NON-NLS-2$ } } private void addOnCallService(Job job, GridLayout gridLayout) { String onCallService = "-"; //$NON-NLS-1$ if (job.getJobType().isREP()) { if (job.isCallServiceFlag()) { onCallService = ServiceMessages.getString("yes"); } else { onCallService = ServiceMessages.getString("no"); } } createInfoTextView(gridLayout, ServiceMessages.getString("onCall"), onCallService); //$NON-NLS-1$ } private void addLink(Job job, GridLayout gridLayout) { if (job.getLink().isEmpty()) { createInfoTextView(gridLayout, ServiceMessages.getString("link"), "-"); } else { createLinkTextView(gridLayout, ServiceMessages.getString("link"), job.getLink()); } } private void addBackOffice(Job job, GridLayout gridLayout) { String backOfficeLabel; if (job.getJobType().isMON()) { backOfficeLabel = ServiceMessages.getString("projectLeader"); //$NON-NLS-1$ } else { backOfficeLabel = ServiceMessages.getString("backOffice"); //$NON-NLS-1$ } createInfoTextView(gridLayout, backOfficeLabel, job.getStaffName()); createInfoTextView(gridLayout, "", job.getStaffPhoneNumber()); //$NON-NLS-1$ } private void addJobCreationDate(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("receipt"), job.getHtmlDateTimeNewJobDate()); //$NON-NLS-1$ } private void addInstallationNo(Job job, GridLayout gridLayout) { String vbeln = "-"; //$NON-NLS-1$ if (job.getCommissionNumber().length() > 0) { vbeln = job.getCommissionNumber(); } createInfoTextView(gridLayout, Messages.getString("commNo"), vbeln); //$NON-NLS-1$ } private void addDriveUnit(Job job, GridLayout gridLayout) { String driveUnit = "-"; //$NON-NLS-1$ if (job.getDriveType().length() > 0) { driveUnit = job.getDriveType(); } createInfoTextView(gridLayout, ServiceMessages.getString("drive"), driveUnit); //$NON-NLS-1$ } private void addResponsible(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("caseHandler"), job.getTechnicalName()); //$NON-NLS-1$ createInfoTextView(gridLayout, "", job.getTechnicalPhoneNumber()); //$NON-NLS-1$ } private void addSalesperson(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("salesPerson"), job.getSellerName()); //$NON-NLS-1$ createInfoTextView(gridLayout, "", job.getSellerPhoneNumber()); //$NON-NLS-1$ } private void addAllowedTime(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("allowedTime"), job.getDefaultTime() + ServiceMessages.getString("hrs")); //$NON-NLS-1$ //$NON-NLS-2$ } private void addErrorMsgCode(Job job, GridLayout gridLayout) { String errorMsgCode = "-"; //$NON-NLS-1$ if (job.getJobType().isREP()) { errorMsgCode = job.getErrorId(); } createInfoTextView(gridLayout, ServiceMessages.getString("errorCode"), errorMsgCode); //$NON-NLS-1$ } private void addCheckCycles(Job job, GridLayout gridLayout) { String checkCycles = "-"; //$NON-NLS-1$ if (job.isCycleOfInstallationFlag()) { checkCycles = ServiceMessages.getString("yes"); } else { checkCycles = ServiceMessages.getString("no"); } createInfoTextView(gridLayout, ServiceMessages.getString("checkCycles"), checkCycles); //$NON-NLS-1$ } private void addDocumentRequired(Job job, GridLayout gridLayout) { String documentRequired = ""; String formDesc1 = getFormDesc(job.getFormDesc1()); String formDesc2 = getFormDesc(job.getFormDesc2()); String formDesc3 = getFormDesc(job.getFormDesc3()); documentRequired += documentRequired.isEmpty() ? formDesc1:(formDesc1.isEmpty() ? "": ", " + formDesc1); documentRequired += documentRequired.isEmpty() ? formDesc2:(formDesc2.isEmpty() ? "": ", " + formDesc2); documentRequired += documentRequired.isEmpty() ? formDesc3:(formDesc3.isEmpty() ? "": ", " + formDesc3); createInfoTextView(gridLayout, ServiceMessages.getString("Document"), documentRequired); //$NON-NLS-1$ } private String getFormDesc(String formDesc) { String result = ""; JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(formDesc); if (jobFormDesc != null && !jobFormDesc.getFormDesc().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { result = jobFormDesc.getText(); } return result; } private void addSAV(Job job, GridLayout gridLayout) { // Title createInfoTextView(gridLayout, ServiceMessages.getString("SAV"), ""); //$NON-NLS-1$ //$NON-NLS-2$ // SAV Code createInfoTextView(gridLayout, ServiceMessages.getString("maintenanceCode"), job.getMaintenanceContractType()); //$NON-NLS-1$ // SAV geplant createInfoTextView(gridLayout, ServiceMessages.getString("maintenancePlanned"), job.getServicePlanMonth1() + " " //$NON-NLS-1$ //$NON-NLS-2$ + job.getServicePlanMonth2() + " " //$NON-NLS-1$ + job.getServicePlanMonth3() + " " //$NON-NLS-1$ + job.getServicePlanMonth4() + " " //$NON-NLS-1$ + job.getServicePlanMonth5() + " " //$NON-NLS-1$ + job.getServicePlanMonth6() + " "); //$NON-NLS-1$ // SAV offen createInfoTextView(gridLayout, ServiceMessages.getString("openMaintenance"), job.getServiceOpen()); //$NON-NLS-1$ } private void addResponsibleSAN(Job job, GridLayout gridLayout) { String responsibleSan = "-"; //$NON-NLS-1$ if (job.getContactName().length() > 0) { responsibleSan = job.getContactName(); } createInfoTextView(gridLayout, ServiceMessages.getString("SAVResponsible"), responsibleSan); //$NON-NLS-1$ if (job.getContactPhoneNumber().length() > 0) { createInfoTextView(gridLayout, "", job.getContactPhoneNumber()); //$NON-NLS-1$ } } private void addMoreInformations(Job job, GridLayout gridLayout) { createInfoTextView(gridLayout, ServiceMessages.getString("moreInformations"), ServiceMessages.getString(job.isMoreInformationsFlag() == true ? "yes" : "no")); } private void addEmptyRow(GridLayout gridLayout) { createInfoTextView(gridLayout, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Adds Notes layout and contents. * * @param job * @param targetLinearLayout */ private void addImportantContents(Job job, LinearLayout targetLinearLayout) { GridLayout gridLayout = createGridLayout(ServiceMessages.getString("Important")); gridLayout.setColumnCount(1); addNoteTextView(gridLayout, job.getDescription()); addNoteTextView(gridLayout, job.getInformation()); targetLinearLayout.addView(cardView); } private void addNoteTextView(GridLayout gridLayout, String text) { if (text.isEmpty()) { return; } TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewParams = new GridLayout.LayoutParams(); gridTextViewParams.width = 0; gridTextViewParams.height = LayoutParams.WRAP_CONTENT; gridTextViewParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); textView.setLayoutParams(gridTextViewParams); textView.setText(text.replace("\\n", System.getProperty("line.separator"))); //$NON-NLS-1$ //$NON-NLS-2$ textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridLayout.addView(textView); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailInfoInstallationTypeForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.text.InputFilter; import android.text.InputType; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Drive; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The commission number form for job details. * * @see "[MIG-995] Editing of installation type" */ public class JobDetailInfoInstallationTypeForm extends SuperForm{ private static Log log = LogFactory.getLog(JobDetailInfoInstallationTypeForm.class); protected Job job; protected MDEditText zantrtypDescription; @Override public void onFormCall(Object argument) { if (argument instanceof JobDetailFormArgument) { JobDetailFormArgument formArguments = (JobDetailFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); // zantrty description zantrtypDescription = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("correctInstallationType"), //$NON-NLS-1$ InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); zantrtypDescription.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); zantrtypDescription.setFocusable(true); zantrtypDescription.setFocusableInTouchMode(true); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("editingInstallationType")); //$NON-NLS-1$ zantrtypDescription.setText(job.getDriveType()); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job)); } @Override protected boolean isValid() { boolean result = true; if (zantrtypDescription.getText().toString().isEmpty()) { //$NON-NLS-1$ zantrtypDescription.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ result = false; } return result; } @Override protected boolean onSave() { saveButton.setEnabled(false); new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { log.info("Installation type " + job.getDriveType()); job.setDriveType(zantrtypDescription.getText().toString()); app.dbutil.updateJob(job); log.info("New Installation type " + job.getDriveType()); if(new RemoteTransactionHandler().runSaveOrder(job, null)) { return onBackPressed(); } return null; } }; return true; } @Override public void onFormReset() { super.onFormReset(); // commissionNumberLayout.clear(); saveButton.setEnabled(true); } @Override protected void clearErrorMessages() { super.clearErrorMessages(); // commissionNumberLayout.clearError(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDetailReportForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.DialogInterface; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportFormListForm.ReportFormListFormArguments; import ch.mfiles.kaba.kolibri.service.ui.widgets.GridLayoutForm; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceFormUtil; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The report form for job detail. * * @author nop (21-03-2017) * @see "[MIG-51] implement of report overview" */ public class JobDetailReportForm extends GridLayoutForm { private static Log log = LogFactory.getLog(JobDetailReportForm.class); private RelativeLayout reportRelativeLayout; private LinearLayout cardLinearLayout; private CommonConstants.CommissionNumber.Type commissionType = CommonConstants.CommissionNumber.Type.CORRECT; private GridLayout timeGridLayout; private Job job; private int textColor = LayoutUtils.DEFAULT_TEXT_COLOR; JobDetailReportForm detailReportForm; /** * Default working type for repair orders: Non ("Bitte w�hlen..") because * relevant working type is taken from the report (ZKDMOBREP) record */ protected static final String DEFAULT_REP_ARBA = "00"; //$NON-NLS-1$ /** * Default working type for assambly orders: Non ("Bitte w�hlen..") because * relevant working type is taken from the report (ZKDMOBREP) record */ protected static final String DEFAULT_MON_ARBA = "00"; //$NON-NLS-1$ /** * Default working type for maintenance orders: "Vertragsservice" */ protected static final String DEFAULT_SAV_ARBA = "05"; //$NON-NLS-1$ private enum CardType { TIME, REPORT_DATA, CHECKLIST, MATERIAL, MESSAGE, IMAGE, DOCUMENT, MEASUREMENT, FORM } TimeUtil timeUtil = null; public JobDetailReportForm(Context context, ServiceApplication app) { super(context, app); timeUtil = new TimeUtil(app, app.dbutil, this); } /** * Gets view. * * @param job */ public View getView(Job job) { this.job = job; job.loadAddresses(app.dbutil); job.loadReports(app.dbutil); if (job.getStatus().isFinalized()) { textColor = LayoutUtils.DEFAULT_LABEL_COLOR; } else { textColor = LayoutUtils.DEFAULT_TEXT_COLOR; } createLayoutAndContents(); detailReportForm = this; return getParentView(reportRelativeLayout); } /** * Creates layout and contents. */ public void createLayoutAndContents() { reportRelativeLayout = new RelativeLayout(context); reportRelativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); createReportLayoutAndContents(job); reportRelativeLayout.addView(cardLinearLayout); } /** * Creates REP report layout and contents. * * @param job * @param targetLinearLayout * @param title */ private void createReportLayoutAndContents(Job job) { appendTime(); appendReportData(); if (job.getJobType().isMON()) { appendChecklist(); } appendMaterials(); appendMessages(); appendImages(); appendDocuments(); appendMeasurements(); appendForms(); } /** * Creates report text view. * * @param gridLayout * @param text */ private void createReportTextView(GridLayout gridLayout, String text) { createReportTextView(gridLayout, text, textColor); } private void createReportTextView(GridLayout gridLayout, String text, int color) { TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 1f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(text); gridTextViewKey.setTextColor(color); gridLayout.addView(gridTextViewKey); } private void createReportTextView(GridLayout gridLayout, String key, String value) { createReportTextView(gridLayout, key, value, false); } private void createReportTextView(GridLayout gridLayout, String key, String value , boolean isBold) { TextView gridTextViewKey = new TextView(gridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.4f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(key); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout gridRelativeLayout = new RelativeLayout(gridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.6f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(gridLayout.getContext()); gridTextViewValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); if (isBold) { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); } else { gridTextViewValue.setTypeface(CommonConstants.Font.getDefaultRegularFont()); } RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(value); gridTextViewValue.setTextColor(textColor); gridRelativeLayout.addView(gridTextViewValue); gridLayout.addView(gridTextViewKey); gridLayout.addView(gridRelativeLayout); } private void createReportTextViewWithIcon( GridLayout gridLayout, final String timeInfo, final CardType cardType) { createReportTextViewWithIcon(gridLayout, timeInfo, cardType, CommonConstants.Mode.EDIT); } private void createReportTextViewWithIcon(final GridLayout gridLayout, final String timeInfo, final CardType cardType, final String mode) { if (job.getStatus().isFinalized()) { return; } RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, gridLayout.getColumnCount(), 1f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(context); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(""); //$NON-NLS-1$ gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridRelativeLayout.addView(gridTextViewValue); LinearLayout linearLayout = new LinearLayout(context); RelativeLayout.LayoutParams linearLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); linearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.HORIZONTAL); createTimeContents(timeInfo, linearLayout); linearLayout.addView(createAddEditImageView(cardType, mode)); gridRelativeLayout.addView(linearLayout); gridLayout.addView(gridRelativeLayout); } private void createReportViewWithIcon(final GridLayout gridLayout, final String timeInfo, final CardType cardType, final String mode, View view, ImageView image) { RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, gridLayout.getColumnCount(), 1f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); TextView gridTextViewValue = new TextView(context); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); gridTextViewValue.setLayoutParams(gridTextViewValueParams); gridTextViewValue.setText(""); //$NON-NLS-1$ gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridRelativeLayout.addView(gridTextViewValue); LinearLayout linearLayout = new LinearLayout(context); RelativeLayout.LayoutParams linearLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); linearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.HORIZONTAL); if(view != null) { gridRelativeLayout.addView(view); } if(image != null) { linearLayout.addView(image); } else { linearLayout.addView(createAddEditImageView(cardType, mode)); } gridRelativeLayout.addView(linearLayout); gridLayout.addView(gridRelativeLayout); } private ImageView createAddEditImageView(final CardType cardType, final String mode) { ImageView editImageView = new ImageView(context); editImageView.setContentDescription(mode); editImageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); Images editImage = ImagesUtil.Images.EDIT; if (mode.equalsIgnoreCase(CommonConstants.Mode.NEW)) { editImage = ImagesUtil.Images.ADD_BLACK; } editImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(editImage, CommonConstants.Images.IMAGE_DPI))); editImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (CardType.REPORT_DATA == cardType) { if (mode.equalsIgnoreCase(CommonConstants.Mode.NEW)) { showCommissionNumberDialog(); } else { app.injectAndLeaveToForm(ReportEditForm.class, new FormArguments(job, null)); } } else if (CardType.TIME == cardType) { app.injectAndLeaveToForm(ReportTimeListForm.class, new ReportTimeListForm.ReportTimeListFormArguments(job, null)); } else if (CardType.CHECKLIST == cardType) { app.injectAndLeaveToForm(ReportChecklistForm.class, new FormArguments(job, null)); } else if (CardType.MATERIAL == cardType) { app.injectAndLeaveToForm(ReportMaterialListForm.class, new ReportMaterialListForm.ReportMaterialListFormArguments(job)); } else if (CardType.MESSAGE == cardType) { app.injectAndLeaveToForm(ReportMessageNewEditForm.class, new ReportMessageNewEditForm.FormArguments(job)); } else if (CardType.IMAGE == cardType) { app.injectAndLeaveToForm(ReportImageAttachmentsListForm.class, new ReportImageAttachmentsListForm.ReportImageAttachmentsListFormArguments(job)); } else if (CardType.DOCUMENT == cardType) { app.injectAndLeaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); } else if (CardType.MEASUREMENT == cardType) { app.injectAndLeaveToForm(ReportMeasurementForm.class, new ReportMeasurementForm.ReportMeasurementFormArguments(job)); } else if (CardType.FORM == cardType) { app.injectAndLeaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); } } }); return editImageView; } private void createTimeContents(final String timeInfo, LinearLayout linearLayout) { if (timeInfo != null) { ImageView timeInfoImageView = new ImageView(context); LinearLayout.LayoutParams editImageViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); editImageViewParams.rightMargin = 30; timeInfoImageView.setLayoutParams(editImageViewParams); createStartStopTimeImage(job, timeInfoImageView); if (CommonConstants.Mode.STOP.equals(timeInfo)) { timeInfoImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean result = timeUtil.startJobTimeCapturing(job); if (result) { timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, job, new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { appendTimeContent(); onTimeAction.runOnTimeAction(); } }); } } }); } else { timeInfoImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timeUtil.stopTime(job, new RunOnUIThread() { @Override public void runOnUIThread() { appendTimeContent(); onTimeAction.runOnTimeAction(); } }); } }); } linearLayout.addView(timeInfoImageView); } } private void createStartStopTimeImage(final Job job, ImageView timeInfoImageView) { Images timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; timeInfoImageView.setEnabled(false); if (ServiceJobUtil.isJobStartTimeable(job)) { if (app.dbutil.selectPlayingJobReportTimeByReport(job.getCurrentReport()) != null) { timeStatusImage = ImagesUtil.Images.STOP_TIME; timeInfoImageView.setEnabled(true); } else { List jobWithOpenTimesheetList = app.dbutil.selectJobWithOpenTimesheet(); if(jobWithOpenTimesheetList.isEmpty()) { timeStatusImage = ImagesUtil.Images.START_TIME; timeInfoImageView.setEnabled(true); } else { timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; timeInfoImageView.setEnabled(false); for (Job jobWithOpenTimesheet : jobWithOpenTimesheetList) { if (jobWithOpenTimesheet.getPersonalNumber() == job.getPersonalNumber() && jobWithOpenTimesheet.getCommissionNumber().equalsIgnoreCase(job.getCommissionNumber()) && jobWithOpenTimesheet.getJobType() == job.getJobType()) { timeStatusImage = ImagesUtil.Images.START_TIME; timeInfoImageView.setEnabled(true); } } } } } timeInfoImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(timeStatusImage, CommonConstants.Images.IMAGE_DPI))); } private void appendReportData() { Address address = job.getObjectAddress(); GridLayout gridLayout = createGridLayout(ServiceMessages.getString("reportData")); //$NON-NLS-1$ gridLayout.setColumnCount(1); gridLayout.setContentDescription("reportData"); if (job.getCurrentReport().getReportStatus().isNew() || job.getStatus().isFinalized()) { String comNo = job.getCommissionNumber(); if (StringUtil.isNotEmpty(job.getCurrentReport().getCommissionNumber()) && job.getCurrentReport().getCommissionNumber().length() > 1) { comNo = job.getCurrentReport().getCommissionNumber(); } // Anlagen-Nummer if (StringUtil.isNotEmpty(comNo)) createReportTextView(gridLayout, comNo, textColor); // Standort if (StringUtil.isNotEmpty(address.getLocation())) { createReportTextView(gridLayout, address.getLocation(), textColor); } // Strasse / PLZ / Anlage-Ort if (StringUtil.isNotEmpty(address.getStreet()) || StringUtil.isNotEmpty(address.getPostalCode()) || StringUtil.isNotEmpty(address.getCity())) createReportTextView(gridLayout, address.getStreet() + " " + address.getPostalCode() + " " + address.getCity(), textColor); //$NON-NLS-1$ //$NON-NLS-2$ if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.REPORT_DATA); } } else { createReportTextView(gridLayout, Messages.getString("noReportRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ if ((job.getStatus().isReceived() || job.getStatus().isPartlyDone() || job.getStatus().isInProgress()) && !job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.REPORT_DATA, CommonConstants.Mode.NEW); } } cardLinearLayout.addView(cardView); } private void appendTime() { timeGridLayout = createGridLayout(Messages.getString("times")); //$NON-NLS-1$ timeGridLayout.setColumnCount(1); appendTimeContent(); ((LayoutParams) cardView.getLayoutParams()).topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; cardLinearLayout.addView(cardView); } private void appendTimeContent() { Report report = job.getCurrentReport(); log.info("report status " + report.getReportStatus().toString()); log.info("report guid " + report.getGuId() + " has times -> " + report.getTimes().size()); timeGridLayout.removeAllViews(); String timeInfo = CommonConstants.Mode.STOP; // Aufgewendete Zeit (nur wenn vorhanden) report.loadTimes(app.dbutil); List reportTimeList = report.getTimes(); if (reportTimeList.isEmpty()) { createReportTextView(timeGridLayout, Messages.getString("noTimesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ createReportTextViewWithIcon(timeGridLayout, timeInfo, CardType.TIME, CommonConstants.Mode.NEW); } else { long diffTime = 0; for (int i = 0; i < reportTimeList.size(); i++) { JobReportTime reportTime = reportTimeList.get(i); WorkType WorkType = app.dbutil.selectWorkTypeByJobTypeAndWorkTypeCode(job.getJobType(), reportTime.getWorkTypeCode()); String workType = (WorkType == null ? "" : WorkType.getText()); if (!DateUtils.getInitialDateTime().equals(reportTime.getStopTime())) { timeInfo = CommonConstants.Mode.STOP; createReportTextView(timeGridLayout, DateTimeUtil.showDate(reportTime.getDate()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(reportTime.getStartTime()) + "-" //$NON-NLS-1$ + DateTimeUtil.showTime(reportTime.getStopTime()) + " " //$NON-NLS-1$ + workType); } else { timeInfo = CommonConstants.Mode.PLAYING; createReportTextView(timeGridLayout, DateTimeUtil.showDate(reportTime.getDate()) + " " //$NON-NLS-1$ + DateTimeUtil.showTime(reportTime.getStartTime()) + "-", LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ } diffTime += DateTimeUtil.getTimeDifference(reportTime.getStopTime(), reportTime.getStartTime()); } // total label createReportTextView(timeGridLayout, ServiceMessages.getString("total") //$NON-NLS-1$ , textColor); // time createReportTextView(timeGridLayout, DateTimeUtil.showTime(diffTime)); createReportTextViewWithIcon(timeGridLayout, timeInfo, CardType.TIME); } } private ImageView materialEditImageView; private void appendMaterials() { materialEditImageView = new ImageView(context); materialEditImageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); Images editImage = ImagesUtil.Images.EDIT; // if (mode.equalsIgnoreCase(CommonConstants.Mode.NEW)) { // editImage = ImagesUtil.Images.ADD_BLACK; // } materialEditImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(editImage, CommonConstants.Images.IMAGE_DPI))); materialEditImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { app.injectAndLeaveToForm(ReportMaterialListForm.class, new ReportMaterialListForm.ReportMaterialListFormArguments(job)); } }); GridLayout gridLayout = createGridLayout(Messages.getString("material")); //$NON-NLS-1$ gridLayout.setColumnCount(1); // Verwendetes Material (nur wenn vorhanden) List reportMatList = app.dbutil.selectReportMaterialListByLimit(job.getLatestReport().getGuId(), 3); if (!reportMatList.isEmpty()) { for (int i = 0; i < reportMatList.size(); i++) { ReportMaterial reportMat = reportMatList.get(i); Material part = app.dbutil.selectMaterialByMatNo(reportMat.getSparePartNumber()); String material = reportMat.getAmount() + " " + reportMat.getUnit(); //$NON-NLS-1$ if (part == null) { material += " " + reportMat.getProductName(); //$NON-NLS-1$ } else { material += " " + part.getMaterialShortText(); //$NON-NLS-1$ } createReportTextView(gridLayout, material, textColor); } if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.MATERIAL); } } else { createReportTextView(gridLayout, Messages.getString("noMaterialRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ if (!job.getStatus().isNew() && !job.getStatus().isForwarded() && !job.getStatus().isFinalized()) { AppCompatCheckBox noMaterial = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("noMaterialused")); //$NON-NLS-1$ RelativeLayout.LayoutParams gridCheckBoxViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridCheckBoxViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); noMaterial.setLayoutParams(gridCheckBoxViewValueParams); log.info("isNoMaterial " + job.getLatestReport().isNoMaterial()); noMaterial.setChecked(job.getLatestReport().isNoMaterial()); materialEditImageView.setVisibility(View.VISIBLE); noMaterial.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton paramCompoundButton, final boolean checked) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { job.getLatestReport().setNoMaterial(checked); log.info("report " + job.getLatestReport().getGuId() + " status " + job.getLatestReport().getReportStatus().toString() + " isNoMaterial " + job.getLatestReport().isNoMaterial()); app.dbutil.insertReplaceReport(job.getLatestReport()); // app.dbutil.updateReport(report); app.dbutil.updateJob(job); job.loadReports(app.dbutil); log.info("report " + app.dbutil.selectCountFromTable(DbConstants.Report.REPORT, " WHERE " + DbConstants.Report.GUID + "='" + job.getLatestReport().getGuId()+ "'")); Report report = job.getLatestReport(); log.info("report " + report.getGuId() + " status " + report.getReportStatus().toString() + " isNoMaterial " + report.isNoMaterial()); return null; } @Override protected void runOnUIThread() { if(checked) { materialEditImageView.setVisibility(View.INVISIBLE); } else { materialEditImageView.setVisibility(View.VISIBLE); } } }; } }); createReportViewWithIcon(gridLayout, null, CardType.MATERIAL, CommonConstants.Mode.NEW, noMaterial, materialEditImageView); } } cardLinearLayout.addView(cardView); } private void appendMessages() { Report report = job.getCurrentReport(); GridLayout gridLayout = createGridLayout(Messages.getString("messages")); //$NON-NLS-1$ String messageId = ""; //$NON-NLS-1$ List reportTextList = app.dbutil.selectJobMessageListByReport(report); boolean isEmptyMessage = true; for (int i = 0; i < reportTextList.size(); i++) { JobMessage zkdmobmsg = reportTextList.get(i); String messageIdTemp = zkdmobmsg.getMessageId(); String key = ""; //$NON-NLS-1$ if (!messageId.equals(messageIdTemp)) { key = app.enumUtil.messageRecipientEnum.get(zkdmobmsg.getMessageId()); } String message = ""; log.info("zkdmobmsg " + zkdmobmsg.getMessageCode()); if(job.getJobType().isMON()) { JobMonText jobMonText = app.dbutil.selectReportMONMessageByMsgcAndLangu(zkdmobmsg.getMessageCode(), ""); if(jobMonText != null) { message = jobMonText.getText(); } } else { ReportMessage reportMessage = app.dbutil.selectReportMessageByMsgc(zkdmobmsg.getMessageCode()); if(reportMessage != null) { message = reportMessage.getMessage(); } } if(!message.isEmpty() || !zkdmobmsg.getFullText().isEmpty()) { isEmptyMessage = false; createReportTextView(gridLayout, key, message, true); createReportTextView(gridLayout, "", zkdmobmsg.getFullText()); //$NON-NLS-1$ } } if (isEmptyMessage) { createReportTextView(gridLayout, Messages.getString("noMessagesRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ createReportTextViewWithIcon(gridLayout, null, CardType.MESSAGE, CommonConstants.Mode.NEW); } else { if (!job.getStatus().isFinalized()) { createReportTextView(gridLayout, ""); //$NON-NLS-1$ createReportTextViewWithIcon(gridLayout, null, CardType.MESSAGE); } } cardLinearLayout.addView(cardView); } private void appendImages() { GridLayout gridLayout = createGridLayout(Messages.getString("images")); //$NON-NLS-1$ gridLayout.setColumnCount(1); List reportImageAttachmentsList = app.dbutil.selectReportJobFileImageListByReport(job.getLatestReport()); // If no data available: "No report images captured"; text red // // If a document was added: "At least 5 images necessary", text red // if image(s) added: text black, status of report images if (!reportImageAttachmentsList.isEmpty()) { createReportTextView(gridLayout, reportImageAttachmentsList.size() + " " + Messages.getString("images"), textColor); int sentCount = 0; for (JobFile jobFile : reportImageAttachmentsList) { if (jobFile.getSentDate().getTime() > 0) { sentCount++; } } String status = ServiceMessages.getString("status") + ": "; if (sentCount == 0) { // "Not send" when no image was send to backend yet status += ServiceMessages.getString("notSend"); } else if (sentCount < reportImageAttachmentsList.size()) { // "Partially send" when some (but not all) images are send status += ServiceMessages.getString("partiallySend"); } else if (sentCount == reportImageAttachmentsList.size()) { // "Send" when all images are send to backend already status += ServiceMessages.getString("sent"); } createReportTextView(gridLayout, status, textColor); if (!ServiceJobUtil.isInstallationWorkTypeComplete(job)) { createReportTextView(gridLayout, MessageFormat.format(ServiceMessages.getString("AtLeastXImagesNecessary") , new Object[] { ServiceConstants.REQUIRE_IMAGE}), LayoutUtils.DEFAULT_ERROR_COLOR); } if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.IMAGE); } } else { String text = Messages.getString("noImagesRecorded"); int imageRequire = 0; if (!ServiceJobUtil.isReportImageComplete(job)) { imageRequire = 1; } if (!ServiceJobUtil.isInstallationWorkTypeComplete(job)) { imageRequire = ServiceConstants.REQUIRE_IMAGE; } if (imageRequire > 0) { text = MessageFormat.format(ServiceMessages.getString("AtLeastXImagesNecessary") , new Object[] { imageRequire}); } createReportTextView(gridLayout, text, LayoutUtils.DEFAULT_ERROR_COLOR); //$NON-NLS-1$ createReportTextViewWithIcon(gridLayout, null, CardType.IMAGE, CommonConstants.Mode.NEW); } cardLinearLayout.addView(cardView); } private void appendDocuments() { GridLayout gridLayout = createGridLayout(Messages.getString("documents")); //$NON-NLS-1$ gridLayout.setColumnCount(1); List documentRequires = ServiceJobUtil.isReportDocsComplete(job); if (!job.getCurrentReport().getDocumentAttachments().isEmpty()) { Iterator> iterator = job.getLatestReport().getDocumentFormDescMap().values().iterator(); while (iterator.hasNext()) { List jobFiles = iterator.next(); JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(jobFiles.get(0).getFormDesc()); String docText = jobFiles.size() + " " + jobFormDesc.getText(); if (jobFiles.get(0).getNoForm().isEmpty()) { docText = jobFiles.size() + " " + jobFormDesc.getText(); } else { // noForm docText = jobFormDesc == null ? "":jobFormDesc.getText() + " :" + app.dbutil.selectJobNoFormByNoForm(jobFiles.get(0).getNoForm()).getText(); } documentRequires.remove(jobFiles.get(0).getFormDesc()); createReportTextView(gridLayout, docText, textColor); } showRequire(gridLayout, documentRequires); if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.DOCUMENT); } } else { if (!ServiceJobUtil.isReportDocsComplete(job).isEmpty()) { showRequire(gridLayout, documentRequires); } else { createReportTextView(gridLayout, Messages.getString("noDocumentsRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); } createReportTextViewWithIcon(gridLayout, null, CardType.DOCUMENT, CommonConstants.Mode.NEW); } cardLinearLayout.addView(cardView); } private void showRequire(GridLayout gridLayout, List documentRequires) { documentRequires = ServiceJobUtil.isReportDocsComplete(job); if (!documentRequires.isEmpty()) { for (String formDocRequire : documentRequires) { JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(formDocRequire); if (jobFormDesc != null) { createReportTextView(gridLayout, getDocumentRequireMessage(jobFormDesc.getText()), textColor); } } } } private String getDocumentRequireMessage(String jobFormDesc) { return MessageFormat.format(ServiceMessages.getString("DocumentReqired"), new Object[] { jobFormDesc}); } private void appendMeasurements() { GridLayout gridLayout = createGridLayout(Messages.getString("measurement")); //$NON-NLS-1$ gridLayout.setColumnCount(1); job.getLatestReport().loadMeasurements(app.dbutil); if (!job.getLatestReport().getMeasurements().isEmpty()) { // If no measurement done: "No measurement available"; text red // If a measurement is done: "Measurement: Complete"; text black // If a measurement has errors or is not complete: "Measurement incomplete", text red // TODO how to know that measurement is error if (!job.getStatus().isNew() && !job.getStatus().isForwarded() && !job.getStatus().isFinalized()) { if (ServiceJobUtil.isTooMuchMeasurementAreMadeForOnemeasurePoint(job.getLatestReport().getMeasurements())) { createReportTextView(gridLayout, ServiceJobUtil.getTooMuchMeasurementAreMadeForOnemeasurePointMessage(), LayoutUtils.DEFAULT_ERROR_COLOR); } else { createReportTextView(gridLayout, ServiceMessages.getString("MeasurementComplete"), textColor); } if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.MEASUREMENT); } } } else { createReportTextView(gridLayout, Messages.getString("noMeasurementsRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); createReportTextViewWithIcon(gridLayout, null, CardType.MEASUREMENT, CommonConstants.Mode.NEW); } // TODO If a measurement has errors or is not complete: "Measurement incomplete", text red cardLinearLayout.addView(cardView); } private void appendChecklist() { GridLayout gridLayout = createGridLayout(ServiceMessages.getString("Checklist")); //$NON-NLS-1$ gridLayout.setColumnCount(1); if (job.getLatestReport().isChedklistEdited()) { createReportTextView(gridLayout, ServiceMessages.getString("completed"), textColor); if (!job.getStatus().isFinalized()) { createReportTextViewWithIcon(gridLayout, null, CardType.CHECKLIST); } } else { createReportTextView(gridLayout, ServiceMessages.getString("notEdit"), LayoutUtils.DEFAULT_ERROR_COLOR); createReportTextViewWithIcon(gridLayout, null, CardType.CHECKLIST, CommonConstants.Mode.NEW); } cardLinearLayout.addView(cardView); } private void appendForms() { GridLayout gridLayout = createGridLayout(ServiceMessages.getString("Forms")); //$NON-NLS-1$ gridLayout.setColumnCount(2); String mode = CommonConstants.Mode.NEW; // If no form edited or done: // Icon: + (add) // Active: Always, until report was send // // If a form is edited or done: // Icon: (Edit) // Active: Until report was send // ZKDMOB.FORMDESC1 = 01 (document required as mandatory for user to add an attachment or a generic form to report) // Now check FORM.ID (CHAR4) the 2nd and 3rd digit // -> If those digits of FORM.ID (for example F010)are the same as in ZKKDMOB.FORMDESC1 (in this case 01), the user has to add this generic form // -> If those digits of FORM.ID (for example F020) aren't the same (in this case 01), the user has to add a document as a picture (as already implemented actually) if (app.dbutil.selectFormInstanceListByGuid( job.getLatestReport().getGuId()).isEmpty()) { gridLayout.setColumnCount(1); List documentRequires = ServiceJobUtil.isReportDocsComplete(job); if (!documentRequires.isEmpty()) { for (String formDocRequire : documentRequires) { JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(formDocRequire); String text = MessageFormat.format(ServiceMessages.getString("FormReqired"), new Object[] { jobFormDesc.getText()}); createReportTextView(gridLayout, text, LayoutUtils.DEFAULT_ERROR_COLOR); } } else { createReportTextView(gridLayout, ServiceMessages.getString("noFormsRecorded"), LayoutUtils.DEFAULT_ERROR_COLOR); } } else { gridLayout.setColumnCount(2); for (Form form : app.dbutil.selectFormList()) { List formItemList = app.dbutil.selectFormItemListByFormIdAndFormVersion(form.getId(), form.getVersion()); if (!formItemList.isEmpty()) { List formInstances = app.dbutil.selectFormInstanceListByGuidAndFormId(job.getLatestReport().getGuId(), form.getId()); if (!formInstances.isEmpty()) { gridLayout.addView(createFormGridLayout(form, formInstances, formItemList)); if (ServiceFormUtil.isFormEdited(formInstances) || ServiceFormUtil.isFormDone(formItemList, formInstances)) { mode = CommonConstants.Mode.EDIT; } } } } } createReportTextViewWithIcon(gridLayout, null, CardType.FORM, mode); cardLinearLayout.addView(cardView); } private GridLayout createFormGridLayout(Form form, List formInstances, List formItemList) { GridLayout formGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); formGridLayout.setLayoutParams(gridLayoutParams); formGridLayout.setColumnCount(2); formGridLayout.setUseDefaultMargins(true); formGridLayout.setColumnCount(2); LinearLayout formCheckedLayout = new LinearLayout(context); formCheckedLayout.setOrientation(LinearLayout.HORIZONTAL); formCheckedLayout.setPadding(0, 0, 0, 0); ImageView checkImageView = new ImageView(context); LinearLayout.LayoutParams checkImageRelativeLayoutParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 26), LayoutUtils.convertDpToPixel(context, 26)); checkImageRelativeLayoutParams.gravity = Gravity.CENTER_VERTICAL; checkImageRelativeLayoutParams.weight = 0.20f; checkImageRelativeLayoutParams.leftMargin = 0; checkImageView.setLayoutParams(checkImageRelativeLayoutParams); checkImageView.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage( ServiceFormUtil.getCheckImageStatus( formItemList, formInstances) , CommonConstants.Images.IMAGE_DPI))); formCheckedLayout.addView(checkImageView); LinearLayout formNameLayout = new LinearLayout(context); formNameLayout.setOrientation(LinearLayout.HORIZONTAL); formNameLayout.setPadding(0, 0, 0, 0); TextView formName = new TextView(context); formName.setGravity(Gravity.CENTER_VERTICAL); formName.setText(form.getName()); formName.setTextColor(job.getStatus().isFinalized()? textColor:ServiceFormUtil.getTextColor(formItemList, formInstances)); LinearLayout.LayoutParams formNameTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); formNameTextParams.width = 0; formNameTextParams.weight = 0.80f; formNameTextParams.gravity = Gravity.CENTER_VERTICAL; formNameTextParams.topMargin = 6; formName.setLayoutParams(formNameTextParams); formNameLayout.addView(formName); formGridLayout.addView(formCheckedLayout); formGridLayout.addView(formNameLayout); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = 0; params.height = LayoutParams.WRAP_CONTENT; params.columnSpec = GridLayout.spec(0, 2, 1f); formGridLayout.setLayoutParams(params); return formGridLayout; } private void showCommissionNumberDialog() { List items = new ArrayList(); items.add(ServiceMessages.getString("correct") + " " + job.getCommissionNumber()); //$NON-NLS-1$ if(!job.getJobType().isMON()) { items.add(ServiceMessages.getString("unknown")); //$NON-NLS-1$ } items.add(ServiceMessages.getString("invalid")); //$NON-NLS-1$ MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("commNoCheck"),ServiceMessages.getString("cancel")); //$NON-NLS-1$ //$NON-NLS-2$ if((job.getJobType().isMON() || job.getJobType().isSAV() || job.getJobType().isREP()) && !job.getCommissionNumber().isEmpty()) { commissionType = CommonConstants.CommissionNumber.Type.CORRECT; } else { commissionType = CommonConstants.CommissionNumber.Type.UNKNOWN; } alertDialog.setSingleChoiceItems(items.toArray(new String[0]), commissionType.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(!job.getJobType().isMON()) { switch (which) { case 0: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; break; case 1: commissionType = CommonConstants.CommissionNumber.Type.UNKNOWN; break; case 2: commissionType = CommonConstants.CommissionNumber.Type.INVALID; break; default: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; } } else { switch (which) { case 0: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; break; case 1: commissionType = CommonConstants.CommissionNumber.Type.INVALID; break; default: commissionType = CommonConstants.CommissionNumber.Type.CORRECT; } } } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new DialogInterface.OnClickListener() { //$NON-NLS-1$ @Override public void onClick(DialogInterface dialog, int which) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportEditForm.class, new FormArguments(job, commissionType)); } }, false); } }); alertDialog.show(); } public static class FormArguments { private Job job; private CommonConstants.CommissionNumber.Type commissionType; protected FormArguments() { } public FormArguments(Job job, CommonConstants.CommissionNumber.Type commissionType) { this.job = job; this.commissionType = commissionType; } public Job getJob() { return job; } public CommonConstants.CommissionNumber.Type getCommissionType() { return commissionType; } } private OnTimeAction onTimeAction; public interface OnTimeAction { void runOnTimeAction(); } public void setOnTimeActionListener(OnTimeAction onTimeAction) { this.onTimeAction = onTimeAction; } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobDownloadResultForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.businessobjects.ServerJob; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobSearchListForm.JobSearchListFormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The Job Download Result Form. * * * @see "[MIG-451] Visualize already downloaded jobs by job search" */ public class JobDownloadResultForm extends SuperForm{ private static Log log = LogFactory.getLog(JobDownloadResultForm.class); private String jobType; private CheckBoxListWidget checkBoxListWidget; private List selectedList; private Map downloadErrorMap; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.jobType = formArguments.getJobType(); this.selectedList = formArguments.getSelectedList(); this.downloadErrorMap = formArguments.getDownloadErrorMap(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } public static class FormArguments { private String jobType; private List selectedList; private Map downloadErrorMap; public FormArguments(String jobType, List selectedList, Map downloadErrorMap) { this.jobType = jobType; this.selectedList = selectedList; this.downloadErrorMap = downloadErrorMap; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public List getSelectedList() { return selectedList; } public void setSelectedList(List selectedList) { this.selectedList = selectedList; } public Map getDownloadErrorMap() { return downloadErrorMap; } public void setDownloadErrorMap(Map downloadErrorMap) { this.downloadErrorMap = downloadErrorMap; } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); saveButton.setVisible(false); // create download action ActionCtrl downloadButton = addActionCtrl(false, true, 1, "onConfirmonPressed"); //$NON-NLS-1$ downloadButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DONE_WHITE, CommonConstants.Images.IMAGE_DPI))); downloadButton.setTitle(ServiceMessages.getString("confirm")); //$NON-NLS-1$ RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); checkBoxListWidget = new CheckBoxListWidget(context); checkBoxListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); checkBoxListWidget.setDividerHeight(1); checkBoxListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // set empty items ArrayList items = new ArrayList(); checkBoxListWidget.addItems(items); contentLinearLayout.addView(checkBoxListWidget); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { setFormTitle(jobType + " " + ServiceMessages.getString("download")); //$NON-NLS-1$ //$NON-NLS-2$ app.messageUtil.showContinueMessage(); checkBoxListWidget.clean(); ArrayList items = new ArrayList(); for (String jobNumber : selectedList) { ServerJob data = app.dbutil.selectServerJob(jobNumber); final CheckBoxListWidgetItem item = new CheckBoxListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(StringUtil.removeAllLeadingZero(data.getJobNumber()) + ": " + data.getStreet() + " " + data.getPostalCode() + " " + data.getCity()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ item.setStringLine1(JobType.MON.equals(jobType)?data.getcommissionNumberNoLeadingZero():data.getCommissionNumber() + " " + data.getLocation()); //$NON-NLS-1$ item.setCheck(false); if (downloadErrorMap.containsKey(jobNumber)) { // show error message item.setTextColor(LayoutUtils.DEFAULT_RED); item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_ERROR, CommonConstants.Images.IMAGE_DPI))); item.setStringLine2(downloadErrorMap.get(jobNumber)); } else { item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_SUCCESS, CommonConstants.Images.IMAGE_DPI))); item.setStringLine2(jobType + "-Code: " + data.getServiceContractType() + "*/ " + data.getMonthYear() + "**" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } items.add(item); } checkBoxListWidget.addItems(items); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobSearchListForm.class, new JobSearchListFormArguments(jobType)); } protected ApplicationEvent onConfirmonPressed() { return app.closeForm(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.res.ColorStateList; import android.support.v7.widget.AppCompatRadioButton; import android.text.InputFilter; import android.text.InputType; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.businessobjects.Drive; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The job new/edit form class. * * @author nop (02-03-2017) * * @see "[MIG-46] implement of "create job" */ public class JobEditForm extends AddressEditSuperForm implements OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(JobEditForm.class); protected String vbeln; protected int personalNumber; protected String commissionFormat; protected boolean isNewJob = false; protected Address objectAddress; protected Address partnerAddress; protected MDSpinner zantrtypValue; protected MDEditText zantrtypDescription; protected AppCompatRadioButton firmaRadioButton; protected AppCompatRadioButton personRadioButton; protected MDSpinner personTitleValue; protected MDEditText personFirstName; protected MDEditText personLastName; protected MDEditText personAddition; protected MDSpinner companyTitleValue; protected MDEditText company; protected MDEditText companyName; protected MDEditText companyAddition; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; vbeln = formArguments.getVbeln(); job = formArguments.getJob(); objectAddress = job.getObjectAddress(); partnerAddress = job.getPartnerAddress(); job.setCommissionNumber(vbeln); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); return view; } public View createJobDetailNewEditView(Context context) { RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout headerLinearLayout = new LinearLayout(context); headerLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerLinearLayout.setOrientation(LinearLayout.VERTICAL); // zantrty zantrtypValue = MDSpinner.createDefaultSpinner(headerLinearLayout, ServiceMessages.getString("drive"), true); //$NON-NLS-1$ zantrtypValue.setTag("ZANTRTYP"); //$NON-NLS-1$ zantrtypValue.setOnItemSelectedListener(this); // zantrty description zantrtypDescription = MDEditText.createDefaultEditText(context, false); zantrtypDescription.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); zantrtypDescription.setEnabled(false); zantrtypDescription.setFocusable(true); zantrtypDescription.setFocusableInTouchMode(true); headerLinearLayout.addView(zantrtypDescription); contentLinearLayout.addView(headerLinearLayout); RadioGroup radioGroup = new RadioGroup(context); LinearLayout.LayoutParams radioGroupParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); radioGroupParams.topMargin = 10; radioGroupParams.bottomMargin = 10; radioGroup.setLayoutParams(radioGroupParams); radioGroup.setPadding(10, 0, 10, 10); radioGroup.setOrientation(LinearLayout.HORIZONTAL); radioGroup.setOnCheckedChangeListener(this); contentLinearLayout.addView(radioGroup); ColorStateList colorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_enabled } }, new int[] { LayoutUtils.DEFAULT_TEXT_COLOR }); firmaRadioButton = new AppCompatRadioButton(context); firmaRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 3f)); firmaRadioButton.setText(ServiceMessages.getString("enterprise")); //$NON-NLS-1$ firmaRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); firmaRadioButton.setSupportButtonTintList(colorStateList); firmaRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); firmaRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(firmaRadioButton); personRadioButton = new AppCompatRadioButton(context); personRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); personRadioButton.setText(ServiceMessages.getString("person")); //$NON-NLS-1$ personRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); personRadioButton.setSupportButtonTintList(colorStateList); personRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); personRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(personRadioButton); RelativeLayout formRelativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams formRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); formRelativeLayoutParams.topMargin = 10; formRelativeLayout.setLayoutParams(formRelativeLayoutParams); formRelativeLayout.setPadding(LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); // person title personTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ personTitleValue.setTag("PERSON_TITLE"); //$NON-NLS-1$ personTitleValue.setOnItemSelectedListener(this); linearLayout.addView(personTitleValue.getTopParent(), 0); personFirstName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("firstName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ personFirstName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(personFirstName), 1); personLastName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("lastName"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true, this); //$NON-NLS-1$ personLastName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(personLastName), 2); personAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ personAddition.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(personAddition), 3); // company company = MDEditText.createDefaultEditText(context, ServiceMessages.getString("enterprise"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true, this); //$NON-NLS-1$ company.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(company), 0); companyAddition = MDEditText.createDefaultEditText(context, ServiceMessages.getString("addition"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ companyAddition.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(companyAddition), 1); // company title companyTitleValue = MDSpinner.createDefaultSpinner(context, ServiceMessages.getString("title"), false); //$NON-NLS-1$ companyTitleValue.setTag("COMPANY_TITLE"); //$NON-NLS-1$ companyTitleValue.setOnItemSelectedListener(this); linearLayout.addView(companyTitleValue.getTopParent(), 2); companyName = MDEditText.createDefaultEditText(context, ServiceMessages.getString("name"), InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, true, this); //$NON-NLS-1$ companyName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY)}); linearLayout.addView(MDEditText.getTextInputLayout(companyName), 3); formRelativeLayout.addView(linearLayout); contentLinearLayout.addView(formRelativeLayout); ScrollView scrollView = new ScrollView(context); LinearLayout.LayoutParams scrollViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); scrollView.setLayoutParams(scrollViewParams); relativeLayout.addView(contentLinearLayout); scrollView.addView(relativeLayout); return scrollView; } @Override public void loadData() { if(zantrtypValue == null) { view.addView(createJobDetailNewEditView(context)); } // set dialog's title setFormTitle(ServiceMessages.getString("jobEdit")); //$NON-NLS-1$ personalNumber = app.dbutil.getUser().getPersonalNumber(); // zantrty List driveValueList = new ArrayList(); List driverList = app.dbutil.selectDriveList(); if (!driverList.isEmpty()) { for (int i = 0; i < driverList.size(); i++) { Drive drive = driverList.get(i); driveValueList.add(new CustomSpinnerItem(drive.getCode(), drive.getText(), drive.getLongText())); } } zantrtypValue.setContents(driveValueList); if (StringUtil.isNotEmpty(job.getDriveType()) && !driveValueList.isEmpty()) { zantrtypValue.setSelectionByName(job.getDriveType()); } else { zantrtypValue.setSelection(0); } Drive zantrtyp = app.dbutil.selectDriveByText(job.getDriveType()); if (zantrtyp != null && zantrtyp.isLongText()) { zantrtypDescription.setText(job.getDescription()); } // title List titleValueList = new ArrayList(); @SuppressWarnings("rawtypes") Iterator itr = app.enumUtil.titelEnum.iterator(); while (itr.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) itr.next(); titleValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } personTitleValue.setContents(titleValueList); companyTitleValue.setContents(titleValueList); if (StringUtil.isNotEmpty(objectAddress.getTitle()) && !titleValueList.isEmpty()) { String title = app.enumUtil.titelEnum.get(objectAddress.getTitle()); personTitleValue.setSelectionByName(title); companyTitleValue.setSelectionByName(title); } else { personTitleValue.setSelection(0); companyTitleValue.setSelection(0); } personFirstName.setText(objectAddress.getName1()); personLastName.setText(objectAddress.getName2()); personAddition.setText(objectAddress.getName3()); company.setText(objectAddress.getName1()); companyName.setText(objectAddress.getName2()); companyAddition.setText(objectAddress.getName3()); location.setText(objectAddress.getLocation()); street.setText(objectAddress.getStreet()); zip.setText(objectAddress.getPostalCode()); city.setText(objectAddress.getCity()); tel1.setText(objectAddress.getTelNumber1()); tel2.setText(objectAddress.getTelNumber2()); fax.setText(objectAddress.getFaxNumber()); email.setText(objectAddress.getEmail()); if (objectAddress.isPrivate()) { personRadioButton.setChecked(true); } else { firmaRadioButton.setChecked(true); } } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { clearErrorMessages(); if (firmaRadioButton.isChecked()) { setPersonInfomation(false); setFimaInfomation(true); } else if (personRadioButton.isChecked()) { setPersonInfomation(true); setFimaInfomation(false); } } private void setFimaInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } company.setVisibility(visibility); companyAddition.setVisibility(visibility); companyTitleValue.setRequired(isVisible); companyTitleValue.getTopParent().setVisibility(visibility); companyName.setVisibility(visibility); } private void setPersonInfomation(boolean isVisible) { int visibility = View.VISIBLE; if (!isVisible) { visibility = View.GONE; } personTitleValue.getTopParent().setVisibility(visibility); personFirstName.setVisibility(visibility); personLastName.setVisibility(visibility); personAddition.setVisibility(visibility); } @Override public void onFormReset() { super.onFormReset(); zantrtypValue.setSelection(0); zantrtypDescription.getText().clear(); personTitleValue.setSelection(0); personFirstName.getText().clear(); personLastName.getText().clear(); personAddition.getText().clear(); companyTitleValue.setSelection(0); company.getText().clear(); companyName.getText().clear(); companyAddition.getText().clear(); } @Override protected boolean isValid() { boolean result = super.isValid(); String selectMessage = Messages.getString("pleaseSelectValue"); //$NON-NLS-1$ String provideMessage = Messages.getString("pleaseProvideValue"); //$NON-NLS-1$ if (zantrtypValue.getSelectedItemPosition() == 0) { zantrtypValue.setError(selectMessage); result = false; } if (firmaRadioButton.isChecked()) { if (companyTitleValue.isRequired() && companyTitleValue.getSelectedItemPosition() == 0) { companyTitleValue.setError(selectMessage); result = false; } if ("".equals(company.getText().toString().trim())) { //$NON-NLS-1$ company.setError(provideMessage); result = false; } if ("".equals(companyName.getText().toString().trim())) { //$NON-NLS-1$ companyName.setError(provideMessage); result = false; } } else { if (personTitleValue.isRequired() && personTitleValue.getSelectedItemPosition() == 0) { personTitleValue.setError(selectMessage); result = false; } if ("".equals(personLastName.getText().toString().trim())) { //$NON-NLS-1$ personLastName.setError(provideMessage); result = false; } } return result; } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (objectAddress.isInitial()) { objectAddress.setJobNumber(job.getJobNumber()); objectAddress.setJobType(job.getJobType()); objectAddress.setPartnerNummer("$" + CommonConstants.randomInt(9)); //$NON-NLS-1$ job.setIdObjectAddress(objectAddress); app.dbutil.insertAddress(objectAddress); } if (partnerAddress.isInitial()) { partnerAddress.setJobNumber(job.getJobNumber()); partnerAddress.setJobType(job.getJobType()); partnerAddress.setPartnerNummer("$" + CommonConstants.randomInt(9)); //$NON-NLS-1$ job.setIdByPartnerAddress(partnerAddress); app.dbutil.insertAddress(partnerAddress); } assignToObject(); app.dbutil.updateJob(job); return onBackPressed(); } }; return true; } public void assignToObject() { job.setCommissionNumber(vbeln); job.setDriveType(zantrtypValue.getSelectedName()); job.setDescription(zantrtypDescription.getText().toString()); job.setPersonalNumber(personalNumber); String title = ""; //$NON-NLS-1$ // private address if (personRadioButton.isChecked()) { if (personTitleValue.getSelectedItemPosition() != 0) { title = personTitleValue.getSelectedId(); } partnerAddress.setName1(personFirstName.getText().toString()); partnerAddress.setName2(personLastName.getText().toString()); objectAddress.setName1(personLastName.getText().toString()); partnerAddress.setName3(personAddition.getText().toString()); partnerAddress.setPrivate(true); objectAddress.setPrivate(true); } // enterprise address else if (firmaRadioButton.isChecked()) { if (companyTitleValue.getSelectedItemPosition() != 0) { title = companyTitleValue.getSelectedId(); } objectAddress.setName1(company.getText().toString()); partnerAddress.setName1(company.getText().toString()); partnerAddress.setName2(companyName.getText().toString()); partnerAddress.setName3(companyAddition.getText().toString()); partnerAddress.setPrivate(false); objectAddress.setPrivate(false); } objectAddress.setTitle(title); partnerAddress.setTitle(title); objectAddress.setLocation(location.getText().toString()); objectAddress.setStreet(street.getText().toString()); objectAddress.setCity(city.getText().toString()); objectAddress.setPostalCode(zip.getText().toString()); partnerAddress.setTelNumber1(tel1.getText().toString()); partnerAddress.setTelNumber2(tel2.getText().toString()); partnerAddress.setFaxNumber(fax.getText().toString()); partnerAddress.setEmail(email.getText().toString()); objectAddress.setDIRTYFLG(true); partnerAddress.setDIRTYFLG(true); } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("ZANTRTYP".equals(parent.getTag())) { //$NON-NLS-1$ zantrtypValue.clearError(); CustomSpinnerItem zantrtypCustomSpinner = (CustomSpinnerItem)zantrtypValue.getSelectedItem(); if ("ANDERE".equalsIgnoreCase(zantrtypCustomSpinner.getName())) { //$NON-NLS-1$ zantrtypDescription.setEnabled(true); zantrtypDescription.setText(zantrtypCustomSpinner.getDescription()); zantrtypDescription.requestFocus(zantrtypCustomSpinner.getDescription().length()); zantrtypDescription.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); } else { zantrtypDescription.setEnabled(false); zantrtypDescription.setText(zantrtypCustomSpinner.getDescription()); zantrtypDescription.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); } } else if ("PERSON_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ personTitleValue.clearError(); } else if ("COMPANY_TITLE".equals(parent.getTag())) { //$NON-NLS-1$ companyTitleValue.clearError(); } } @Override public void onNothingSelected(AdapterView arg0) { // Do nothing } public boolean checkDbKeys(String mldnr, String parnrJob, String parnr) { if (mldnr == null || parnrJob == null || parnr == null) { return false; } if (parnrJob.equalsIgnoreCase(parnr)) { return false; } else if (app.dbutil.cntJobid(mldnr) > 0) { return false; } else if (app.dbutil.cntPerNo(parnrJob) > 0) { return false; } else if (app.dbutil.cntPerNo(parnr) > 0) { return false; } return true; } public static class FormArguments { private boolean isNewJob; private String vbeln; private Job job; private Address objectAddress; private Address partnerAddress; protected FormArguments() { } protected FormArguments(Job job) { } public FormArguments(boolean isNewJob, String vbeln, Job job, Address objectAddress, Address partnerAddress) { this.isNewJob = isNewJob; this.vbeln = vbeln; this.job = job; this.objectAddress = objectAddress; this.partnerAddress = partnerAddress; } public boolean isNewJob() { return isNewJob; } public String getVbeln() { return vbeln; } public Job getJob() { return job; } public Address getObjectAddress() { return objectAddress; } public Address getPartnerAddress() { return partnerAddress; } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { super.onTextChanged(s, start, before, count); if (personLastName.hasFocus()) { personLastName.clearError(); } if (company.hasFocus()) { company.clearError(); } if (companyName.hasFocus()) { companyName.clearError(); } } @Override public void clearErrorMessages() { super.clearErrorMessages(); zantrtypValue.clearError(); if (firmaRadioButton.isChecked()) { companyTitleValue.clearError(); } else { personTitleValue.clearError(); } personLastName.clearError(); company.clearError(); companyName.clearError(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobForwardForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.stepstone.stepper.StepperLayout; import com.stepstone.stepper.VerificationError; import com.stepstone.stepper.internal.type.AbstractStepperType; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RadioButton; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReturnReason; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.adapters.StepAdapter; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.RadioButtonListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.RadioButtonListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StepUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Forward a Job with 2 steps form. * * @author cyu (29-08-2019) * * @see "[MIG-463] Forwarding of partly done jobs" */ public class JobForwardForm extends SuperForm { private static Log log = LogFactory.getLog(JobForwardForm.class); private Job job; private MDSpinner reasonValue; private Image backImage; private StepperLayout stepper; private RadioButtonListWidget dialoglistWidget; private RadioButtonListWidgetItem radioButtonListWidgetItemSelected = null; private RadioButton radioButtonSelected = null; @Override public void onFormCall(Object argument) { if (argument instanceof JobForwardFormArgument) { JobForwardFormArgument formArguments = (JobForwardFormArgument) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobListForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); saveButton.setVisible(false); view.addView(createStepView()); return view; } private View createStepView() { StepUtil jobContentStep = new StepUtil(createForwardReasonStep(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(!reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { return null; } else { reasonValue.setError(Messages.getString("pleaseSelectValue")); return new VerificationError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } @Override public void onSelected() { //update UI when selected } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText } }); StepUtil partnerDialogStepUtil = new StepUtil(createPartnerDialogStep(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(radioButtonListWidgetItemSelected != null) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { job.setStatusEdit(new Date()); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.FORWARDED, JobStatus.SAP_Forwarded, reasonValue.getSelectedId()); return app.leaveToForm(JobListForm.class); } }, false); return null; } else { app.showMessage(ServiceMessages.getString("noEmployeeSelected"), true); //$NON-NLS-1$ return new VerificationError(ServiceMessages.getString("noEmployeeSelected")); //$NON-NLS-1$ } } @Override public void onSelected() { loadPartner(); } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText } }); StepAdapter myStepAdapter = new StepAdapter(context, jobContentStep, partnerDialogStepUtil); // create a mobile stepper with 'dot' progress stepper = new StepperLayout.Builder(context) .setStepperType(AbstractStepperType.DOTS).create(); // link layout to step adapter stepper.setAdapter(myStepAdapter); return stepper; } private View createForwardReasonStep(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout reasonLinearLayout = new LinearLayout(context); reasonLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); reasonLinearLayout.setOrientation(LinearLayout.VERTICAL); // reason reasonValue = MDSpinner.createDefaultSpinner(reasonLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { reasonValue.setError(null); reasonValue.clearError(); } @Override public void onNothingSelected(AdapterView arg0) { } }); contentLinearLayout.addView(reasonLinearLayout); return contentLinearLayout; } private View createPartnerDialogStep(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); dialoglistWidget = new RadioButtonListWidget(context); // Search View SearchView partnerSearchView = new SearchView(context); partnerSearchView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); partnerSearchView.setQueryHint(ServiceMessages.getString("search")); //$NON-NLS-1$ partnerSearchView.setFocusable(true); partnerSearchView.setFocusableInTouchMode(true); partnerSearchView.setBackgroundColor(LayoutUtils.DEFAULT_SEARCH_COLOR); partnerSearchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String queryText) { dialoglistWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { dialoglistWidget.getAdapter().getFilter().filter(queryText); return true; } }); contentLinearLayout.addView(partnerSearchView); contentLinearLayout.addView(dialoglistWidget); return contentLinearLayout; } private void loadPartner() { dialoglistWidget.clean(); final List partnerList = app.dbutil.selectEmployeeList(app.dbutil.getUser(), ""); //$NON-NLS-1$ final ArrayList items = new ArrayList(); for (int i = 0; i < partnerList.size(); i++) { final Employee partner = partnerList.get(i); final RadioButtonListWidgetItem item = new RadioButtonListWidgetItem(); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHONE, CommonConstants.Images.IMAGE_DPI))); item.setLeftRadioButtonTag(String.valueOf(partner.getPersonalNumber())); item.setTitleText(partner.getLastName() + " " + partner.getFirstName()); //$NON-NLS-1$ item.setStringLine1(ServiceMessages.getString("telWColon") + partner.getPhoneNumber()); //$NON-NLS-1$ item.setStringLine2(ServiceMessages.getString("personalNumber") + ":" + partner.getPersonalNumber()); //$NON-NLS-1$ //$NON-NLS-2$ item.setOnClickListener(onPartnerItemClicked(item, partner)); if (radioButtonListWidgetItemSelected != null) { if (radioButtonListWidgetItemSelected.getLeftRadioButtonTag().equalsIgnoreCase(item.getLeftRadioButtonTag())) { item.setCheck(true); } } items.add(item); } dialoglistWidget.addItems(items); } private OnClickListener onPartnerItemClicked(final RadioButtonListWidgetItem item, final Employee partner) { return new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton && partner.getPhoneNumber() != null) { String phoneNumber = partner.getPhoneNumber().replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance(), new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } if (v instanceof RadioButton) { RadioButton radioButton = (RadioButton) v; if (radioButton.isChecked()) { job.setJobForward(partner.getPersonalNumber()); } //MIG-228 Forward of a job to a partner caused a app crash // remove checked all radioButtonListWidgetItem if(radioButtonListWidgetItemSelected != null) { radioButtonListWidgetItemSelected.setCheck(false); } radioButtonListWidgetItemSelected = item; // remove checked all radioButton if(radioButtonSelected != null) { radioButtonSelected.setChecked(false); } radioButtonSelected = radioButton; radioButtonListWidgetItemSelected.setCheck(true); radioButtonSelected.setChecked(true); } } }; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); radioButtonListWidgetItemSelected = null; // set dialog's title setFormTitle(ServiceMessages.getString("forward")); //$NON-NLS-1$ List reasonValueList = new ArrayList(); List reasonList = app.dbutil.selectJobDeleteReasonList(); for (int i = 0; i < reasonList.size(); i++) { Reason reason = reasonList.get(i); reasonValueList.add(new CustomSpinnerItem(reason.getReasonText(), reason.getText(), reason.getText())); } reasonValue.setContents(reasonValueList); return null; } @Override public void onFormReset() { super.onFormReset(); stepper.setCurrentStepPosition(0); } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return onBackPressed(); } }; return true; } public static class JobForwardFormArgument { private Job job; protected JobForwardFormArgument() { } public JobForwardFormArgument(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLayoutChangeListener; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.util.BackupHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil.JobStatusFilter; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.SoundUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDeleteForm.JobDeleteFormArguments; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm.JobSearchFormArguments; import ch.mfiles.kaba.kolibri.service.forms.RescheduleJobForm.RescheduleJobFormArguments; import ch.mfiles.kaba.kolibri.service.util.ReportUtil; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; public class JobListForm extends ServiceNavigationForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(JobListForm.class); private JobStatusFilter jobStatusFilter = JobStatusFilter.active; private DefaultListWidget listWidget; private RelativeLayout listItemLayout; private LinearLayout emptyMessageView; private LinearLayout checkAllFinalizeJobLayout; private TextView finalizeText; private ImageView checkImageView; private AHBottomNavigation bottomNavigation; private SearchView searchView; private ActionCtrl searchAction; private ActionCtrl downloadAction; private ActionCtrl scanAction; private TimeUtil timeUtil; private ActionCtrl deleteAction; private List selectedJobList; /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; timeUtil = new TimeUtil(app, app.dbutil, this); // hide runtime menu items setRuntimeMenuHidden(true); // create SearchView searchView = new SearchView(context); searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END)); searchView.setOnQueryTextListener(this); // create search action searchAction = addActionCtrl(false, true, 1, "actionSearch"); //$NON-NLS-1$ searchAction.setTitle(ServiceMessages.getString("search")); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); // create scan action scanAction = addActionCtrl(false, true, 1, "actionScan"); //$NON-NLS-1$ scanAction.setTitle(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); // create save action downloadAction = addActionCtrl(false, true, 1, "actionDownload"); //$NON-NLS-1$ downloadAction.setTitle(ServiceMessages.getString("download")); //$NON-NLS-1$ downloadAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_WHITE, CommonConstants.Images.IMAGE_DPI))); // create delete action deleteAction = addActionCtrl(false, true, 1, "actionDelete"); //$NON-NLS-1$ deleteAction.setTitle(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setVisible(false); setVisibleAction(true); log.info("creating listWidgetView"); //$NON-NLS-1$ checkAllFinalizeJobLayout = new LinearLayout(context); checkAllFinalizeJobLayout.setOrientation(LinearLayout.HORIZONTAL); checkAllFinalizeJobLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS())); LinearLayout.LayoutParams checkFinalizeLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); checkFinalizeLayoutParams.width = LayoutParams.MATCH_PARENT; checkAllFinalizeJobLayout.setLayoutParams(checkFinalizeLayoutParams); checkAllFinalizeJobLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); checkAllFinalizeJobLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); checkAllFinalizeJobLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean checkAll = false; if (selectedJobList.size() == listWidget.getAdapter().getCount()) { log.info("remvoe all cheked"); checkAll = false; selectedJobList.clear(); } else { log.info("check all"); checkAll = true; selectedJobList.clear(); for (int i = 0; i < listWidget.getAdapter().getCount(); i++) { Job job = (Job) ((DetailListWidgetItem) listWidget.getAdapter().getItem(i)).getData(); selectedJobList.add(job); } } ArrayList items = new ArrayList(); for (int i=0;i * * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); log.info("onFormShow content " + getContentView().getHeight() + " buttom size " + bottomNavigation.getHeight()); if(CommSetupHelper.isProductionEnvironment()) { app.refreshMasterData(false); app.messageUtil.showContinueMessage(); // check for a valid and recent backup... BackupHandler.getInstance().checkOverdueBackup(app); if(emptyMessageView.getChildCount() > 0) emptyMessageView.removeAllViewsInLayout(); // FIXME: remove test code File testFile1 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time1: " + testFile1.lastModified()); try { Thread.sleep(100); } catch (InterruptedException e) { } File testFile2 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time2: " + testFile2.lastModified()); File testFile3 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time3: " + testFile3.lastModified()); try (FileInputStream in = new FileInputStream(testFile3)) { while (in.read(new byte[1024]) > 0) ; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } File testFile4 = new File(Runtime.getInstallationFolder(), "custom/ch.mfiles.kaba.kolibri.common.CommonApplication/\\ZKDMAEXPNS"); log.error("Mod-Time4: " + testFile4.lastModified()); } setFormTitle(ServiceMessages.getString("jobList")); bottomNavigation.refresh(); if (jobStatusFilter != null && bottomNavigation !=null) { if (jobStatusFilter == JobStatusFilter.planned) { bottomNavigation.setCurrentItem(1); } else if (jobStatusFilter == JobStatusFilter.finalized) { bottomNavigation.setCurrentItem(2); } else { jobStatusFilter = JobStatusFilter.active; bottomNavigation.setCurrentItem(0); } } // TODO for test only Person user = app.dbutil.getUser(); // app.dbutil.deleteOldUser(user.getPersonalNumber()); // user.setPersonalNumber(98102); // user.setWarehouseNumber("F032"); // user.setFirstName("Zehnder Jörg"); // user.setCommunicationNumberFormat("DE"); // user.setExpensesActive(false); // app.dbutil.updateUser(user); // user.setPersonalNumber(1644); // user.setWarehouseNumber("F996"); // user.setFirstName("Christoph"); // app.dbutil.switchUser(user); return null; } protected ApplicationEvent actionDownload() { // SoundUtil.playRawSound(context, "zxing_beep"); SoundUtil.playRawSound(context, "ssm 11"); KeyboardUtil.closeKeyboard(appman, getView()); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().callForm(JobSearchForm.class, new JobSearchFormArguments(null)); } }, false); return null; } protected ApplicationEvent actionSearch() { KeyboardUtil.closeKeyboard(appman, getView()); // hide menu setVisibleAction(false); searchView.setIconified(false); MenuItem searchItem = JobListForm.this.getToolbar().getMenu().getItem(0); searchItem.setIcon(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEARCH_WHITE, CommonConstants.Images.IMAGE_DPI))); searchItem.setActionView(searchView); searchItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_WITH_TEXT); MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem menuItem) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { setVisibleAction(true); return null; } }, false); return true; } }); return null; } protected ApplicationEvent actionScan() { app.scanSavJob(); return null; } protected ApplicationEvent actionDelete() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if(selectedJobList.isEmpty()) { return null; } if (app.showConfirmDeleteDialog()) { // inform SAP about the status change (only SAV) // Requirement, mail 17.5.2012: // Do not transmit deleted state to SAP if job status is 'abgeschlossen' or 'weitergelietet'. for (Job job : selectedJobList) { deleteJob(job); } selectedJobList.clear(); } return app.leaveToForm(JobListForm.class); } }, false); return null; } public void loadTable() { List jobList = app.dbutil.selectJobList(); int listWidgetHeight = getContentView().getHeight() - bottomNavigation.getHeight(); if(listWidget.getHeight() > 0 && listWidget.getHeight() != listWidgetHeight) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, listWidgetHeight); listWidget.setLayoutParams(params); } if (jobStatusFilter == JobStatusFilter.finalized) { ((LayoutParams) listWidget.getLayoutParams()).topMargin = checkAllFinalizeJobLayout.getHeight(); ((LayoutParams) listWidget.getLayoutParams()).bottomMargin = checkAllFinalizeJobLayout.getHeight(); ((LayoutParams) listWidget.getLayoutParams()).height -= checkAllFinalizeJobLayout.getHeight(); } else { ((LayoutParams) listWidget.getLayoutParams()).topMargin = 0; ((LayoutParams) listWidget.getLayoutParams()).bottomMargin = 0; } listWidget.clean(); selectedJobList = new ArrayList(); log.info("Job /" + jobList.size()); ArrayList items = new ArrayList<>(); for (int i = 0; i < jobList.size(); i++) { final Job job = jobList.get(i); job.loadReports(app.dbutil); job.getLatestReport().checkIfTimeStartOverOndDay(app.dbutil); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setData(job); setItemContent(job, item); setClickListener(job, item); setItemStatus(job, item); if(jobStatusFilter == JobStatusFilter.active && ServiceJobUtil.isJobActive(job)){ log.info("Active"); items.add(item); } if(jobStatusFilter == JobStatusFilter.planned && ServiceJobUtil.isJobInPlanned(job)){ log.info("Planed"); items.add(item); } if(jobStatusFilter == JobStatusFilter.finalized && ServiceJobUtil.isJobFinalized(job)){ log.info("Finalized"); items.add(item); } log.info(DateTimeUtil.showDateTime(job.getStatusEdit()) + " status edit date STEDTDATE"); log.info("EDATE -> " + DateTimeUtil.showDateTime(job.getAppointmentDate())); log.info("EDATE_DT -> " + DateTimeUtil.showDateTime(job.getJobRescheduleDate())); log.info("EDATE_TI -> " + DateTimeUtil.showDateTime(job.getJobRescheduleTime())); log.info("ACTIVE_DATE -> " + DateTimeUtil.showDateTime(job.getActiveJobDate())); log.info("STATUS -> " + job.getStatus().getCode().toString()); listWidget.setOnItemClickListener(createOnItemClickListener()); } if (!items.isEmpty()) { emptyMessageView.setVisibility(View.GONE); listWidget.addItems(items); } else { emptyMessageView.setVisibility(View.VISIBLE); if (jobStatusFilter == JobStatusFilter.finalized) { ((LayoutParams) emptyMessageView.getLayoutParams()).topMargin = checkAllFinalizeJobLayout.getHeight(); } else { ((LayoutParams) emptyMessageView.getLayoutParams()).topMargin = 0; } } } private void setItemStatus(final Job job, final DefaultListWidgetItem item) { if (jobStatusFilter == JobStatusFilter.finalized) { item.isShowCheckBox(true); } item.setOverlayIcon(null); if(job.getStatus().isInProgress()) { item.setOverlayIcon(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ALARM_RED, CommonConstants.Images.IMAGE_MAX_DPI))); } else { if(job.getLatestReport() != null) { List reportTimeList = job.getLatestReport().getTimes(); if(!reportTimeList.isEmpty()) { item.setOverlayIcon(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ALARM_BLACK, CommonConstants.Images.IMAGE_MAX_DPI))); } } } } private void setClickListener(final Job job, final DefaultListWidgetItem item) { item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setSelectedJob(job); if (v instanceof CheckBox) { item.setCheck(((CheckBox) v).isChecked()); if(((CheckBox) v).isChecked()) { selectedJobList.add(job); } else { selectedJobList.remove(job); } setEnableDeleteAction(); } else { showPopupMenu(v); } } }); } private void setItemContent(final Job job, final DefaultListWidgetItem item) { item.setStatusColor(job.getStatusColor()); item.setStatusType(job.getStatusType()); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.MENU, CommonConstants.Images.IMAGE_MAX_DPI))); job.loadAddresses(app.dbutil); Address objAddress = job.getObjectAddress(); Address customerAddress = job.getCustomerAddress(); item.setTitleText(objAddress.getPostalCode() + " " + objAddress.getCity()); item.setStringLine1(objAddress.getStreet() + ", " + app.getAddressTitle(customerAddress)); if (job.getJobType().isMON()) { item.setStringLine2(job.getCommissionNumberNoLeadingZero()); } else { item.setStringLine2(job.getCommissionNumber()+ ' ' + '/' + ' ' + (job.getWeek() > 0 ? "KW: " + job.getWeek() : ServiceMessages.getString("AppointmentDate") + ' ' + DateTimeUtil.showDateTime(job.getAppointmentDate())) ); } item.setStringLine3(objAddress.getLocation()); } private OnItemClickListener createOnItemClickListener() { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { Job jobClicked = (Job) ((DetailListWidgetItem) listWidget.getAdapter().getItem(position)).getData(); log.info(" job " + jobClicked.getJobNumber() + " commm " + (jobClicked.getJobType().isMON() ? jobClicked.getCommissionNumberNoLeadingZero():jobClicked.getCommissionNumber())); setSelectedJob(jobClicked); app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailFormArgument(getSelectedJob())); } }; } private void showPopupMenu(View v) { /* * Create the context menu. * see "[MIG-67] Context menu for jobs doesn't work" */ ImageButton imageButton = (ImageButton) v; PopupMenu popupMenu = new PopupMenu(context, imageButton); popupMenu.setGravity(Gravity.CENTER | Gravity.RIGHT); // Accept Images acceptStatusImage = ImagesUtil.Images.ASSIGNMENT_TURNED_IN_DISABLED; if (ServiceJobUtil.isJobAcceptable(getSelectedJob())) { acceptStatusImage = ImagesUtil.Images.ASSIGNMENT_TURNED_IN; } addPopupMenuItem(popupMenu, ServiceConstants.Index.ONE, ServiceMessages.getString("accept"), acceptStatusImage); //$NON-NLS-1$ // Forward Images forwardStatusImage = ImagesUtil.Images.ASSIGNMENT_IND_DISABLED; if (ServiceJobUtil.isJobForwardable(getSelectedJob())) { forwardStatusImage = ImagesUtil.Images.ASSIGNMENT_IND; } addPopupMenuItem(popupMenu, ServiceConstants.Index.TWO, ServiceMessages.getString("forward"), forwardStatusImage); //$NON-NLS-1$ // Delete Images deleteStatusImage = ImagesUtil.Images.DELETE_DISABLED_BLACK; if (ServiceJobUtil.isJobDeletable(getSelectedJob())) { deleteStatusImage = ImagesUtil.Images.DELETE_BLACK; } addPopupMenuItem(popupMenu, ServiceConstants.Index.THREE, ServiceMessages.getString("erase"), deleteStatusImage); //$NON-NLS-1$ // Reschedule Images rscheduleImage = ImagesUtil.Images.SCHEDULE_DISABLED_BLACK; if (ServiceJobUtil.isJobRescheduleable(getSelectedJob())) { rscheduleImage = ImagesUtil.Images.SCHEDULE_BLACK; } addPopupMenuItem(popupMenu, ServiceConstants.Index.FOUR, ServiceMessages.getString("reschedule"), rscheduleImage); //$NON-NLS-1$ // Call createCallMenuItem(popupMenu); // Send Images sendImage = ImagesUtil.Images.SEND_DISABLED_BLACK; if (app.isJobAndReportComplete(getSelectedJob())) { sendImage = ImagesUtil.Images.SEND_BLACK; } addPopupMenuItem(popupMenu, ServiceConstants.Index.SIX, ServiceMessages.getString("send"), sendImage); //$NON-NLS-1$ // Time createTimeMenuItem(popupMenu); //forces to show PopupMenu icon. try { Field[] fields = popupMenu.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { //$NON-NLS-1$ field.setAccessible(true); Object menuPopupHelper = field.get(popupMenu); Class classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); //$NON-NLS-1$ setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (ClassNotFoundException e) { log.error("Found Class Not Found Exception:", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { log.error("Found Illegal Access Exception:", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { log.error("Found Invocation Target Exception:", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { log.error("Found NoSuch Method Exception:", e); //$NON-NLS-1$ } // handles click event. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { handleMenuItemClicked(menuItem); return true; } }); popupMenu.show(); } private void createTimeMenuItem(PopupMenu popupMenu) { String timeLabel = "start"; //$NON-NLS-1$ Images timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; if (ServiceJobUtil.isJobStartTimeable(getSelectedJob())) { if (app.dbutil.selectPlayingJobReportTimeByReport(getSelectedJob().getCurrentReport()) != null) { timeLabel = "stop"; //$NON-NLS-1$ timeStatusImage = ImagesUtil.Images.STOP_TIME; } else { if(app.dbutil.selectJobWithOpenTimesheet().isEmpty()) { timeStatusImage = ImagesUtil.Images.START_TIME; } else { timeStatusImage = ImagesUtil.Images.START_TIME_DISABLED; } } } addPopupMenuItem(popupMenu, ServiceConstants.Index.SEVEN, ServiceMessages.getString(timeLabel), timeStatusImage); } private void createCallMenuItem(PopupMenu popupMenu) { Address partnerOfInstallAddress = getSelectedJob().getPartnerOfInstallAddress(); String contact = ServiceMessages.getString("NoPhoneNumber"); //$NON-NLS-1$ Images phoneStatusImage = ImagesUtil.Images.PHONE_DISABLED; if (StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber1()) || StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber2())) { phoneStatusImage = ImagesUtil.Images.PHONE; contact = app.enumUtil.titelEnum.get(partnerOfInstallAddress.getTitle()); contact += "\n" + partnerOfInstallAddress.getName1(); //$NON-NLS-1$ if (!"0003".equals(partnerOfInstallAddress.getTitle())) { //$NON-NLS-1$ contact += "\n" + partnerOfInstallAddress.getName2(); //$NON-NLS-1$ } log.info("contact " + contact); } addPopupMenuItem(popupMenu, ServiceConstants.Index.FIVE, contact, phoneStatusImage); } private void addPopupMenuItem(PopupMenu popupMenu, int index, String label, Images image) { popupMenu.getMenu() .add(Menu.NONE, index, Menu.NONE, label) .setIcon(getBitmanDrawable(app.imagesUtil.getImage(image, CommonConstants.Images.IMAGE_DPI))); } private void handleMenuItemClicked(MenuItem menuItem) { if (menuItem.getItemId() == ServiceConstants.Index.ONE) { if (ServiceJobUtil.isJobAcceptable(getSelectedJob())) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { getSelectedJob().calculateActiveDate(); updateJobStatus(JobStatus.RECEIVED, JobStatus.SAP_Confirmed); // If there's a job in status NEW with a planned date and the user confirms the job, //there should be a notification, that the job is now displayed in filter "planned". if (ServiceJobUtil.isJobInPlanned(getSelectedJob())) { showPlannedJobDialog(); } return app.leaveToForm(JobListForm.class); } }, false); } } else if (menuItem.getItemId() == ServiceConstants.Index.TWO) { if (ServiceJobUtil.isJobForwardable(getSelectedJob())) { app.injectAndLeaveToForm(JobForwardForm.class, new JobForwardForm.JobForwardFormArgument(getSelectedJob())); } } else if (menuItem.getItemId() == ServiceConstants.Index.THREE) { if (ServiceJobUtil.isJobDeletable(getSelectedJob())) { actionDelete(getSelectedJob()); } else { app.showMessage(ServiceMessages.getString("jobCannotBeDeletedPleaseSendBackOpenReports")); //$NON-NLS-1$ } } else if (menuItem.getItemId() == ServiceConstants.Index.FOUR) { if (ServiceJobUtil.isJobRescheduleable(getSelectedJob())) { app.injectAndLeaveToForm(RescheduleJobForm.class, new RescheduleJobFormArguments(getSelectedJob())); } } else if (menuItem.getItemId() == ServiceConstants.Index.FIVE) { actionCall(); } else if (menuItem.getItemId() == ServiceConstants.Index.SIX) { actionSend(getSelectedJob()); } else if (menuItem.getItemId() == ServiceConstants.Index.SEVEN && ServiceJobUtil.isJobStartTimeable(getSelectedJob())) { actionTime(getSelectedJob()); } } private void actionDelete(final Job job) { if ((job.getStatus().isNew() || job.getStatus().isReceived() || job.getStatus().isPartlyDone()) && (job.getJobType().isREP() || job.getJobType().isSAV())) { //Delete a job with reason //The job has the status NEW, RECEIVED (without report data) or PARTLY_DONE. //The job has the type REP or SAV. app.injectAndLeaveToForm(JobDeleteForm.class, new JobDeleteFormArguments(job)); } else { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showConfirmDeleteDialog()) { // inform SAP about the status change (only SAV) // Requirement, mail 17.5.2012: // Do not transmit deleted state to SAP if job status is 'abgeschlossen' or 'weitergelietet'. deleteJob(job); } return app.leaveToForm(JobListForm.class); } }, false); } } private void showPlannedJobDialog() { MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("plannedJob"),ServiceMessages.getString("ok")); //$NON-NLS-1$ //$NON-NLS-2$ alertDialog.setMessage(ServiceMessages.getString("showPlannedJobDialogText")); alertDialog.show(); } private void deleteJob(final Job job) { log.info("deleteJob status isNew " + job.getStatus().isNew()); if (job.getStatus().isNew() || job.getStatus().isReceived() || job.getStatus().isPartlyDone()) { updateJobStatus(JobStatus.DELETED, JobStatus.SAP_Deleted); if (job.getStatus().isDeleted() && app.dbutil.deleteJob(job)) { app.showMessage(ServiceMessages.getString("jobDeleted"), true); //$NON-NLS-1$ } } else { if (app.dbutil.deleteJob(job)) app.showMessage(ServiceMessages.getString("jobDeleted"), true); //$NON-NLS-1$ } } private void actionCall() { Address partnerOfInstallAddress = getSelectedJob().getPartnerOfInstallAddress(); if (StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber1()) || StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber2())) { String tel = ""; //$NON-NLS-1$ if (StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber1())) { tel = partnerOfInstallAddress.getTelNumber1(); } if (StringUtil.isEmpty(tel) && StringUtil.isNotEmpty(partnerOfInstallAddress.getTelNumber2())) { tel = partnerOfInstallAddress.getTelNumber2(); } String phoneNumber = tel.replaceAll("\\s+","").trim(); //$NON-NLS-1$ //$NON-NLS-2$ int permissionCheck = ContextCompat.checkSelfPermission(appman.getContext(), Manifest.permission.CALL_PHONE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { appman.requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, ServiceConstants.PERMISSION_REQUEST_CODE); } else { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); //$NON-NLS-1$ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } private void actionSend(Job job) { if (app.isJobAndReportComplete(getSelectedJob())) { ReportUtil reportUtil = new ReportUtil(this, app); reportUtil.onSendingReport(job); reloadSelectedJob(); loadTable(); } } private void actionTime(final Job job) { if (ServiceJobUtil.isJobStartTimeable(getSelectedJob()) && app.dbutil.selectPlayingJobReportTimeByReport(getSelectedJob().getCurrentReport()) == null && !app.dbutil.selectJobWithOpenTimesheet().isEmpty()) { return; } app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.dbutil.selectPlayingJobReportTimeByReport(getSelectedJob().getCurrentReport()) != null) { timeUtil.stopTime(job, new RunOnUIThread() { @Override public void runOnUIThread() { //Auto-generated method stub } }); } else { boolean result = timeUtil.startJobTimeCapturing(getSelectedJob()); if (result) { timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, getSelectedJob(), new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { // do nothing } }); } } return app.leaveToForm(JobListForm.class); } }, false); } public static class JobListFormArguments { private Job job; protected JobListFormArguments() { } public JobListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } private void setVisibleAction(boolean visible) { searchAction.setVisible(visible); downloadAction.setVisible(visible); scanAction.setVisible(visible); } private void setEnableDeleteAction() { if (selectedJobList != null && !selectedJobList.isEmpty()) { deleteAction.setEnabled(true); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); String message = MessageFormat.format(ServiceMessages.getString("jobsSelected"), new Object[] { selectedJobList.size(), listWidget.getItems().size()}); //$NON-NLS-1$ if (selectedJobList.size() == listWidget.getAdapter().getCount()) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_CHECKED, CommonConstants.Images.IMAGE_DPI))); finalizeText.setText(message); } else { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_SOME, CommonConstants.Images.IMAGE_DPI))); finalizeText.setText(message); } } else { deleteAction.setEnabled(false); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_UNCHECKED, CommonConstants.Images.IMAGE_DPI))); finalizeText.setText(ServiceMessages.getString("noJobSelected")); } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobNewForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.stepstone.stepper.StepperLayout; import com.stepstone.stepper.VerificationError; import com.stepstone.stepper.internal.type.AbstractStepperType; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RadioGroup.OnCheckedChangeListener; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.StepAdapter; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StepUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Create new Job with 2 steps form. * * @author cyu (05-07-2017) * * @see "[MIG-156] Rework of create a job: Search jobs / Create a job" */ public class JobNewForm extends JobEditForm implements OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(JobNewForm.class); private CommissionNumberLayout commissionNumberLayout; private AppCompatCheckBox unknownCheckBox; private StepperLayout stepper; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; vbeln = formArguments.getComNo(); job = formArguments.getJob(); objectAddress = job.getObjectAddress(); partnerAddress = job.getPartnerAddress(); job.setCommissionNumber(vbeln); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobSearchForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); getToolbar().setNavigationIcon(getBitmanDrawable(backImage)); view.addView(createStepView()); return view; } private View createStepView() { StepUtil commissionNumberStep = new StepUtil(createCommissionNumberView(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(unknownCheckBox.isChecked()) { job = new Job(); return null; } else { if(commissionNumberLayout.getCommissionNumber().length() == 0) { return new VerificationError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ } else { commissionNumberLayout.clearError(); } stepper.setNextButtonEnabled(false); runCreateOrder(); return new VerificationError(""); //$NON-NLS-1$ } } @Override public void onSelected() { //update UI when selected saveButton.setVisible(false); } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText commissionNumberLayout.setError(error.getErrorMessage()); stepper.setNextButtonEnabled(true); } }); StepUtil jobContentStep = new StepUtil(createJobDetailNewEditView(context), new com.stepstone.stepper.Step() { @Override public VerificationError verifyStep() { //return null if the user can go to the next step, create a new VerificationError instance otherwise if(isValid()) { stepper.setCompleteButtonEnabled(false); onSave(); return null; } else { return new VerificationError(""); //$NON-NLS-1$ } } @Override public void onSelected() { //update UI when selected // MIG-220 "Form of Address" filed (Anrede) is not mandatory on the GUI "create order" street.setRequired(true); zip.setRequired(true); city.setRequired(true); } @Override public void onError(VerificationError error) { //handle error inside of the fragment, e.g. show error on EditText } }); StepAdapter myStepAdapter = new StepAdapter(context, commissionNumberStep, jobContentStep); // create a mobile stepper with 'dot' progress stepper = new StepperLayout.Builder(context) .setStepperType(AbstractStepperType.DOTS).create(); // link layout to step adapter stepper.setAdapter(myStepAdapter); return stepper; } private void runCreateOrder() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { job = new RemoteTransactionHandler() .runCreateOrder(personalNumber, commissionNumberLayout.getCommissionNumber()); if(job == null) { return null; } job.calculateActiveDate(); log.info("Received job from server with status " + job.getStatus().getCode() + " comNo. " + job.getCommissionNumber()); //$NON-NLS-1$ //$NON-NLS-2$ app.showMessage("create order success."); //$NON-NLS-1$ new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); // Calendar calendar = Calendar.getInstance(); // calendar.set(Calendar.MONTH, +2); // job.setDateTime(calendar.getTime()); // app.dbutil.updateJob(job); return app.leaveToForm(JobListForm.class); } @Override public void runOnUIThread() { if(job == null) { commissionNumberLayout.setError(ServiceMessages.getString("CannotCreateOrder")); } } }; } private View createCommissionNumberView(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); // Commission Number commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, contentLinearLayout, true); //$NON-NLS-1$ commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); commissionNumberLayout.setJobTypeAndFormat(new JobType(JobType.REP), app.dbutil.getUser().getCommunicationNumberFormat()); // Unknown checkBox unknownCheckBox = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("unknown")); //$NON-NLS-1$ unknownCheckBox.setChecked(false); unknownCheckBox.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { if (((AppCompatCheckBox) v).isChecked()) { commissionNumberLayout.setEnabled(false); commissionNumberLayout.setRequired(false); commissionNumberLayout.clear(); //$NON-NLS-1$ commissionNumberLayout.clearError(); } else { commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); commissionNumberLayout.getCommissionNumberText().requestFocus(); } } }); contentLinearLayout.addView(unknownCheckBox); return contentLinearLayout; } @Override public void loadData() { // set dialog's title super.loadData(); setFormTitle(ServiceMessages.getString("createREPJob")); //$NON-NLS-1$ Person user = app.dbutil.getUser(); personalNumber = user.getPersonalNumber(); commissionFormat = user.getCommunicationNumberFormat(); commissionNumberLayout.setJobTypeAndFormat(new JobType(JobType.REP), commissionFormat); } @Override public void onFormReset() { super.onFormReset(); stepper.setCurrentStepPosition(0); commissionNumberLayout.clearError(); commissionNumberLayout.clear(); unknownCheckBox.setChecked(false); commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); stepper.setNextButtonEnabled(true); stepper.setCompleteButtonEnabled(true); } @Override protected boolean onSave() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { createNewJob(); assignToObject(); log.info("active date " + job.getActiveJobDate()); app.dbutil.insertJob(job); log.info("Save order with status " + job.getStatus().getCode()); //$NON-NLS-1$ job.loadAddresses(app.dbutil); job.loadReports(app.dbutil); log.info("save order PARANMNR " + job.getPartnerAddressId() + " OBJNR " + job.getObjectAddressId()); log.info("address PARANMNR " + job.getPartnerAddress().getPartnerNummer() + " OBJNR " + job.getObjectAddress().getPartnerNummer()); if(new RemoteTransactionHandler().runSaveOrder(job, null)) { new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } return onBackPressed(); } }; return true; } private void createNewJob() { try { GuidGenerator generator = new GuidGenerator(); // prepare a new GUID for the next report (will be committed // to the DB if the transaction is successful only) job.setCurrentReportGuId(generator.generate()); } catch (UnknownHostException e) { throw new ApplicationException(e); } catch (NoSuchAlgorithmException e) { throw new ApplicationException(e); } String mldnr = null; String parnrJob = null; String parnrParanmnr = null; while (!checkDbKeys(mldnr, parnrJob, parnrParanmnr)) { mldnr = "$" + CommonConstants.randomInt(9); //$NON-NLS-1$ parnrJob = "$" + CommonConstants.randomInt(9); //$NON-NLS-1$ parnrParanmnr = "$" + CommonConstants.randomInt(9); //$NON-NLS-1$ // if (log.isDebugEnabled()) { log.info("Generierte Keys: MLDNR:" + mldnr + ", PARNR(Job):" + parnrJob + ", PARNR(Paranmnr):" + parnrParanmnr); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } // } job.setJobNumber(mldnr); job.setJobType(JobType.REP); job.setPriority("1"); //$NON-NLS-1$ job.setStatus(JobStatus.INITIAL); // for address objectAddress.setChangeFlag(true); objectAddress.setPartnerNummer(parnrJob); //$NON-NLS-1$ objectAddress.setJobNumber(job.getJobNumber()); objectAddress.setJobType(job.getJobType()); job.setIdObjectAddress(objectAddress); partnerAddress.setChangeFlag(true); partnerAddress.setPartnerNummer(parnrParanmnr); //$NON-NLS-1$ partnerAddress.setJobNumber(job.getJobNumber()); partnerAddress.setJobType(job.getJobType()); job.setIdByPartnerAddress(partnerAddress); } public static class FormArguments { private boolean isNewJob; private String comNo; private Job job; private Address objectAddress; private Address partnerAddress; protected FormArguments() { } protected FormArguments(Job job) { } public FormArguments(boolean isNewJob, String comNo, Job job, Address objectAddress, Address partnerAddress) { this.isNewJob = isNewJob; this.comNo = comNo; this.job = job; this.objectAddress = objectAddress; this.partnerAddress = partnerAddress; } public boolean isNewJob() { return isNewJob; } public String getComNo() { return comNo; } public Job getJob() { return job; } public Address getObjectAddress() { return objectAddress; } public Address getPartnerAddress() { return partnerAddress; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobSearchForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.ScrollView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobSearchListForm.JobSearchListFormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; /** * @author nop (20-04-2017) * * @see "[MIG-52] implement of "search job"" */ public class JobSearchForm extends SuperForm implements OnItemSelectedListener, OnClickListener { private static Log log = LogFactory.getLog(JobSearchForm.class); private MDSpinner jobTypeValue; private MDEditText jobNumber; private CommissionNumberLayout commissionNumberLayout; private MDEditText street; private MDEditText zip; private MDEditText city; private MDSpinner month; private MDSpinner year; private AppCompatButton scanButton; private String jobType; private Map jobSearchMap = new HashMap<>(); private String communicationNumberFormat; private static final String COMMISSION_NUMBER = "commissionNumber"; //$NON-NLS-1$ @Override public void onFormCall(Object argument) { if (argument instanceof JobSearchFormArguments) { JobSearchFormArguments formArguments = (JobSearchFormArguments) argument; this.jobType = formArguments.getJobType(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobListForm.class); } @Override public View onFormLoad(Context context, LayoutInflater inflater) { // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create add action ActionCtrl addAction = addActionCtrl(false, true, 1, "addAction"); //$NON-NLS-1$ addAction.setTitle(ServiceMessages.getString("add")); //$NON-NLS-1$ addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE))); // create reset action ActionCtrl resetAction = addActionCtrl(false, true, 1, "resetAction"); //$NON-NLS-1$ resetAction.setTitle(Messages.getString("reset")); //$NON-NLS-1$ resetAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.RESTORE_WHITE))); // create search action ActionCtrl searchAction = addActionCtrl(false, true, 1, "searchAction"); //$NON-NLS-1$ searchAction.setTitle(ServiceMessages.getString("search")); //$NON-NLS-1$ searchAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.YOUTUBE_SEARCHED_WHITE))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(20, 20, 20, 20); // job type jobTypeValue = MDSpinner.createDefaultSpinner(contentLinearLayout, Messages.getString("typeOfJob"), //$NON-NLS-1$ true); jobTypeValue.setTag("JOBTYPE"); //$NON-NLS-1$ jobTypeValue.setOnItemSelectedListener(this); jobNumber = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("jobNumber"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); jobNumber.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); // Commission Number commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, contentLinearLayout, false); // Street./No. street = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("streetOrNumber"), //$NON-NLS-1$ InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); street.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.SIXTY) }); // ZIP zip = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("zip"), //$NON-NLS-1$ InputType.TYPE_CLASS_NUMBER, false); zip.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TEN) }); // City city = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("city"), //$NON-NLS-1$ InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); city.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FORTY) }); LinearLayout monthYearLinearLayout = new LinearLayout(context); LinearLayout.LayoutParams monthYearLinearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); monthYearLinearLayoutParams.topMargin = 0; monthYearLinearLayout.setLayoutParams(monthYearLinearLayoutParams); monthYearLinearLayout.setOrientation(LinearLayout.HORIZONTAL); monthYearLinearLayout.setPadding(0, 0, 0, 0); contentLinearLayout.addView(monthYearLinearLayout); month = MDSpinner.createDefaultSpinner(monthYearLinearLayout, ServiceMessages.getString("month"), false); //$NON-NLS-1$ month.setTag("MONTH"); //$NON-NLS-1$ LinearLayout.LayoutParams monthParams = (LayoutParams) ((LinearLayout) month.getParent()).getLayoutParams(); monthParams.gravity = Gravity.CENTER | Gravity.START; monthParams.weight = 0.5f; month.setOnItemSelectedListener(this); year = MDSpinner.createDefaultSpinner(monthYearLinearLayout, ServiceMessages.getString("year"), false); //$NON-NLS-1$ year.setTag("YEAR"); //$NON-NLS-1$ LinearLayout.LayoutParams yearParams = (LayoutParams) ((LinearLayout) year.getParent()).getLayoutParams(); yearParams.gravity = Gravity.CENTER | Gravity.END; yearParams.weight = 0.5f; year.setOnItemSelectedListener(this); // Scan Button LinearLayout scanButtonLinearLayout = new LinearLayout(context); scanButtonLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); scanButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); scanButton = new AppCompatButton(context); LinearLayout.LayoutParams scanButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); scanButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; scanButtonParams.topMargin = LayoutUtils.convertDpToPixel(context, 16); scanButton.setLayoutParams(scanButtonParams); scanButton.setText(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanButton.setOnClickListener(this); scanButton.setBackgroundDrawable(gradientDrawable); scanButtonLinearLayout.addView(scanButton); contentLinearLayout.addView(scanButtonLinearLayout); ScrollView scroll = new ScrollView(context); scroll.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scroll.addView(contentLinearLayout); relativeLayout.addView(scroll); view = new LinearLayout(context); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); jobSearchMap.clear(); // set dialog's title setFormTitle(ServiceMessages.getString("searchJob")); //$NON-NLS-1$ fillJobTypeCombo(); fillMonthCombo(); fillYearCombo(); communicationNumberFormat = app.dbutil.getUser().getCommunicationNumberFormat(); if (jobTypeValue.getSelectedItemPosition()==0) { reset(false); } else { setFieldsState(jobTypeValue.getSelectedName()); } return null; } @SuppressWarnings("unused") private ApplicationEvent addAction() { hideSoftInputFromWindow(); reset(false); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { ch.mfiles.kaba.kolibri.service.forms.JobNewForm.FormArguments formArguments = new JobNewForm.FormArguments( true, "", new Job(), new Address(), new Address()); //$NON-NLS-1$ return appman.getActiveApplication().callForm(JobNewForm.class, formArguments); } }, false); return null; } @SuppressWarnings("unused") private ApplicationEvent resetAction() { hideSoftInputFromWindow(); app.dbutil.deleteAllServerJob(); reset(true); return null; } @SuppressWarnings("unused") private ApplicationEvent searchAction() { hideSoftInputFromWindow(); if (isValid()) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (JobType.REP.equals(jobTypeValue.getSelectedName())) { if (new RemoteTransactionHandler().runGetOrder(jobNumber.getText().toString() , jobTypeValue.getSelectedName() , app.dbutil.getUser().getPersonalNumber()).getStatus() == RemoteTransactionResult.Status.success) { StringBuilder builder = new StringBuilder(); String jobNr = jobNumber.getText().toString(); if(jobNr.length() < 10) { for (int i = 0; i < 10 - jobNr.length(); i++) { builder.append("0"); } jobNr = builder.toString() + jobNr; } Job job = app.dbutil.selectJobByJobIdAndJobType(jobNr, jobTypeValue.getSelectedName()); job.calculateActiveDate(); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); return app.leaveToForm(JobListForm.class); } } else { JobSearchCriteria jobSearchCriteria = getJobSearchCriteria(); app.dbutil.deleteAllServerJob(); String vbeln = jobSearchCriteria.getCommissionNumber(); if (new RemoteTransactionHandler().runGetOrderList( jobSearchCriteria.getJobNumber(), app.dbutil.getUser().getPersonalNumber(), jobSearchCriteria.getJobType() , vbeln.trim() , jobSearchCriteria.getStreet().trim() , jobSearchCriteria.getCity().trim() , jobSearchCriteria.getZip().trim(), "", //$NON-NLS-1$ jobSearchCriteria.getMonth() + "/" + jobSearchCriteria.getYear().substring(2, 4))) { //$NON-NLS-1$ return app.leaveToForm(JobSearchListForm.class, new JobSearchListFormArguments(jobSearchCriteria.getJobType())); } } return null; } }; } return null; } @Override protected boolean isValid() { boolean result = super.isValid(); if (jobTypeValue.getSelectedItemPosition() == 0) { jobTypeValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } if (jobTypeValue.getSelectedName().equalsIgnoreCase(JobType.SAV) && month.getSelectedItemPosition() != 0 && year.getSelectedItemPosition() == 0) { year.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } return result; } public void reset(boolean isResetJobType) { super.onFormReset(); jobNumber.getText().clear(); commissionNumberLayout.clear(); street.getText().clear(); zip.getText().clear(); city.getText().clear(); if (isResetJobType) { jobTypeValue.clearContents(); fillJobTypeCombo(); } month.clearContents(); fillMonthCombo(); year.clearContents(); fillYearCombo(); setEnableAndVisibility(false); month.setSelection(0); year.setEnabled(false); jobNumber.setEnabled(false); commissionNumberLayout.setEnabled(false); } private void setEnableAndVisibility(boolean enabled) { street.setEnabled(enabled); zip.setEnabled(enabled); city.setEnabled(enabled); month.setEnabled(enabled); if (!month.isEnabled()) { month.setSelection(0); } year.setEnabled(enabled); int visibility = View.VISIBLE; if (!enabled) { visibility = View.GONE; } scanButton.setVisibility(visibility); } private void setFieldsState(String jobName) { jobType = jobTypeValue.getSelectedName(); commissionNumberLayout.setJobTypeAndFormat(new JobType(jobType), communicationNumberFormat); jobNumber.setEnabled(false); jobNumber.setRequired(false); commissionNumberLayout.setEnabled(false); commissionNumberLayout.setRequired(false); if (JobType.MON.equals(jobName) || JobType.SAV.equals(jobName)) { if (JobType.SAV.equals(jobName)) { year.setSelection(2); setEnableAndVisibility(true); } else { year.setSelection(0); setEnableAndVisibility(false); } commissionNumberLayout.setHint(ServiceMessages.getString(COMMISSION_NUMBER)); commissionNumberLayout.clearError(); commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(false); if (JobType.SAV.equals(jobName)) { jobNumber.clearError(); jobNumber.setEnabled(true); } } else if (JobType.REP.equals(jobName)) { jobNumber.clearError(); jobNumber.setEnabled(true); jobNumber.setRequired(true); } else { setEnableAndVisibility(false); month.setSelection(0); year.setEnabled(false); } } @Override public void clearErrorMessages() { super.clearErrorMessages(); jobTypeValue.clearError(); commissionNumberLayout.clearError(); year.clearError(); } private void fillJobTypeCombo() { if (jobTypeValue.getAdapter() == null) { List jobTypeValueList = new ArrayList(); Iterator itr = app.enumUtil.jobTypeEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); jobTypeValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } jobTypeValue.setContents(jobTypeValueList); } } private void fillMonthCombo() { if (month.getAdapter() == null) { List monthList = new ArrayList(); Iterator itr = app.enumUtil.monthEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); monthList.add(new CustomSpinnerItem((String) entry.getKey(), monthList.isEmpty() ? "-" : (String) entry.getValue())); //$NON-NLS-1$ } month.setContents(monthList); } } private void fillYearCombo() { if (year.getAdapter() == null) { List yearList = new ArrayList(); yearList.add(new CustomSpinnerItem("0000", "-")); //$NON-NLS-1$ //$NON-NLS-2$ int currentYear = GregorianCalendar.getInstance().get(GregorianCalendar.YEAR); for (int i = currentYear - 1; i < currentYear + 2; i++) { yearList.add(new CustomSpinnerItem(Integer.toString(i), Integer.toString(i))); } year.setContents(yearList); } } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("JOBTYPE".equals(parent.getTag())) { if(!StringUtil.isEmpty(jobType) && !jobType.equalsIgnoreCase(jobTypeValue.getSelectedName())) { jobSearchMap.put(jobType, getJobSearchCriteria()); } jobTypeValue.clearError(); reset(false); setFieldsState(jobTypeValue.getSelectedName()); scanButton.setEnabled(jobType.equalsIgnoreCase(JobType.SAV) ? true:false); if(jobSearchMap.containsKey(jobTypeValue.getSelectedName())) { loadJobSearchCriteria(jobSearchMap.get(jobTypeValue.getSelectedName())); } } else if ("YEAR".equals(parent.getTag())) { year.clearError(); } } @Override public void onNothingSelected(AdapterView arg0) { // do nothing } private JobSearchCriteria getJobSearchCriteria() { JobSearchCriteria result = new JobSearchCriteria(); result.setJobType(jobTypeValue.getSelectedName()); result.setJobNumber(jobNumber.getText().toString()); result.setCommissionNumber(commissionNumberLayout.getCommissionNumber()); result.setStreet(street.getText().toString()); result.setZip(zip.getText().toString()); result.setCity(city.getText().toString()); result.setMonth(month.getSelectedId()); result.setYear(year.getSelectedId()); return result; } private void loadJobSearchCriteria(JobSearchCriteria jobSearchCriteria) { jobNumber.setText(jobSearchCriteria.getJobNumber()); commissionNumberLayout.setText(jobSearchCriteria.getCommissionNumber()); street.setText(jobSearchCriteria.getStreet()); zip.setText(jobSearchCriteria.getZip()); city.setText(jobSearchCriteria.getCity()); month.setSelectionById(jobSearchCriteria.getMonth()); year.setSelectionById(jobSearchCriteria.getYear()); } /** * The Job Search Form Arguments Class. * * @author nop */ public static class JobSearchFormArguments { private String jobType; public JobSearchFormArguments(String jobType) { this.jobType = jobType; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } } private class JobSearchCriteria { private volatile String jobType; private volatile String jobNumber; private volatile String commissionNumber; private volatile String street; private volatile String zip; private volatile String city; private volatile String month; private volatile String year; public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public String getCommissionNumber() { return commissionNumber; } public void setCommissionNumber(String commissionNumber) { this.commissionNumber = commissionNumber; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } } @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String commissionNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ return null; } else { app.showMessage(result.toString()); commissionNumber = result.getContents(); log.info("scan result -> " + commissionNumber); //$NON-NLS-1$ commissionNumberLayout.setText(commissionNumber); } return null; } }; } }     service/src/ch/mfiles/kaba/kolibri/service/forms/JobSearchListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.businessobjects.Employee; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.ServerJob; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidgetItem; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult.Status; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm.JobSearchFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The Job List Result Form For Job Search. * * @author nop (20-04-2017) * * @see "[MIG-52] implement of "search job"" */ public class JobSearchListForm extends SuperForm{ private static Log log = LogFactory.getLog(JobSearchListForm.class); private String jobType; private CheckBoxListWidget checkBoxListWidget; private List selectedList = new ArrayList(); @Override public void onFormCall(Object argument) { if (argument instanceof JobSearchListFormArguments) { JobSearchListFormArguments formArguments = (JobSearchListFormArguments) argument; this.jobType = formArguments.getJobType(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); saveButton.setVisible(false); // create download Button ActionCtrl downloadButton = addActionCtrl(false, true, 1, "onDownloadPressed"); //$NON-NLS-1$ downloadButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DOWNLOAD_WHITE, CommonConstants.Images.IMAGE_DPI))); downloadButton.setTitle(ServiceMessages.getString("download")); //$NON-NLS-1$ RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); checkBoxListWidget = new CheckBoxListWidget(context); checkBoxListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); checkBoxListWidget.setDividerHeight(1); checkBoxListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // set empty items ArrayList items = new ArrayList(); checkBoxListWidget.addItems(items); contentLinearLayout.addView(checkBoxListWidget); relativeLayout.addView(contentLinearLayout); view = new LinearLayout(context); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { setFormTitle(jobType + " " + ServiceMessages.getString("download")); //$NON-NLS-1$ //$NON-NLS-2$ app.messageUtil.showContinueMessage(); checkBoxListWidget.clean(); new AsyncTask(this) { private List employeeList; @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { employeeList = app.dbutil.selectEmployeeList(""); return null; } @Override protected void runOnUIThread() { final List jobList = app.dbutil.selectServerJobList(); ArrayList items = new ArrayList(); for (int i = 0; i < jobList.size(); i++) { final ServerJob data = jobList.get(i); final CheckBoxListWidgetItem item = new CheckBoxListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); item.setTitleText(StringUtil.removeAllLeadingZero(data.getJobNumber()) + ": " + data.getStreet() + " " + data.getPostalCode() + " " + data.getCity()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ item.setStringLine1(JobType.MON.equals(jobType)?data.getcommissionNumberNoLeadingZero():data.getCommissionNumber() + " " + data.getLocation()); //$NON-NLS-1$ item.setCheck(false); if (!new JobType(jobType).isMON() && !data.getPersonalNumber().isEmpty() && !data.getPersonalNumber().equalsIgnoreCase("00000000")) { item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK, CommonConstants.Images.IMAGE_DPI))); String fullname = ""; for (Employee employee : employeeList) { if (employee.getPersonalNumber() == Integer.parseInt(data.getPersonalNumber())) { fullname = employee.getFirstName() + " " + employee.getLastName(); } } item.setStringLine2("Bezogen von.: " + fullname + " / "+ StringUtil.removeAllLeadingZero(data.getPersonalNumber())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { item.isShowLeftCheckBox(true); item.setLeftCheckBoxTag(data.getJobNumber()); item.setStringLine2(jobType + "-Code: " + data.getServiceContractType() + "*/ " + data.getMonthYear() + "**" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { CheckBox checkBox = (CheckBox) v; if (checkBox.isChecked()) { selectedList.add(checkBox.getTag().toString()); } else { selectedList.remove(checkBox.getTag().toString()); } item.setCheck(checkBox.isChecked()); } } }); items.add(item); } checkBoxListWidget.addItems(items); } }; return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobSearchForm.class, new JobSearchFormArguments(null)); } @Override public void onFormReset() { super.onFormReset(); jobType = null; selectedList = new ArrayList(); setFormTitle(null); } protected ApplicationEvent onDownloadPressed() { if (selectedList.isEmpty()) { app.showMessage(ServiceMessages.getString("selectOneOrMoreJobs")); //$NON-NLS-1$ return null; } if (ServiceJobUtil.isMaxDownload(selectedList)) { app.showMessage(ServiceMessages.getString("youCanSelectMaximumOf30Jobs")); //$NON-NLS-1$ return null; } downloadJobs(); return null; } private void downloadJobs() { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (ServiceJobUtil.isMaxConfirmDownload(selectedList)) { String message = MessageFormat.format(ServiceMessages.getString("doYouReallyWantToLoadXjobsAtOnce"), new Object[] { selectedList.size()}); //$NON-NLS-1$ if (app.showMessageBox(message, ServiceMessages.getString("confirmation"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ Application.MBOX_ICON_QUESTION) == Application.MBOX_RESULT_NO) { return null; } } Map downloadErrorMap = new HashMap(); for (String mldnr : selectedList) { RemoteTransactionResult result = getOrder(mldnr); if (result.getStatus() == Status.error) { if ("E".equalsIgnoreCase(result.getMessageType()) && !result.getMessage().isEmpty()) { downloadErrorMap.put(mldnr, result.getMessage()); } else { return null; } } } return app.leaveToForm(JobDownloadResultForm.class, new JobDownloadResultForm.FormArguments(jobType, selectedList, downloadErrorMap)); } }; } private RemoteTransactionResult getOrder(String mldnr) { RemoteTransactionResult result = new RemoteTransactionHandler().runGetOrder(mldnr, jobType, app.dbutil.getUser().getPersonalNumber()); if (result.getStatus() == Status.success && result.getMessage().isEmpty()) { Job job = app.dbutil.selectJobByJobIdAndJobType(mldnr, jobType); //MIG-883 Wrong personal number in SAVE_REPORT in a specific use case if (job.getPersonalNumber() != app.dbutil.getUser().getPersonalNumber()) { log.info("pernr " + job.getPersonalNumber() + " received, update to active user."); job.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); } job.calculateActiveDate(); // every job who is downloaded by user have to be set automatically in status RECEIVED (including UPDATE_STATUS to backend). new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } return result; } public static class JobSearchListFormArguments { private String jobType; public JobSearchListFormArguments(String jobType) { this.jobType = jobType; } public JobSearchListFormArguments(String jobType, String commissionNumber) { this.jobType = jobType; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportChecklistForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.FormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ui.LayoutInflater; /** * * see "MIG-611 Checklist for MON-jobs" */ public class ReportChecklistForm extends SuperForm { private static Log log = LogFactory.getLog(ReportChecklistForm.class); private Job job; private Person user; private CheckListRadioGroup stateRadioGroup; private CheckListRadioGroup sIARadioGroup; private CheckListRadioGroup readyRadioGroup; private CheckListRadioGroup instructionRadioGroup; private CheckListRadioGroup testCheckListRadioGroup; @Override public ApplicationEvent onBackPressed() { onCancel(); leaveToJobDetailForm(); return null; } @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 0, 16, 16); stateRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(stateRadioGroup); sIARadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(sIARadioGroup); readyRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(readyRadioGroup); instructionRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(instructionRadioGroup); testCheckListRadioGroup = new CheckListRadioGroup(context); contentLinearLayout.addView(testCheckListRadioGroup); saveButton.setTitle(ServiceMessages.getString("save")); view.addView(contentLinearLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); onFormReset(); // set dialog's title this.setFormTitle(ServiceMessages.getString("Checklist")); //$NON-NLS-1$ loadData(); user = app.dbutil.getUser(); stateRadioGroup.setText(getText("ChecklistStateText")); sIARadioGroup.setText(getText("ChecklistSIAText")); readyRadioGroup.setText(getText("ChecklistReadyText")); instructionRadioGroup.setText(getText("ChecklistInstructionText")); testCheckListRadioGroup.setText(getText("ChecklistTestText")); return null; } @Override public void onFormReset() { super.onFormReset(); stateRadioGroup.reset(); sIARadioGroup.reset(); readyRadioGroup.reset(); instructionRadioGroup.reset(); testCheckListRadioGroup.reset(); } /** * Loads data. */ public void loadData() { Report report = this.job.getCurrentReport(); // All radio button groups have to be unselected (both buttons). log.info("checklist " + report.getChecklistState() ); if (!report.isChecklistStateUnselected()) { stateRadioGroup.setChecked(report.isChecklistState()); } if (!report.isChecklistSIAUnselected()) { sIARadioGroup.setChecked(report.isChecklistSIA()); } if (!report.isChecklistReadyUnselected()) { readyRadioGroup.setChecked(report.isChecklistReady()); } if (!report.isChecklistInstructionUnselected()) { instructionRadioGroup.setChecked(report.isChecklistInstruction()); } if (!report.isChecklistTestUnselected()) { testCheckListRadioGroup.setChecked(report.isChecklistTest()); } } @Override protected boolean isValid() { boolean result = super.isValid(); // View focusView = null; // String errorMessage = Messages.getString("pleaseProvideValue"); return result; } @Override protected boolean onSave() { //The user have to click at least at one button of each group (yes or no) //Check if all radio buttons group have at least one selected button //The checklist cannot be saved if at least one radio button group is unselected (in this case, the user can leave the UI only with "x" icon in app bar if (stateRadioGroup.isEmpty() || sIARadioGroup.isEmpty() || readyRadioGroup.isEmpty() || instructionRadioGroup.isEmpty() || testCheckListRadioGroup.isEmpty()) { return false; } Report report = this.job.getLatestReport(); // assign value to object and insert new report assignToReport(report); app.dbutil.insertReplaceReport(report); log.info("Report saved." + report.getGuId()); app.dbutil.updateJob(job); job.loadReports(app.dbutil); leaveToJobDetailForm(); return true; } private void assignToReport(Report rep) { rep.setChecklistState(stateRadioGroup.isChecked()); rep.setChecklistSIA(sIARadioGroup.isChecked()); rep.setChecklistReady(readyRadioGroup.isChecked()); rep.setChecklistInstruction(instructionRadioGroup.isChecked()); rep.setChecklistTest(testCheckListRadioGroup.isChecked()); } private void leaveToJobDetailForm() { app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailForm.JobDetailFormArgument(job, 2)); } public void onCancel() { } @Override public void clearErrorMessages() { super.clearErrorMessages(); } private String getText(String key) { log.info("ProfileText " + user.getProfileText() + " Language " + user.getLanguage()); if (user.getProfileText().equalsIgnoreCase(CommonConstants.CommissionNumber.CH)) { Locale locale = Locale.ENGLISH; if (user.getLanguage().equalsIgnoreCase("D")) { locale = Locale.GERMAN; } else if (user.getLanguage().equalsIgnoreCase("F")) { locale = Locale.FRANCE; } return ServiceMessages.getString(locale, key); } else if (user.getProfileText().equalsIgnoreCase(CommonConstants.CommissionNumber.DE)) { return ServiceMessages.getString(Locale.GERMAN, key); } return ServiceMessages.getString(key); } private class CheckListRadioGroup extends LinearLayout { private MDRadioButton yesRadioButton; private MDRadioButton noRadioButton; private TextView textView; public CheckListRadioGroup(Context context) { super(context); addView(createVKFView()); } private View createVKFView() { GridLayout gridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); gridLayout.setLayoutParams(gridLayoutParams); gridLayout.setColumnCount(3); RelativeLayout yesRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams yesRelativeLayoutParams = new GridLayout.LayoutParams(); yesRelativeLayoutParams.width = 0; yesRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; yesRelativeLayoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.1f); yesRelativeLayoutParams.leftMargin = LayoutUtils.convertDpToPixel(context, 6); yesRelativeLayout.setLayoutParams(yesRelativeLayoutParams); TextView YesTextView = new TextView(context); YesTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); YesTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams yesTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); YesTextView.setLayoutParams(yesTextViewValueParams); YesTextView.setText(ServiceMessages.getString("yes")); YesTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); YesTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); yesRelativeLayout.addView(YesTextView); gridLayout.addView(yesRelativeLayout); RelativeLayout noRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams noRelativeLayoutParams = new GridLayout.LayoutParams(); noRelativeLayoutParams.width = 0; noRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; noRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.1f); noRelativeLayoutParams.leftMargin = LayoutUtils.convertDpToPixel(context, 6); noRelativeLayout.setLayoutParams(noRelativeLayoutParams); TextView noTextView = new TextView(context); noTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); noTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams noTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); noTextView.setLayoutParams(noTextViewValueParams); noTextView.setText(ServiceMessages.getString("no")); noTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); noTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); noRelativeLayout.addView(noTextView); gridLayout.addView(noRelativeLayout); RelativeLayout emptyGridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams emptyGridRelativeLayoutParams = new GridLayout.LayoutParams(); emptyGridRelativeLayoutParams.width = 0; emptyGridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; emptyGridRelativeLayoutParams.columnSpec = GridLayout.spec(2, 1, 0.8f); emptyGridRelativeLayout.setLayoutParams(emptyGridRelativeLayoutParams); gridLayout.addView(emptyGridRelativeLayout); GridLayout.LayoutParams yesRadioButtonGridLayoutParams = new GridLayout.LayoutParams(); yesRadioButtonGridLayoutParams.width = 0; yesRadioButtonGridLayoutParams.height = LayoutParams.WRAP_CONTENT; yesRadioButtonGridLayoutParams.columnSpec = GridLayout.spec(0, 1, 0.1f); yesRadioButton = MDRadioButton.createDefaultRadioButton(gridLayout, ""); ((LinearLayout) yesRadioButton.getParent()).setLayoutParams(yesRadioButtonGridLayoutParams); GridLayout.LayoutParams noRadioButtonGridLayoutParams = new GridLayout.LayoutParams(); noRadioButtonGridLayoutParams.width = 0; noRadioButtonGridLayoutParams.height = LayoutParams.WRAP_CONTENT; noRadioButtonGridLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.1f); noRadioButton = MDRadioButton.createDefaultRadioButton(gridLayout, ""); ((LinearLayout) noRadioButton.getParent()).setLayoutParams(noRadioButtonGridLayoutParams); RelativeLayout textRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams textRelativeLayoutParams = new GridLayout.LayoutParams(); textRelativeLayoutParams.width = 0; textRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; textRelativeLayoutParams.columnSpec = GridLayout.spec(2, 1, 0.8f); textRelativeLayout.setLayoutParams(textRelativeLayoutParams); textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); textView.setLayoutParams(gridTextViewValueParams); textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textRelativeLayout.addView(textView); gridLayout.addView(textRelativeLayout); yesRadioButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (((MDRadioButton) v).isChecked()) { noRadioButton.setChecked(false); } } }); noRadioButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (((MDRadioButton) v).isChecked()) { yesRadioButton.setChecked(false); } } }); textView.setClickable(true); textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!yesRadioButton.isChecked()) { yesRadioButton.setChecked(true); noRadioButton.setChecked(false); } else { yesRadioButton.setChecked(false); noRadioButton.setChecked(true); } } }); return gridLayout; } public void setText(String text) { textView.setText(text); } public boolean isChecked() { return yesRadioButton.isChecked(); } public void setChecked(boolean checklistState) { if (checklistState) { yesRadioButton.setChecked(true); noRadioButton.setChecked(false); } else { yesRadioButton.setChecked(false); noRadioButton.setChecked(true); } } public void reset() { yesRadioButton.setChecked(false); noRadioButton.setChecked(false); } public boolean isEmpty() { return !yesRadioButton.isChecked() && !noRadioButton.isChecked(); } public void setError(CharSequence error) { yesRadioButton.setError(error); noRadioButton.setError(error); } public void clearError() { yesRadioButton.clearError(); noRadioButton.clearError(); } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportDocumentAttachmentsListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DetailListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.forms.ReportDocumentDetailForm.ReportDocumentDetailFormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class ReportDocumentAttachmentsListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportDocumentAttachmentsListForm.class); protected Job job; private Toolbar toolbar; protected DetailListWidget listWidget; private ActionCtrl addButton; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportDocumentAttachmentsListFormArguments) { ReportDocumentAttachmentsListFormArguments formArguments = (ReportDocumentAttachmentsListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new DetailListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, Messages.getString("noDocumentsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(Messages.getString("documents")); //$NON-NLS-1$ loadImageAttachmentsList(); return null; } private void loadImageAttachmentsList() { listWidget.clean(); Map> reportDocumentsList = app.dbutil.selectDocumentListByReport(job.getLatestReport()); view.removeAllViews(); if(reportDocumentsList.isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); Iterator> iterator = reportDocumentsList.values().iterator(); List> docs = new ArrayList>(); while (iterator.hasNext()) { List jobFiles = iterator.next(); final DetailListWidgetItem item = new DetailListWidgetItem(); item.isShowEllipInTextEnd(true); item.isShowRightLayout(false); String title = ""; String line1 = "-"; String line2 = ""; JobFormDesc jobFormDesc = app.dbutil.selectJobFormDescByFormDesc(jobFiles.get(0).getFormDesc()); if (jobFormDesc != null && !jobFormDesc.getFormDesc().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { line1 = jobFormDesc.getText(); } String noForm = ""; if (job.getFormDesc1().equalsIgnoreCase(jobFiles.get(0).getFormDesc())) { noForm = job.getLatestReport().getNoForm1(); } else if (job.getFormDesc2().equalsIgnoreCase(jobFiles.get(0).getFormDesc())) { noForm = job.getLatestReport().getNoForm2(); } else if (job.getFormDesc3().equalsIgnoreCase(jobFiles.get(0).getFormDesc())) { noForm = job.getLatestReport().getNoForm3(); } if (jobFiles.get(0).getJobFileId().contains("NO_FORM")) { if (noForm.isEmpty()) noForm = jobFiles.get(0).getJobFileId().substring(jobFiles.get(0).getJobFileId().length()-2, jobFiles.get(0).getJobFileId().length()); title = app.dbutil.selectJobNoFormByNoForm(noForm).getText(); line2 = Messages.getString("noDocumentsRecorded"); } else { title = jobFiles.get(0).getDescription(); line2 = jobFiles.size() + " " + Messages.getString("documents"); } item.setTitleText(title); item.setStringLine1(line1); item.setStringLine2(line2); items.add(item); docs.add(jobFiles); } listWidget.setOnItemClickListener(createOnItemClickListener(docs)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List> docs) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { app.injectAndLeaveToForm(ReportDocumentDetailForm.class, new ReportDocumentDetailForm.ReportDocumentDetailFormArguments(job, docs.get(position))); //$NON-NLS-1$ } }; } protected ApplicationEvent onAddPressed() { return app.leaveToForm(ReportDocumentDetailForm.class, new ReportDocumentDetailFormArguments(job, new ArrayList())); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } public static class ReportDocumentAttachmentsListFormArguments { private Job job; public ReportDocumentAttachmentsListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportDocumentAttachmentsNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportDocumentDetailForm.ReportDocumentDetailFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportDocumentAttachmentsNewEditForm extends DialogForm { private static Log log = LogFactory.getLog(ReportDocumentAttachmentsNewEditForm.class); // initialized by the kolibri framework... public static ServiceApplication app; private Job job; private Bitmap bitmap; private JobFile jobFile; private List jobFiles; private ImageView image; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil utilButton; @Override public void onFormCall(Object argument) { if (argument instanceof ReportDocumentAttachmentsNewEditFormArguments) { ReportDocumentAttachmentsNewEditFormArguments formArguments = (ReportDocumentAttachmentsNewEditFormArguments) argument; job = formArguments.getJob(); bitmap = formArguments.getBitmap(); jobFile = formArguments.getJobFile(); jobFiles = formArguments.getJobFiles(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; utilButton = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMaxHeight(800); image.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, null); return false; } }); contentLinearLayout.addView(image); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroup.setPadding(2, 2, 2, 2); radioGroup.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.addView(radioGroup); messages = MDEditText.createDefaultEditText(contentLinearLayout, "description", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); Button deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(jobFile == null) { messages.getText().clear(); } else { actionDelete(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(contentLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("Document")); //$NON-NLS-1$ messages.getText().clear(); image.setImageBitmap(null); if (bitmap == null) { bitmap = jobFile.getSignPicBitmap(); } image.setImageBitmap(bitmap); if(!jobFile.getDescription().isEmpty()) messages.setText(jobFile.getDescription()); return null; } @Override protected ApplicationEvent onSavePressed() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (jobFile.getJobFileId().isEmpty()) { Date date = new Date(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); if (jobFile.isValid()) { jobFiles.add(jobFile); app.dbutil.insertJobFile(jobFile); } else { throw new ApplicationException(); } } else { jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); app.dbutil.updateJobFile(jobFile); } return onBackPressed(); } }; return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ReportDocumentDetailForm.class, new ReportDocumentDetailFormArguments(job, jobFiles)); } private void actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { app.dbutil.deleteJobFile(jobFile); jobFiles.remove(jobFile); } finally { db.commit(); } app.showMessage(ServiceMessages.getString("fileDeleted")); //$NON-NLS-1$ return onBackPressed(); } }; } public static class ReportDocumentAttachmentsNewEditFormArguments { private Job job; private Bitmap bitmap; private JobFile jobFile; private List jobFiles; public ReportDocumentAttachmentsNewEditFormArguments(Job zkdmob ,Bitmap bitmap, JobFile jobFile, List jobFiles) { this.job = zkdmob; this.bitmap = bitmap; this.jobFile = jobFile; this.jobFiles = jobFiles; } public Job getJob() { return job; } public Bitmap getBitmap() { return bitmap; } public JobFile getJobFile() { return jobFile; } public List getJobFiles() { return jobFiles; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportDocumentDetailForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFormDesc; import ch.mfiles.kaba.kolibri.common.businessobjects.JobNoForm; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportDocumentDetailForm extends SuperForm { private static Log log = LogFactory.getLog(ReportDocumentDetailForm.class); private Toolbar toolbar; protected ImageListWidget listWidget; private ActionUtil utilButton; private ActionCtrl addButton; private Button deleteButton; private LinearLayout emptyMessageView; private LinearLayout listLinearLayout; private MDSpinner documentSpinner; private AppCompatCheckBox notRecordedCheckBox; private MDSpinner reasonSpinner; private Job job; private JobFile doc; private List jobFiles; private boolean noForm1; private boolean noForm2; private boolean noForm3; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportDocumentDetailFormArguments) { ReportDocumentDetailFormArguments formArguments = (ReportDocumentDetailFormArguments) argument; jobFiles = formArguments.getJobFiles(); job = formArguments.getJob(); doc = jobFiles.isEmpty() ? null:jobFiles.get(0); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); utilButton = new ActionUtil(app); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); // create add button Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout documentLinearLayout = new LinearLayout(context); documentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); documentLinearLayout.setOrientation(LinearLayout.VERTICAL); documentSpinner = MDSpinner.createDefaultSpinner(documentLinearLayout, ServiceMessages.getString("Document"), true); //$NON-NLS-1$ documentSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { documentSpinner.clearError(); notRecordedCheckBox.setEnabled(false); if (position == 0) { return; } seteEnabledNotRecordedCheckBox(documentSpinner.getSelectedId()); } }); contentLinearLayout.addView(documentLinearLayout); notRecordedCheckBox = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("notRecorded")); //$NON-NLS-1$ notRecordedCheckBox.setChecked(false); notRecordedCheckBox.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { if(((AppCompatCheckBox)v).isChecked()){ reasonSpinner.setEnabled(true); } else { notRecordedCheckBox.setChecked(false); reasonSpinner.setEnabled(false); } reasonSpinner.clearError(); } }); contentLinearLayout.addView(notRecordedCheckBox); LinearLayout reasonLinearLayout = new LinearLayout(context); reasonLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); reasonLinearLayout.setOrientation(LinearLayout.VERTICAL); reasonSpinner = MDSpinner.createDefaultSpinner(reasonLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonSpinner.setTag("REASON"); //$NON-NLS-1$ reasonSpinner.setEnabled(false); // reasonSpinner.setOnItemSelectedListener(this); contentLinearLayout.addView(reasonLinearLayout); listLinearLayout = new LinearLayout(context); listLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams listLinearLayoutParams = new LinearLayout.LayoutParams(0,0); listLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; listLinearLayoutParams.height = LayoutParams.FILL_PARENT; listLinearLayoutParams.width = LayoutParams.FILL_PARENT; listLinearLayoutParams.weight = 1f; listLinearLayout.setLayoutParams(listLinearLayoutParams); listWidget = new ImageListWidget(context); listLinearLayout.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, Messages.getString("noDocumentsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); contentLinearLayout.addView(listLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (doc == null) { documentSpinner.clearError(); documentSpinner.setSelection(0); notRecordedCheckBox.setChecked(false); reasonSpinner.clearError(); reasonSpinner.setEnabled(false); } else { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("areYouSureThatYouWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } if (noForm1) { job.getLatestReport().setNoForm1(""); } else if (noForm2) { job.getLatestReport().setNoForm2(""); } else if (noForm3) { job.getLatestReport().setNoForm3(""); } app.dbutil.insertReplaceReport(job.getLatestReport()); for (JobFile jobFile : jobFiles) { app.dbutil.deleteJobFile(jobFile); } jobFiles.clear(); return app.leaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); } }, false); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(Messages.getString("documents")); //$NON-NLS-1$ loadData(); return null; } public void loadData() { List jobFormDescValueList = new ArrayList(); List jobFormDescs = app.dbutil.selectJobFormDescList(); for (JobFormDesc jobFormDesc : jobFormDescs) { log.info("FormDesc " + jobFormDesc.getFormDesc() + " Text " + jobFormDesc.getText()); jobFormDescValueList.add(new CustomSpinnerItem((String) jobFormDesc.getFormDesc(), (String) jobFormDesc.getText())); } documentSpinner.setContents(jobFormDescValueList); List jobNoFormValueList = new ArrayList(); List jobNoForms = app.dbutil.selectJobNoFormList(); for (JobNoForm jobNoForm : jobNoForms) { log.info("NoForm " + jobNoForm.getNoForm() + " Text " + jobNoForm.getText()); jobNoFormValueList.add(new CustomSpinnerItem((String) jobNoForm.getNoForm(), (String) jobNoForm.getText())); } reasonSpinner.setContents(jobNoFormValueList); notRecordedCheckBox.setEnabled(false); notRecordedCheckBox.setChecked(false); reasonSpinner.setEnabled(false); if (doc == null) { deleteButton.setText(ServiceMessages.getString("clear")); } else { deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ documentSpinner.setSelectionById(doc.getFormDesc()); loadNoForm(); } documentSpinner.setRequired(ServiceJobUtil.isJobRequireFormDesc(job)); loadImageAttachmentsList(); } private void seteEnabledNotRecordedCheckBox(String formDesc) { noForm1 = false; noForm2 = false; noForm3 = false; if (formDesc.equalsIgnoreCase(job.getFormDesc1())) { noForm1 = true; } if (formDesc.equalsIgnoreCase(job.getFormDesc2())) { noForm2 = true; } if (formDesc.equalsIgnoreCase(job.getFormDesc3())) { noForm3 = true; } notRecordedCheckBox.setEnabled(noForm1 || noForm2 || noForm3 || (ServiceJobUtil.isMandatoryByReportMessage(job) && formDesc.equalsIgnoreCase(ServiceConstants.ModernisationNecessary))); if (!notRecordedCheckBox.isEnabled()) { notRecordedCheckBox.setChecked(false); reasonSpinner.setEnabled(false); reasonSpinner.setSelection(0); } } private void loadNoForm() { seteEnabledNotRecordedCheckBox(doc.getFormDesc()); if (notRecordedCheckBox.isEnabled()) { reasonSpinner.setSelectionById(doc.getNoForm()); notRecordedCheckBox.setChecked(!doc.getNoForm().isEmpty()); } reasonSpinner.setEnabled(notRecordedCheckBox.isEnabled() && notRecordedCheckBox.isChecked()); } private void loadImageAttachmentsList() { listWidget.clean(); ArrayList items = new ArrayList(); listLinearLayout.removeAllViews(); if(!jobFiles.isEmpty() && !jobFiles.get(0).getJobFileId().contains("NO_FORM")) { for (int i = 0; i < jobFiles.size(); i++) { final JobFile jobFile = jobFiles.get(i); if (!jobFiles.get(0).getJobFileId().contains("NO_FORM")) { final ImageListWidgetItem item = new ImageListWidgetItem(); item.setDescription(jobFile.getDescription()); item.setImageBitmap(jobFile.getSignPicBitmap()); item.setType(jobFile.getJobFileId()); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(jobFiles)); } } listWidget.addItems(items); listLinearLayout.addView(listWidget); } else { listLinearLayout.addView(emptyMessageView); } } private OnItemClickListener createOnItemClickListener(final List reportImageAttachmentsList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { JobFile jobFile = reportImageAttachmentsList.get(position); app.injectAndLeaveToForm(ReportDocumentAttachmentsNewEditForm.class, new ReportDocumentAttachmentsNewEditForm.ReportDocumentAttachmentsNewEditFormArguments(job, null, jobFile, jobFiles)); //$NON-NLS-1$ } }; } private void leaveToImageNewEditForm(Bitmap bitmap) { if(bitmap == null) return; if(!jobFiles.isEmpty() && jobFiles.get(0).getJobFileId().contains("NO_FORM")) { app.dbutil.deleteJobFile(jobFiles.get(0)); jobFiles.remove(jobFiles.get(0)); if (noForm1) { job.getLatestReport().setNoForm1(""); } else if (noForm2) { job.getLatestReport().setNoForm2(""); } else if (noForm3) { job.getLatestReport().setNoForm3(""); } app.dbutil.insertReplaceReport(job.getLatestReport()); } JobFile jobFile = new JobFile(); jobFile.setGuid(job.getLatestReport().getGuId()); jobFile.setJobNumber(job.getJobNumber()); jobFile.setJobType(job.getJobType()); jobFile.setType("F"); jobFile.setFormType(new FormType(FormType.JPG)); app.injectAndLeaveToForm(ReportDocumentAttachmentsNewEditForm.class, new ReportDocumentAttachmentsNewEditForm.ReportDocumentAttachmentsNewEditFormArguments(job, bitmap, assignToJobFile(jobFile), jobFiles)); } protected ApplicationEvent onAddPressed() { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, null); return null; } @Override public ApplicationEvent onBackPressed() { if (isCancelEdited()) { return app.leaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); } new AsyncTask(this) { private Object errorView = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (doc != null && doc.getNoForm().isEmpty() && notRecordedCheckBox.isChecked() && !isEmptyDocument()) { // change doc attachment to noForm if (app.showMessageBox(ServiceMessages.getString("DocumentsWillBeLost"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } } errorView = saveDocuments(); return null; } @Override public void runOnUIThread() { if (errorView != null) { if(errorView instanceof MDSpinner) { ((MDSpinner) errorView).setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } } }; return null; } private boolean isCancelEdited() { if (doc == null && documentSpinner.getSelectedItemPosition() == 0 && !notRecordedCheckBox.isChecked()) { // cancel create new return true; } if (doc != null && doc.getFormDesc().equalsIgnoreCase(documentSpinner.getSelectedId()) && !doc.getNoForm().isEmpty() && notRecordedCheckBox.isChecked() && doc.getNoForm().equalsIgnoreCase(reasonSpinner.getSelectedId())) { return true; } return false; } private boolean isEmptyDocument() { return (jobFiles.isEmpty() || (!jobFiles.isEmpty() && jobFiles.get(0).getJobFileId().contains("NO_FORM"))); } private Object saveDocuments() { log.info("no form " + reasonSpinner.getSelectedId() + " form desc " + documentSpinner.getSelectedId()); if (documentSpinner.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) && !notRecordedCheckBox.isChecked()) { return documentSpinner; } if (notRecordedCheckBox.isEnabled() && !notRecordedCheckBox.isChecked() && isEmptyDocument()) { app.showMessage("Cannot save document, Please add a file."); return null; } if (!notRecordedCheckBox.isEnabled() && isEmptyDocument()) { app.showMessage("Cannot save document, Please add a file."); return null; } if (notRecordedCheckBox.isEnabled() && notRecordedCheckBox.isChecked() && reasonSpinner.getSelectedId().contentEquals(CommonConstants.PLEASE_SELECT)) { return reasonSpinner; } if ((doc == null) || (doc != null && !doc.getFormDesc().equalsIgnoreCase(documentSpinner.getSelectedId()))) { List documentFileList = app.dbutil.selectDocumentFileListByReport(job.getLatestReport(), documentSpinner.getSelectedId()); List documentFileNoFormList = app.dbutil.selectDocumentFileNoFormListByReportAndDormDesc(job.getLatestReport(), documentSpinner.getSelectedId()); if (!documentFileList.isEmpty()) { // NoForm - > doc already attach some file. showDocAlreadyExisDialog(documentFileList.get(0).getFormDesc()); return null; } else if (!documentFileNoFormList.isEmpty()) { // doc -> NoForm showDocAlreadyExisDialog(documentFileNoFormList.get(0).getFormDesc()); return null; } } if (doc != null && doc.getNoForm().isEmpty() && notRecordedCheckBox.isChecked() && !isEmptyDocument()) { // if (doc != null && notRecordedCheckBox.isChecked() && (!jobFiles.isEmpty() && !jobFiles.get(0).getFormDesc().contains("NO_FORM"))) { for (JobFile jobFile : jobFiles) { app.dbutil.deleteJobFile(jobFile); } jobFiles.clear(); } if (notRecordedCheckBox.isEnabled() && notRecordedCheckBox.isChecked() && !reasonSpinner.getSelectedId().contentEquals(CommonConstants.PLEASE_SELECT)) { if (doc != null) { app.dbutil.deleteJobFile(doc); } doc = new JobFile(); Date date = new Date(); doc.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + reasonSpinner.getSelectedId()); doc.setGuid(job.getLatestReport().getGuId()); doc.setJobNumber(job.getJobNumber()); doc.setJobType(job.getJobType()); doc.setType("F"); app.dbutil.insertJobFile(assignToJobFile(doc)); assignNoFormToReport(notRecordedCheckBox.isChecked() ? reasonSpinner.getSelectedId():""); } // todo case noform chage doc to not empty doc add 1 docimage -> remove all docimage in that doc? for (JobFile jobFile : jobFiles) { app.dbutil.updateJobFile(assignToJobFile(jobFile)); } app.injectAndLeaveToForm(ReportDocumentAttachmentsListForm.class, new ReportDocumentAttachmentsListForm.ReportDocumentAttachmentsListFormArguments(job)); return null; } private void showDocAlreadyExisDialog(final String formDesc) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { app.showMessageBox(MessageFormat.format(ServiceMessages.getString("CannotSaveDocAlreadyExist"), new Object[] { app.dbutil.selectJobFormDescByFormDesc(formDesc).getText()}), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING); return null; } @Override public void runOnUIThread() { if (doc != null) { documentSpinner.setSelectionById(doc.getFormDesc()); } } }; } private void assignNoFormToReport(String noForm) { if (noForm.isEmpty()) { return; } if (noForm1) { job.getLatestReport().setNoForm1(noForm); } else if (noForm2) { job.getLatestReport().setNoForm2(noForm); } else if (noForm3) { job.getLatestReport().setNoForm3(noForm); } app.dbutil.insertReplaceReport(job.getLatestReport()); } private JobFile assignToJobFile(JobFile jobFile) { jobFile.setFormDesc(documentSpinner.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT) ? "":documentSpinner.getSelectedId()); return jobFile; } public static class ReportDocumentDetailFormArguments { private List jobFiles; private Job job; public ReportDocumentDetailFormArguments(Job job, List jobFiles) { this.job = job; this.jobFiles = jobFiles; } public Job getJob() { return job; } public List getJobFiles() { return jobFiles; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.net.ParseException; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.GridLayout; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Checklist; import ch.mfiles.kaba.kolibri.common.businessobjects.Email; import ch.mfiles.kaba.kolibri.common.businessobjects.ErrorCode; import ch.mfiles.kaba.kolibri.common.businessobjects.Incident; import ch.mfiles.kaba.kolibri.common.businessobjects.Invoice; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.NextIntervention; import ch.mfiles.kaba.kolibri.common.businessobjects.Progress; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ServiceRefused; import ch.mfiles.kaba.kolibri.common.businessobjects.StateOfInstallation; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerAdapter; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.CommissionNumberLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDCalendar; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailReportForm.FormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (21-03-2017) * * see "MIG-50] implement of "create/edit report" " */ public class ReportEditForm extends SuperForm implements TextWatcher, OnCheckedChangeListener, OnItemSelectedListener { private static Log log = LogFactory.getLog(ReportEditForm.class); private int lastContentRow = 0; private Job job; private CommonConstants.CommissionNumber.Type commissionType; private CommissionNumberLayout commissionNumberLayout; private MDEditText jobNumber; private GridLayout workTypeGridLayout; private MDSpinner workTypeValue; private AppCompatCheckBox reasoning; private AppCompatCheckBox openPending; private AppCompatCheckBox safetyReport; private AppCompatCheckBox collectively; private AppCompatCheckBox governmentReport; private MDRadioButton partialRepair; private MDRadioButton finalRepair; private LinearLayout interventionLayout; private MDCalendar nextInterventionDateValue; private TimeEditText nextInterventionTimeText; private MDSpinner installationStateValue; private MDSpinner interventioValue; private GridLayout progressGridLayout; private MDSpinner progressValue; private MDSpinner billingValue; private MDSpinner sendReportToValue; private MDSpinner addressValue; private MDEditText customerSupportEditText; private GridLayout checklistGridLayout; private MDSpinner checklistValue; private GridLayout incidentAGridLayout; private MDSpinner incidentAValue; private GridLayout incidentBGridLayout; private MDSpinner incidentBValue; private GridLayout systemErrorGridLayout; private MDEditText systemError; private TextView serviceText; private LinearLayout servicePerformedLayout; private TextView servicePerformedText; private GridLayout servicePerformedMonthGridLayout; private MDSpinner servicePerformedMonthValue; private GridLayout servicePerformedYearGridLayout; private MDSpinner servicePerformedYearValue; private TextView serviceRefusedText; private GridLayout serviceRefusedGridLayout; private MDSpinner serviceRefusedValue; private AppCompatCheckBox january; private AppCompatCheckBox february; private AppCompatCheckBox march; private AppCompatCheckBox april; private AppCompatCheckBox may; private AppCompatCheckBox june; private AppCompatCheckBox july; private AppCompatCheckBox august; private AppCompatCheckBox september; private AppCompatCheckBox october; private AppCompatCheckBox november; private AppCompatCheckBox december; private AppCompatButton monthButton; private MDEditText distance; private MDEditText expenses; private MDEditText cycleOfInstallation; private MDSpinner errorValue; private EditText errorEditText1; private AppCompatCheckBox errorCheckbox; private MDSpinner error2Value; private EditText error2EditText1; private AppCompatCheckBox error2Checkbox; private MDSpinner errorMontValue; private EditText errorMontEditText1; private AppCompatCheckBox errorMontCheckbox; private AppCompatButton deleteButton; private List> monthCheckBoxesList; private Map emailMap = new HashMap(); private ScrollView scrollView; @Override public ApplicationEvent onBackPressed() { onCancel(); leaveToJobDetailForm(); return null; } @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; this.job = formArguments.getJob(); commissionType = formArguments.getCommissionType(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING , LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); GridLayout gridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); gridLayout.setLayoutParams(gridLayoutParams); gridLayout.setColumnCount(3); // Commission Number LinearLayout commissionNumberLinearLayout = new LinearLayout(context); commissionNumberLinearLayout.setOrientation(LinearLayout.VERTICAL); commissionNumberLinearLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); commissionNumberLayout = CommissionNumberLayout.createCommissionNumberText(app, this, commissionNumberLinearLayout, true); //$NON-NLS-1$ gridLayout.addView(commissionNumberLinearLayout); // Job Number jobNumber = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("jobNumber"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ jobNumber.setRawInputType(InputType.TYPE_CLASS_TEXT); jobNumber.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.THIRTY_FIVE)}); jobNumber.addTextChangedListener(this); jobNumber.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); // Type Of Work workTypeGridLayout = new GridLayout(context); workTypeGridLayout.setLayoutParams(gridLayoutParams); workTypeGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); workTypeValue = MDSpinner.createDefaultSpinner(workTypeGridLayout, ServiceMessages.getString("typeOfWork"), true); //$NON-NLS-1$ workTypeValue.setTag("TYPEOFWORK"); //$NON-NLS-1$ workTypeValue.setOnItemSelectedListener(this); workTypeValue.setContentDescription(ServiceMessages.getString("typeOfWork")); gridLayout.addView(workTypeGridLayout); reasoning = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("followup")); //$NON-NLS-1$ reasoning.setTag("REASONING"); //$NON-NLS-1$ reasoning.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 2)); reasoning.setOnCheckedChangeListener(this); gridLayout.addView(reasoning); openPending = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("openPending")); //$NON-NLS-1$ openPending.setTag("OPENPENDING"); //$NON-NLS-1$ openPending.setLayoutParams(getGridLayoutParams(getRowIndex(), 0, 2)); openPending.setOnCheckedChangeListener(this); gridLayout.addView(openPending); safetyReport = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("securityReport")); //$NON-NLS-1$ safetyReport.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); gridLayout.addView(safetyReport); collectively = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("collectiveSignature")); //$NON-NLS-1$ collectively.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); gridLayout.addView(collectively); governmentReport = CommonUtilForm.getCheckBox(context, ServiceMessages.getString("governmentReport")); //$NON-NLS-1$ governmentReport.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); gridLayout.addView(governmentReport); // Repair Type partialRepair = MDRadioButton.createDefaultRadioButton(gridLayout, ServiceMessages.getString("partialRepair")); //$NON-NLS-1$ partialRepair.setTag("PARTIALREPAIR"); //$NON-NLS-1$ partialRepair.setContentDescription("partialRepair"); ((LinearLayout) partialRepair.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 2)); partialRepair.setOnCheckedChangeListener(this); finalRepair = MDRadioButton.createDefaultRadioButton(gridLayout, ServiceMessages.getString("endRepair")); //$NON-NLS-1$ finalRepair.setTag("FINALREPAIR"); //$NON-NLS-1$ finalRepair.setContentDescription("endRepair"); ((LinearLayout) finalRepair.getParent()).setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); finalRepair.setOnCheckedChangeListener(this); interventionLayout = new LinearLayout(context); interventionLayout.setOrientation(LinearLayout.VERTICAL); interventionLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); LinearLayout dayLinearLayout = new LinearLayout(context); dayLinearLayout.setOrientation(LinearLayout.HORIZONTAL); // Next intervention Date // nextInterventionDateValue = new MDCalendar(context); nextInterventionDateValue = MDCalendar.createDefaultCalendar(dayLinearLayout, ServiceMessages.getString("date"), false); //$NON-NLS-1$ // nextInterventionDateValue.setLabel(ServiceMessages.getString("date")); nextInterventionDateValue.setEnabled(false); LinearLayout.LayoutParams daysValueParams = new LinearLayout.LayoutParams(0, 0); // daysValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; daysValueParams.width = 0; daysValueParams.height = LayoutParams.WRAP_CONTENT; daysValueParams.weight = 0.5f; daysValueParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 4); ((LinearLayout) nextInterventionDateValue.getParent()).setLayoutParams(daysValueParams); nextInterventionDateValue.setFocusableInTouchMode(false); nextInterventionDateValue.setSimpleDateFormat(new SimpleDateFormat(DateTimeUtil.DATE_FORMAT, new Locale("de", "CH"))); // nextInterventionDateValue.setOnDateSelected(new onDateSelected() { // // @Override // public void onDateSelected(Date date) { // nextInterventionDateValue.clearError(); // List dateTypeValueList = new ArrayList(); // String dateString = DateTimeUtil.showDate(date); // dateTypeValueList.add(new CustomSpinnerItem(dateString, dateString)); // nextInterventionDateValue.setContents(dateTypeValueList); // } // }); // Next intervention Time nextInterventionTimeText = TimeEditText.createDefaultEditText(dayLinearLayout,ServiceMessages.getString("time"), false); // nextInterventionTimeText.setTag("VON"); //$NON-NLS-1$ nextInterventionTimeText.setEnabled(false); LinearLayout.LayoutParams nextInterventionTimeLayoutParams = new LinearLayout.LayoutParams(0, 0); nextInterventionTimeLayoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; nextInterventionTimeLayoutParams.width = 0; nextInterventionTimeLayoutParams.height = LayoutParams.WRAP_CONTENT; nextInterventionTimeLayoutParams.weight = 0.5f; nextInterventionTimeText.getParentTextInputLayout().setLayoutParams(nextInterventionTimeLayoutParams); nextInterventionTimeText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && nextInterventionTimeText.getText().toString().equalsIgnoreCase("00:00")) { nextInterventionTimeText.getText().clear(); nextInterventionTimeText.append(""); } if (!hasFocus && nextInterventionTimeText.getText().toString().isEmpty()) { nextInterventionTimeText.setText("00:00"); } } }); interventionLayout.addView(dayLinearLayout); installationStateValue = MDSpinner.createDefaultSpinner(interventionLayout, ServiceMessages.getString("installationState"), true); installationStateValue.setContentDescription(ServiceMessages.getString("installationState")); installationStateValue.setEnabled(false); installationStateValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { installationStateValue.clearError(); } }); interventioValue = MDSpinner.createDefaultSpinner(interventionLayout, ServiceMessages.getString("interventionType"), true); interventioValue.setContentDescription(ServiceMessages.getString("interventionType")); interventioValue.setEnabled(false); interventioValue.setOnItemSelectedListener(this); interventioValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { interventioValue.clearError(); } }); gridLayout.addView(interventionLayout); // Progress progressGridLayout = new GridLayout(context); progressGridLayout.setLayoutParams(gridLayoutParams); progressGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); progressValue = MDSpinner.createDefaultSpinner(progressGridLayout, ServiceMessages.getString("progress"), false); //$NON-NLS-1$ progressValue.setTag("PROGRESS"); //$NON-NLS-1$ progressValue.setOnItemSelectedListener(this); gridLayout.addView(progressGridLayout); // Billing billingValue = MDSpinner.createDefaultSpinner(gridLayout, Messages.getString("billing"), true); //$NON-NLS-1$ billingValue.setTag("BILLING"); //$NON-NLS-1$ ((LinearLayout) billingValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); billingValue.setOnItemSelectedListener(this); // Customer Support sendReportToValue = MDSpinner.createDefaultSpinner(gridLayout, ServiceMessages.getString("sendReportTo"), false); //$NON-NLS-1$ sendReportToValue.setTag("CUSTOMERSUPPORT"); //$NON-NLS-1$ ((LinearLayout) sendReportToValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); sendReportToValue.setOnItemSelectedListener(this); LinearLayout customerSupportLayout = new LinearLayout(context); customerSupportLayout.setOrientation(LinearLayout.HORIZONTAL); GridLayout.LayoutParams customerSupportLayoutParams = getGridLayoutParams(getNewRowIndex(), 0, 3); customerSupportLayoutParams.bottomMargin = 10; customerSupportLayout.setLayoutParams(customerSupportLayoutParams); gridLayout.addView(customerSupportLayout); // Address addressValue = MDSpinner.createDefaultSpinner(customerSupportLayout, null, false); addressValue.setTag("ADDRESS"); //$NON-NLS-1$ LinearLayout.LayoutParams addressValueParams = new LinearLayout.LayoutParams(0, 0); addressValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; addressValueParams.width = 0; addressValueParams.height = LayoutParams.WRAP_CONTENT; addressValueParams.weight = 0.5f; addressValueParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 4); addressValue.setOnItemSelectedListener(this); ((LinearLayout) addressValue.getParent()).setLayoutParams(addressValueParams); // Customer support edit text customerSupportEditText = MDEditText.createDefaultEditText(customerSupportLayout, "", InputType.TYPE_TEXT_VARIATION_PERSON_NAME, false); //$NON-NLS-1$ LinearLayout.LayoutParams textInputLayoutParams = new LinearLayout.LayoutParams(0, 0); textInputLayoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; textInputLayoutParams.width = 0; textInputLayoutParams.height = LayoutParams.WRAP_CONTENT; textInputLayoutParams.weight = 0.5f; customerSupportEditText.getParentTextInputLayout().setLayoutParams(textInputLayoutParams); // customerSupportEditText.setOnFocusChangeListener(new OnFocusChangeListener() { // // @Override // public void onFocusChange(View v, boolean hasFocus) { // if ("02".equalsIgnoreCase(sendReportToValue.getSelectedId()) && !hasFocus && !isEmailValid()) { // customerSupportEditText.setSelected(true); // app.showWarningMessageBox(CommonConstants.Regex.EMAIL_VALIDATION_MSG); // } // } // // // }); // Check list checklistGridLayout = new GridLayout(context); checklistGridLayout.setLayoutParams(gridLayoutParams); checklistGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); checklistValue = MDSpinner.createDefaultSpinner(checklistGridLayout, Messages.getString("checkList"), false); //$NON-NLS-1$ checklistValue.setTag("CHECKLIST"); //$NON-NLS-1$ checklistValue.setOnItemSelectedListener(this); gridLayout.addView(checklistGridLayout); // Incident A incidentAGridLayout = new GridLayout(context); incidentAGridLayout.setLayoutParams(gridLayoutParams); incidentAGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); incidentAValue = MDSpinner.createDefaultSpinner(incidentAGridLayout, ServiceMessages.getString("incidentA"), false); //$NON-NLS-1$ incidentAValue.setOnItemSelectedListener(this); gridLayout.addView(incidentAGridLayout); // Incident B incidentBGridLayout = new GridLayout(context); incidentBGridLayout.setLayoutParams(gridLayoutParams); incidentBGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); incidentBValue = MDSpinner.createDefaultSpinner(incidentBGridLayout, ServiceMessages.getString("incidentB"), false); //$NON-NLS-1$ incidentBValue.setOnItemSelectedListener(this); gridLayout.addView(incidentBGridLayout); // System Error systemErrorGridLayout = new GridLayout(context); systemErrorGridLayout.setLayoutParams(gridLayoutParams); systemErrorGridLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); systemError = MDEditText.createDefaultEditText(systemErrorGridLayout, Messages.getString("installationError"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ systemError.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); gridLayout.addView(systemErrorGridLayout); // service serviceText = CommonUtilForm.getTextView(context, "Service"); //$NON-NLS-1$ serviceText.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); gridLayout.addView(serviceText); // Service Performed servicePerformedLayout = new LinearLayout(context); LinearLayout.LayoutParams linearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); servicePerformedLayout.setLayoutParams(linearLayoutParams); servicePerformedLayout.setOrientation(LinearLayout.VERTICAL); servicePerformedText = CommonUtilForm.getTextView(context, ServiceMessages.getString("servicePerformed")); //$NON-NLS-1$ servicePerformedText.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); servicePerformedText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); servicePerformedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); servicePerformedText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams textLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); textLayoutParams.setMargins(0, LayoutUtils.convertDpToPixel(context, 4), 0, 0); servicePerformedText.setLayoutParams(textLayoutParams); servicePerformedLayout.addView(servicePerformedText); servicePerformedLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 0, 1)); gridLayout.addView(servicePerformedLayout); // Month servicePerformedMonthGridLayout = new GridLayout(context); servicePerformedMonthGridLayout.setLayoutParams(gridLayoutParams); servicePerformedMonthGridLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); servicePerformedMonthValue = MDSpinner.createDefaultSpinner(servicePerformedMonthGridLayout, null, false); servicePerformedMonthValue.setTag("COMPLETEMONTH"); //$NON-NLS-1$ servicePerformedMonthValue.setOnItemSelectedListener(this); servicePerformedMonthValue.setEnabled(false); servicePerformedMonthValue.setRequired(false); gridLayout.addView(servicePerformedMonthGridLayout); // Year servicePerformedYearGridLayout = new GridLayout(context); servicePerformedYearGridLayout.setLayoutParams(gridLayoutParams); servicePerformedYearGridLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); servicePerformedYearValue = MDSpinner.createDefaultSpinner(servicePerformedYearGridLayout, null, false); servicePerformedYearValue.setTag("COMPLETEYEAR"); //$NON-NLS-1$ servicePerformedYearValue.setOnItemSelectedListener(this); servicePerformedYearValue.setEnabled(false); servicePerformedYearValue.setRequired(false); gridLayout.addView(servicePerformedYearGridLayout); // Service Refused serviceRefusedText = CommonUtilForm.getTextView(context, ServiceMessages.getString("serviceRefused")); //$NON-NLS-1$ serviceRefusedText.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); serviceRefusedText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); serviceRefusedText.setEnabled(false); gridLayout.addView(serviceRefusedText); serviceRefusedGridLayout = new GridLayout(context); serviceRefusedGridLayout.setLayoutParams(gridLayoutParams); serviceRefusedGridLayout.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 2)); serviceRefusedValue = MDSpinner.createDefaultSpinner(serviceRefusedGridLayout, "", false); serviceRefusedValue.setTag("SERVICEREFUSED"); //$NON-NLS-1$ serviceRefusedValue.setOnItemSelectedListener(this); serviceRefusedValue.setEnabled(false); gridLayout.addView(serviceRefusedGridLayout); january = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ january.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); january.setId(1); january.setTag("JANUARY"); //$NON-NLS-1$ january.setOnCheckedChangeListener(this); gridLayout.addView(january); may = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ may.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); may.setId(5); may.setTag("MAY"); //$NON-NLS-1$ may.setOnCheckedChangeListener(this); gridLayout.addView(may); september = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ september.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); september.setId(9); september.setTag("SEPTEMBER"); //$NON-NLS-1$ september.setOnCheckedChangeListener(this); gridLayout.addView(september); february = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ february.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); february.setId(2); february.setTag("FEBRUARY"); //$NON-NLS-1$ february.setOnCheckedChangeListener(this); gridLayout.addView(february); june = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ june.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); june.setId(6); june.setTag("JUNE"); //$NON-NLS-1$ june.setOnCheckedChangeListener(this); gridLayout.addView(june); october = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ october.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); october.setId(10); october.setTag("OCTOBER"); //$NON-NLS-1$ october.setOnCheckedChangeListener(this); gridLayout.addView(october); march = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ march.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); march.setId(3); march.setTag("MARCH"); //$NON-NLS-1$ march.setOnCheckedChangeListener(this); gridLayout.addView(march); july = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ july.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); july.setId(7); july.setTag("JULY"); //$NON-NLS-1$ july.setOnCheckedChangeListener(this); gridLayout.addView(july); november = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ november.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); november.setId(11); november.setTag("NOVEMBER"); //$NON-NLS-1$ november.setOnCheckedChangeListener(this); gridLayout.addView(november); april = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ april.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 1)); april.setId(4); april.setTag("APRIL"); //$NON-NLS-1$ april.setOnCheckedChangeListener(this); gridLayout.addView(april); august = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ august.setLayoutParams(getGridLayoutParams(getRowIndex(), 1, 1)); august.setId(8); august.setTag("AUGUST"); //$NON-NLS-1$ august.setOnCheckedChangeListener(this); gridLayout.addView(august); december = CommonUtilForm.getCheckBox(context, ""); //$NON-NLS-1$ december.setLayoutParams(getGridLayoutParams(getRowIndex(), 2, 1)); december.setId(12); december.setTag("DECEMBER"); //$NON-NLS-1$ december.setOnCheckedChangeListener(this); gridLayout.addView(december); // Button LinearLayout monthButtonLinearLayout = new LinearLayout(context); monthButtonLinearLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); monthButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); gradientDrawable.setCornerRadius(7); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); monthButton = new AppCompatButton(context); LinearLayout.LayoutParams monthButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); monthButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; monthButton.setLayoutParams(monthButtonParams); monthButton.setText(ServiceMessages.getString("change")); //$NON-NLS-1$ monthButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { if (january.isEnabled()) { setEnableMonthCheckBoxes(false); } else { setEnableMonthCheckBoxes(true); } } }); monthButton.setBackgroundDrawable(gradientDrawable); monthButtonLinearLayout.addView(monthButton); gridLayout.addView(monthButtonLinearLayout); // Distance distance = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("distance"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ distance.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FOUR)}); distance.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); // Expenses expenses = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("expenses"), InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ expenses.setDirectionRight(true); expenses.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.SIX)}); expenses.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); expenses.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { expenses.setText(getExpense()); } } }); cycleOfInstallation = MDEditText.createDefaultEditText(gridLayout, ServiceMessages.getString("cycleOfInstallation"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ cycleOfInstallation.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.EIGHT)}); cycleOfInstallation.getParentTextInputLayout().setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); // error errorValue = MDSpinner.createDefaultSpinner(gridLayout, ServiceMessages.getString("errorMessages"), false); //$NON-NLS-1$ ((LinearLayout) errorValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); errorEditText1 = CommonUtilForm.getEditText(context, "H", InputType.TYPE_CLASS_NUMBER); //$NON-NLS-1$ errorEditText1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorEditText1Params = getGridLayoutParams(getNewRowIndex(), 0, 1); errorEditText1.setLayoutParams(errorEditText1Params); gridLayout.addView(errorEditText1); EditText errorEditText2 = CommonUtilForm.getEditText(context, "E", InputType.TYPE_CLASS_TEXT); //$NON-NLS-1$ errorEditText2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorEditText2Params = getGridLayoutParams(getRowIndex(), 1, 1); errorEditText2.setLayoutParams(errorEditText2Params); gridLayout.addView(errorEditText2); errorCheckbox = CommonUtilForm.getCheckBox(context, "FM"); //$NON-NLS-1$ GridLayout.LayoutParams errorCheckboxParams = getGridLayoutParams(getRowIndex(), 2, 1); errorCheckboxParams.setGravity(Gravity.BOTTOM); errorCheckbox.setLayoutParams(errorCheckboxParams); gridLayout.addView(errorCheckbox); error2Value = MDSpinner.createDefaultSpinner(gridLayout, null, false); ((LinearLayout) error2Value.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); error2EditText1 = CommonUtilForm.getEditText(context, "H", InputType.TYPE_CLASS_NUMBER); //$NON-NLS-1$ error2EditText1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams error2EditText1Params = getGridLayoutParams(getNewRowIndex(), 0, 1); error2EditText1.setLayoutParams(error2EditText1Params); gridLayout.addView(error2EditText1); EditText error2EditText2 = CommonUtilForm.getEditText(context, "E", InputType.TYPE_CLASS_TEXT); //$NON-NLS-1$ error2EditText2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams error2EditText2Params = getGridLayoutParams(getRowIndex(), 1, 1); error2EditText2.setLayoutParams(error2EditText2Params); gridLayout.addView(error2EditText2); error2Checkbox = CommonUtilForm.getCheckBox(context, "FM"); //$NON-NLS-1$ GridLayout.LayoutParams error2CheckboxParams = getGridLayoutParams(getRowIndex(), 2, 1); error2CheckboxParams.setGravity(Gravity.BOTTOM); error2Checkbox.setLayoutParams(error2CheckboxParams); gridLayout.addView(error2Checkbox); errorMontValue = MDSpinner.createDefaultSpinner(gridLayout, null, false); ((LinearLayout) errorMontValue.getParent()).setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); errorMontEditText1 = CommonUtilForm.getEditText(context, "H", InputType.TYPE_CLASS_NUMBER); //$NON-NLS-1$ errorMontEditText1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorMontEditText1Params = getGridLayoutParams(getNewRowIndex(), 0, 1); errorMontEditText1.setLayoutParams(errorMontEditText1Params); gridLayout.addView(errorMontEditText1); EditText errorMontEditText2 = CommonUtilForm.getEditText(context, "E", InputType.TYPE_CLASS_TEXT); //$NON-NLS-1$ errorMontEditText2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.ONE)}); GridLayout.LayoutParams errorMontEditText2Params = getGridLayoutParams(getRowIndex(), 1, 1); errorMontEditText2.setLayoutParams(errorMontEditText2Params); gridLayout.addView(errorMontEditText2); errorMontCheckbox = CommonUtilForm.getCheckBox(context, "FM"); //$NON-NLS-1$ GridLayout.LayoutParams errorMontCheckboxParams = getGridLayoutParams(getRowIndex(), 2, 1); errorMontCheckboxParams.setGravity(Gravity.BOTTOM); errorMontCheckbox.setLayoutParams(errorMontCheckboxParams); gridLayout.addView(errorMontCheckbox); // Button LinearLayout deleteButtonLinearLayout = new LinearLayout(context); deleteButtonLinearLayout.setLayoutParams(getGridLayoutParams(getNewRowIndex(), 0, 3)); deleteButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable deleteButtonGradientDrawable = new GradientDrawable(); deleteButtonGradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); deleteButtonGradientDrawable.setCornerRadius(7); deleteButtonGradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); deleteButton = new AppCompatButton(context); LinearLayout.LayoutParams deleteButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); deleteButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; deleteButton.setLayoutParams(deleteButtonParams); deleteButton.setText(ServiceMessages.getString("deleteCompleteReport")); //$NON-NLS-1$ deleteButton.setOnClickListener(new View.OnClickListener() { private boolean showConfirmDeleteDialog() { return app.showMessageBox(ServiceMessages.getString("DoYouReallyWantToDeleteTheCompleteReport"), ServiceMessages.getString("DeleteReport"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK; } @Override public void onClick(View paramView) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (showConfirmDeleteDialog()) { if (!app.dbutil.deleteCompleteReport(job.getLatestReport())) { log.error("Unable to delete complete report"); return null; } job.loadReports(app.dbutil); boolean restorePartlyDone = ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job); if (new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, "")) { //$NON-NLS-1$ log.info("after updateStatus" + job.getStatus().toString()); //$NON-NLS-1$ } if (restorePartlyDone) { job.setStatus(JobStatus.PARLTY_DONE); GuidGenerator generator = new GuidGenerator(); try { int nextReportIdx = job.getNextReportIdx(app.dbutil); String nextReportGuId = generator.generate(); job.setCurrentReportGuId(nextReportGuId); Report nextReport = new Report(job.getJobNumber(), job.getJobType(), nextReportGuId, nextReportIdx, job.isCycleOfInstallationFlag()); app.dbutil.insertReplaceReport(nextReport); job.loadReports(app.dbutil); app.dbutil.updateJob(job); } catch (UnknownHostException | NoSuchAlgorithmException e) { throw new ApplicationException(e); } } leaveToJobDetailForm(); return null; } return null; } }; } }); deleteButton.setBackgroundDrawable(deleteButtonGradientDrawable); deleteButton.setContentDescription("delete"); deleteButtonLinearLayout.addView(deleteButton); gridLayout.addView(deleteButtonLinearLayout); linearLayout.addView(gridLayout); saveButton.setTitle(ServiceMessages.getString("save")); scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(linearLayout); view.addView(scrollView); return view; } private GridLayout.LayoutParams getGridLayoutParams(int row, int col, int colspan) { GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = 0; params.height = LayoutParams.WRAP_CONTENT; params.columnSpec = GridLayout.spec(col, colspan, 1f); params.rowSpec = GridLayout.spec(row, 1, 1f); return params; } private int getNewRowIndex() { return lastContentRow += 1; } private int getRowIndex() { return lastContentRow; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title this.setFormTitle(ServiceMessages.getString("report")); //$NON-NLS-1$ scrollView.scrollTo(0, 0); commissionNumberLayout.setRequired(true); progressValue.setRequired(false); commissionNumberLayout.setJobTypeAndFormat(this.job.getJobType(), app.dbutil.getUser().getCommunicationNumberFormat()); if (this.job.getJobType().isSAV()) { checklistValue.setRequired(true); } else { checklistValue.setRequired(false); } setShowReportContentByJobType(this.job.getJobType()); openPending.setChecked(false); errorCheckbox.setChecked(false); error2Checkbox.setChecked(false); errorMontCheckbox.setChecked(false); jobNumber.setText(""); //$NON-NLS-1$ customerSupportEditText.setText(""); //$NON-NLS-1$ fillComboStateOfInstallation(); fillComboIntervention(); fillComboTypeOfWork(); fillComboAddress(); fillComboChecklist(); fillComboError(); fillComboCustomerSupport(); fillComboIncident(); fillComboBilling(); fillComboServiceRefused(); fillComboServicePerformedYear(); initCheckboxMonths(); nextInterventionDateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); nextInterventionTimeText.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); installationStateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); interventioValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); setServicePerformedEnabled(); setServiceRefusedEnabled(); nextInterventionDateValue.setContents(new ArrayList()); if (this.job.getJobType().isMON()) { progressValue.setRequired(true); fillComboProgress(); } loadData(); setEnableMonthCheckBoxes(false); return null; } @Override public void onFormReset() { super.onFormReset(); clearAllValue(); } /** * Loads data. */ public void loadData() { Report report = this.job.getCurrentReport(); log.info("report guid " + report.getGuId() + " has times -> " + report.getTimes().size()); log.info("Report status " + report.getReportStatus());// Create new report log.info("Partial Repair " + report.isPartialRepair() + " Final Repair" + report.isFinalRepair()); clearPartialRepairAndFinalRepair(); if (report.getReportStatus().isInitial() || (report.getReportStatus().isReceived())) { setCheckboxes(this.job.getServicePlanMonth1()); setCheckboxes(this.job.getServicePlanMonth2()); setCheckboxes(this.job.getServicePlanMonth3()); setCheckboxes(this.job.getServicePlanMonth4()); setCheckboxes(this.job.getServicePlanMonth5()); setCheckboxes(this.job.getServicePlanMonth6()); sortCheckBoxesAscList(monthCheckBoxesList); fillComboServicePerformedMonth(monthCheckBoxesList); log.info("OrderNumber " + this.job.getOrderNumber()); log.info("JobNumber " + this.job.getJobNumber()); jobNumber.setText(this.job.getOrderNumber()); if (this.job.getCommissionNumber().length() > 0) { commissionNumberLayout.setText(this.job.getCommissionNumber()); } if (this.job.getJobType().isSAV()) { workTypeValue.setSelectionById(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT); } } else { // load existing report String komnr = ""; //$NON-NLS-1$ if (report.getCommissionNumber().length() > 0) { komnr = report.getCommissionNumber(); } if (StringUtil.isEmpty(komnr) && this.job.getCommissionNumber().length() > 0) { komnr = this.job.getCommissionNumber(); } if (StringUtil.isNotEmpty(komnr)) { commissionNumberLayout.setText(komnr); } loadReport(report); } if (job.getCurrentReport().getReportStatus().isReceived()) { deleteButton.setEnabled(false); } else { deleteButton.setEnabled(true); } log.info("serviceRefusedValue " + serviceRefusedValue + " isServiceRefusedFlag " + job.isServiceRefusedFlag()); setComNo(report); cycleOfInstallation.setRequired(job.isCycleOfInstallationFlag()); log.info("JobType REP " + job.getJobType().isREP() + " isServiceRefusedFlag " + job.isServiceRefusedFlag()); } private void setComNo(Report report) { if(commissionType == null) { commissionType = job.getReportCommissionNumberType(); } if(CommonConstants.CommissionNumber.Type.CORRECT == commissionType) { commissionNumberLayout.setEnabled(false); commissionNumberLayout.setRequired(false); } else if(CommonConstants.CommissionNumber.Type.UNKNOWN == commissionType) { commissionNumberLayout.setEnabled(false); commissionNumberLayout.setText(""); //$NON-NLS-1$ commissionNumberLayout.setRequired(false); } else { // invalid commissionNumberLayout.setEnabled(true); commissionNumberLayout.setRequired(true); if(!report.getCommissionNumber().isEmpty()) { commissionNumberLayout.setText(report.getCommissionNumber()); } } } private void setShowReportContentByJobType(JobType jobType) { int visibility = View.VISIBLE; boolean required = true; if(jobType.isMON()) { visibility = View.GONE; required = false; } openPending.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); governmentReport.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); progressGridLayout.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); progressValue.setVisibility(jobType.isMON()? View.VISIBLE:View.GONE); interventionLayout.setVisibility(!jobType.isMON()? View.VISIBLE:View.GONE); reasoning.setVisibility(visibility); partialRepair.setVisibility(visibility); finalRepair.setVisibility(visibility); workTypeGridLayout.setVisibility(visibility); workTypeValue.setRequired(required); checklistGridLayout.setVisibility(visibility); checklistValue.setVisibility(visibility); checklistValue.setRequired(required); incidentAGridLayout.setVisibility(visibility); incidentAValue.setVisibility(visibility); incidentBGridLayout.setVisibility(visibility); incidentBValue.setVisibility(visibility); systemErrorGridLayout.setVisibility(visibility); systemError.setVisibility(visibility); serviceText.setVisibility(visibility); servicePerformedLayout.setVisibility(visibility); servicePerformedText.setVisibility(visibility); servicePerformedMonthGridLayout.setVisibility(visibility); servicePerformedMonthValue.setVisibility(visibility); servicePerformedYearGridLayout.setVisibility(visibility); servicePerformedYearValue.setVisibility(visibility); january.setVisibility(visibility); february.setVisibility(visibility); march.setVisibility(visibility); april.setVisibility(visibility); may.setVisibility(visibility); june.setVisibility(visibility); july.setVisibility(visibility); august.setVisibility(visibility); september.setVisibility(visibility); october.setVisibility(visibility); november.setVisibility(visibility); december.setVisibility(visibility); monthButton.setVisibility(visibility); distance.setVisibility(visibility); expenses.setVisibility(visibility); cycleOfInstallation.setVisibility(visibility); int serviceRefusedVisibility = View.GONE; if (job.getJobType().isREP()) { serviceRefusedVisibility = View.VISIBLE; } serviceRefusedGridLayout.setVisibility(serviceRefusedVisibility); serviceRefusedText.setVisibility(serviceRefusedVisibility); serviceRefusedValue.setVisibility(serviceRefusedVisibility); } private boolean isEmailValid() { if (!customerSupportEditText.getText().toString().trim().isEmpty()) { Pattern pattern = Pattern.compile(CommonConstants.Regex.EMAIL_VALIDATOR); Matcher matcher = pattern.matcher(customerSupportEditText.getText().toString()); if(!matcher.matches()) { customerSupportEditText.setError(CommonConstants.Regex.EMAIL_VALIDATION_MSG); return false; } } return true; } @Override protected boolean isValid() { boolean result = super.isValid(); View focusView = null; String errorMessage = Messages.getString("pleaseProvideValue"); log.info("commissionType " + commissionType); log.info("commissionNumber.isRequired() " + commissionNumberLayout.isRequired()); if (commissionType == CommonConstants.CommissionNumber.Type.INVALID && commissionNumberLayout.isRequired()) { //$NON-NLS-1$ if("".equals(commissionNumberLayout.getCommissionNumber().trim()) || "0".equals(commissionNumberLayout.getCommissionNumber().trim())) { commissionNumberLayout.setError(errorMessage); //$NON-NLS-1$ result = false; focusView = commissionNumberLayout.getCommissionNumberText(); } else if(!commissionNumberLayout.getCommissionNumberText().isValid()) { commissionNumberLayout.setError(commissionNumberLayout.getErrorMessage()); //$NON-NLS-1$ result = false; focusView = commissionNumberLayout.getCommissionNumberText(); } log.info("commissionNumber " + result); } if (workTypeValue.isRequired() && workTypeValue.getSelectedItemPosition() == 0) { workTypeValue.setError(errorMessage); //$NON-NLS-1$ // berprfung abbrechen, sonst NPE beim prfen der SAV monate! result = false; log.info("workTypeValue " + result); if (focusView == null) focusView = workTypeValue; } if (!job.getJobType().isMON()) { if ( !partialRepair.isChecked() && !finalRepair.isChecked()) { finalRepair.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("partialRepair " + result); if (focusView == null) focusView = finalRepair; } } if (progressValue.isRequired() && progressValue.getSelectedItemPosition() == 0) { progressValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("progressValue " + result); if (focusView == null) focusView = progressValue; } // Arbeitsart 05: Vertragsservice // Checkliste 00: Bitte whlen.. (Initialwert) // SAV ausgefhrt (Monat) 00: --- (Initialwert) if (CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT.equalsIgnoreCase(workTypeValue.getSelectedId()) && servicePerformedMonthValue.getSelectedItemPosition() == 0) { //$NON-NLS-1$ checklistValue.setRequired(true); servicePerformedMonthValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("workTypeValue " + result); if (focusView == null) focusView = servicePerformedMonthValue; } if (checklistValue.isRequired() && checklistValue.getSelectedItemPosition() == 0) { checklistValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("checklistValue " + result); if (focusView == null) focusView = checklistValue; } log.info("servicePerformedYearValue " + servicePerformedYearValue.getSelectedItemPosition()); if (servicePerformedYearValue.isEnabled() && (servicePerformedText.getText().toString().contains("*")) && servicePerformedYearValue.getSelectedItemPosition() == 0) { servicePerformedYearValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("servicePerformedYearValue " + result); if (focusView == null) focusView = servicePerformedYearValue; } if (servicePerformedMonthValue.isEnabled() && (servicePerformedText.getText().toString().contains("*")) && (servicePerformedMonthValue.getSelectedItemPosition() == 0 && serviceRefusedValue.getSelectedItemPosition() == 0)) { servicePerformedMonthValue.setError(errorMessage); result = false; log.info("servicePerformedMonthValue " + result); if (focusView == null) focusView = servicePerformedMonthValue; } if (serviceRefusedValue.isEnabled() && (serviceRefusedText.getText().toString().contains("*")) && serviceRefusedValue.getSelectedItemPosition() == 0){ serviceRefusedValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("serviceRefusedValue " + result); if (focusView == null) focusView = serviceRefusedValue; } if (customerSupportEditText.isEnabled()) { if (customerSupportEditText.getText().toString().trim().isEmpty()) { result = false; customerSupportEditText.setError(errorMessage); } if (!customerSupportEditText.getText().toString().trim().isEmpty() && (CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL.equalsIgnoreCase(sendReportToValue.getSelectedId()))) { //$NON-NLS-1$ result = isEmailValid(); log.info("email " + result); } } log.info("cycleOfInstallation " + cycleOfInstallation.isRequired() + " " + cycleOfInstallation.getText().toString()); if (cycleOfInstallation.isRequired() && cycleOfInstallation.getText().toString().isEmpty()) { cycleOfInstallation.setError(errorMessage); result = false; log.info("cycleOfInstallation " + result); if (focusView == null) focusView = cycleOfInstallation; } if (nextInterventionDateValue.isEnabled() && nextInterventionDateValue.isRequired() && nextInterventionDateValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { nextInterventionDateValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("nextInterventionDateValue " + result); if (focusView == null) focusView = nextInterventionDateValue; } if (nextInterventionTimeText.isEnabled() && !nextInterventionTimeText.isValid() && !nextInterventionTimeText.getText().toString().isEmpty()) { nextInterventionTimeText.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("nextInterventionTimeText " + result); if (focusView == null) focusView = nextInterventionTimeText; } if (installationStateValue.isEnabled() && installationStateValue.isRequired() && installationStateValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { installationStateValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("installationStateValue " + result); if (focusView == null) focusView = installationStateValue; } if (interventioValue.isEnabled() && interventioValue.isRequired() && interventioValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { interventioValue.setError(errorMessage); //$NON-NLS-1$ result = false; log.info("interventioValue " + result); if (focusView == null) focusView = interventioValue; } if (!result && focusView != null) { scrollView.scrollTo(0, (int) focusView.getY()); focusView.requestFocus(); } return result; } @Override protected boolean onSave() { Report report = this.job.getLatestReport(); boolean isNomaterial = report.isNoMaterial(); report.setNoMaterial(isNomaterial); // assign value to object and insert new report assignToReport(report); if(report.isValid()) { // The dialog is therefore displayed in the following cases: // ZKDMOB.KNZGARANT = true // ZKDMOBREP.ARBA = 01 or 02 // ZKDMOBREP.VERRC = 00 if ( job.isGuarantee() && (workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_REPAIR) || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_ON_CALL)) && billingValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { // show guarantee dialog app.injectAndLeaveToForm(ReportGuaranteeForm.class, new FormArguments(job, null)); } else { app.dbutil.insertReplaceReport(report); log.info("Report saved." + report.getGuId()); leaveToJobDetailForm(); } return true; } return false; } private void assignToReport(Report rep) { rep.setReportStatus(ReportStatus.NEW); rep.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); rep.setOrderNumber(jobNumber.getText().toString()); if (commissionType == CommonConstants.CommissionNumber.Type.UNKNOWN) { rep.setCommissionNumber(CommonConstants.CommissionNumber.DEFAULT); // dummy value } else { rep.setCommissionNumber(commissionNumberLayout.getCommissionNumber()); } if (job.isMoreInformationsFlag() && !job.getJobType().isMON()) { log.info("nextInterventionDateValue " + nextInterventionDateValue.getSelectedId()); if (nextInterventionDateValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { rep.setNextInterventionDate(new Date(0)); } else { String time = nextInterventionTimeText.getText().toString(); Date nextInterventionDate = DateTimeUtil.parseDateFromHHmm(time.isEmpty() ? "00:00" : time, DateTimeUtil.parseDateFromddMMyyyy(nextInterventionDateValue.getSelectedName())); log.info("nextInterventionDate " + DateTimeUtil.showDateTime(nextInterventionDate)); rep.setNextInterventionDate(nextInterventionDate); } if (installationStateValue.getSelectedItemPosition() != 0) { rep.setStateOfInstallation(installationStateValue.getSelectedId()); } if (interventioValue.getSelectedItemPosition() != 0) { rep.setNextInterventionCode(interventioValue.getSelectedId()); } } if (workTypeValue.getSelectedItemPosition() != 0) { rep.setWorkType(workTypeValue.getSelectedId()); rep.setTimesWorkType(workTypeValue.getSelectedId(), app.dbutil); } rep.setSafetyReport(safetyReport.isChecked()); rep.setCollectively(collectively.isChecked()); if (job.getJobType().isMON()) { rep.setOpenPending(openPending.isChecked()); rep.setGovernmentReport(governmentReport.isChecked()); rep.setMonStk(progressValue.getSelectedId()); log.info("set progress " + rep.getMonStk()); } else { rep.setReasoning(reasoning.isChecked()); rep.setPartialRepair(partialRepair.isChecked()); rep.setFinalRepair(finalRepair.isChecked()); if (checklistValue.getSelectedItemPosition() != 0) { rep.setChecklist(checklistValue.getSelectedName()); } else { rep.setChecklist(""); //$NON-NLS-1$ } log.info("checklist " + rep.getChecklist()); setIncident(rep); rep.setSystemError(systemError.getText().toString()); serServicePlan(rep); if (serviceRefusedValue.getSelectedItemPosition() != 0) { rep.setServiceRefused(serviceRefusedValue.getSelectedId()); } else { rep.setServiceRefused(""); } rep.setDistance(distance.getText().toString()); rep.setExpenses(getExpense()); rep.setCycleOfInstallation(cycleOfInstallation.getText().toString()); } rep.setBilling(billingValue.getSelectedId()); log.info("CustomerSupport " + rep.getCustomerSupport() + " text " + rep.getCustomerSupportText()); log.info("Billing " + rep.getBilling()); if (sendReportToValue.getSelectedItemPosition() != 0) { rep.setCustomerSupport(sendReportToValue.getSelectedId()); rep.setCustomerSupportText(customerSupportEditText.getText().toString()); } else { rep.setCustomerSupport(""); //$NON-NLS-1$ rep.setCustomerSupportText(""); //$NON-NLS-1$ } if (errorValue.getSelectedItemPosition() != 0) { rep.setErrorId1(errorValue.getSelectedId()); } rep.setErrorH1(errorEditText1.getText().toString()); rep.setErrorFlag1(errorCheckbox.isChecked()); if (error2Value.getSelectedItemPosition() != 0) { rep.setErrorId2(error2Value.getSelectedId()); } rep.setErrorH2(error2EditText1.getText().toString()); rep.setErrorFlag2(error2Checkbox.isChecked()); if (errorMontValue.getSelectedItemPosition() != 0) { rep.setErrorId3(errorMontValue.getSelectedId()); } rep.setErrorH3(errorMontEditText1.getText().toString()); rep.setErrorFlag3(errorMontCheckbox.isChecked()); } private void setIncident(Report rep) { String incidentA = StringUtil.removeAllLeadingZero(incidentAValue.getSelectedId()); String incidentB = StringUtil.removeAllLeadingZero(incidentBValue.getSelectedId()); if (incidentAValue.getSelectedItemPosition() == 0) { //$NON-NLS-1$ incidentA = ""; //$NON-NLS-1$ } if (incidentBValue.getSelectedItemPosition() == 0) { //$NON-NLS-1$ incidentB = ""; //$NON-NLS-1$ } rep.setIncidentAB(incidentA + incidentB); log.info("IncidentAB " + rep.getIncidentAB()); } private void serServicePlan(Report rep) { String saverl = servicePerformedMonthValue.getSelectedId(); saverl = saverl.concat(servicePerformedYearValue.getSelectedId().substring(2, 4)); rep.setMonthYear(saverl); rep.setServicePlanMonth1(""); //$NON-NLS-1$ rep.setServicePlanMonth2(""); //$NON-NLS-1$ rep.setServicePlanMonth3(""); //$NON-NLS-1$ rep.setServicePlanMonth4(""); //$NON-NLS-1$ rep.setServicePlanMonth5(""); //$NON-NLS-1$ rep.setServicePlanMonth6(""); //$NON-NLS-1$ if (monthCheckBoxesList != null) { sortCheckBoxesAscList(monthCheckBoxesList); for (int i = 0; i < monthCheckBoxesList.size(); i++) { switch (i) { case 0: rep.setServicePlanMonth1((String) monthCheckBoxesList.get(0).get("KEY")); //$NON-NLS-1$ break; case 1: rep.setServicePlanMonth2((String) monthCheckBoxesList.get(1).get("KEY")); //$NON-NLS-1$ break; case 2: rep.setServicePlanMonth3((String) monthCheckBoxesList.get(2).get("KEY")); //$NON-NLS-1$ break; case 3: rep.setServicePlanMonth4((String) monthCheckBoxesList.get(3).get("KEY")); //$NON-NLS-1$ break; case 4: rep.setServicePlanMonth5((String) monthCheckBoxesList.get(4).get("KEY")); //$NON-NLS-1$ break; case 5: rep.setServicePlanMonth6((String) monthCheckBoxesList.get(5).get("KEY")); //$NON-NLS-1$ break; default: break; } } monthCheckBoxesList.clear(); } } private void leaveToJobDetailForm() { app.injectAndLeaveToForm(JobDetailForm.class, new JobDetailForm.JobDetailFormArgument(job, 2)); } public void onCancel() { monthCheckBoxesList.clear(); } private void fillComboTypeOfWork() { List typeOfWorkValueList = new ArrayList(); List workTypeList = app.dbutil.selectWorkTypeListByJobType(job.getJobType()); for (WorkType workType : workTypeList) { log.info("WorkType " + workType.getWorkTypeCode() + " text " + workType.getText() + " Guarantee " + workType.isGuarantee()); typeOfWorkValueList.add(new CustomSpinnerItem((String) workType.getWorkTypeCode(), (String) workType.getText())); } workTypeValue.setContents(typeOfWorkValueList); } private void fillComboProgress() { List billingValueList = new ArrayList(); List progresses = app.dbutil.selectProgress(); for (Progress progress : progresses) { log.info("Progress " + progress.getProgressCode() + " text " + progress.getText() + " Spras " + progress.getSpras()); billingValueList.add(new CustomSpinnerItem( progress.getProgressCode(), progress.getText())); } progressValue.setContents(billingValueList); } private void fillComboBilling() { List billingValueList = new ArrayList(); List invoiceList = app.dbutil.selectInvoiceList(); for (Invoice invoice : invoiceList) { billingValueList.add(new CustomSpinnerItem( invoice.getCode(), invoice.getText())); } billingValue.setContents(billingValueList); /** * Sets the "Standard" as default select. * see "[MIG-122] Create / edit report: The default of billing have to be "Standard"" */ billingValue.setSelection(0); } private void fillComboCustomerSupport() { List customerSupportValueList = new ArrayList(); Iterator> itr = app.enumUtil.reportSendTypeEnum.iterator(); while (itr.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = itr.next(); customerSupportValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } sendReportToValue.setContents(customerSupportValueList); } private void fillComboAddress() { List addressValueList = new ArrayList(); emailMap.clear(); addressValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, Messages.getString("pleaseSelect"))); //$NON-NLS-1$ //$NON-NLS-2$ Map addressesMap = this.job.getAddresses(); // addressValueList.add(new CustomSpinnerItem(this.job.getPartnerOfInstallAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.PARTNER_OF_INSTALLATION_ADDRESS))); retrieveAddressFromList(job.getPartnerOfInstallAddressId()).getEmail(); if (addressesMap.containsKey(this.job.getPartnerOfInstallAddressId())) { emailMap.put(this.job.getPartnerOfInstallAddressId(), retrieveAddressFromList(job.getPartnerOfInstallAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getPartnerOfInstallAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.PARTNER_OF_INSTALLATION_ADDRESS))); } if (addressesMap.containsKey(this.job.getKdnServiceAddressId())) { emailMap.put(this.job.getKdnServiceAddressId(), retrieveAddressFromList(job.getKdnServiceAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getKdnServiceAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.KDN_SERVICE_ADDRESS))); } if (addressesMap.containsKey(this.job.getCustomerAddressId())) { emailMap.put(this.job.getCustomerAddressId(), retrieveAddressFromList(job.getCustomerAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getCustomerAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.CUSTOMER_ADDRESS))); } if (addressesMap.containsKey(this.job.getPartnerAddressId())) { emailMap.put(this.job.getPartnerAddressId(), retrieveAddressFromList(job.getPartnerAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getPartnerAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.PARTNET_ADDRESS))); } if (addressesMap.containsKey(this.job.getObjectAddressId())) { emailMap.put(this.job.getObjectAddressId(), retrieveAddressFromList(job.getObjectAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getObjectAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.OBJECT_ADDRESS))); } if (addressesMap.containsKey(this.job.getOwnerAddressId())) { emailMap.put(this.job.getOwnerAddressId(), retrieveAddressFromList(job.getOwnerAddressId()).getEmail()); addressValueList.add(new CustomSpinnerItem(this.job.getOwnerAddressId(), app.enumUtil.addressTypeEnum.get(CommonConstants.Address.OWNER_ADDRESS))); } NumberFormat formatter = new DecimalFormat(CommonConstants.PLEASE_SELECT); if (CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL.equalsIgnoreCase(sendReportToValue.getSelectedId())) { List emails = app.dbutil.selectEmailListByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); for (int i = 0; i < emails.size(); i++) { emails.get(i); String key = formatter.format(emailMap.size() + i + 1); addressValueList.add(new CustomSpinnerItem(key, ServiceMessages.getString("email") + " " + (i+2))); emailMap.put(key, emails.get(i).getEmail()); } } addressValue.setContents(addressValueList); } private void fillComboChecklist() { List checklistValueList = new ArrayList(); List checklists = app.dbutil.selectCheckList(); if (checklists != null) { for (int i = 0; i < checklists.size(); i++) { Checklist checklist = checklists.get(i); checklistValueList.add(new CustomSpinnerItem((String) checklist.getChecklistCode(), (String) checklist.getText())); } checklistValue.setContents(checklistValueList); } } private void fillComboIncident() { List incidentAValueList = new ArrayList(); List incidentBValueList = new ArrayList(); incidentAValueList.add(new CustomSpinnerItem("X", "Bitte w\u00E4hlen...")); incidentBValueList.add(new CustomSpinnerItem("X", "Bitte w\u00E4hlen...")); List incidentList = app.dbutil.selectIncidentList(); if (incidentList != null) { for (int i = 0; i < incidentList.size(); i++) { Incident incident = incidentList.get(i); log.info("Incident " + incident.getErrorCode() + " Fct " + incident.getFct() + " text " + incident.getText()); if ("A".equalsIgnoreCase(incident.getFct())) { //$NON-NLS-1$ incidentAValueList.add(new CustomSpinnerItem((String) incident.getErrorCode(), (String) incident.getText())); } else if ("B".equalsIgnoreCase(incident.getFct())){ incidentBValueList.add(new CustomSpinnerItem((String) incident.getErrorCode(), (String) incident.getText())); } } incidentAValue.setContents(incidentAValueList); incidentBValue.setContents(incidentBValueList); } } private void fillComboServiceRefused() { List serviceRefusedValueList = new ArrayList(); List serviceRefusedList = app.dbutil.selectServiceRefusedList(); log.info("ServiceRefused " + serviceRefusedList.size()); for (ServiceRefused serviceRefused : serviceRefusedList) { log.info("Service Refused " + serviceRefused.getCode() + " Code " + serviceRefused.getCode() + " text " + serviceRefused.getText()); serviceRefusedValueList.add(new CustomSpinnerItem((String) serviceRefused.getCode(), (String) serviceRefused.getText())); } serviceRefusedValue.setContents(serviceRefusedValueList); } private void fillComboServicePerformedMonth(List> comboCheckedList) { Report report = this.job.getLatestReport(); List servicePerformedValueMonthList = new ArrayList(); servicePerformedValueMonthList.add(new CustomSpinnerItem("00", "---")); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < comboCheckedList.size(); i++) { servicePerformedValueMonthList.add( new CustomSpinnerItem(comboCheckedList.get(i).get("KEY").toString(), comboCheckedList.get(i).get("VALUE").toString())); //$NON-NLS-1$ //$NON-NLS-2$ } servicePerformedMonthValue.setContents(servicePerformedValueMonthList); if (!report.getReportStatus().isInitial() && report.getMonthYear().length() > 0) { String saverl = report.getMonthYear().substring(0, 1); servicePerformedMonthValue.setSelectionById(saverl); } } private void fillComboServicePerformedYear() { List servicePerformedYearValueList = new ArrayList(); Report report = job.getLatestReport(); // Get the current year int year = DateTimeUtil.getToday().get(Calendar.YEAR); servicePerformedYearValueList.add(new CustomSpinnerItem("0000", "---")); //$NON-NLS-1$ //$NON-NLS-2$ for (int n=year-1; n<=year+1; n++) { servicePerformedYearValueList.add(new CustomSpinnerItem(String.valueOf(n), String.valueOf(n).substring(2))); } servicePerformedYearValue.setContents(servicePerformedYearValueList); if (!report.getReportStatus().isInitial() && report.getMonthYear().length() > 0 && report.getMonthYear().length() == 4) { String saverl = report.getMonthYear().substring(2, 4); servicePerformedYearValue.setSelectionByName(saverl); } } private void fillComboError() { List errorCodeList = app.dbutil.selectErrorCodeList(); if (errorCodeList != null) { List errorValueList = new ArrayList(); List error2ValueList = new ArrayList(); List errorMontValueList = new ArrayList(); for (int i = 0; i < errorCodeList.size(); i++) { ErrorCode errorCode = errorCodeList.get(i); errorValueList.add(new CustomSpinnerItem(errorCode.getErrorCode(), errorCode.getText())); error2ValueList.add(new CustomSpinnerItem(errorCode.getErrorCode(), errorCode.getText())); errorMontValueList.add(new CustomSpinnerItem(errorCode.getErrorCode(), errorCode.getText())); } errorValue.setContents(errorValueList); error2Value.setContents(error2ValueList); errorMontValue.setContents(errorMontValueList); } } private void fillCustomerSupportEditText() { addressValue.clearError(); customerSupportEditText.clearError(); customerSupportEditText.setEnabled(true); addressValue.setEnabled(true); // Entfernen des eMail-Adressen Valitators customerSupportEditText.setInputType(InputType.TYPE_CLASS_TEXT); // 01: Fax if (CommonConstants.Report.CUSTOMER_SUPPORT_FAX.equalsIgnoreCase(sendReportToValue.getSelectedId())) { //$NON-NLS-1$ // 00: Bitte whlen.. if (addressValue.getSelectedItemPosition() != 0) { customerSupportEditText.setInputType(InputType.TYPE_CLASS_PHONE); Address address = retrieveAddressFromList(addressValue.getSelectedId().toString()); customerSupportEditText.setText(address.getFaxNumber()); } } // 02: eMail else if (CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL.equalsIgnoreCase(sendReportToValue.getSelectedId())) { //$NON-NLS-1$ // eMail adress validator customerSupportEditText.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); String emailFromAddress = emailMap.get(addressValue.getSelectedId()); if (emailFromAddress != null && !emailFromAddress.isEmpty()) { customerSupportEditText.setText(emailFromAddress); } else { if (addressValue.getSelectedItemPosition() > 0) { app.showMessage("No Email form " + addressValue.getSelectedName()); } } } // 03: Formular -> Aufragsnummer als Defaultwert einsetzen else if (CommonConstants.Report.CUSTOMER_SUPPORT_FOMULAR.equalsIgnoreCase(sendReportToValue.getSelectedId())) { //$NON-NLS-1$ customerSupportEditText.setText(this.job.getJobNumber()); addressValue.setEnabled(false); } else { addressValue.setSelection(0); customerSupportEditText.setText(""); //$NON-NLS-1$ customerSupportEditText.setEnabled(false); addressValue.setEnabled(false); } } private void fillComboStateOfInstallation() { List stateOfInstallationList = new ArrayList(); List stateOfInstallations = app.dbutil.selectStateOfInstallation(); for (StateOfInstallation stateOfInstallation : stateOfInstallations) { log.info("StateOfInstallation " + stateOfInstallation.getCode() + " text " + stateOfInstallation.getText()); stateOfInstallationList.add(new CustomSpinnerItem( stateOfInstallation.getCode(), stateOfInstallation.getText())); } installationStateValue.setContents(stateOfInstallationList); } private void fillComboIntervention() { List interventionList = new ArrayList(); List nextInterventions = app.dbutil.selectNextIntervention(); for (NextIntervention nextIntervention : nextInterventions) { log.info("NextIntervention " + nextIntervention.getCode() + " text " + nextIntervention.getText()); interventionList.add(new CustomSpinnerItem( nextIntervention.getCode(), nextIntervention.getText())); } interventioValue.setContents(interventionList); } private Address retrieveAddressFromList(String addressNr) { Map addresses = this.job.getAddresses(); if (addresses.containsKey(addressNr)) { return addresses.get(addressNr); } else { log.error("Attempt to obtain an non existing address from job " + this.job.getJobNumber() + " AddressId = " + addressNr); //$NON-NLS-1$ //$NON-NLS-2$ return new Address(); } } private void clearCheckboxMonths() { january.setChecked(false); february.setChecked(false); march.setChecked(false); april.setChecked(false); may.setChecked(false); june.setChecked(false); july.setChecked(false); august.setChecked(false); september.setChecked(false); october.setChecked(false); november.setChecked(false); december.setChecked(false); } @Override public void onNothingSelected(AdapterView arg0) { // Do nothing } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("TYPEOFWORK".equals(parent.getTag())) { //$NON-NLS-1$ workTypeValue.clearError(); setCheckListEnabled(); setServicePerformedEnabled(); setServiceRefusedEnabled(); } else if ("PROGRESS".equals(parent.getTag())) { //$NON-NLS-1$ progressValue.clearError(); } else if ("BILLING".equals(parent.getTag())) { //$NON-NLS-1$ billingValue.clearError(); } else if ("CUSTOMERSUPPORT".equals(parent.getTag())) { //$NON-NLS-1$ sendReportToValue.clearError(); addressValue.clearError(); customerSupportEditText.clearError(); if(sendReportToValue.getSelectedItemPosition() == 0 || CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER.equalsIgnoreCase(sendReportToValue.getSelectedId())) { customerSupportEditText.setText(""); //$NON-NLS-1$ customerSupportEditText.setEnabled(false); addressValue.setEnabled(false); return; } customerSupportEditText.setEnabled(true); addressValue.setEnabled(true); if (this.job.getCurrentReport().getCustomerSupport().equalsIgnoreCase(sendReportToValue.getSelectedId())) { customerSupportEditText.setText(this.job.getCurrentReport().getCustomerSupportText()); } else { customerSupportEditText.getText().clear(); fillComboAddress(); if(CommonConstants.Report.CUSTOMER_SUPPORT_FOMULAR.equalsIgnoreCase(sendReportToValue.getSelectedId())) { customerSupportEditText.setText(this.job.getJobNumber()); addressValue.setEnabled(false); return; } if (addressValue.getSelectedItemPosition() > 0) { fillCustomerSupportEditText(); } } } else if ("ADDRESS".equals(parent.getTag())) { //$NON-NLS-1$ fillCustomerSupportEditText(); } else if ("CHECKLIST".equals(parent.getTag())) { //$NON-NLS-1$ checklistValue.clearError(); } else if ("COMPLETEMONTH".equals(parent.getTag())) { //$NON-NLS-1$ servicePerformedMonthValue.clearError(); servicePerformedYearValue.setEnabled(false); servicePerformedYearValue.clearError(); if (pos != ServiceConstants.Index.ZERO) { servicePerformedYearValue.setEnabled(true); } setServicePerformedEnabled(); setServiceRefusedEnabled(); } else if ("COMPLETEYEAR".equals(parent.getTag())) { //$NON-NLS-1$ servicePerformedYearValue.clearError(); setServicePerformedEnabled(); setServiceRefusedEnabled(); } else if ("SERVICEREFUSED".equals(parent.getTag())) { serviceRefusedValue.clearError(); setServicePerformedEnabled(); setServiceRefusedEnabled(); } } @Override public void afterTextChanged(Editable s) { // Do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // clear error message if (customerSupportEditText.hasFocus()) customerSupportEditText.clearError(); } @Override public void clearErrorMessages() { super.clearErrorMessages(); workTypeValue.clearError(); nextInterventionDateValue.clearError(); nextInterventionTimeText.clearError(); installationStateValue.clearError(); interventioValue.clearError(); billingValue.clearError(); checklistValue.clearError(); servicePerformedMonthValue.clearError(); commissionNumberLayout.clearError(); finalRepair.clearError(); customerSupportEditText.clearError(); cycleOfInstallation.clearError(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { String tag = buttonView.getTag().toString(); if (buttonView instanceof MDRadioButton) { finalRepair.clearError(); if ("PARTIALREPAIR".equals(buttonView.getTag().toString())) { finalRepair.setChecked(!partialRepair.isChecked()); if (isChecked) { app.showMessage(ServiceMessages.getString("secondVisitNeeded"), true); } } if ("FINALREPAIR".equals(buttonView.getTag().toString())) { app.clearMessage(); partialRepair.setChecked(!finalRepair.isChecked()); } nextInterventionDateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); nextInterventionTimeText.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); installationStateValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); interventioValue.setEnabled(job.isMoreInformationsFlag() && partialRepair.isChecked()); nextInterventionDateValue.setRequired(installationStateValue.isEnabled() && partialRepair.isChecked()); installationStateValue.setRequired(installationStateValue.isEnabled() && partialRepair.isChecked()); interventioValue.setRequired(interventioValue.isEnabled() && partialRepair.isChecked()); nextInterventionDateValue.clearError(); nextInterventionTimeText.clearError(); installationStateValue.clearError(); interventioValue.clearError(); } if (buttonView instanceof AppCompatCheckBox) { setCheckMonth(buttonView, tag); if ("REASONING".equals(buttonView.getTag().toString()) && isChecked) { //$NON-NLS-1$ app.showMessage(ServiceMessages.getString("rideToSideNotCharged")); //$NON-NLS-1$ } if ("OPENPENDING".equals(buttonView.getTag().toString()) && isChecked) { //$NON-NLS-1$ // app.showMessage(ServiceMessages.getString("rideToSideNotCharged")); //$NON-NLS-1$ } } } private void setCheckMonth(CompoundButton buttonView, String tag) { if (isMonth(tag.toUpperCase())){ AppCompatCheckBox dummy = (AppCompatCheckBox) buttonView; Map dummyMap = getAppCompatCheckBoxMap(dummy); if (dummy.isChecked()) { if (monthCheckBoxesList == null) monthCheckBoxesList = new ArrayList>(); if (!isContainValueInList(dummyMap)) { monthCheckBoxesList.add(dummyMap); } } else { removeMapFromCheckBoxesList(dummyMap); } if (monthCheckBoxesList.size() > 6) { app.showMessage(ServiceMessages.getString("maximumOfCheckdBoxesIs6")); //$NON-NLS-1$ dummy.setChecked(false); removeMapFromCheckBoxesList(dummyMap); } sortCheckBoxesAscList(monthCheckBoxesList); fillComboServicePerformedMonth(monthCheckBoxesList); } } private boolean isMonth(String tag) { boolean result = false; switch (tag) { case "JANUARY": //$NON-NLS-1$ case "FEBRUARY": //$NON-NLS-1$ case "MARCH": //$NON-NLS-1$ case "APRIL": //$NON-NLS-1$ case "MAY": //$NON-NLS-1$ case "JUNE": //$NON-NLS-1$ case "JULY": //$NON-NLS-1$ case "AUGUST": //$NON-NLS-1$ case "SEPTEMBER": //$NON-NLS-1$ case "OCTOBER": //$NON-NLS-1$ case "NOVEMBER": //$NON-NLS-1$ case "DECEMBER": //$NON-NLS-1$ result = true; break; default: break; } return result; } private Map getAppCompatCheckBoxMap(AppCompatCheckBox checkBox) { Map map = new HashMap(); String id = String.valueOf(checkBox.getId()); String key = id.length() == 1 ? "0" + id : id; //$NON-NLS-1$ map.put("KEY", key); //$NON-NLS-1$ map.put("VALUE", checkBox.getText().toString()); //$NON-NLS-1$ return map; } private void removeMapFromCheckBoxesList(Map input) { if (monthCheckBoxesList != null && !monthCheckBoxesList.isEmpty()) { for (Iterator> iter = monthCheckBoxesList.iterator(); iter.hasNext();) { Map map = iter.next(); Object innerKey = map.get("KEY"); //$NON-NLS-1$ if (innerKey.equals(input.get("KEY"))) { //$NON-NLS-1$ iter.remove(); return; } } } } private boolean isContainValueInList(Map input) { boolean result = false; if (monthCheckBoxesList != null && !monthCheckBoxesList.isEmpty()) { for (Map map : monthCheckBoxesList) { Object innerKey = map.get("KEY"); //$NON-NLS-1$ if (innerKey.equals(input.get("KEY"))) { //$NON-NLS-1$ result = true; return result; } } } return result; } private void setEnableMonthCheckBoxes(boolean enable) { january.setEnabled(enable); february.setEnabled(enable); march.setEnabled(enable); april.setEnabled(enable); may.setEnabled(enable); june.setEnabled(enable); july.setEnabled(enable); august.setEnabled(enable); september.setEnabled(enable); october.setEnabled(enable); november.setEnabled(enable); december.setEnabled(enable); } private AppCompatCheckBox getCheckboxByMonthCode(String monthCode) { AppCompatCheckBox result = null; if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.JAN)) { result = january; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.FEB)) { result = february; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.MAR)) { result = march; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.APR)) { result = april; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.MAY)) { result = may; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.JUN)) { result = june; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.JUL)) { result = july; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.AUG)) { result = august; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.SEP)) { result = september; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.OCT)) { result = october; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.NOV)) { result = november; } else if (monthCode.equalsIgnoreCase(CommonConstants.Report.Month.DEC)) { result = december; } return result; } private void setCheckboxes(String savlfd) { if (monthCheckBoxesList == null) monthCheckBoxesList = new ArrayList>(); AppCompatCheckBox checkBoxMonth = getCheckboxByMonthCode(savlfd); if (checkBoxMonth != null) { checkBoxMonth.setChecked(true); } } private void initCheckboxMonths() { Iterator> itr = app.enumUtil.monthEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); // Leerelement ausschliessen if (!CommonConstants.PLEASE_SELECT.equalsIgnoreCase((String) entry.getKey())) { //$NON-NLS-1$ AppCompatCheckBox checkBoxMonth = getCheckboxByMonthCode((String) entry.getKey()); if(checkBoxMonth != null) { checkBoxMonth.setText((String) entry.getValue()); checkBoxMonth.setChecked(false); } } } } private void sortCheckBoxesAscList(List> listToBeSorted) { Comparator> mapComparator = new Comparator>() { @Override public int compare(Map m1, Map m2) { return m1.get("KEY").toString().compareTo(m2.get("KEY").toString()); //$NON-NLS-1$ //$NON-NLS-2$ } }; Collections.sort(listToBeSorted, mapComparator); } private void clearAllValue() { commissionType = null; clearPartialRepairAndFinalRepair(); commissionNumberLayout.clear(); jobNumber.getText().clear(); workTypeValue.setSelection(0); collectively.setChecked(false); safetyReport.setChecked(false); openPending.setChecked(false); governmentReport.setChecked(false); billingValue.setSelection(0); sendReportToValue.setSelection(0); addressValue.setSelection(0); customerSupportEditText.getText().clear(); checklistValue.setSelection(0); incidentAValue.setSelection(0); incidentBValue.setSelection(0); systemError.getText().clear(); serviceRefusedValue.setSelection(0); servicePerformedMonthValue.setSelection(0); servicePerformedYearValue.setSelection(0); distance.getText().clear(); expenses.getText().clear(); errorValue.setSelection(0); errorEditText1.getText().clear(); errorCheckbox.setChecked(false); error2Value.setSelection(0); error2EditText1.getText().clear(); error2Checkbox.setChecked(false); errorMontValue.setSelection(0); errorMontEditText1.getText().clear(); errorMontCheckbox.setChecked(false); monthCheckBoxesList.clear(); reasoning.setChecked(false); cycleOfInstallation.getText().clear(); clearCheckboxMonths(); servicePerformedMonthValue.setSelection(0); servicePerformedYearValue.setSelection(0); serviceRefusedValue.setSelection(0); nextInterventionDateValue.clearContents(); nextInterventionTimeText.getText().clear(); } private void loadReport(Report report) { jobNumber.setText(report.getOrderNumber()); // disable checkbox if report is already part of signature bundle collectively.setChecked(report.isCollectively()); collectively.setEnabled(report.getSignatureGuId().isEmpty()); safetyReport.setChecked(report.isSafetyReport()); setSelectTheSpinner(billingValue, report.getBilling()); setSelectTheSpinner(workTypeValue, report.getWorkType()); if (!report.getCustomerSupport().isEmpty()) { setSelectTheSpinner(sendReportToValue, report.getCustomerSupport()); } if(!report.getCustomerSupportText().isEmpty()) { customerSupportEditText.setText(report.getCustomerSupportText()); Iterator> emailEntrySetIterator = emailMap.entrySet().iterator(); while (emailEntrySetIterator.hasNext()) { java.util.Map.Entry emailEntry = emailEntrySetIterator.next(); if (emailEntry.getValue().equalsIgnoreCase(report.getCustomerSupportText())) { addressValue.setSelectionById(emailEntry.getKey()); } } } else { addressValue.setSelection(1); } setSelectTheSpinner(checklistValue, report.getChecklist()); if (report.getIncidentAB().length() > 0) { //$NON-NLS-1$ setSelectTheSpinner(incidentAValue, "0" + report.getIncidentAB().substring(0, 1)); setSelectTheSpinner(incidentBValue, "0" + report.getIncidentAB().substring(1)); } cycleOfInstallation.setText(report.getCycleOfInstallation()); setSelectTheSpinner(errorValue, report.getErrorId1()); if (StringUtil.isNotEmpty(report.getErrorH1())) errorEditText1.setText(report.getErrorH1()); errorCheckbox.setChecked(report.isErrorFlag1()); setSelectTheSpinner(error2Value, report.getErrorId2()); if (StringUtil.isNotEmpty(report.getErrorH2())) error2EditText1.setText(report.getErrorH2()); error2Checkbox.setChecked(report.isErrorFlag2()); setSelectTheSpinner(errorMontValue, report.getErrorId3()); if (StringUtil.isNotEmpty(report.getErrorH3())) errorMontEditText1.setText(report.getErrorH3()); errorMontCheckbox.setChecked(report.isErrorFlag3()); systemError.setText(report.getSystemError()); setCheckboxes(report.getServicePlanMonth1()); setCheckboxes(report.getServicePlanMonth2()); setCheckboxes(report.getServicePlanMonth3()); setCheckboxes(report.getServicePlanMonth4()); setCheckboxes(report.getServicePlanMonth5()); setCheckboxes(report.getServicePlanMonth6()); sortCheckBoxesAscList(monthCheckBoxesList); fillComboServicePerformedMonth(monthCheckBoxesList); if (report.getMonthYear().length() > 2) { setSelectTheSpinner(servicePerformedMonthValue, report.getMonthYear().substring(0, 2)); setSelectTheSpinner(servicePerformedYearValue, report.getMonthYear().substring(2, 4)); } else { setSelectTheSpinner(servicePerformedMonthValue, report.getMonthYear()); } setSelectTheSpinner(serviceRefusedValue, report.getServiceRefused()); if (job.getJobType().isMON()) { openPending.setChecked(report.isOpenPending()); governmentReport.setChecked(report.isGovernmentReport()); setSelectTheSpinner(progressValue, report.getMonStk()); log.info("progress " + report.getMonStk()); } else { if (!report.isPartialRepair() && !report.isFinalRepair()) { clearPartialRepairAndFinalRepair(); } else { partialRepair.setChecked(report.isPartialRepair()); finalRepair.setChecked(report.isFinalRepair()); } log.info("getNextInterventionDate " + DateTimeUtil.showDateTime(report.getNextInterventionDate())); if (report.getNextInterventionDate().getTime() > 0 ) { nextInterventionDateValue.setSelectedDate(report.getNextInterventionDate()); String nextInterventionTime = DateTimeUtil.showTimeGMT(report.getNextInterventionDate()); // if (!nextInterventionTime.equalsIgnoreCase("00:00") ) { nextInterventionTimeText.setText(nextInterventionTime); // } } installationStateValue.setSelectionById(report.getStateOfInstallation()); interventioValue.setSelectionById(report.getNextInterventionCode()); distance.setText(report.getDistance()); expenses.setText(report.getExpenses()); reasoning.setChecked(report.isReasoning()); } } private void setSelectTheSpinner(Spinner spinner, String input) { CustomSpinnerAdapter adapter = (CustomSpinnerAdapter) spinner.getAdapter(); int spinnerPosition = adapter.getPosition(input); spinner.setSelection(spinnerPosition); } private String getExpense(){ String userInput = expenses.getText().toString(); if (!TextUtils.isEmpty(userInput)) { try { Locale locale = Locale.ENGLISH; if (userInput.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(userInput))); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("###.##", symbols); format.setMaximumFractionDigits(2); userInput = format.format(floatValue); } catch (NumberFormatException e) { return ""; } catch (ParseException e) { return ""; } catch (java.text.ParseException e) { return ""; } } return userInput; } private void setCheckListEnabled() { // Mandatory: // log.info("select work type " + workTypeValue.getSelectedName() + " is guarantee "); boolean checklisRequired = (job.getJobType().isSAV() || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT) || isWorkTypeMantenanceVonovia() ); checklistValue.setRequired(checklisRequired); checklistValue.clearError(); } private void setServicePerformedEnabled() { // Mandatory: Only if // or // or // servicePerformedMonthValue.setEnabled(false); if (servicePerformedMonthValue.getVisibility() == View.GONE) { return; } boolean isServicePerformedMandatory = ((job.getJobType().isSAV() && !(isWorkTypeMantenanceVonovia())) || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT)); boolean isServicePerformedRequired = (isServicePerformedMandatory || (job.isServiceRefusedFlag() && serviceRefusedValue.getSelectedItemPosition() == 0)); String text = servicePerformedText.getText().toString().replaceAll("\\*", "").trim();servicePerformedText.setEnabled(false); servicePerformedMonthValue.setEnabled(true); servicePerformedMonthValue.clearError(); servicePerformedYearValue.clearError(); servicePerformedText.setText(text); if (isServicePerformedRequired) { servicePerformedText.setText(servicePerformedText.getText().toString() + " *"); } } private void setServiceRefusedEnabled() { // Mandatory: Only if // ZKDMOB.AUART = REP and ZKDMOB.KNZSAVPFL = X and ZKDMOBREP.ARBA = // Displayed: Job type = REP / SAV serviceRefusedValue.setEnabled(false); if (serviceRefusedGridLayout.getVisibility() == View.GONE) { return; } serviceRefusedValue.setEnabled(job.isServiceRefusedFlag()); boolean isServiceRefusedRequired = job.isServiceRefusedFlag() && job.getJobType().isREP() && servicePerformedMonthValue.getSelectedItemPosition() == 0 && servicePerformedYearValue.getSelectedItemPosition() == 0 && (!workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_SERVICE_CONTACT) && !isWorkTypeMantenanceVonovia()); String text = serviceRefusedText.getText().toString().replaceAll("\\*", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ serviceRefusedValue.clearError(); serviceRefusedText.setText(text); if (job.isServiceRefusedFlag() && isServiceRefusedRequired) { serviceRefusedText.setText(serviceRefusedText.getText().toString() + " *"); } } /** * * @return true if worktype = 98 or 99. */ private boolean isWorkTypeMantenanceVonovia() { return (workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA) || workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_MAINTENANCE_VONOVIA)); } private void clearPartialRepairAndFinalRepair() { partialRepair.setOnCheckedChangeListener(null); finalRepair.setOnCheckedChangeListener(null); partialRepair.setChecked(false); finalRepair.setChecked(false); partialRepair.setOnCheckedChangeListener(this); finalRepair.setOnCheckedChangeListener(this); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportFormListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.CheckBoxListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.util.ServiceFormUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class ReportFormListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportFormListForm.class); protected Job job; private Form formSelected = null; private Toolbar toolbar; protected CheckBoxListWidget listWidget; private ActionCtrl addButton; private LinearLayout emptyMessageView; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportFormListFormArguments) { ReportFormListFormArguments formArguments = (ReportFormListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new CheckBoxListWidget(context); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noFormsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("Forms")); //$NON-NLS-1$ loadFormTable(); return null; } private void loadFormTable() { listWidget.clean(); view.removeAllViews(); if (app.dbutil.selectFormInstanceListByGuid( job.getLatestReport().getGuId()).isEmpty()) { view.addView(emptyMessageView); } else { ArrayList items = new ArrayList(); List formItem = new ArrayList(); for (final Form form : app.dbutil.selectFormList()) { List formItemList = app.dbutil.selectFormItemListByFormIdAndFormVersion(form.getId(), form.getVersion()); if (!formItemList.isEmpty()) { List formInstances = app.dbutil.selectFormInstanceListByGuidAndFormId(job.getLatestReport().getGuId(), form.getId()); if (!formInstances.isEmpty()) { final CheckBoxListWidgetItem item = new CheckBoxListWidgetItem(); item.isShowRightLayout(true); item.setCheck(false); item.setDrawable(getBitmanDrawable(app.imagesUtil.getImage(ServiceFormUtil.getCheckImageStatus(formItemList, formInstances), CommonConstants.Images.IMAGE_MAX_DPI))); item.setTitleText(form.getName()); item.setStringLine1(form.getDescription()); item.setStringLine2(String.valueOf(form.getVersion())); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EDIT, CommonConstants.Images.IMAGE_MAX_DPI))); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { formSelected = form; leaveToEditForm(); } }); items.add(item); formItem.add(form); } } } listWidget.setClickable(false); // listWidget.setOnItemClickListener(createOnItemClickListener(formItem)); listWidget.addItems(items); view.addView(listWidget); } } private OnItemClickListener createOnItemClickListener(final List formList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { formSelected = formList.get(position); leaveToEditForm(); } }; } private void leaveToEditForm() { if (formSelected == null) { return; } app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportFormNewEditForm.class, new ReportFormNewEditForm.FormArguments(job, formSelected)); } }, false); } private void showFormsDialog() { List items = new ArrayList(); formSelected = null; final List forms = app.dbutil.selectValidFormList(); for (Form form : forms) { log.info("Form " + form.getName() + " id " + form.getId() + " status " + form.getStatus() + " valid from " + DateTimeUtil.showDateTime(form.getValidFrom()) + " valid to " + DateTimeUtil.showDateTime(form.getValidTo())); items.add(form.getName()); } MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("ChooseForm"), ServiceMessages.getString("cancel")); alertDialog.setSingleChoiceItems(items.toArray(new String[0]), -1, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { formSelected = forms.get(which); } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { leaveToEditForm(); } }); alertDialog.show(); } protected ApplicationEvent onAddPressed() { showFormsDialog(); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } public static class ReportFormListFormArguments { private Job job; public ReportFormListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportFormNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.businessobjects.FormValueList; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormItemType; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.BitmapLoadUtils; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportFormListForm.ReportFormListFormArguments; import ch.mfiles.kaba.kolibri.service.ui.widgets.FormImageLayout; import ch.mfiles.kaba.kolibri.service.util.SignatureUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.ui.SignatureView; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.LayoutHelper; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ReportFormNewEditForm extends SuperForm { private static Log log = LogFactory.getLog(ReportFormNewEditForm.class); protected Job job; private Form form; private List formItems; private LinearLayout formContentLinearLayout; private ScrollView scrollView; private Toolbar toolbar; private final String CONTENT_VIEW = "CONTENT"; private Map formItemValueMap = new HashMap(); private Map cardMap = new HashMap(); private AppCompatButton deleteButton; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; job = formArguments.getJob(); form = formArguments.getForm(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); // set invisible save button // saveButton.setVisible(false); formContentLinearLayout = new LinearLayout(context); formContentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); formContentLinearLayout.setOrientation(LinearLayout.VERTICAL); formContentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout content = new LinearLayout(context); content.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); content.setOrientation(LinearLayout.VERTICAL); // Button LinearLayout deleteButtonLinearLayout = new LinearLayout(context); // deleteButtonLinearLayout.setLayoutParams(getGridLayoutParams(31, 0, 3)); deleteButtonLinearLayout.setOrientation(LinearLayout.VERTICAL); GradientDrawable deleteButtonGradientDrawable = new GradientDrawable(); deleteButtonGradientDrawable.setColor(LayoutUtils.DEFAULT_BUTON_COLOR); deleteButtonGradientDrawable.setCornerRadius(7); deleteButtonGradientDrawable.setStroke(2, LayoutUtils.DEFAULT_BUTON_COLOR); deleteButton = new AppCompatButton(context); LinearLayout.LayoutParams deleteButtonParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); deleteButtonParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; deleteButton.setLayoutParams(deleteButtonParams); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new View.OnClickListener() { private boolean showConfirmDeleteDialog() { return app.showMessageBox(ServiceMessages.getString("areYouSureThatYouWantToDeleteRecord"), ServiceMessages.getString("warning"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK; } @Override public void onClick(View paramView) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (showConfirmDeleteDialog()) { app.dbutil.deleteFormInstanceByGuidAndFormId(job.getCurrentReport().getGuId(), String.valueOf(form.getId())); // delete saved signature. Iterator> itrView = formItemValueMap.entrySet().iterator(); while (itrView.hasNext()) { Entry entry = itrView.next(); FormItemValue formItemValue = (FormItemValue)entry.getValue(); FormInstance formInstance = formItemValue.getFormInstance(); if (formInstance != null && !formInstance.getAttachmentValue().isEmpty()) { if (formItemValue.getView() instanceof SignatureView) { app.deleteFile(formInstance.getAttachmentValue()); } if (formItemValue.getView() instanceof FormImageLayout) { app.deleteFile(formInstance.getAttachmentValue()); } formInstance.setAttachmentValue(""); } } return app.leaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); } return null; } }; } }); deleteButton.setBackgroundDrawable(deleteButtonGradientDrawable); deleteButton.setContentDescription("delete"); deleteButtonLinearLayout.addView(deleteButton); content.addView(formContentLinearLayout); content.addView(deleteButtonLinearLayout); saveButton.setTitle(ServiceMessages.getString("save")); scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(content); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); toolbar.setEnabled(true); setFormTitle(form.getName()); createContent(); scrollView.scrollBy(0, 0); return null; } private void resetAllContents() { formContentLinearLayout.removeAllViews(); cardMap.clear(); formItemValueMap.clear(); } private void createContent() { resetAllContents(); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_MARGIN); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(form.getName()); titleTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(titleTextView); TextView descriptionTextView = new TextView(context); descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); descriptionTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); descriptionTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); descriptionTextView.setText(form.getDescription()); descriptionTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(descriptionTextView); formContentLinearLayout.addView(linearLayout); formItems = app.dbutil.selectFormItemListByFormIdAndFormVersion(form.getId(), form.getVersion()); deleteButton.setEnabled(!formItems.isEmpty()); if (formItems.isEmpty()) { return; } for (FormItem formItem : formItems) { if (cardMap.containsKey(formItem.getCardName())) { } else { CardView cardView = createCardView(formItem.getCardName()); formContentLinearLayout.addView(cardView); cardMap.put(formItem.getCardName(), cardView); } LinearLayout cardContent = (LinearLayout) cardMap.get(formItem.getCardName()).findViewWithTag(CONTENT_VIEW); cardContent.addView(createView(formItem)); } } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); if (toolbar.isEnabled()) { toolbar.setEnabled(false); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("TheFormIsDiscardedContinue"), ServiceMessages.getString("discardForm"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { app.injectAndLeaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); } toolbar.setEnabled(true); return null; } }, false); } return null; } @Override protected boolean isValid() { boolean result = super.isValid(); View focusView = null; String errorMessage = Messages.getString("pleaseProvideValue"); Iterator> itrView = formItemValueMap.entrySet().iterator(); while (itrView.hasNext()) { Entry entry = itrView.next(); FormItemValue formItemValue = (FormItemValue)entry.getValue(); if (formItemValue.getView() instanceof MDSpinner) { final MDSpinner mdSpinner = (MDSpinner)formItemValue.getView(); if (mdSpinner.isRequired() && (mdSpinner.getSelectedId() == CommonConstants.PLEASE_SELECT || mdSpinner.getSelectedId().isEmpty()) ) { result = false; focusView = mdSpinner; mdSpinner.setError(errorMessage); } log.info("combo box " + mdSpinner.getTextView().getText() + " value " + mdSpinner.getSelectedName()+ " --> " + mdSpinner.getSelectedId()); } if (formItemValue.getView() instanceof MDEditText) { final MDEditText editText = (MDEditText)formItemValue.getView(); if (editText.getText().toString().isEmpty() && editText.isRequired()) { result = false; editText.setError(errorMessage); focusView = editText; } } if (formItemValue.getView() instanceof FormImageLayout) { FormImageLayout formImageLayout = (FormImageLayout)formItemValue.getView(); if (formImageLayout.isRequire() && formImageLayout.getImageBitmap() == null) { result = false; app.showMessage(formImageLayout.getErrorMessage(), true); } } } if (!result && focusView != null) { scrollView.scrollTo(0, (int) focusView.getY()); focusView.requestFocus(); } return result; } @Override protected boolean onSave() { List newFormInstances = new ArrayList(); Iterator> itrView = formItemValueMap.entrySet().iterator(); while (itrView.hasNext()) { Entry entry = itrView.next(); FormItemValue formItemValue = (FormItemValue)entry.getValue(); FormInstance formInstance = formItemValue.getFormInstance(); if (formInstance == null) { formInstance = new FormInstance(); formInstance.setGuid(job.getCurrentReport().getGuId()); formInstance.setFormId(form.getId()); formInstance.setFormItemId(String.valueOf(entry.getKey())); formInstance.setFormVersion(formItemValue.getFormItem().getFormVersion()); formInstance.setFormItemType(formItemValue.getFormItem().getFormItemType().getCode()); } newFormInstances.add(assignToFormInstance(formItemValue.getView(), formInstance)); } app.dbutil.insertOrReplaceJobReportFormInstanceList(newFormInstances); app.injectAndLeaveToForm(ReportFormListForm.class, new ReportFormListFormArguments(job)); return false; } private FormInstance assignToFormInstance(View view, FormInstance formInstance) { if (view instanceof RadioButton) { RadioButton radioButton = (RadioButton)view; formInstance.setBooleanValue(radioButton.isChecked()); } if (view instanceof MDSpinner) { final MDSpinner mdSpinner = (MDSpinner)view; formInstance.setValueId(mdSpinner.getSelectedId()); formInstance.setValueListId(String.valueOf(mdSpinner.getTag())); log.info("combo box " + mdSpinner.getTextView().getText() + " value " + mdSpinner.getSelectedName() + " --> " + mdSpinner.getSelectedId()); log.info("ValueId " + formInstance.getValueId() + " ValueListId " + formInstance.getValueListId()); } if (view instanceof AppCompatCheckBox) { AppCompatCheckBox appCompatCheckBox = (AppCompatCheckBox)view; formInstance.setBooleanValue(appCompatCheckBox.isChecked()); } if (view instanceof MDEditText) { final MDEditText editText = (MDEditText)view; if (!editText.getText().toString().isEmpty()) { if (editText.getInputType() == InputType.TYPE_CLASS_NUMBER) { formInstance.setFloatValue(Double.valueOf(editText.getText().toString())); } else { formInstance.setStringValue(editText.getText().toString()); } } } if (view instanceof SignatureView) { SignatureView signatureView = (SignatureView)view; String imagePath; if (!formInstance.getAttachmentValue().isEmpty()) { imagePath = formInstance.getAttachmentValue(); // app.deleteFile(imagePath); } else { // Generate file name and path for the signature file imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, form.getId() + "_" + formInstance.getFormItemId() + "_" + Long.toString(new Date().getTime()) + ".bmp", true); } if (signatureView.isDirty()) { // signature from UI -> save file try { log.info("image path " + imagePath); if (log.isDebugEnabled()) log.debug("Save signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ String originalImagePath = SignatureUtil.getOriginalSignatureFileName(imagePath); signatureView.save(originalImagePath); signatureView.save(imagePath, SignatureUtil.TARGET_WIDTH, SignatureUtil.TARGET_HEIGHT, SignatureUtil.TARGET_DENSITY); log.info("originalImagePath path " + originalImagePath); formInstance.setAttachmentValue(imagePath); } catch (IOException e) { throw new ApplicationException(e); } } } if (view instanceof FormImageLayout) { FormImageLayout formImageLayout = (FormImageLayout)view; String imagePath; if (!formInstance.getAttachmentValue().isEmpty()) { imagePath = formInstance.getAttachmentValue(); } else { // Generate file name and path for the signature file imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, form.getId() + "_" + formInstance.getFormItemId() + "_" + Long.toString(new Date().getTime()) + ".jpg", true); } if (formImageLayout.getImageBitmap() != null) { // image loaded from UI -> save Image File (new/edit) FileUtils.writeBitmapToFile(imagePath, formImageLayout.getImageBitmap()); formInstance.setAttachmentValue(imagePath); } else { app.deleteFile(imagePath); formInstance.setAttachmentValue(""); } } return formInstance; } protected CardView createCardView(String title) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 10, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MIN_MARGIN); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_MARGIN); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(title); titleTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(titleTextView); // --------------- content-------------------- LinearLayout content = new LinearLayout(context); content.setTag(CONTENT_VIEW); content.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); content.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(content); // --------------- content-------------------- cardView.addView(linearLayout); return cardView; } private LinearLayout createView(FormItem formItem) { LinearLayout result = null; log.info("FormItemType " + formItem.getFormItemType().getCode()); switch (formItem.getFormItemType().getCode()) { case FormItemType.RDBT: result = createRadio(formItem); break; case FormItemType.COMB: result = createComboBox(formItem); break; case FormItemType.CHKB: result = createCheckBox(formItem); break; case FormItemType.TEXT: result = createTextInput(formItem); break; case FormItemType.NUMF: result = createTextInput(formItem); break; case FormItemType.SIGN: result = createSignature(formItem); break; case FormItemType.TITL: result = createTitle(formItem); break; case FormItemType.SEPR: result = createSeparator(formItem); break; case FormItemType.IMAG: result = createImage(formItem); break; default: result = new LinearLayout(context); break; } return result; } private LinearLayout createRadio(FormItem formItem) { LinearLayout radioLinearLayout = new LinearLayout(context); radioLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioLinearLayout.setOrientation(LinearLayout.VERTICAL); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setOrientation(LinearLayout.VERTICAL); RadioButton radioButton = new RadioButton(context); radioButton.setTag(formItem.getId()); radioButton.setText(formItem.getLabel()); radioButton.setChecked(false); radioGroup.addView(radioButton); // contentItemMap.put(formItem.getId(), radioButton); // // if (valueItemMap.containsKey(formItem.getId())) { // radioButton.setChecked(Boolean.valueOf(valueItemMap.get(formItem.getId()))); // } FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { radioButton.setChecked(Boolean.valueOf(formInstance.isBooleanValue())); formItemValue.setFormInstance(formInstance); } formItemValue.setView(radioButton); formItemValueMap.put(formItem.getId(), formItemValue); return radioLinearLayout; } private LinearLayout createComboBox(FormItem formItem) { LinearLayout comboBoxLinearLayout = new LinearLayout(context); comboBoxLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); final MDSpinner combo = MDSpinner.createDefaultSpinner(comboBoxLinearLayout, formItem.getLabel(), formItem.isMandatory()); combo.setTag(formItem.getId()); combo.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { combo.clearError(); } }); combo.setTag(formItem.getValueListId()); List formValueLists = app.dbutil.selectValueListsByValueListId(formItem.getValueListId()); List customSpinnerItemList = new ArrayList(); String emptyText = formItem.getEmptyText(); log.info("formItem " + formItem.getLabel() + " EmptyText " + formItem.getEmptyText()); customSpinnerItemList.add(new CustomSpinnerItem("", emptyText)); boolean isDuplicated = false; String defaultValueId = ""; for (FormValueList formValueList : formValueLists) { log.info("formValueList " + formValueList.getValueId() + " value " + formValueList.getValue() + " default " + formValueList.isDefaultValue()); if (formValueList.getValue().equalsIgnoreCase(emptyText)) { isDuplicated = true; defaultValueId = formValueList.getValueId(); } if (formValueList.isDefaultValue()) { defaultValueId = formValueList.getValueId(); } customSpinnerItemList.add(new CustomSpinnerItem(formValueList.getValueId(), formValueList.getValue())); } if (isDuplicated) { customSpinnerItemList.remove(0); } combo.setContents(customSpinnerItemList); if (!defaultValueId.isEmpty()) { combo.setSelectionById(defaultValueId); } FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { combo.setSelectionById(formInstance.getValueId()); formItemValue.setFormInstance(formInstance); } formItemValue.setView(combo); formItemValueMap.put(formItem.getId(), formItemValue); return comboBoxLinearLayout; } private LinearLayout createCheckBox(FormItem formItem) { LinearLayout checkBoxViewLinearLayout = new LinearLayout(context); checkBoxViewLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); AppCompatCheckBox checkBox = CommonUtilForm.getCheckBox(context, formItem.getLabel()); //$NON-NLS-1$ checkBox.setChecked(false); checkBox.setTag(formItem.getId()); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); checkBoxViewLinearLayout.addView(checkBox); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { checkBox.setChecked(formInstance.isBooleanValue()); formItemValue.setFormInstance(formInstance); } formItemValue.setView(checkBox); formItemValueMap.put(formItem.getId(), formItemValue); return checkBoxViewLinearLayout; } private LinearLayout createTextInput(FormItem formItem) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout barcodeLinearLayout = new LinearLayout(context); barcodeLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams barcodeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLinearLayoutParams.gravity = Gravity.CENTER; barcodeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.weight = 1; barcodeLinearLayout.setLayoutParams(barcodeLinearLayoutParams); barcodeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); int type = InputType.TYPE_CLASS_NUMBER; if (formItem.getFormItemType().isTEXT()) { type = InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; } if (formItem.getFormItemType().isNUMF()) { type = InputType.TYPE_CLASS_NUMBER; } final MDEditText barcodeEditText = MDEditText.createDefaultEditText(barcodeLinearLayout, formItem.getLabel(), type, formItem.isMandatory()); LinearLayout.LayoutParams barcodeLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLayoutParams.gravity = Gravity.CENTER; barcodeLayoutParams.width = 0; barcodeLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLayoutParams.weight = formItem.getFormItemType().isTEXT()? 0.9f:1f; barcodeEditText.getParentTextInputLayout().setLayoutParams(barcodeLayoutParams); log.info("text " + formItem.getLabel() + " is Require " + formItem.isMandatory()); barcodeEditText.setTag(formItem.getId()); if (formItem.getMaxStringSize() > 0) { barcodeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(formItem.getMaxStringSize()) }); } barcodeEditText.clearFocus(); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { barcodeEditText.setText(formItem.getFormItemType().isNUMF()? String.valueOf(formInstance.getFloatValue()) : formInstance.getStringValue()); formItemValue.setFormInstance(formInstance); } formItemValue.setView(barcodeEditText); formItemValueMap.put(formItem.getId(), formItemValue); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = formItem.getFormItemType().isTEXT()? 0.1f:0f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { private String barcode = ""; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { if (barcodeEditText.getInputType() == (InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)) { if (!barcode.isEmpty()) { barcodeEditText.requestFocus(); barcodeEditText.getText().clear(); barcodeEditText.append(barcode); } } } }; } }); cameraLinearLayout.addView(gridImageView); barcodeLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(barcodeLinearLayout); return contentLinearLayout; } private LinearLayout createSeparator(FormItem formItem) { LinearLayout separatorLayout = new LinearLayout(context); separatorLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); separatorLayout.setOrientation(LinearLayout.HORIZONTAL); separatorLayout.setPadding(0, 0, 0, LayoutUtils.DEFAULT_MIN_PADDING); DividerView dividerView = new DividerView(context); separatorLayout.addView(dividerView); return separatorLayout; } private LinearLayout createTitle(FormItem formItem) { LinearLayout titleLinearLayout = new LinearLayout(context); titleLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); textView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textView.setPadding(5, 10, 5, 5); textView.setText(formItem.getLabel()); textView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); titleLinearLayout.addView(textView); return titleLinearLayout; } private LinearLayout createSignature(FormItem formItem) { LinearLayout signatureLinearLayout = new LinearLayout(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardViewParams.setMargins(0, 0, 0, 0); int height = LayoutParams.MATCH_PARENT; if (LayoutHelper.getDisplayMetrics().widthPixels > SignatureUtil.TARGET_WIDTH) { height = (int) (LayoutHelper.getDisplayMetrics().widthPixels * SignatureUtil.ASPECT_RATIO); } cardViewParams.width = LayoutParams.MATCH_PARENT; if (height > 0) { cardViewParams.height = height; } signatureLinearLayout.setLayoutParams(cardViewParams); signatureLinearLayout.setPadding(0, 0, 0, 0); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); SignatureView signatureView = new SignatureView(context); linearLayout.addView(signatureView); signatureLinearLayout.addView(linearLayout); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { try { signatureView.load(SignatureUtil.getOriginalSignatureFileName(formInstance.getAttachmentValue())); // signatureView.lock(); } catch (IOException e) { log.error("Found IOException:", e); //$NON-NLS-1$ app.showMessageBox(ServiceMessages.getString("signatureCanNotBeLoadedFromFile"), //$NON-NLS-1$ ServiceMessages.getString("error"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_ERROR); } formItemValue.setFormInstance(formInstance); } formItemValue.setView(signatureView); formItemValueMap.put(formItem.getId(), formItemValue); return signatureLinearLayout; } private LinearLayout createImage(FormItem formItem) { LinearLayout imageViewLinearLayout = new LinearLayout(context); imageViewLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); final FormImageLayout imageLayout = new FormImageLayout(context); imageViewLinearLayout.addView(imageLayout.createFormImageLayout(app, formItem.getLabel(), formItem.isMandatory(), new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Iterator iterator = formItemValueMap.values().iterator(); while (iterator.hasNext()) { FormItemValue formItemValue = iterator.next(); if (formItemValue.getView() instanceof MDEditText) { MDEditText textInput = (MDEditText) formItemValue.getView(); textInput.clearFocus(); } } } })); FormItemValue formItemValue = new FormItemValue(); formItemValue.setFormItem(formItem); FormInstance formInstance = app.dbutil.selectFormInstanceByGuidFormIdAndFormItemId( job.getCurrentReport().getGuId(), form.getId(), formItem.getId()); if (formInstance != null) { if (!formInstance.getAttachmentValue().isEmpty()) { BitmapLoadUtils.decodeBitmapInBackground(appman.getContext(), Uri.fromFile(new File(formInstance.getAttachmentValue())), new BitmapLoadUtils.BitmapLoadCallback() { @Override public void onFailure(@NonNull Exception bitmapWorkerException) { } public void onBitmapLoaded(Bitmap bitmap, int exifOrientation) { imageLayout.setBitmap(bitmap); } }); formItemValue.setFormInstance(formInstance); } } formItemValue.setView(imageLayout); formItemValueMap.put(formItem.getId(), formItemValue); return imageViewLinearLayout; } public static class FormArguments { private Job job; private Form form; public FormArguments(Job job, Form form) { this.job = job; this.form = form; } public Job getJob() { return job; } public Form getForm() { return form; } public void setForm(Form form) { this.form = form; } } public final class FormItemValue { FormItemValue() { } private String id; private View view; private FormInstance formInstance; private FormItem formItem; public String getId() { return id; } public void setId(String id) { this.id = id; } public View getView() { return view; } public void setView(View view) { this.view = view; } public FormInstance getFormInstance() { return formInstance; } public void setFormInstance(FormInstance formInstance) { this.formInstance = formInstance; } public FormItem getFormItem() { return formItem; } public void setFormItem(FormItem formItem) { this.formItem = formItem; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportImageAttachmentsListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * New Form. */ public class ReportImageAttachmentsListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportImageAttachmentsListForm.class); protected Job job; private Toolbar toolbar; protected ImageListWidget listWidget; private ActionUtil utilButton; private ActionCtrl addButton; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportImageAttachmentsListFormArguments) { ReportImageAttachmentsListFormArguments formArguments = (ReportImageAttachmentsListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); utilButton = new ActionUtil(app); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new ImageListWidget(context); view.addView(listWidget); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("images")); //$NON-NLS-1$ loadImageAttachmentsList(); return null; } private void loadImageAttachmentsList() { listWidget.clean(); ArrayList items = new ArrayList(); List reportImageAttachmentsList = app.dbutil.selectReportJobFileImageListByReport(job.getLatestReport()); addButton.setEnabled(true); addButton.setImage(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI)); for (int i = 0; i < reportImageAttachmentsList.size(); i++) { final JobFile jobFile = reportImageAttachmentsList.get(i); final ImageListWidgetItem item = new ImageListWidgetItem(); item.setDescription(jobFile.getDescription()); item.setImageBitmap(jobFile.getSignPicBitmap()); log.info("Type " + jobFile.getType()); String type = "Intern"; if("E".equalsIgnoreCase(jobFile.getType())) { type = "z. Hd. Kunden"; } item.setType(type); item.setStatus(ServiceMessages.getString("status") + ": " + ServiceMessages.getString(jobFile.getSentDate().getTime() > 0 ? "sent" : "notSend")); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(reportImageAttachmentsList)); } listWidget.addItems(items); } private OnItemClickListener createOnItemClickListener(final List reportImageAttachmentsList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { JobFile jobFile = reportImageAttachmentsList.get(position); app.injectAndLeaveToForm(ReportImageAttachmentsNewEditForm.class, new ReportImageAttachmentsNewEditForm.ReportImageAttachmentsNewEditFormArguments(job, null, jobFile)); //$NON-NLS-1$ } }; } private void leaveToImageNewEditForm(Bitmap bitmap) { if(bitmap == null) return; app.injectAndLeaveToForm(ReportImageAttachmentsNewEditForm.class, new ReportImageAttachmentsNewEditForm.ReportImageAttachmentsNewEditFormArguments(job, bitmap, null)); } protected ApplicationEvent onAddPressed() { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, null); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } public static class ReportImageAttachmentsListFormArguments { private Job job; public ReportImageAttachmentsListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportImageAttachmentsNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.support.v7.widget.AppCompatRadioButton; import android.support.v7.widget.GridLayout; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportImageAttachmentsListForm.ReportImageAttachmentsListFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportImageAttachmentsNewEditForm extends DialogForm { private static Log log = LogFactory.getLog(ReportImageAttachmentsNewEditForm.class); // initialized by the kolibri framework... public static ServiceApplication app; private Job job; private Bitmap bitmap; private JobFile jobFile; private ImageView image; private ActionCtrl sendAction; private AppCompatRadioButton internalRadioButton; private AppCompatRadioButton externalRadioButton; private MDEditText messages; private TextView messageLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; protected Context context; protected DefaultListWidget listWidget; protected LinearLayout view; private ActionUtil actionUtil; private LinearLayout sentDateLinearLayout; private TextView sentDateText; private Button deleteButton; private boolean isSent = false; @Override public void onFormCall(Object argument) { if (argument instanceof ReportImageAttachmentsNewEditFormArguments) { ReportImageAttachmentsNewEditFormArguments formArguments = (ReportImageAttachmentsNewEditFormArguments) argument; job = formArguments.getJob(); bitmap = formArguments.getBitmap(); jobFile = formArguments.getJobFile(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; actionUtil = new ActionUtil(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); sendAction = addActionCtrl(false, true, 1, "onSendingReportImage"); //$NON-NLS-1$ // set invisible save button saveButton.setVisible(false); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_CENTER); image.setMaxHeight(800); image.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { actionUtil.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap result) { if(bitmap == null) return; bitmap = result; image.setImageBitmap(bitmap); } }, null); return false; } }); contentLinearLayout.addView(image); RadioGroup radioGroup = new RadioGroup(context); radioGroup.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); radioGroup.setPadding(2, 2, 2, 2); radioGroup.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.addView(radioGroup); ColorStateList colorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_enabled } }, new int[] { LayoutUtils.DEFAULT_TEXT_COLOR }); internalRadioButton = new AppCompatRadioButton(context); internalRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 3f)); internalRadioButton.setText(ServiceMessages.getString("internal")); //$NON-NLS-1$ internalRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); internalRadioButton.setSupportButtonTintList(colorStateList); internalRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); internalRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(internalRadioButton); externalRadioButton = new AppCompatRadioButton(context); externalRadioButton.setLayoutParams(new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); externalRadioButton.setText(ServiceMessages.getString("external")); //$NON-NLS-1$ externalRadioButton.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); externalRadioButton.setSupportButtonTintList(colorStateList); externalRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); externalRadioButton.setTypeface(CommonConstants.Font.getDefaultRegularFont()); radioGroup.addView(externalRadioButton); messages = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("description"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); messages.setSingleLine(false); messages.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); messageLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); sentDateLinearLayout = new LinearLayout(context); sentDateLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); sentDateLinearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); sentDateLinearLayout.setOrientation(LinearLayout.VERTICAL); GridLayout sentTimeGridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); sentTimeGridLayout.setLayoutParams(gridLayoutParams); sentTimeGridLayout.setColumnCount(2); sentTimeGridLayout.setUseDefaultMargins(true); TextView gridTextViewKey = new TextView(context); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.2f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(ServiceMessages.getString("sentDate")); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); sentTimeGridLayout.addView(gridTextViewKey); RelativeLayout gridRelativeLayout = new RelativeLayout(context); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.8f); gridRelativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); sentDateText = new TextView(context); sentDateText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); sentDateText.setTypeface(CommonConstants.Font.getDefaultRegularFont()); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_LEFT, RelativeLayout.TRUE); sentDateText.setLayoutParams(gridTextViewValueParams); sentDateText.setText("-"); sentDateText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); gridRelativeLayout.addView(sentDateText); sentTimeGridLayout.addView(gridRelativeLayout); sentDateLinearLayout.addView(sentTimeGridLayout); contentLinearLayout.addView(sentDateLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { actionDelete(); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(contentLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("image")); //$NON-NLS-1$ messages.getText().clear(); image.setImageBitmap(null); sentDateText.setText(""); isSent = false; if (jobFile == null) { image.setImageBitmap(bitmap); if(!internalRadioButton.isChecked() && !externalRadioButton.isChecked()) { internalRadioButton.setChecked(true); } } else { bitmap = jobFile.getSignPicBitmap(); image.setImageBitmap(bitmap); if("I".equalsIgnoreCase(jobFile.getType())) { internalRadioButton.setChecked(true); externalRadioButton.setChecked(false); } else { internalRadioButton.setChecked(false); externalRadioButton.setChecked(true); } if(!jobFile.getDescription().isEmpty()) messages.setText(jobFile.getDescription()); if (jobFile.getSentDate().getTime() > 0) { isSent = true; sentDateText.setText(DateTimeUtil.HtmlDateTime(jobFile.getSentDate())); } } setControlsEnabled(); return null; } private String getType() { if(internalRadioButton.isChecked()) { return "I"; } return "E"; } @Override public ApplicationEvent onBackPressed() { saveImage(); return app.leaveToForm(ReportImageAttachmentsListForm.class, new ReportImageAttachmentsListFormArguments(job)); } private void saveImage() { if (jobFile == null) { jobFile = new JobFile(); Date date = new Date(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setGuid(job.getLatestReport().getGuId()); jobFile.setJobNumber(job.getJobNumber()); jobFile.setJobType(job.getJobType()); jobFile.setType(getType()); jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); app.dbutil.insertJobFile(jobFile); } else { jobFile.setType(getType()); jobFile.setDescription(messages.getText().toString()); jobFile.setSignPicBitmap(bitmap); app.dbutil.updateJobFile(jobFile); } } private void actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } app.showMessage(ServiceMessages.getString("fileDeleted")); if(jobFile != null) { db.startTransaction(); try { app.dbutil.deleteJobFile(jobFile); } finally { db.commit(); } return onBackPressed(); } return app.leaveToForm(ReportImageAttachmentsListForm.class, new ReportImageAttachmentsListFormArguments(job)); } }; } public ApplicationEvent onSendingReportImage() { sendAction.setEnabled(false); saveImage(); if (new RemoteTransactionHandler().runSavePicture(jobFile)) { jobFile.setSentDate(new Date()); isSent = true; sentDateText.setText(DateTimeUtil.HtmlDateTime(jobFile.getSentDate())); app.dbutil.updateJobFile(jobFile); } setControlsEnabled(); return null; } private void setControlsEnabled() { if (isSent) { sendAction.setEnabled(false); sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { sendAction.setEnabled(true); sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); } image.setEnabled(!isSent); internalRadioButton.setClickable(!isSent); externalRadioButton.setClickable(!isSent); internalRadioButton.setTextColor(isSent? LayoutUtils.DEFAULT_LABEL_COLOR:LayoutUtils.DEFAULT_TEXT_COLOR); externalRadioButton.setTextColor(isSent? LayoutUtils.DEFAULT_LABEL_COLOR:LayoutUtils.DEFAULT_TEXT_COLOR); messages.setEnabled(!isSent); deleteButton.setEnabled(!isSent); sentDateLinearLayout.setVisibility(isSent ? View.VISIBLE:View.GONE); sentDateText.setVisibility(isSent ? View.VISIBLE:View.GONE); } public static class ReportImageAttachmentsNewEditFormArguments { private Job job; private Bitmap bitmap; private JobFile jobFile; public ReportImageAttachmentsNewEditFormArguments(Job zkdmob ,Bitmap bitmap, JobFile jobFile) { this.job = zkdmob; this.bitmap = bitmap; this.jobFile = jobFile; } public Job getJob() { return job; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public JobFile getJobFile() { return jobFile; } public void setJobFile(JobFile jobFile) { this.jobFile = jobFile; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportMaterialListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.support.v7.widget.GridLayout; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Billing; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.MaterialListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.MaterialListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.forms.ReportMaterialNewEditForm.ReportMaterialNewEditFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; /** * New Form. */ public class ReportMaterialListForm extends SuperForm { private static Log log = LogFactory.getLog(ReportMaterialListForm.class); protected Job job; protected MaterialListWidget listWidget; private LinearLayout listLinearLayout; private TextView summayPriceTextView; int materialType; private ReportMaterial selectedReportMaterial; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportMaterialListFormArguments) { ReportMaterialListFormArguments formArguments = (ReportMaterialListFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); // GridLayout priceGridLayout = new GridLayout(context); RelativeLayout.LayoutParams priceGridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); priceGridLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, 65), LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 52), LayoutUtils.convertDpToPixel(context, 10)); priceGridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); priceGridLayout.setLayoutParams(priceGridLayoutParams); priceGridLayout.setColumnCount(2); priceGridLayout.setUseDefaultMargins(true); Drawable[] drawables = new Drawable[] { new ColorDrawable(Color.LTGRAY), new ColorDrawable(Color.WHITE)}; LayerDrawable borderDrawable = new LayerDrawable(drawables); // Set padding for background color layer borderDrawable.setLayerInset(1, // Index of the drawable to adjust [background color layer] 0, // Number of pixels to add to the left bound [left border] 0, // Number of pixels to add to the top bound [top border] 0, // Number of pixels to add to the right bound [right border] 4 // Number of pixels to add to the bottom bound [bottom border] ); priceGridLayout.setBackground(borderDrawable); TextView gridTextViewKey = new TextView(priceGridLayout.getContext()); GridLayout.LayoutParams gridTextViewKeyParams = new GridLayout.LayoutParams(); gridTextViewKeyParams.width = 0; gridTextViewKeyParams.height = LayoutParams.WRAP_CONTENT; gridTextViewKeyParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1, 0.5f); gridTextViewKey.setLayoutParams(gridTextViewKeyParams); gridTextViewKey.setText(ServiceMessages.getString("summaryTotal")); gridTextViewKey.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); gridTextViewKey.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); gridTextViewKey.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); priceGridLayout.addView(gridTextViewKey); RelativeLayout gridRelativeLayout = new RelativeLayout(priceGridLayout.getContext()); GridLayout.LayoutParams gridRelativeLayoutParams = new GridLayout.LayoutParams(); gridRelativeLayoutParams.width = 0; gridRelativeLayoutParams.height = LayoutParams.WRAP_CONTENT; gridRelativeLayoutParams.columnSpec = GridLayout.spec(1, 1, 0.5f); gridRelativeLayout.setLayoutParams(gridRelativeLayoutParams); summayPriceTextView = new TextView(priceGridLayout.getContext()); summayPriceTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); summayPriceTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); RelativeLayout.LayoutParams gridTextViewValueParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridTextViewValueParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); summayPriceTextView.setLayoutParams(gridTextViewValueParams); // summayPriceTextView.setText("value"); // gridTextViewValue.setTextColor(textColor); gridRelativeLayout.addView(summayPriceTextView); priceGridLayout.addView(gridRelativeLayout); contentLinearLayout.addView(priceGridLayout); listLinearLayout = new LinearLayout(context); listLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams listLinearLayoutParams = new LinearLayout.LayoutParams(0,0); listLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; listLinearLayoutParams.height = LayoutParams.FILL_PARENT; listLinearLayoutParams.width = LayoutParams.FILL_PARENT; listLinearLayoutParams.weight = 1f; listLinearLayout.setLayoutParams(listLinearLayoutParams); listWidget = new MaterialListWidget(context); listLinearLayout.addView(listWidget); contentLinearLayout.addView(listLinearLayout); view.addView(contentLinearLayout); // create scan action ActionCtrl scanAction = addActionCtrl(false, true, 1, "onScanPressed"); //$NON-NLS-1$ scanAction.setTitle(ServiceMessages.getString("scan")); //$NON-NLS-1$ scanAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_WHITE, CommonConstants.Images.IMAGE_DPI))); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); ActionCtrl actionAdd = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ actionAdd.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("spareParts")); //$NON-NLS-1$ loadMaterialList(); return null; } private void loadMaterialList() { listWidget.clean(); ArrayList items = new ArrayList(); List reportMaterialList = app.dbutil.selectReportMaterialList(job.getCurrentReport().getGuId()); float summayPrice = 0; // Re: MIG-379 Release 2.1.8: No validation for "No material used" // The checkbox should not be activated without user input, even if the user enters the material report overview and leave the form without any input. // if(reportMaterialList.isEmpty()) { // if(!job.getLatestReport().isNoMaterial()) { // job.getLatestReport().setNoMaterial(true); // DatabaseUtil.getInstance().updateReport(job.getLatestReport()); // } // } for (int i = 0; i < reportMaterialList.size(); i++) { final ReportMaterial reportMaterial = reportMaterialList.get(i); final MaterialListWidgetItem item = new MaterialListWidgetItem(); // N = normal material, out of masterdata // P = personal material, self created material // K = K-material, without material number String status = "N"; //$NON-NLS-1$ String price = ""; Billing billing = app.dbutil.selectBillingTypeByJobTypeAndCode(job.getJobType(), reportMaterial.getAccountCode()); if (billing != null) { item.setStringLine2(billing.getText()); } if (reportMaterial.isK14()) { status = "K"; //$NON-NLS-1$ price = reportMaterial.getPrice(); } else { Material selectedMaterial = app.dbutil.selectMaterialByMatNo(reportMaterial.getSparePartNumber()); MaterialPerson materialPerson = app.dbutil.selectMaterialPersonByMatNo(reportMaterial.getSparePartNumber()); if (selectedMaterial != null) { reportMaterial.setSparePartNumber(selectedMaterial.getMaterialNumber()); reportMaterial.setProductName(selectedMaterial.getMaterialShortText()); reportMaterial.setUnit(selectedMaterial.getUnit()); price = (billing != null && billing.getCode().equalsIgnoreCase(ServiceConstants.MATERIAL_BILLING_NEW_PRICE)) ? selectedMaterial.getNewPrice():selectedMaterial.getSubstitutePrice(); } else if (materialPerson != null) { reportMaterial.setSparePartNumber(materialPerson.getMaterialNumber()); reportMaterial.setProductName(materialPerson.getMaterialShortText()); status = "P"; //$NON-NLS-1$ } } item.isShowEllipInTextEnd(true); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); item.setStatusColor(LayoutUtils.DEFAULT_MATERIAL_COLOR); item.setStatusType(status); item.setTitleText(reportMaterial.getProductName()); item.setStringLine1(reportMaterial.getAmount() + " " + reportMaterial.getUnit()); //$NON-NLS-1$ if (price.isEmpty()) { item.setStringPrice("-"); } else { float floatPeice = Float.valueOf(price); float sum = floatPeice * Float.valueOf(reportMaterial.getAmount()); log.info("sum = " + sum); item.setStringPrice(price.isEmpty() ? "-" : formatDecimal(sum)); summayPrice += sum; } item.setStringPrice(price); log.info(price); item.setReplacement(reportMaterial.isDelivery() ? ServiceMessages.getString("additionalDelivery") :""); item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedReportMaterial = reportMaterial; if (v instanceof ImageButton) { onDeletePressed(); } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(reportMaterialList)); } summayPriceTextView.setText(summayPrice > 0? formatDecimal(summayPrice): "-"); listWidget.addItems(items); } private String formatDecimal (float floatValue) { try { log.info("user language " + app.dbutil.getUser().getLanguage()); Locale locale = Locale.ENGLISH; if (app.dbutil.getUser().getLanguage().contains("D")) { //locale = Locale.GERMAN;// outbut = 3.347,20 } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("#,###.00", symbols); format.setMaximumFractionDigits(2); return format.format(floatValue); } catch (NumberFormatException e) { } return ""; } private void onDeletePressed() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { app.dbutil.deleteReportMaterial(selectedReportMaterial); List listParts = app.dbutil.selectReportMaterialList(job.getCurrentReportGuId(app.dbutil)); for (int i = 0; i < listParts.size(); i++) { app.dbutil.updateReportMaterialIdx(listParts.get(i), i); } } finally { db.commit(); } app.showMessage(ServiceMessages.getString("materialWasDeleted")); //$NON-NLS-1$ return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); loadMaterialList(); } }; } private OnItemClickListener createOnItemClickListener(final List reportMatList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { ReportMaterial reportMaterial = reportMatList.get(position); app.injectAndLeaveToForm(ReportMaterialNewEditForm.class, new ReportMaterialNewEditFormArguments(job, reportMaterial, reportMaterial.isK14(), "")); //$NON-NLS-1$ } }; } protected ApplicationEvent onAddPressed() { showMaterialDialog(job); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } protected ApplicationEvent onScanPressed() { new AsyncTask(this) { private String barcode; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(ReportMaterialListForm.this); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { app.showMessage(result.toString()); barcode = result.getContents(); log.info("scan result -> " + result.getContents()); //$NON-NLS-1$ return app.leaveToForm(ReportMaterialNewEditForm.class, new ReportMaterialNewEditFormArguments(job, null, false, barcode)); } return null; } }; return null; } private void showMaterialDialog(final Job job) { String[] items = { ServiceMessages.getString("normalMaterial"), ServiceMessages.getString("K14Material") }; //$NON-NLS-1$ //$NON-NLS-2$ MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("typeOfMaterial"),ServiceMessages.getString("cancel")); //$NON-NLS-1$ //$NON-NLS-2$ alertDialog.setSingleChoiceItems(items, materialType, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { materialType = which; } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new OnClickListener() { //$NON-NLS-1$ public void onClick(android.content.DialogInterface dialog, int which) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportMaterialNewEditForm.class, new ReportMaterialNewEditFormArguments(job, null, materialType == 1, "")); //$NON-NLS-1$ } }, false); } }); alertDialog.show(); } public static class ReportMaterialListFormArguments { private Job job; public ReportMaterialListFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportMaterialNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.content.Context; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Billing; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Material; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialPerson; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.MaterialSearchForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.AmountEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDCheckBox; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.MaterialSearchView.SuggessionItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportMaterialListForm.ReportMaterialListFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; public class ReportMaterialNewEditForm extends MaterialSearchForm { private static Log log = LogFactory.getLog(ReportMaterialNewEditForm.class); public static ServiceApplication app; // don't make this CommonApplication private Job job; private ReportMaterial part; private boolean isKMaterial; private MDEditText priceEditText; private MDSpinner billingeTypeValue; private AmountEditText amountEditText; private MDSpinner unitValueText; private MDEditText sizeEditText; public MDEditText barcodeEditText; private MDCheckBox otherTypeCheckBox; private MDCheckBox expressCheckBox; private MDEditText explanation; private TextView explanationLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; public Button deleteButton; private Material selectedMaterial = null; private MaterialPerson selectedMaterialPerson = null; @Override public void onFormCall(Object argument) { if (argument instanceof ReportMaterialNewEditFormArguments) { ReportMaterialNewEditFormArguments formArguments = (ReportMaterialNewEditFormArguments) argument; job = formArguments.getJob(); part = formArguments.getPart(); isKMaterial = formArguments.isK14; barcode = formArguments.getBarcode(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); saveButton.setVisible(false); numberEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { return null; } @Override protected void runOnUIThread() { if (!hasFocus) { if (numberEditText.getText().toString().startsWith(CommonConstants.Material.NUMBER_PREFIX) && numberEditText.getText().toString().length() == 3) { numberEditText.setText(""); } if (numberEditText.getText().toString().isEmpty()) { numberEditText.clearError(); return; } Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } else { loadMaterialsList(numberEditText.getText().toString()); if(selectedMaterial != null || selectedMaterialPerson != null) { // hideSoftInputFromWindow(); } } } else { if (numberEditText.getText().toString().isEmpty()) { numberEditText.setText(CommonConstants.Material.NUMBER_PREFIX + "-"); } } } }; } }); nameEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { loadMaterialsList(nameEditText.getText().toString()); } else { nameEditText.clearError(); } } }); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout detailItemLinearLayout = new LinearLayout(context); detailItemLinearLayout.setOrientation(LinearLayout.HORIZONTAL); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); priceEditText = MDEditText.createDefaultEditText(detailItemLinearLayout, ServiceMessages.getString("price"), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL, false); //$NON-NLS-1$ priceEditText.setTag("PRICE"); //$NON-NLS-1$ priceEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.ELEVEN) }); priceEditText.setEnabled(false); priceEditText.setDirectionRight(false); priceEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { priceEditText.setText(getPrice()); } else { String userInput = priceEditText.getText().toString(); // if (userInput.startsWith(CommonConstants.TimeSheet.EXPENSES_PREFIX)) { // userInput = userInput.replaceAll(CommonConstants.TimeSheet.EXPENSES_PREFIX, ""); // } // String temps[] = userInput.split(" "); // if (temps.length > 1 && !TextUtils.isEmpty(temps[1])) { // userInput = temps[1]; // } priceEditText.setTextAndSelection(userInput); } } }); LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); priceInputLayoutParams.gravity = Gravity.CENTER; priceInputLayoutParams.width = 0; priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; priceInputLayoutParams.weight = 0.3f; priceEditText.getParentTextInputLayout().setLayoutParams(priceInputLayoutParams); final LinearLayout billingLinearLayout = new LinearLayout(context); billingLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams billingValueParams = new LinearLayout.LayoutParams(0, 0); billingValueParams.gravity = Gravity.CENTER | Gravity.LEFT; billingValueParams.width = 0; billingValueParams.height = LayoutParams.MATCH_PARENT; billingValueParams.weight = 0.7f; billingLinearLayout.setLayoutParams(billingValueParams); billingeTypeValue = MDSpinner.createDefaultSpinner(billingLinearLayout, Messages.getString("billing"), true); //$NON-NLS-1$ billingeTypeValue.setTag("BILLING"); //$NON-NLS-1$ billingeTypeValue.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (part != null && selectedMaterial == null) { selectedMaterial = app.dbutil.selectMaterialByMatNo(part.getSparePartNumber()); } setPrice(); } }); detailItemLinearLayout.addView(billingLinearLayout); contentLinearLayout.addView(detailItemLinearLayout); LinearLayout stockItemLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); stockItemLinearLayout.setOrientation(LinearLayout.HORIZONTAL); amountEditText = AmountEditText.createDefaultEditText(stockItemLinearLayout, ServiceMessages.getString("amount"), true); //$NON-NLS-1$ LinearLayout.LayoutParams stockInputLayoutParams = new LinearLayout.LayoutParams(0, 0); stockInputLayoutParams.gravity = Gravity.CENTER; stockInputLayoutParams.width = 0; stockInputLayoutParams.height = LayoutParams.MATCH_PARENT; stockInputLayoutParams.weight = 0.3f; amountEditText.getParentTextInputLayout().setLayoutParams(stockInputLayoutParams); // Unit final LinearLayout mUnitValueLinearLayout = new LinearLayout(context); mUnitValueLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams mUnitValueParams = new LinearLayout.LayoutParams(0, 0); mUnitValueParams.gravity = Gravity.LEFT; mUnitValueParams.width = 0; mUnitValueParams.height = LayoutParams.MATCH_PARENT; mUnitValueParams.weight = 0.3f; mUnitValueLinearLayout.setLayoutParams(mUnitValueParams); unitValueText = MDSpinner.createDefaultSpinner(mUnitValueLinearLayout, ServiceMessages.getString("unit"), false); //$NON-NLS-1$ unitValueText.setTag("UNIT"); //$NON-NLS-1$ unitValueText.setEnabled(false); LinearLayout.LayoutParams unitValueUnderlineLinearLayout = (LinearLayout.LayoutParams) billingeTypeValue.getUnderline().getLayoutParams(); unitValueUnderlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); unitValueText.getUnderline().setLayoutParams(unitValueUnderlineLinearLayout); unitValueText.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView parent) { } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { unitValueText.clearError(); if (isKMaterial) { numberEditText.setInputType(InputType.TYPE_CLASS_TEXT); numberEditText.removeTextChangedListener(materialNumberMaskWatcher); numberEditText.setText(getKmaterialNumberByUnit(unitValueText.getSelectedId())); } else { numberEditText.setInputType(InputType.TYPE_CLASS_PHONE); numberEditText.addTextChangedListener(materialNumberMaskWatcher); } } }); stockItemLinearLayout.addView(mUnitValueLinearLayout); sizeEditText = MDEditText.createDefaultEditText(stockItemLinearLayout, Messages.getString("Containersize"), InputType.TYPE_CLASS_PHONE, false); //$NON-NLS-1$ sizeEditText.setTag("SIZE"); //$NON-NLS-1$ sizeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); sizeEditText.setEnabled(false); LinearLayout.LayoutParams sizeInputLayoutParams = new LinearLayout.LayoutParams(0, 0); sizeInputLayoutParams.gravity = Gravity.LEFT; sizeInputLayoutParams.width = 0; sizeInputLayoutParams.height = LayoutParams.MATCH_PARENT; sizeInputLayoutParams.weight = 0.3f; sizeEditText.getParentTextInputLayout().setLayoutParams(sizeInputLayoutParams); contentLinearLayout.addView(stockItemLinearLayout); LinearLayout barcodeLinearLayout = new LinearLayout(context); barcodeLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams barcodeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLinearLayoutParams.gravity = Gravity.CENTER; barcodeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLinearLayoutParams.weight = 1; barcodeLinearLayout.setLayoutParams(barcodeLinearLayoutParams); barcodeEditText = MDEditText.createDefaultEditText(barcodeLinearLayout, ServiceMessages.getString("GuaranteeMaterial"), InputType.TYPE_CLASS_NUMBER, false); //$NON-NLS-1$ barcodeEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY) }); // LinearLayout.LayoutParams priceInputLayoutParams = new LinearLayout.LayoutParams(0, 0); // priceInputLayoutParams.gravity = Gravity.CENTER; // priceInputLayoutParams.width = 0; // priceInputLayoutParams.height = LayoutParams.MATCH_PARENT; // priceInputLayoutParams.weight = 0.3f; LinearLayout.LayoutParams barcodeLayoutParams = new LinearLayout.LayoutParams(0, 0); barcodeLayoutParams.gravity = Gravity.CENTER; barcodeLayoutParams.width = 0; barcodeLayoutParams.height = LayoutParams.MATCH_PARENT; barcodeLayoutParams.weight = 0.9f; barcodeEditText.getParentTextInputLayout().setLayoutParams(barcodeLayoutParams); barcodeEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (s.toString().isEmpty() && explanation.isRequired()) { explanation.setRequired(false); explanation.clearError(); } if (!s.toString().isEmpty() && !explanation.isRequired()) { explanation.setRequired(true); } } }); final LinearLayout cameraLinearLayout = new LinearLayout(context); cameraLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams cameraValueParams = new LinearLayout.LayoutParams(0, 0); cameraValueParams.gravity = Gravity.BOTTOM | Gravity.LEFT; cameraValueParams.width = 0; cameraValueParams.height = LayoutParams.MATCH_PARENT; cameraValueParams.weight = 0.1f; cameraValueParams.topMargin = 25; cameraLinearLayout.setLayoutParams(cameraValueParams); ImageView gridImageView = new ImageView(context); RelativeLayout.LayoutParams gridImageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); gridImageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); gridImageViewParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE); gridImageView.setLayoutParams(gridImageViewParams); gridImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CAMERA_BLACK, CommonConstants.Images.IMAGE_DPI))); gridImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(app.getCurrentForm()) { private String barcode = ""; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { ZXingBarcodeScanner s = new ZXingBarcodeScanner(app.getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will ReportMaterialListForm if (result == null) { app.showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ } else { barcode = result.getContents(); } return null; } @Override public void runOnUIThread() { if (!barcode.isEmpty()) { barcodeEditText.setInputType(InputType.TYPE_CLASS_TEXT); barcodeEditText.setText(barcode); barcodeEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } } }; } }); cameraLinearLayout.addView(gridImageView); barcodeLinearLayout.addView(cameraLinearLayout); contentLinearLayout.addView(barcodeLinearLayout); explanation = MDEditText.createDefaultEditText(contentLinearLayout, ServiceMessages.getString("explanationForReturn"), InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ explanation.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); explanation.setSingleLine(false); explanation.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { explanationLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); explanationLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; explanationLengthView.setLayoutParams(messageLengthViewParams); explanationLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(explanationLengthView); LinearLayout expressOtherTypeLinearLayout = new LinearLayout(context); expressOtherTypeLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams expressOtherTypeLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); expressOtherTypeLinearLayoutParams.gravity = Gravity.CENTER; expressOtherTypeLinearLayoutParams.width = LayoutParams.MATCH_PARENT; expressOtherTypeLinearLayoutParams.height = LayoutParams.MATCH_PARENT; expressOtherTypeLinearLayoutParams.weight = 0.5f; expressOtherTypeLinearLayout.setLayoutParams(expressOtherTypeLinearLayoutParams); LinearLayout.LayoutParams otherTypeCheckBoxLayoutParams = new LinearLayout.LayoutParams(0, 0); otherTypeCheckBoxLayoutParams.gravity = Gravity.CENTER; otherTypeCheckBoxLayoutParams.width = 0; otherTypeCheckBoxLayoutParams.height = LayoutParams.MATCH_PARENT; otherTypeCheckBoxLayoutParams.weight = 0.5f; otherTypeCheckBox = MDCheckBox.createDefaultCheckBox(expressOtherTypeLinearLayout, ServiceMessages.getString("otherTypeOfMaterial")); //$NON-NLS-1$ ((LinearLayout) otherTypeCheckBox.getParent()).setLayoutParams(otherTypeCheckBoxLayoutParams); LinearLayout.LayoutParams expressCheckBoxLayoutParams = new LinearLayout.LayoutParams(0, 0); expressCheckBoxLayoutParams.gravity = Gravity.CENTER; expressCheckBoxLayoutParams.width = 0; expressCheckBoxLayoutParams.height = LayoutParams.MATCH_PARENT; expressCheckBoxLayoutParams.weight = 0.5f; expressCheckBox = MDCheckBox.createDefaultCheckBox(expressOtherTypeLinearLayout, ServiceMessages.getString("additionalDelivery")); //$NON-NLS-1$ ((LinearLayout) expressCheckBox.getParent()).setLayoutParams(expressCheckBoxLayoutParams); contentLinearLayout.addView(expressOtherTypeLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setText(Messages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (part == null) { resetView(); return; } appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("areYouSureWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } db.startTransaction(); try { DatabaseUtil.getInstance().deleteReportMaterial(part); List listParts = DatabaseUtil.getInstance().selectReportMaterialList(job.getCurrentReportGuId(DatabaseUtil.getInstance())); for (int i = 0; i < listParts.size(); i++) { DatabaseUtil.getInstance().updateReportMaterialIdx(listParts.get(i), i); } } finally { db.commit(); } return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } }, false); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); addContentLinearLayout(contentLinearLayout); return view; } private String getPrice(){ String userInput = priceEditText.getText().toString(); String temp = StringUtil.removeLettersAndCountDot(userInput, '.'); if (temp.isEmpty()) { return ""; } try { Locale locale = Locale.ENGLISH; if (temp.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(temp))); if (floatValue > 499.99) { floatValue = (float) 499.99; } DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("##0.00", symbols); format.setMaximumFractionDigits(2); if (floatValue > 0) { temp = format.format(floatValue); userInput = temp; } else { userInput = ""; } } catch (NumberFormatException e) { return ""; } catch (ParseException e) { return ""; } return userInput; } @Override protected void loadData() { super.loadData(); fillBillingTypeCombo(); fillUnitCombo(); searchView.setQuery("", false); //$NON-NLS-1$ searchView.clearFocus(); if (part == null) { resetView(); deleteButton.setText(ServiceMessages.getString("clear")); //$NON-NLS-1$ searchView.setVisibility(View.VISIBLE); } else { nameEditText.setText(part.getProductName()); numberEditText.setText(part.getSparePartNumber()); priceEditText.setText(part.getPrice()); // format with CHF priceEditText.setText(getPrice()); billingeTypeValue.setSelectionById(part.getAccountCode()); amountEditText.setText(part.getAmount()); //$NON-NLS-1$ //$NON-NLS-2$ barcodeEditText.setText(part.getBarcode()); unitValueText.setSelectionById(part.getUnit()); expressCheckBox.setChecked(part.isDelivery()); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ barcodeEditText.setText(part.getBarcode()); explanation.setText(part.getExplanationText()); otherTypeCheckBox.setChecked(part.isOtherType()); searchView.setVisibility(View.INVISIBLE); } if (isKMaterial) { priceEditText.setRequired(true); unitValueText.setRequired(true); numberEditText.setRequired(false); numberEditText.setEnabled(false); priceEditText.setEnabled(true); unitValueText.setEnabled(true); String value = ServiceConstants.KMaterialNumber.K_14; if (part != null && !part.getUnit().isEmpty()) { value =part.getUnit(); } unitValueText.setSelectionById(value); expressCheckBox.setEnabled(false); } else { priceEditText.setRequired(false); unitValueText.setRequired(false); numberEditText.setRequired(true); numberEditText.setEnabled(true); priceEditText.setEnabled(false); unitValueText.setEnabled(false); expressCheckBox.setEnabled(true); } System.out.println("loadData barcode " + barcode); } @Override public void loadMaterialsList(String queryText) { searchView.getSuggessionItemList().clear(); List materialList = app.dbutil.selectMaterialListByMatNrAndMatName(queryText, queryText); List materialPersonList = app.dbutil.selectMaterialPersonListByMatNoAndMatName(queryText, queryText); for (Material matPart : materialList) { searchView.getSuggessionItemList().add(new SuggessionItem(matPart.getMaterialNumber(), matPart.getMaterialShortText())); } for (MaterialPerson zkdmobmatpers : materialPersonList) { searchView.getSuggessionItemList().add(new SuggessionItem(zkdmobmatpers.getMaterialNumber(), zkdmobmatpers.getMaterialShortText())); } int matHits = materialList.size() + materialPersonList.size(); if (matHits > 0 && matHits == 1) { // Exactly found an article from the StammMat if (materialList.size() == 1) { selectedMaterial = materialList.get(0); } else if (materialPersonList.size() == 1) { // Exactly found an article from PersMat selectedMaterialPerson = materialPersonList.get(0); } } if (selectedMaterial != null) { unitValueText.setSelectionById(selectedMaterial.getUnit().toUpperCase()); setPrice(); amountEditText.getText().clear(); barcodeEditText.getText().clear(); expressCheckBox.setChecked(false); } else if (selectedMaterialPerson != null) { amountEditText.getText().clear(); barcodeEditText.getText().clear(); sizeEditText.getText().clear(); unitValueText.setSelection(0); expressCheckBox.setChecked(false); explanation.getText().clear(); } if (isKMaterial) { numberEditText.setText(getKmaterialNumberByUnit(unitValueText.getSelectedId())); } } private void fillBillingTypeCombo() { List billingValueList = new ArrayList(); List billings = app.dbutil.selectBillingTypeListByJobType(job.getJobType()); for (Billing billing : billings) { log.info("VRCD (id) " + billing.getCode() + " Text " + billing.getText()); billingValueList.add(new CustomSpinnerItem((String) billing.getCode(), billing.getText())); } billingeTypeValue.setContents(billingValueList); } private void fillUnitCombo() { List unitValueList = new ArrayList(); unitValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, Messages.getString("pleaseSelect"))); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.M, ServiceConstants.MatUnit.M)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.MM, ServiceConstants.MatUnit.MM)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.KG, ServiceConstants.MatUnit.KG)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueList.add(new CustomSpinnerItem(ServiceConstants.MatUnit.ST, ServiceConstants.MatUnit.ST)); //$NON-NLS-1$ //$NON-NLS-2$ unitValueText.setContents(unitValueList); } @Override protected void resetView() { super.resetView(); priceEditText.clearError(); amountEditText.clearError(); barcodeEditText.clearError(); sizeEditText.clearError(); selectedMaterial = null; selectedMaterialPerson = null; priceEditText.getText().clear(); billingeTypeValue.setSelection(0); billingeTypeValue.clearError(); amountEditText.getText().clear(); barcodeEditText.getText().clear(); sizeEditText.getText().clear(); unitValueText.setSelection(0); unitValueText.clearError(); expressCheckBox.setChecked(false); explanation.getText().clear(); explanation.clearError(); otherTypeCheckBox.setChecked(false); } @Override public ApplicationEvent onBackPressed() { if (isKMaterial) { if (nameEditText.getText().toString().isEmpty()) { return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } } else { if (nameEditText.getText().toString().isEmpty() && numberEditText.getText().toString().isEmpty()) { return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } } new AsyncTask(this) { private List editErrorList = new ArrayList(); private List spinnerErrorList = new ArrayList(); private List checkBoxErrorList = new ArrayList(); @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { editErrorList.clear(); spinnerErrorList.clear(); checkBoxErrorList.clear(); if (nameEditText.getText().toString().isEmpty()) { editErrorList.add(nameEditText); } if (amountEditText.isRequired() && amountEditText.getText().toString().isEmpty()) { editErrorList.add(amountEditText); } if (isKMaterial) { if (priceEditText.getText().toString().isEmpty()) { editErrorList.add(priceEditText); } if (unitValueText.getSelectedItemPosition() == 0) { spinnerErrorList.add(unitValueText); } } else { if (numberEditText.getText().toString().isEmpty()) { editErrorList.add(numberEditText); } } if (explanation.isRequired() && explanation.getText().toString().isEmpty()) { editErrorList.add(explanation); } return null; } @Override public void runOnUIThread() { priceEditText.clearFocus(); amountEditText.clearFocus(); sizeEditText.clearFocus(); barcodeEditText.clearFocus(); numberEditText.clearError(); nameEditText.clearError(); amountEditText.clearError(); sizeEditText.clearError(); priceEditText.clearError(); barcodeEditText.clearError(); explanation.clearError(); // Create a new, empty report object and save it to the database if (job.getLatestReport().getReportStatus().isReceived()) { DatabaseUtil.getInstance().insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(DatabaseUtil.getInstance()), job.getNextReportIdx(DatabaseUtil.getInstance()), job.isCycleOfInstallationFlag())); job.loadReports(DatabaseUtil.getInstance()); } if (editErrorList.isEmpty() && spinnerErrorList.isEmpty() && checkBoxErrorList.isEmpty()) { if ((part == null) && (selectedMaterial == null) && (selectedMaterialPerson == null) && !isKMaterial) { if (addMaterialPerson()) { insertUpdateMaterial(); } } else { insertUpdateMaterial(); } } else { if (!editErrorList.isEmpty()) { for (MDEditText errorText : editErrorList) { errorText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ } } if (!spinnerErrorList.isEmpty()) { for (MDSpinner spinner : spinnerErrorList) { spinner.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } if (!checkBoxErrorList.isEmpty()) { for (MDCheckBox checkBox : checkBoxErrorList) { checkBox.setError(ServiceMessages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } } } }; return null; } private void insertUpdateMaterial() { insertUpdateSpareParts(); app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return app.leaveToForm(ReportMaterialListForm.class, new ReportMaterialListFormArguments(job)); } }, false); } private boolean addMaterialPerson() { // Mat: sum of the articles from the excise and the pers. // Mat table (exact match of article number necessary!) loadMaterialsList(nameEditText.getText().toString()); String materialName = ""; if (selectedMaterial != null) { materialName = selectedMaterial.getMaterialShortText(); } else if (selectedMaterialPerson != null) { materialName = selectedMaterialPerson.getMaterialShortText(); } if (!materialName.isEmpty() && materialName.equalsIgnoreCase(numberEditText.getText().toString())) { MessageUtil.getInstance().showMessage(ServiceMessages.getString("materialWithThisNameAlreadyExists")); return false; } loadMaterialsList(numberEditText.getText().toString()); if(!numberEditText.getText().toString().isEmpty() && !nameEditText.getText().toString().isEmpty()) { String materialNumber = ""; if (selectedMaterial != null) { materialNumber = selectedMaterial.getMaterialNumber(); } else if (selectedMaterialPerson != null) { materialNumber = selectedMaterialPerson.getMaterialNumber(); } if (!materialNumber.isEmpty() && materialNumber.equalsIgnoreCase(numberEditText.getText().toString())) { MessageUtil.getInstance().showMessage(ServiceMessages.getString("materialWithThisNumberAlreadyExists")); return false; } } if (!isKMaterial) { // Article does not yet exist and can be used as Pers. Mat Pattern pattern = Pattern.compile(CommonConstants.Material.REGEX); Matcher matcher = pattern.matcher(numberEditText.getText().toString()); if (!matcher.matches()) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { app.showMessageBox(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ return null; } @Override public void runOnUIThread() { numberEditText.setError(ServiceMessages.getString("WrongFormatXX-XXXX-XXX/XX")); //$NON-NLS-1$ } }; return false; } } selectedMaterialPerson = new MaterialPerson(); selectedMaterialPerson.setMaterialNumber(numberEditText.getText().toString()); selectedMaterialPerson.setMaterialShortText(nameEditText.getText().toString()); app.dbutil.insertMaterialPerson(selectedMaterialPerson); return true; } private void insertUpdateSpareParts() { ReportMaterial reportMaterial = new ReportMaterial(); boolean newReportMaterial = part == null; if (part != null) { reportMaterial = part; } else { reportMaterial.setGuid(job.getLatestReport().getGuId()); reportMaterial.setPersonalNumber(app.dbutil.getUser().getPersonalNumber()); reportMaterial.setCommissionNumber(job.getCommissionNumber()); reportMaterial.setExpressDelivery(""); //$NON-NLS-1$ } reportMaterial.setAmount(amountEditText.getText().toString()); reportMaterial.setDelivery(expressCheckBox.isChecked()); reportMaterial.setAccountCode(billingeTypeValue.getSelectedId()); reportMaterial.setProductName(nameEditText.getText().toString()); reportMaterial.setSparePartNumber(numberEditText.getText().toString()); reportMaterial.setUnit(unitValueText.getSelectedItemPosition() == 0 ? "" : unitValueText.getSelectedId()); reportMaterial.setBarcode(barcodeEditText.getText().toString()); reportMaterial.setExplanationText(explanation.getText().toString()); reportMaterial.setOtherType(otherTypeCheckBox.isChecked()); reportMaterial.setK14(isKMaterial); reportMaterial.setPrice(isKMaterial ? getPrice().replace("0.0", "") : ""); if (newReportMaterial) { app.dbutil.insertNewReportMaterial(reportMaterial); } else { app.dbutil.updateReportMaterial(reportMaterial); } } public static class ReportMaterialNewEditFormArguments { private Job job; private ReportMaterial part; private boolean isK14; private String barcode; public ReportMaterialNewEditFormArguments(Job job, ReportMaterial part, boolean isK14, String barcode) { this.job = job; this.part = part; this.isK14 = isK14; this.barcode = barcode; } public Job getJob() { return job; } public ReportMaterial getPart() { return part; } public boolean isK14() { return isK14; } public String getBarcode() { return barcode; } } private String getKmaterialNumberByUnit(String unit) { if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.M)) { return ServiceConstants.KMaterialNumber.K_11; } else if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.MM)) { return ServiceConstants.KMaterialNumber.K_12; } else if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.KG)) { return ServiceConstants.KMaterialNumber.K_13; } else if(unit.equalsIgnoreCase(ServiceConstants.MatUnit.ST)) { return ServiceConstants.KMaterialNumber.K_14; } else { return ServiceConstants.KMaterialNumber.K_Material; } } private void setPrice() { if (selectedMaterial != null) { log.info("billing " + billingeTypeValue.getSelectedId() + " " + billingeTypeValue.getSelectedName()); log.info("new price " + selectedMaterial.getNewPrice()); log.info("Substitute Price " + selectedMaterial.getSubstitutePrice()); if (billingeTypeValue.getSelectedId().equalsIgnoreCase(ServiceConstants.MATERIAL_BILLING_NEW_PRICE)) { priceEditText.setText(selectedMaterial.getNewPrice()); } else { priceEditText.setText(selectedMaterial.getSubstitutePrice()); } priceEditText.setText(getPrice()); } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportMeasurementForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Typeface; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable.OnCheckedChange; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable.OnEnabledChange; import ch.mfiles.kaba.kolibri.service.ui.widgets.MeasurementTable.OnItemsChange; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportMeasurementForm extends SuperForm { private static Log log = LogFactory.getLog(ReportMeasurementForm.class); protected Job job; private Toolbar toolbar; private MeasurementTable measurementTable; private MeasurementTable measurementTable2; private MeasurementTable measurementTable3; private CardView cardView1; private CardView cardView2; private CardView cardView3; private boolean isKmgInstalles = true; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ReportMeasurementFormArguments) { ReportMeasurementFormArguments formArguments = (ReportMeasurementFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); LinearLayout cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); measurementTable = new MeasurementTable(this, app, "01"); measurementTable2 = new MeasurementTable(this, app, "02"); measurementTable3 = new MeasurementTable(this, app, "03"); cardView1 = createCardView(Messages.getString("measurement") + " 1", measurementTable); cardView2 = createCardView(Messages.getString("measurement") + " 2", measurementTable2); cardView3 = createCardView(Messages.getString("measurement") + " 3", measurementTable3); cardLinearLayout.addView(cardView1); cardLinearLayout.addView(cardView2); cardLinearLayout.addView(cardView3); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING , LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); linearLayout.addView(cardLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); scrollView.addView(linearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // check if KMG-LITE app is present PackageManager pm = appman.getContext().getPackageManager(); PackageInfo pckInfo = null; try { pckInfo = pm.getPackageInfo("de.gte.kmglite.blapp", PackageManager.GET_ACTIVITIES); } catch (NameNotFoundException e) { } if (pckInfo == null) { app.showMessage("KMG-LITE App not installed!"); isKmgInstalles = false; } loadMeasurementTables(); return null; } private void loadMeasurementTables() { measurementTable.loadTable(app.dbutil.selectReportMeasurementListByMeasuringPoint(job.getLatestReport(), "01")); measurementTable2.loadTable(app.dbutil.selectReportMeasurementListByMeasuringPoint(job.getLatestReport(), "02")); measurementTable3.loadTable(app.dbutil.selectReportMeasurementListByMeasuringPoint(job.getLatestReport(), "03")); } protected CardView createCardView(String title, MeasurementTable measurementTable) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 0, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MIN_MARGIN); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_MARGIN); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView titleTextView = new TextView(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(title); titleTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); linearLayout.addView(titleTextView); // --------------- content-------------------- linearLayout.addView(measurementTable.getTable()); // --------------- content-------------------- // --------------- button-------------------- linearLayout.addView(createButtonLayout(measurementTable)); // --------------- button-------------------- cardView.addView(linearLayout); return cardView; } private RelativeLayout createButtonLayout(final MeasurementTable measurementTable) { RelativeLayout buttonRelativeLayout = new RelativeLayout(context); RelativeLayout.LayoutParams buttonRelativeLayoutParams = new RelativeLayout.LayoutParams( LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); buttonRelativeLayout.setLayoutParams(buttonRelativeLayoutParams); LinearLayout buttonLinearLayout = new LinearLayout(context); RelativeLayout.LayoutParams buttonLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); buttonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); buttonLayoutParams.topMargin = LayoutUtils.convertDpToPixel(context, 5); buttonLayoutParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 5); buttonLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); buttonLinearLayout.setLayoutParams(buttonLayoutParams); buttonLinearLayout.setOrientation(LinearLayout.HORIZONTAL); final ImageView deleteImageView = new ImageView(context); deleteImageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); LinearLayout.LayoutParams deleteImageViewParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 28), LayoutUtils.convertDpToPixel(context, 28)); deleteImageViewParams.rightMargin = 30; deleteImageView.setLayoutParams(deleteImageViewParams); deleteImageView.setEnabled(false); deleteImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); measurementTable.onCheckedChange(new OnCheckedChange() { @Override public void onCheckedChange(List checkedList) { setButtonDeleteEnabled(deleteImageView, !checkedList.isEmpty()); } }); measurementTable.onEnabledChange(new OnEnabledChange() { @Override public void onEnabledChange(boolean enabled) { setButtonDeleteEnabled(deleteImageView, enabled); } }); deleteImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onDeleted(measurementTable.getCheckedList()); } }); final ImageView scanImageView = new ImageView(context); LinearLayout.LayoutParams scanImageViewParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 28), LayoutUtils.convertDpToPixel(context, 28)); scanImageView.setLayoutParams(scanImageViewParams); scanImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onStartMeasurement(measurementTable.getMeasurementPoint(), measurementTable.getList()); } }); measurementTable.onEnabledChange(new OnEnabledChange() { @Override public void onEnabledChange(boolean enabled) { log.info("onEnabledChange " +enabled ); setButtonScanEnabled(scanImageView, enabled); } }); setButtonScanEnabled(scanImageView, isKmgInstalles); LinearLayout iconLinearLayout = new LinearLayout(context); RelativeLayout.LayoutParams iconLinearLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); iconLinearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); iconLinearLayout.setLayoutParams(iconLinearLayoutParams); iconLinearLayout.setOrientation(LinearLayout.HORIZONTAL); iconLinearLayout.addView(deleteImageView); iconLinearLayout.addView(scanImageView); buttonLinearLayout.addView(iconLinearLayout); final LinearLayout messageLinearLayout = new LinearLayout(context); RelativeLayout.LayoutParams messageLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); messageLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); messageLayoutParams.topMargin = LayoutUtils.convertDpToPixel(context, 5); messageLinearLayout.setLayoutParams(messageLayoutParams); messageLinearLayout.setOrientation(LinearLayout.HORIZONTAL); TextView gridTextViewValue = new TextView(context); gridTextViewValue.setText(ServiceJobUtil.getTooMuchMeasurementAreMadeForOnemeasurePointMessage()); gridTextViewValue.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); messageLinearLayout.addView(gridTextViewValue); buttonRelativeLayout.addView(messageLinearLayout); measurementTable.onItemsChange(new OnItemsChange() { @Override public void onItemsChange() { int visibility = View.GONE; if (measurementTable.getList() != null && measurementTable.getList().size() > ServiceConstants.MAX_MEASUREMENT_FOR_ONE_POINT) { visibility = View.VISIBLE; } messageLinearLayout.setVisibility(visibility); } }); buttonRelativeLayout.addView(buttonLinearLayout); return buttonRelativeLayout; } private void setButtonDeleteEnabled(final ImageView deleteImageView, boolean enabled) { if (enabled) { deleteImageView.setEnabled(true); deleteImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { deleteImageView.setEnabled(false); deleteImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } } private void setButtonScanEnabled(final ImageView scanImageView, boolean enabled) { if (enabled) { scanImageView.setEnabled(true); scanImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.REMOTE_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { scanImageView.setEnabled(false); scanImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.REMOTE_BLACK, CommonConstants.Images.IMAGE_DPI))); } } private void setEnabled(boolean enabled) { measurementTable.setEnabled(enabled); measurementTable2.setEnabled(enabled); measurementTable3.setEnabled(enabled); } private void onDeleted(final List measurements) { if (measurements.isEmpty()) { return; } setEnabled(false); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (app.showMessageBox(ServiceMessages.getString("TheCapturedDataWillBeDeleted"), ServiceMessages.getString("DeleteMeasurement"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { deleteMeasurements(measurements); } return null; } protected void runOnUIThread() { setEnabled(true); loadMeasurementTables(); } }; } private void onStartMeasurement(final String measurementPoint, final List measurements) { setEnabled(false); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { log.warn("Device does not support Bluetooth"); } if (!mBluetoothAdapter.isEnabled()) { app.showWarningMessageBox(ServiceMessages.getString("BluetoothIsNotTurnOn")); setEnabled(true); } else { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { onStartMeasurement(measurementPoint); return null; } protected void runOnUIThread() { setEnabled(true); loadMeasurementTables(); } }; } } private void deleteMeasurements(List measurements) { for (ReportMeasurement reportMeasurement : measurements) { app.dbutil.deleteReportMeasurement(reportMeasurement); } } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } private Intent getMeasuredValues() { Intent result = null; if (isKmgInstalles) { Intent message = new Intent("de.gte.kmglite.blapp.measure"); message.setClassName("de.gte.kmglite.blapp", "de.gte.kmglite.blapp.MeasureInterfaceActivity"); result = appman.startActivityForResult(message); } return result; } protected void onStartMeasurement(String measurementPoint) { boolean measuredValues = true; while (measuredValues) { Intent result = getMeasuredValues(); ReportMeasurement reportMeasurement = null; try { if (result != null) { try { reportMeasurement = parseJson(new JSONObject(result.getStringExtra("measurement"))); } catch (JSONException e) { log.error(e.getMessage()); e.printStackTrace(); } } else { // TODO for test only reportMeasurement = readJsonFile(); measuredValues = false; } } catch (Exception e) { log.info("user cancelled measurement"); } if (reportMeasurement != null) { reportMeasurement.setGuid(job.getCurrentReport().getGuId()); reportMeasurement.setCommissionNumber(job.getCommissionNumber()); reportMeasurement.setMeasurementPoint(measurementPoint); reportMeasurement.setPersonalNumber(job.getPersonalNumber()); int nextMeasurement = app.dbutil.selectNextMeasurementFromReportMeasurement(job.getLatestReport(), measurementPoint); reportMeasurement.setMeasurement((nextMeasurement < 10 ? "0" + nextMeasurement:""+nextMeasurement)); app.dbutil.insertReportMeasurement(reportMeasurement); } } } private ReportMeasurement readJsonFile() { int permissionCheck = ContextCompat.checkSelfPermission(UIActivity.getInstance() , Manifest.permission.READ_EXTERNAL_STORAGE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UIActivity.getInstance() , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE , Manifest.permission.WRITE_EXTERNAL_STORAGE}, ServiceConstants.PERMISSION_REQUEST_CODE); } File jsonFile = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/ch.mfiles.kolibri/files", "KMG-LITE-20200509-154849.json"); try { FileReader fileReader = new FileReader(jsonFile); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuilder stringBuilder = new StringBuilder(); String line = bufferedReader.readLine(); while (line != null){ stringBuilder.append(line).append("\n"); line = bufferedReader.readLine(); } // This responce will have Json Format String String responce = stringBuilder.toString(); JSONObject jsonObject = new JSONObject(responce); return parseJson(jsonObject); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } catch (JSONException e) { log.error(e); } return null; } private ReportMeasurement parseJson(JSONObject jsonObject) { try { ReportMeasurement reportMeasurement = new ReportMeasurement(); reportMeasurement.setDynamicPowerPeakValue(jsonObject.getString("DynamicPower")); reportMeasurement.setStaticEndPower(jsonObject.getString("EndPower")); reportMeasurement.setDynamicTime(jsonObject.getString("DynamicTime")); reportMeasurement.setSNOfDevice(jsonObject.getString("SerialNumber")); reportMeasurement.setDeviceType(jsonObject.getString("DeviceType")); // "CalibrationDate":"2020-05-08T00:00:00" SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String dateStr = jsonObject.getString("CalibrationDate"); Date calibrationDate = sdf.parse(dateStr); reportMeasurement.setCalibrationDate(calibrationDate); return reportMeasurement; } catch (JSONException e) { log.error(e); e.printStackTrace(); } catch (ParseException e) { log.error(e); e.printStackTrace(); } return null; } public static class ReportMeasurementFormArguments { private Job job; public ReportMeasurementFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportMessageNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.PorterDuff.Mode; import android.graphics.Typeface; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMonText; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMessage; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * @author nop (12-05-2017) * * @see "[MIG-53] implement of "report messages"" */ public class ReportMessageNewEditForm extends SuperForm implements OnItemSelectedListener, TextWatcher { private static Log log = LogFactory.getLog(ReportMessageNewEditForm.class); private Job job; private MDSpinner messageType; private MDSpinner messageCode; private MDEditText messages; private TextView messageLengthView; private Map messageMap = new HashMap(); @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); messageType = new MDSpinner(context); messageType.setTag("MESSAGETYPE"); //$NON-NLS-1$ LinearLayout.LayoutParams spinnerLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); spinnerLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), 0, 0, 0); messageType.setLayoutParams(spinnerLayoutParams); messageType.getBackground().setColorFilter(LayoutUtils.DEFAULT_WHITE, Mode.SRC_ATOP); messageType.setOnItemSelectedListener(this); toolbar.addView(messageType); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); messageCode = MDSpinner.createDefaultSpinner(contentLinearLayout, ServiceMessages.getString("template"), false); //$NON-NLS-1$ messageCode.setTag("MESSAGETEMPLATE"); //$NON-NLS-1$ messageCode.setOnItemSelectedListener(this); messages = MDEditText.createDefaultEditText(contentLinearLayout, "", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ messages.setFilters(new InputFilter[] {new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE_HUNDRED_AND_TEN)}); messages.setSingleLine(false); messages.addTextChangedListener(this); messageLengthView = CommonUtilForm.getTextView(context, "0/" + CommonConstants.MaxLength.FIVE_HUNDRED_AND_TEN.toString()); //$NON-NLS-1$ LinearLayout.LayoutParams messageLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); messageLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; messageLengthView.setLayoutParams(messageLengthViewParams); messageLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(messageLengthView); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); Button deleteButton = new Button(context); deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { messageCode.setSelection(0); messages.getText().clear(); JobMessage jobMessage = messageMap.get(messageType.getSelectedId()); jobMessage.setMessageCode(""); jobMessage.setMessageCodeText(""); jobMessage.setFullText(""); messageMap.put(messageType.getSelectedId(), jobMessage); } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(relativeLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); loadData(); return null; } /** * Loads data. */ public void loadData() { fillComboMessageType(); // set select(Customer (Kunde)) for the first time messageType.setSelection(ServiceConstants.Index.ZERO); } private void fillComboMessageType() { // Create a new, empty report object and save it to the database if (job.getLatestReport().getReportStatus().isReceived()) { app.dbutil.insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(app.dbutil), job.getNextReportIdx(app.dbutil), job.isCycleOfInstallationFlag())); job.loadReports(app.dbutil); } Iterator itr = app.enumUtil.messageRecipientEnum.iterator(); Map messageRecipientMap = new HashMap(); while (itr.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) itr.next(); JobMessage jobMessage = app.dbutil.selectJobMessageListByreportAndMsgId(job.getCurrentReport(), (String) entry.getKey()); if (jobMessage == null) { jobMessage = new JobMessage(); jobMessage.setGuId(job.getLatestReport().getGuId()); jobMessage.setMessageId((String) entry.getKey()); } System.out.println("Recipient " + entry.getValue()); messageMap.put((String) entry.getKey(), jobMessage); messageRecipientMap.put((String) entry.getKey(), entry); } List messageTypeValueList = new ArrayList(); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.CUSTOMER, (String) messageRecipientMap.get(CommonConstants.Message.CUSTOMER).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.HEAD_OF_DEPARTMENT, (String) messageRecipientMap.get(CommonConstants.Message.HEAD_OF_DEPARTMENT).getValue())); if (job.getJobType().isMON()) { messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.PROJECT_MANAGER, (String) messageRecipientMap.get(CommonConstants.Message.PROJECT_MANAGER).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.DISPOSITION, (String) messageRecipientMap.get(CommonConstants.Message.DISPOSITION).getValue())); } else { messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.KDZ1, (String) messageRecipientMap.get(CommonConstants.Message.KDZ1).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.KDZ2, (String) messageRecipientMap.get(CommonConstants.Message.KDZ2).getValue())); messageTypeValueList.add(new CustomSpinnerItem(CommonConstants.Message.KDZ3, (String) messageRecipientMap.get(CommonConstants.Message.KDZ3).getValue())); } messageType.setContents(messageTypeValueList); } private void fillComboMessageTemplate(String msgid) { List messageTemplateValueList = new ArrayList(); if(job.getJobType().isMON()) { List jobMonTextMessageList = app.dbutil.selectJobMonMessageByLangu(app.dbutil.getUser().getLanguage()); for (JobMonText jobMonText : jobMonTextMessageList) { messageTemplateValueList.add(new CustomSpinnerItem(jobMonText.getMonText(), jobMonText.getText())); } } else { List reportMessageList = app.dbutil.selectReportMessage(); for (ReportMessage reportMessage : reportMessageList) { if (msgid.equalsIgnoreCase(CommonConstants.Message.CUSTOMER)) { if (reportMessage.isKND()) { messageTemplateValueList.add(new CustomSpinnerItem(reportMessage.getMessageCode(), reportMessage.getMessage())); } } else if (msgid.equalsIgnoreCase(CommonConstants.Message.HEAD_OF_DEPARTMENT)) { if (reportMessage.isABTL()) { messageTemplateValueList.add(new CustomSpinnerItem(reportMessage.getMessageCode(), reportMessage.getMessage())); } } else { if (reportMessage.isKDZ()) { messageTemplateValueList.add(new CustomSpinnerItem(reportMessage.getMessageCode(), reportMessage.getMessage())); } } } } messageCode.setContents(messageTemplateValueList); } @Override public ApplicationEvent onBackPressed() { // Create a new, empty report object and save it to the database if (job.getLatestReport().getReportStatus().isReceived()) { app.dbutil.insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(app.dbutil), job.getNextReportIdx(app.dbutil), job.isCallServiceFlag())); job.loadReports(app.dbutil); } Iterator itr = messageMap.keySet().iterator(); while (itr.hasNext()) { String key = (String) itr.next(); JobMessage jobMessage = messageMap.get(key); if (!app.dbutil.insertJobMessage(jobMessage)){ app.dbutil.updateJobMessage(jobMessage); } } job.loadReports(app.dbutil); return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } @Override public void onFormReset() { super.onFormReset(); messages.setText(""); //$NON-NLS-1$ messageLengthView.setText(""); //$NON-NLS-1$ } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("MESSAGETYPE".equals(parent.getTag())) { //$NON-NLS-1$ fillComboMessageTemplate(messageType.getSelectedId()); ((TextView) parent.getChildAt(0)).setTextColor(LayoutUtils.DEFAULT_WHITE); ((TextView) parent.getChildAt(0)).setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); ((TextView) parent.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); JobMessage jobMessage = messageMap.get(messageType.getSelectedId()); if (jobMessage.getMessageCode().isEmpty()) { messageCode.setSelection(0); } else { messageCode.setSelectionById(jobMessage.getMessageCode()); } if (jobMessage.getFullText().isEmpty()) { messages.getText().clear(); } else { messages.setText(jobMessage.getFullText()); } } else if ("MESSAGETEMPLATE".equals(parent.getTag())) { updateMessage(); } } @Override public void onNothingSelected(AdapterView arg0) { // Auto-generated method stub } public static class FormArguments { private Job job; protected FormArguments() { } public FormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } @Override public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) { // Auto-generated method stub } @Override public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { // Auto-generated method stub } @Override public void afterTextChanged(Editable paramEditable) { messageLengthView.setText(paramEditable.length() + "/" + CommonConstants.MaxLength.FIVE_HUNDRED_AND_TEN.toString()); //$NON-NLS-1$ updateMessage(); } private void updateMessage() { JobMessage jobMessage = messageMap.get(messageType.getSelectedId()); if (messageCode.getSelectedItemPosition() != 0) { jobMessage.setMessageCode(messageCode.getSelectedId()); jobMessage.setMessageCodeText(messageCode.getSelectedName()); } else { jobMessage.setMessageCode(""); jobMessage.setMessageCodeText(""); } jobMessage.setMessageId(messageType.getSelectedId()); if (StringUtil.isNotEmpty(messages.getText().toString())) { jobMessage.setFullText(messages.getText().toString()); } messageMap.put(messageType.getSelectedId(), jobMessage); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportSummaryForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.PorterDuff.Mode; import android.graphics.Typeface; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.ReportContentWidget; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.SignatureForm.Arguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The summary of report. * * @author cyu (23-06-2017) * * @see "[MIG-159] implement of report summary" */ public class ReportSummaryForm extends SuperForm implements OnItemSelectedListener{ private static Log log = LogFactory.getLog(ReportSummaryForm.class); private List jobList; private MDSpinner reportValue; private ReportContentWidget reportContentWidget; @Override public void onFormCall(Object argument) { if (argument instanceof Arguments) { Arguments formArguments = (Arguments) argument; jobList = formArguments.getJobList(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); LinearLayout headerLinearLayout = new LinearLayout(context); headerLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); headerLinearLayout.setOrientation(LinearLayout.VERTICAL); reportValue = new MDSpinner(context); reportValue.setTag("REPORT"); //$NON-NLS-1$ LinearLayout.LayoutParams spinnerLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); spinnerLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), 0, 0, 0); reportValue.setLayoutParams(spinnerLayoutParams); reportValue.getBackground().setColorFilter(LayoutUtils.DEFAULT_WHITE, Mode.SRC_ATOP); reportValue.setOnItemSelectedListener(this); toolbar.addView(reportValue); RelativeLayout relativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams addressRelativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); addressRelativeLayoutParams.setMargins(0, 0, 0, LayoutUtils.DEFAULT_MAX_MARGIN); relativeLayout.setLayoutParams(addressRelativeLayoutParams); LinearLayout cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); reportContentWidget = new ReportContentWidget(app, app.dbutil, context); cardLinearLayout.addView(reportContentWidget.createTimesCard()); cardLinearLayout.addView(reportContentWidget.createReportCard()); cardLinearLayout.addView(reportContentWidget.createMaterialCard()); cardLinearLayout.addView(reportContentWidget.createMessageCard()); // cardLinearLayout.addView(reportContentWidget.createImageCard()); ScrollView scrollView = new ScrollView(context); LinearLayout.LayoutParams scrollViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); scrollView.setLayoutParams(scrollViewParams); scrollView.addView(cardLinearLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { List reportValueList = new ArrayList(); if (!jobList.isEmpty()) { for (int i = 0; i < jobList.size(); i++) { Job job = jobList.get(i); String text = ServiceMessages.getString("report") + " " + (i+1) + " " + ServiceMessages.getString("of") + " " + jobList.size(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ reportValueList.add(new CustomSpinnerItem(job.getJobNumber(), text, text)); } } reportValue.setContents(reportValueList); return null; } private void loadReportContents(Job job) { job.loadAddresses(app.dbutil); reportContentWidget.setJob(job); reportContentWidget.loadTimes(false); reportContentWidget.loadReport(); reportContentWidget.loadMaterial(); reportContentWidget.loadMessage(); // reportContentWidget.loadImage(); } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("REPORT".equals(parent.getTag())) { //$NON-NLS-1$ ((TextView) parent.getChildAt(0)).setTextColor(LayoutUtils.DEFAULT_WHITE); ((TextView) parent.getChildAt(0)).setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); ((TextView) parent.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); loadReportContents(jobList.get(reportValue.getSelectedItemPosition())); } } @Override public void onNothingSelected(AdapterView arg0) { // Do nothing } @Override public ApplicationEvent onBackPressed() { // appman.inject(new KolibriRunnable() { // @Override // public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, // Registry reg) { // return appman.getActiveApplication().leaveToForm(SignatureForm.class, new SignatureForm.Arguments(jobList, true)); // } // }, false); return app.closeForm(); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportTimeListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.SearchView.OnQueryTextListener; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobDetailForm.JobDetailFormArgument; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.DateUtils; /** * New Form. */ public class ReportTimeListForm extends SuperForm implements OnQueryTextListener { private static Log log = LogFactory.getLog(ReportTimeListForm.class); /** * The dialog's add action. */ protected ActionCtrl addButton; protected Job job; protected JobReportTime selectedTime; protected TimeListWidget listWidget; private TimeUtil timeUtil; @Override public void onFormCall(Object argument) { if (argument != null) { if (argument instanceof ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments) { ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments formArguments = (ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments) argument; job = formArguments.getJob(); selectedTime = formArguments.getTime(); if (null != selectedTime) { loadTimeList(); } } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); timeUtil = new TimeUtil(app, app.dbutil, this); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); listWidget = new TimeListWidget(context); view.addView(listWidget); saveButton.setVisible(false); // create save action Image addImage = app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI); addButton = addActionCtrl(false, true, 1, "onAddPressed"); //$NON-NLS-1$ addButton.setImage(addImage); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("jobTime")); //$NON-NLS-1$ loadTimeList(); return null; } private void loadTimeList() { listWidget.clean(); Report report = job.getCurrentReport(); // Time spent (only if available) report.loadTimes(app.dbutil); List reportTimeList = report.getTimes(); ArrayList items = new ArrayList(); for (int i = 0; i < reportTimeList.size(); i++) { final JobReportTime reportTime = reportTimeList.get(i); final TimeListWidgetItem item = new TimeListWidgetItem(); log.info("IDX " + reportTime.getIdx() + " time from " + DateTimeUtil.showDateTime(reportTime.getStartTime()) + " to " + DateTimeUtil.showDateTime(reportTime.getStopTime())); item.setDateTitle(DateTimeUtil.showDayOfMonth(reportTime.getDate())); item.setDateText(DateTimeUtil.showDayOfWeek(reportTime.getStartTime())); WorkType WorkType = app.dbutil.selectWorkTypeByJobTypeAndWorkTypeCode(job.getJobType(), reportTime.getWorkTypeCode()); item.setTitleText(WorkType == null ? "" : WorkType.getText()); String line1 = ServiceMessages.getString("inProgress"); //$NON-NLS-1$ if (DateUtils.getInitialDateTime().equals(reportTime.getStopTime())) { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.STOP_TIME, CommonConstants.Images.IMAGE_DPI))); item.setTextColor(LayoutUtils.DEFAULT_RED); } else { line1 = DateTimeUtil.showTime(reportTime.getStartTime()) + "-" + DateTimeUtil.showTime(reportTime.getStopTime()) + " " + ServiceMessages.getString("clock"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } item.setStringLine1(line1); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton) { selectedTime = reportTime; actionTime(); } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(reportTimeList)); } listWidget.addItems(items); } private OnItemClickListener createOnItemClickListener(final List reportTimeList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { if(((TimeListWidgetItem) listWidget.getItemAtPosition(position)).getTextColor() == LayoutUtils.DEFAULT_TEXT_COLOR) { app.injectAndLeaveToForm(ReportTimeNewEditForm.class, new ReportTimeListFormArguments(job, reportTimeList.get(position))); } } }; } private void actionTime() { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (DateUtils.getInitialDateTime().equals(selectedTime.getStopTime())) { timeUtil.stopTime(job, new RunOnUIThread() { @Override public void runOnUIThread() { loadTimeList(); } }); } return null; } }, false); } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(JobDetailForm.class, new JobDetailFormArgument(job, 2)); } @Override public boolean onQueryTextSubmit(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } @Override public boolean onQueryTextChange(String queryText) { listWidget.getAdapter().getFilter().filter(queryText); return true; } protected ApplicationEvent onAddPressed() { app.injectAndLeaveToForm(ReportTimeNewEditForm.class, new ReportTimeListFormArguments(job, null)); return null; } public static class ReportTimeListFormArguments { private Job job; private JobReportTime time; public ReportTimeListFormArguments(Job job, JobReportTime time) { this.job = job; this.time = time; } public Job getJob() { return job; } public JobReportTime getTime() { return time; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ReportTimeNewEditForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.WorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDCalendar; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ReportTimeListForm.ReportTimeListFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class ReportTimeNewEditForm extends SuperForm implements OnItemSelectedListener { private static Log log = LogFactory.getLog(ReportTimeNewEditForm.class); private Job job; private JobReportTime time; private MDSpinner workTypeValue; private MDCalendar dateValue; private TimeEditText fromText; private TimeEditText toText; private Button deleteButton; private boolean isExistTime; private String defaultTime = "00:00"; @Override public void onFormCall(Object argument) { if (null == argument) { // create new time } else { if (argument instanceof ReportTimeListFormArguments) { ReportTimeListFormArguments formArguments = (ReportTimeListFormArguments) argument; time = formArguments.getTime(); job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout dateLinearLayout = new LinearLayout(context); dateLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; dateLinearLayout.setLayoutParams(leftIconLinearLayoutParams); final LinearLayout dayLinearLayout = new LinearLayout(context); dayLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams dateValueParams = new LinearLayout.LayoutParams(0, 0); dateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; dateValueParams.width = 0; dateValueParams.height = LayoutParams.MATCH_PARENT; dateValueParams.weight = 0.5f; dayLinearLayout.setLayoutParams(dateValueParams); // date dateValue = MDCalendar.createDefaultCalendar(dayLinearLayout, ServiceMessages.getString("date"), false); //$NON-NLS-1$ dateValue.setTag("DATUM"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) dateValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateValue.getUnderline().setLayoutParams(underlineLinearLayout); dateValue.setSimpleDateFormat(new SimpleDateFormat("dd.MM")); dateLinearLayout.addView(dayLinearLayout); fromText = TimeEditText.createDefaultEditText(dateLinearLayout,ServiceMessages.getString("from"), true); //$NON-NLS-1$ fromText.setTag("VON"); //$NON-NLS-1$ LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; fromText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); toText = TimeEditText.createDefaultEditText(dateLinearLayout, ServiceMessages.getString("to"), true); //$NON-NLS-1$ toText.setTag("BIS"); //$NON-NLS-1$ toText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.FIVE) }); LinearLayout.LayoutParams toInputLayoutParams = new LinearLayout.LayoutParams(0, 0); toInputLayoutParams.gravity = Gravity.CENTER; toInputLayoutParams.width = 0; toInputLayoutParams.height = LayoutParams.MATCH_PARENT; toInputLayoutParams.weight = 0.5f; toText.getParentTextInputLayout().setLayoutParams(toInputLayoutParams); contentLinearLayout.addView(dateLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // work type workTypeValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("workType"), true); //$NON-NLS-1$ workTypeValue.setTag("ARBEITSART"); //$NON-NLS-1$ workTypeValue.setOnItemSelectedListener(this); contentLinearLayout.addView(workTypeLinearLayout); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (time == null) { resetTime(); workTypeValue.setSelectionById(job.getDefaultJobTimeARBA()); if (!isExistTime) { Calendar calendar = Calendar.getInstance(); dateValue.setSelectedDate(calendar.getTime()); dateValue.setEnabled(true); } } else { deleteTime(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } private void resetTime() { fromText.setText(defaultTime); fromText.clearFocus(); toText.setText(defaultTime); toText.clearFocus(); fromText.clearFocus(); toText.clearFocus(); fromText.getText().clear(); toText.getText().clear(); fromText.clearError(); toText.clearError(); } // private DatePickerDialog getDatePickerDialog() { // Calendar calendar = Calendar.getInstance(); // return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { // // @Override // public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // setDate(year, monthOfYear, dayOfMonth); // } // // }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); // } // private void setDate(int year, int monthOfYear, int dayOfMonth) { // Calendar calendar = DateTimeUtil.getToday(); // calendar.set(Calendar.YEAR, year); // calendar.set(Calendar.MONTH, monthOfYear); // calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); // // dateSelected = calendar.getTime(); // List dateTypeValueList = new ArrayList(); // dateValue.setSelectedDate(calendar.getTime()); // // String date = DateTimeUtil.showDayMonth(calendar.getTime()); // dateTypeValueList.add(new CustomSpinnerItem(date, date)); // dateValue.setContents(dateTypeValueList); // if (!isExistTime || job.getCurrentReport().getTimes().size() == 1) { // dateValue.setEnabled(true); // } // } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set invisible save button saveButton.setVisible(false); if(job.getJobType().isMON()) { workTypeValue.setRequired(true); workTypeValue.setEnabled(true); } else { workTypeValue.setRequired(false); workTypeValue.setEnabled(false); } loadData(); return null; } public void loadData() { resetTime(); isExistTime = !job.getCurrentReport().getTimes().isEmpty(); List workTypeValueList = new ArrayList(); List workTypeList = app.dbutil.selectWorkTypeListByJobType(job.getJobType()); for (WorkType workType : workTypeList) { log.info("WorkType " + workType.getWorkTypeCode() + " text " + workType.getText() + " Guarantee " + workType.isGuarantee()); workTypeValueList.add(new CustomSpinnerItem((String) workType.getWorkTypeCode(), (String) workType.getText())); } workTypeValue.setContents(workTypeValueList); //$NON-NLS-1$ Calendar calendar = Calendar.getInstance(); if (time == null) { if (isExistTime) { JobReportTime selectedTime = job.getCurrentReport().getTimes().get(0); calendar.setTime(selectedTime.getDate()); } dateValue.setSelectedDate(calendar.getTime()); setFormTitle(DateTimeUtil.showDate(job.getCurrentReport().getCreateDate())); if (job.getLatestReport().getTimes().isEmpty()) workTypeValue.setSelectionById(job.getDefaultJobTimeARBA()); else workTypeValue.setSelectionById((job.getLatestReport().getTimes().get(0)).getWorkTypeCode()); deleteButton.setText(ServiceMessages.getString("clear")); //$NON-NLS-1$ if (isExistTime) { dateValue.setEnabled(false); } else { dateValue.setEnabled(true); } } else { loadTime(calendar); } } private void loadTime(Calendar calendar) { if (isExistTime && job.getCurrentReport().getTimes().size() == 1) { dateValue.setEnabled(true); } else { dateValue.setEnabled(false); } calendar.setTime(time.getDate()); dateValue.setSelectedDate(calendar.getTime()); setFormTitle(DateTimeUtil.showDate(time.getDate())); if (!time.getStartTime().equals(DateUtils.getInitialDateTime())) { fromText.setText(DateTimeUtil.showTimeGMT(time.getStartTime())); fromText.clearFocus(); } if (!time.getStopTime().equals(DateUtils.getInitialDateTime())) { toText.setText(DateTimeUtil.showTimeGMT(time.getStopTime())); toText.clearFocus(); } if (!time.getWorkTypeCode().isEmpty()) { workTypeValue.setSelectionById(time.getWorkTypeCode()); } deleteButton.setText(ServiceMessages.getString("delete")); //$NON-NLS-1$ } @Override public ApplicationEvent onBackPressed() { // not edited if (time == null && fromText.getText().toString().isEmpty() && toText.getText().toString().isEmpty()) { return app.leaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); } if (time != null && fromText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStartTime())) && toText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStopTime())) && (!job.getJobType().isMON() || (job.getJobType().isMON() && time.getWorkTypeCode().equalsIgnoreCase(workTypeValue.getSelectedId())))) { return app.leaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); } new AsyncTask(this) { private Object errorView = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { errorView = saveTime(); return null; } @Override public void runOnUIThread() { if (errorView != null) { if(errorView instanceof MDEditText) { ((MDEditText) errorView).setError(ServiceMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ } else if(errorView instanceof MDSpinner) { ((MDSpinner) errorView).setError(ServiceMessages.getString("pleaseSelectValue")); //$NON-NLS-1$ } } } }; return null; } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (null == time) { // create new time } else { if ("ARBEITSART".equals(parent.getTag())) { //$NON-NLS-1$ if (position != 0) workTypeValue.clearError(); } else if ("DATUM".equals(parent.getTag())) { //$NON-NLS-1$ dateValue.setSelected(false); dateValue.clearFocus(); } } } @Override public void onNothingSelected(AdapterView parent) { // Auto-generated method stub } private void deleteTime() { if (time == null) { return; } appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(ServiceMessages.getString("areYouSureThatYouWantToDeleteRecord"), ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } // If the row to delete is a running time capturing, the job status will change to "angenommen" if (time.getStopTime().compareTo(DateUtils.getInitialDateTime()) == 0) { job.setStatus(new JobStatus(JobStatus.RECEIVED)); } job.getCurrentReport().getTimes().remove(time); // Save the list of timesheet entries to the current report job.getLatestReport().setTimes(app.dbutil, new ArrayList(job.getCurrentReport().getTimes())); job.getLatestReport().loadTimes(app.dbutil); app.dbutil.updateJob(job); time = null; app.injectAndLeaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); return null; } }, false); } /** * Saves the time entries in the table to the DB by the following steps: *
- Validate the values in the fields on the GUI *
- Fill the zkdmobrtim objects into a list *
- Sort the list by "VON" attribute *
- Number the IDX attribute consecutively *
- Open a DB transaction *
- Delete the existing zkdmobrtim belonging to this report *
- Insert the current list of zkdmobrtim records *
- Commit the transaction *
- Refresh the table with the newly ordered list * @return ApplicationEvent */ public Object saveTime() { JobReportTime jobReportTime; if (fromText.getText().length() == 0) { return fromText; } if (toText.getText().length() == 0) { return toText; } Date startTime = DateTimeUtil.parseDateFromHHmm(fromText.getText().toString(), dateValue.getSelectedDate()); Date stopTime = DateTimeUtil.parseDateFromHHmm(toText.getText().toString(), dateValue.getSelectedDate()); if(startTime == null) { return fromText; } if(stopTime == null) { return toText; } if(fromText.getText().toString().equalsIgnoreCase(toText.getText().toString())) { log.info("the same time "); return toText; } log.info("startTime " + DateTimeUtil.showDateTime(startTime)); log.info("stopTime " + DateTimeUtil.showDateTime(stopTime)); if (startTime.after(stopTime)) { return fromText; } if (startTime.after(new Date())) { app.showWarningMessageBox(ServiceMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ return fromText; } if (stopTime.after(new Date())) { app.showWarningMessageBox(ServiceMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ return toText; } if(workTypeValue.isRequired() && workTypeValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { return workTypeValue; } if (time != null) { jobReportTime = time; jobReportTime.setDate(dateValue.getSelectedDate()); jobReportTime.setStartTime(startTime); jobReportTime.setStopTime(stopTime); jobReportTime.setWorkTypeCode(workTypeValue.getSelectedId()); } else { jobReportTime = new JobReportTime(); // jobReportTime.setGuid(job.getLatestReport().getGuId()); // jobReportTime.setIdx(app.dbutil.selectNextIDXFromJobReportTimeByGUID(job.getCurrentReport().getGuId())); jobReportTime.setDate(dateValue.getSelectedDate()); jobReportTime.setStartTime(startTime); jobReportTime.setStopTime(stopTime); jobReportTime.setWorkTypeCode(workTypeValue.getSelectedId()); } saveTimeSheet(jobReportTime); return null; } /** * Saves all records in the table control to the ZKDMOBREP object an to the database. * ZKDMOBRTIM.IDX attributes will be numbered consecutively according the VON attribute. * * @param selectedRecord The currently selected record will be selected again (in the table control). */ private void saveTimeSheet(JobReportTime selectedRecord) { // check if there are no overlapping entries List overlappingJobReportTimeList = ServiceJobUtil.isJobTimesheetOverlapping(job.getLatestReport().getTimes(), selectedRecord); JobReportTime overlappingJobReportTime = null; if(overlappingJobReportTimeList.size() > 0) { Iterator iterator = overlappingJobReportTimeList.iterator(); while (iterator.hasNext()){ JobReportTime jobReportTime = (JobReportTime) iterator.next(); if(jobReportTime.getStartTime().getTime() == selectedRecord.getStartTime().getTime() || jobReportTime.getStopTime().getTime() == selectedRecord.getStopTime().getTime()) { overlappingJobReportTime = jobReportTime; break; } Object[] arguments = new Object[] { DateTimeUtil.showTime(selectedRecord.getStartTime()) + " - " + DateTimeUtil.showTime(selectedRecord.getStopTime()) , DateTimeUtil.showTime(jobReportTime.getStartTime()) + " - " + DateTimeUtil.showTime(jobReportTime.getStopTime())}; String errorMessage = MessageFormat.format(Messages.getString("overlapping"), arguments); app.showWarningMessageBox(errorMessage); return; } } if(overlappingJobReportTime != null) { // update for (int i = 0; i < job.getLatestReport().getTimes().size(); i++) { if(job.getLatestReport().getTimes().get(i).getIdx() == overlappingJobReportTime.getIdx() && job.getLatestReport().getTimes().get(i).getGuId().equalsIgnoreCase(overlappingJobReportTime.getGuId()) && job.getLatestReport().getTimes().get(i).getDate().getTime() == overlappingJobReportTime.getDate().getTime()) { job.getLatestReport().getTimes().get(i).setStartTime(selectedRecord.getStartTime()); job.getLatestReport().getTimes().get(i).setStopTime(selectedRecord.getStopTime()); } } } else { // add new selectedRecord.setGuid(job.getLatestReport().getGuId()); selectedRecord.setIdx(app.dbutil.selectNextIDXFromJobReportTimeByGUID(job.getCurrentReport().getGuId())); job.getLatestReport().getTimes().add(selectedRecord); } // Save the list of timesheet entries to the current report job.getLatestReport().setTimes(app.dbutil, new ArrayList(job.getLatestReport().getTimes())); job.getLatestReport().loadTimes(app.dbutil); app.dbutil.updateJob(job); app.injectAndLeaveToForm(ReportTimeListForm.class, new ReportTimeListFormArguments(job, time)); } }     service/src/ch/mfiles/kaba/kolibri/service/forms/RescheduleJobForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Reason; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class RescheduleJobForm extends SuperForm implements OnItemSelectedListener { private static Log log = LogFactory.getLog(RescheduleJobForm.class); private Job job; private MDSpinner dateValue; private TimeEditText timeText; private Date dateSelected = new Date(); private String defaultTime = "00:00"; private ActionCtrl sendButton; private MDSpinner reasonValue; @Override public void onFormCall(Object argument) { if (null == argument) { // create new time } else { if (argument instanceof RescheduleJobFormArguments) { RescheduleJobFormArguments formArguments = (RescheduleJobFormArguments) argument; job = formArguments.getJob(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); saveButton.setVisible(false); sendButton = addActionCtrl(false, true, 1, "onSendPressed"); //$NON-NLS-1$ sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout dateLinearLayout = new LinearLayout(context); dateLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; dateLinearLayout.setLayoutParams(leftIconLinearLayoutParams); final LinearLayout dayLinearLayout = new LinearLayout(context); dayLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams dateValueParams = new LinearLayout.LayoutParams(0, 0); dateValueParams.gravity = Gravity.CENTER | Gravity.LEFT; dateValueParams.width = 0; dateValueParams.height = LayoutParams.MATCH_PARENT; dateValueParams.weight = 0.5f; dayLinearLayout.setLayoutParams(dateValueParams); // date dateValue = MDSpinner.createDefaultSpinner(dayLinearLayout, ServiceMessages.getString("date"), false); //$NON-NLS-1$ dateValue.setTag("DATUM"); //$NON-NLS-1$ LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) dateValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); dateValue.getUnderline().setLayoutParams(underlineLinearLayout); dateLinearLayout.addView(dayLinearLayout); dateValue.setFocusable(false); dateValue.setFocusableInTouchMode(false); dateValue.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { DatePickerDialog datePickerDialog = getDatePickerDialog(); datePickerDialog.setButton(android.content.DialogInterface.BUTTON_NEGATIVE, ServiceMessages.getString("cancel"), new android.content.DialogInterface.OnClickListener() { //$NON-NLS-1$ @Override public void onClick(android.content.DialogInterface dialog, int which) { if (which == android.content.DialogInterface.BUTTON_NEGATIVE) { dateValue.setEnabled(true); dialog.dismiss(); } } }); dateValue.setEnabled(false); datePickerDialog.show(); return true; } }); timeText = TimeEditText.createDefaultEditText(dateLinearLayout, ServiceMessages.getString("time"), true); //$NON-NLS-1$ timeText.setTag("BIS"); //$NON-NLS-1$ timeText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus && job.getJobRescheduleTime().getTime() == 0 && timeText.getText().toString().equalsIgnoreCase(defaultTime)) { timeText.getText().clear(); } if(!hasFocus && timeText.getText().toString().isEmpty()) { timeText.setText(defaultTime); //$NON-NLS-1$ } } }); LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; timeText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); contentLinearLayout.addView(dateLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // reason reasonValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, ServiceMessages.getString("reason"), true); //$NON-NLS-1$ reasonValue.setTag("REASON"); //$NON-NLS-1$ reasonValue.setOnItemSelectedListener(this); contentLinearLayout.addView(workTypeLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); return view; } private DatePickerDialog getDatePickerDialog() { Calendar calendar = Calendar.getInstance(); return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDate(year, monthOfYear, dayOfMonth); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } private void setDate(int year, int monthOfYear, int dayOfMonth) { Calendar calendar = DateTimeUtil.getToday(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); dateSelected = calendar.getTime(); List dateTypeValueList = new ArrayList(); String date = DateTimeUtil.showDate(calendar.getTime()); dateTypeValueList.add(new CustomSpinnerItem(date, date)); dateValue.setContents(dateTypeValueList); dateValue.setEnabled(true); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(ServiceMessages.getString("RescheduleJob")); // set invisible save button saveButton.setVisible(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendButton.setEnabled(false); loadData(); return null; } public void loadData() { List reasonValueList = new ArrayList(); List reasonList = app.dbutil.selectReasonList(); if(reasonList.isEmpty()) { reasonValueList.add(new CustomSpinnerItem(CommonConstants.PLEASE_SELECT, "Bitte w�hlen..")); } for (int i = 0; i < reasonList.size(); i++) { Reason reason = reasonList.get(i); reasonValueList.add(new CustomSpinnerItem(reason.getReasonText(), reason.getText(), reason.getText())); } reasonValue.setContents(reasonValueList); // timeText.clearError(); Calendar calendar = Calendar.getInstance(); if(job.getJobRescheduleDate().getTime() != 0) { calendar.setTime(job.getJobRescheduleDate()); } setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); if(job.getJobRescheduleTime().getTime() != 0) { timeText.setText(DateTimeUtil.showTimeGMT(job.getJobRescheduleTime())); } else { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); timeText.setText(DateTimeUtil.showTimeGMT(calendar.getTime())); } timeText.clearFocus(); } @Override public ApplicationEvent onBackPressed() { // not edited new AsyncTask(this) { private MDEditText errorText = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { return app.leaveToForm(JobListForm.class); } @Override public void runOnUIThread() { if (errorText != null) { errorText.setError(ServiceMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ } } }; return null; } public ApplicationEvent onSendPressed() { if(reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { reasonValue.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ return null; } Date time = DateTimeUtil.parseDateFromHHmm(timeText.getText().toString(), dateSelected); if(time == null || (time != null && time.before(new Date()))) { dateValue.setError(ServiceMessages.getString("pleaseEnterValidDate")); //$NON-NLS-1$ return null; } job.setJobRescheduleDate(time); job.setJobRescheduleTime(time); job.setAppointmentDate(time); job.calculateActiveDate(); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(new RemoteTransactionHandler().runUpdateEdate(job.getJobNumber(), job.getJobType().getCode() , job.getJobRescheduleDate() , job.getJobRescheduleTime() , reasonValue.getSelectedId())) { app.dbutil.updateJob(job); } return app.leaveToForm(JobListForm.class); } }; return null; } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if ("DATUM".equals(parent.getTag())) { //$NON-NLS-1$ dateValue.setSelected(false); dateValue.clearFocus(); } reasonValue.setError(null); reasonValue.clearError(); if(reasonValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); sendButton.setEnabled(false); } else { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_BLACK, CommonConstants.Images.IMAGE_DPI))); sendButton.setEnabled(true); } } @Override public void onNothingSelected(AdapterView parent) { // Auto-generated method stub } public static class RescheduleJobFormArguments { private Job job; public RescheduleJobFormArguments(Job job) { this.job = job; } public Job getJob() { return job; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ServiceNavigationForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.forms.NavigationForm; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DeviceMirrorringHandler; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * The super class of all forms within this application. Contains common * members, methods and controls. * */ public abstract class ServiceNavigationForm extends NavigationForm { private static Log log = LogFactory.getLog(ServiceNavigationForm.class); // initialized by the kolibri framework... public static ServiceApplication app; protected Context context; NavigationMenuListItem vehicleInventory; private Job job; private JobReportTime selectedJobTime; public Job getSelectedJob() { return job; } public void setSelectedJob(Job job) { this.job = job; this.job.loadAddresses(app.dbutil); this.job.loadReports(app.dbutil); } public void reloadSelectedJob() { this.job = app.dbutil.selectJobByJobIdAndJobType(job.getJobNumber(), job.getJobType().getCode()); this.job.loadReports(app.dbutil); } public JobReportTime getSelectedJobtime() { return selectedJobTime; } public void setSelectedJobTime(JobReportTime jobTime) { selectedJobTime = jobTime; } public ApplicationEvent actionExit() { return appman.exitApplication(); } protected void updateJobStatus(final String localStatus, final String sapStatus) { log.info("updateJobStatus status isNew " + getSelectedJob().getStatus().isNew()); //$NON-NLS-1$ if (new RemoteTransactionHandler().updateStatus(db, getSelectedJob(), localStatus, sapStatus, "")) { //$NON-NLS-1$ log.info("after updateStatus" + getSelectedJob().getStatus().toString()); //$NON-NLS-1$ reloadSelectedJob(); log.info("after reloadSelectedJob" + getSelectedJob().getStatus().toString()); //$NON-NLS-1$ if (JobStatus.RECEIVED.equals(localStatus)) { // remove existing a new job notification new Notifications(app).removeNotification(CommonConstants.Notification.NEW_JOB); } } } @Override public void onMenuItemClickListener(ListView menuView) { menuView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, final View innerView, int position, long id) { onMenuItemClicked(innerView); } }); } private void onMenuItemClicked(final View innerView) { if ("VEHICLE_INVENTORY".equals(innerView.getTag()) && !vehicleInventory.isEnable()) { return; } new AsyncTask(app.getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if ("TIMESHEET_APP".equals(innerView.getTag())) { //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.TIMESHEET_APP)) { app.showWarningMessageBox( ServiceMessages.getString("gilgenTimesheetApplicationIsNotInstalled")); //$NON-NLS-1$ return null; } return Runtime.getApplicationManager().leaveToApplication(CommonConstants.Application.TIMESHEET_APP, true); } else if ("MATERIAL_APP".equals(innerView.getTag())) { //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.MATERIAL_APP)) { app.showWarningMessageBox(ServiceMessages.getString("gilgenMaterialApplicationIsNotInstalled")); //$NON-NLS-1$ return null; } return Runtime.getApplicationManager().leaveToApplication(CommonConstants.Application.MATERIAL_APP, true); } else if ("VEHICLE_INVENTORY".equals(innerView.getTag())) { new RemoteTransactionHandler().runGetDeliveryList(app.dbutil.getUser().getPersonalNumber(), monitor); return app.callForm(ArticleListForm.class); } else if ("REFRESH_MASTER_DATA".equals(innerView.getTag())) { //$NON-NLS-1$ app.refreshMasterData(true); } else if ("COLLECTIVE_SIGNATURE".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(SignatureBundleListForm.class); } else if ("SHORT_MESSAGES".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(ShortMessageListForm.class); } else if ("EMPLOYEES".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(EmployeeListForm.class); } else if ("ABSENCE_NOTIFICATION".equals(innerView.getTag())) { //$NON-NLS-1$ return app.callForm(AbsenceNotificationListForm.class); } else if ("RELEASE_DEVICE".equals(innerView.getTag())) { //$NON-NLS-1$ return releaseDevice(); } else if ("EXIT_APP".equals(innerView.getTag())) { //$NON-NLS-1$ return appman.exitApplication(); } return null; } @Override protected void runOnUIThread() { getView().closeDrawers(); if ("REFRESH_MASTER_DATA".equals(innerView.getTag())) { createVehicleInventoryItem(); onMenuItemNotifyDataSetChanged(); } } }; } protected ApplicationEvent releaseDevice() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (DeviceMirrorringHandler.getInstance().releaseDevice( String.valueOf(DatabaseUtil.getInstance().getUser().getPersonalNumber()), app, monitor)) return appman.exitFramework(); return null; } }; return null; } @Override public ApplicationEvent onBackPressed() { return null; } @Override public void onMenuItemLoad(List menuListView) { if (!menuListView.isEmpty()) { menuListView.clear(); } // Timesheet App NavigationMenuListItem timesheetApp = new NavigationMenuListItem(); timesheetApp.setTag("TIMESHEET_APP"); //$NON-NLS-1$ timesheetApp.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.PLAY_WITH_CIRCLE, CommonConstants.Images.IMAGE_DPI))); timesheetApp.setText(ServiceMessages.getString("timesheetApp")); //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.TIMESHEET_APP)) { timesheetApp.setEnable(false); } menuListView.add(timesheetApp); // Material App NavigationMenuListItem materialApp = new NavigationMenuListItem(); materialApp.setTag("MATERIAL_APP"); //$NON-NLS-1$ materialApp.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.SETTING, CommonConstants.Images.IMAGE_DPI))); materialApp.setText(ServiceMessages.getString("materialApp")); //$NON-NLS-1$ if (null == app.appman.getApplicationDescriptor(CommonConstants.Application.MATERIAL_APP)) { materialApp.setEnable(false); } menuListView.add(materialApp); // Vehicle Inventory vehicleInventory = new NavigationMenuListItem(); vehicleInventory.setTag("VEHICLE_INVENTORY"); //$NON-NLS-1$ vehicleInventory.setText(ServiceMessages.getString("vehicleInventory")); createVehicleInventoryItem(); menuListView.add(vehicleInventory); // Refresh Master Data NavigationMenuListItem refreshMasterData = new NavigationMenuListItem(); refreshMasterData.setTag("REFRESH_MASTER_DATA"); //$NON-NLS-1$ refreshMasterData.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.UPDATE, CommonConstants.Images.IMAGE_DPI))); refreshMasterData.setText(ServiceMessages.getString("refreshMasterData")); //$NON-NLS-1$ menuListView.add(refreshMasterData); // Collective Signature NavigationMenuListItem collectiveSignature = new NavigationMenuListItem(); collectiveSignature.setTag("COLLECTIVE_SIGNATURE"); //$NON-NLS-1$ collectiveSignature.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.LIST, CommonConstants.Images.IMAGE_DPI))); collectiveSignature.setText(ServiceMessages.getString("collectiveSignature")); //$NON-NLS-1$ menuListView.add(collectiveSignature); // Short Messages NavigationMenuListItem shortMessages = new NavigationMenuListItem(); shortMessages.setTag("SHORT_MESSAGES"); //$NON-NLS-1$ shortMessages.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EMAIL, CommonConstants.Images.IMAGE_DPI))); shortMessages.setText(ServiceMessages.getString("shortMessages")); //$NON-NLS-1$ menuListView.add(shortMessages); // Employees NavigationMenuListItem userList = new NavigationMenuListItem(); userList.setTag("EMPLOYEES"); //$NON-NLS-1$ userList.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.CONTACT_PHONE, CommonConstants.Images.IMAGE_DPI))); userList.setText(ServiceMessages.getString("employees")); //$NON-NLS-1$ menuListView.add(userList); // Absence notification NavigationMenuListItem AbsenceNotification = new NavigationMenuListItem(); AbsenceNotification.setTag("ABSENCE_NOTIFICATION"); //$NON-NLS-1$ AbsenceNotification.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.ABSENCE_BLACK, CommonConstants.Images.IMAGE_DPI))); AbsenceNotification.setText(ServiceMessages.getString("absences")); //$NON-NLS-1$ menuListView.add(AbsenceNotification); // Release device (device mirroring) NavigationMenuListItem releaseDevice = new NavigationMenuListItem(); releaseDevice.setTag("RELEASE_DEVICE"); //$NON-NLS-1$ releaseDevice.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.OFFLINE_SHARE, CommonConstants.Images.IMAGE_DPI))); releaseDevice.setText(ServiceMessages.getString("releaseDevice")); //$NON-NLS-1$ menuListView.add(releaseDevice); // Exit Service Application NavigationMenuListItem exitServiceApplication = new NavigationMenuListItem(); exitServiceApplication.setTag("EXIT_APP"); //$NON-NLS-1$ exitServiceApplication.setIcon( getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EXIT, CommonConstants.Images.IMAGE_DPI))); exitServiceApplication.setText(ServiceMessages.getString("exitServiceApplication")); //$NON-NLS-1$ menuListView.add(exitServiceApplication); onMenuItemNotifyDataSetChanged(); } private void createVehicleInventoryItem() { if (app.dbutil.getUser().getWarehouseNumber().isEmpty()) { vehicleInventory.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.WRENCH_DISABLED, CommonConstants.Images.IMAGE_DPI))); vehicleInventory.setEnable(false); } else { vehicleInventory.setIcon(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.WRENCH_BLACK, CommonConstants.Images.IMAGE_DPI))); vehicleInventory.setEnable(true); } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ShortMessageForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.ShortMessageListForm.FormArguments; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (12-05-2017) * * @see "[MIG-55] implement of "short messages"" */ public class ShortMessageForm extends SuperForm { private static Log log = LogFactory.getLog(ShortMessageForm.class); private ShortMessage msg; private TextView subject; private TextView longText; private ActionCtrl sendAction; @Override public void onFormCall(Object argument) { if (argument instanceof FormArguments) { FormArguments formArguments = (FormArguments) argument; msg = formArguments.getShortMessage(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create send action sendAction = addActionCtrl(false, true, 1, "actionSend"); //$NON-NLS-1$ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); subject = new TextView(context); subject.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); subject.setTypeface(CommonConstants.Font.getDefaultRegularFont()); LinearLayout.LayoutParams betreffParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); betreffParams.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; subject.setLayoutParams(betreffParams); subject.setPadding(0, 30, 0, 30); subject.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); contentLinearLayout.addView(subject); longText = new TextView(context); longText.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); longText.setPadding(30, 30, 30, 30); longText.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); longText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setStroke(5, LayoutUtils.DEFAULT_DISABLED_COLOR); // longText.setBackground(gradientDrawable); contentLinearLayout.addView(longText); relativeLayout.addView(contentLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(relativeLayout); view.addView(scrollView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(ServiceMessages.getString("shortMessages")); //$NON-NLS-1$ sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(false); if (msg.isConfirmed()/* && !msg.getStatus().equalsIgnoreCase(CommonConstants.ZSHORTMSG.Status.CONFIRMED)*/) { sendAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); sendAction.setEnabled(true); } subject.setText(msg.getSubject()); longText.setText(msg.getMessage().trim()); // remove existing a short message notification new Notifications(app).removeNotification(CommonConstants.Notification.SHORT_MESSAGE); return null; } @Override public ApplicationEvent onBackPressed() { return app.leaveToForm(ShortMessageListForm.class); } protected ApplicationEvent actionSend() { hideSoftInputFromWindow(); if (msg.isConfirmed()) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (new RemoteTransactionHandler().runComfirmShortMSG(msg)) { // remove existing a short message notification new Notifications(app).removeNotification(CommonConstants.Notification.SHORT_MESSAGE); return appman.getActiveApplication().leaveToForm(ShortMessageListForm.class); } return null; } }; } return null; } @Override public void onFormReset() { super.onFormReset(); subject.setText(""); //$NON-NLS-1$ longText.setText(""); //$NON-NLS-1$ } }     service/src/ch/mfiles/kaba/kolibri/service/forms/ShortMessageListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ShortMessage; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (12-05-2017) * * @see "[MIG-55] implement of "short messages"" */ public class ShortMessageListForm extends SuperForm { private DefaultListWidget listWidget; private LinearLayout emptyMessageView; private List selectedList = new ArrayList(); @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create delete action ActionCtrl deleteAction = addActionCtrl(false, true, 1, "actionDelete"); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); listWidget = new DefaultListWidget(context); // set empty items ArrayList items = new ArrayList(); listWidget.addItems(items); listWidget.setVisibility(View.GONE); view.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noShortMessageAvailable")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); emptyMessageView.setVisibility(View.GONE); view.addView(emptyMessageView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); if (emptyMessageView.getChildCount() > 0) { emptyMessageView.removeAllViewsInLayout(); } setFormTitle(ServiceMessages.getString("shortMessages")); //$NON-NLS-1$ loadTable(); return null; } private void loadTable() { listWidget.clean(); selectedList.clear(); final List msgList = app.dbutil.selectShortMessageListbyPerNo(app.dbutil.getUser().getPersonalNumber()); if (!msgList.isEmpty()) { ArrayList items = new ArrayList(); for (int i = 0; i < msgList.size(); i++) { final ShortMessage msg = msgList.get(i); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setStatusColor(msg.getStatusColor()); item.setStatusType(msg.getConfirmedMsg()); item.isShowCheckBox(true); item.setTitleText(msg.getSubject()); item.setStringLine1(msg.getReceiveDate()); item.setStringLine2(DateTimeUtil.showTime(msg.getReceiveTime()) + " " + ServiceMessages.getString("clock")); //$NON-NLS-1$ //$NON-NLS-2$ if (msg.isConfirmed() && !msg.getStatus().equalsIgnoreCase(CommonConstants.ShortMessage.Status.CONFIRMED)) { item.isEnabledCheckBox(false); } else { item.isEnabledCheckBox(true); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { CheckBox checkBox = (CheckBox) v; if (checkBox.isChecked()) { if (selectedList == null) { selectedList = new ArrayList(); } selectedList.add(msg); } else { removeShortMessageFromList(msg); } } } }); items.add(item); listWidget.setOnItemClickListener(createOnItemClickListener(msgList)); } listWidget.addItems(items); listWidget.setVisibility(View.VISIBLE); emptyMessageView.setVisibility(View.GONE); } else { listWidget.setVisibility(View.GONE); emptyMessageView.setVisibility(View.VISIBLE); } } private OnItemClickListener createOnItemClickListener(final List msgList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(ShortMessageForm.class, new FormArguments((ShortMessage) msgList.get(position))); } }, false); } }; } @Override public ApplicationEvent onBackPressed() { hideSoftInputFromWindow(); return app.closeForm(); } @Override public void onFormReset() { super.onFormReset(); selectedList = new ArrayList(); setFormTitle(null); } protected ApplicationEvent actionDelete() { hideSoftInputFromWindow(); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (selectedList.isEmpty()) { app.showMessage(ServiceMessages.getString("selectOneOrMoreShortMessages")); //$NON-NLS-1$ return null; } String message = MessageFormat.format(ServiceMessages.getString("doYouReallyWantToDeleteXShortMessagesAtOnce"), //$NON-NLS-1$ new Object[] { selectedList.size() }); if (app.showMessageBox(message, ServiceMessages.getString("confirmation"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ Application.MBOX_ICON_QUESTION) == Application.MBOX_RESULT_YES) { for (ShortMessage shortMessage : selectedList) { app.dbutil.deleteShortMessage(shortMessage); } app.showMessage(ServiceMessages.getString("theSelectedMessageAreDeleted")); //$NON-NLS-1$ } return null; } @Override public void runOnUIThread() { super.runOnUIThread(); loadTable(); } }; return null; } private void removeShortMessageFromList(ShortMessage msg) { if (selectedList != null && !selectedList.isEmpty()) { for (Iterator iter = selectedList.iterator(); iter.hasNext();) { ShortMessage shortMsg = iter.next(); if (shortMsg.getPersonalNumber() == msg.getPersonalNumber() && shortMsg.getMessageKey() == msg.getMessageKey()) { iter.remove(); return; } } } } /** * The Short Message Form Arguments Class. * @author nop */ public static class FormArguments { private ShortMessage shortMessage; public FormArguments(ShortMessage shortMessage) { this.shortMessage = shortMessage; } public ShortMessage getShortMessage() { return shortMessage; } public void setShortMessage(ShortMessage shortMessage) { this.shortMessage = shortMessage; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/SignatureBundleListForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.DefaultListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; /** * The Signature List. * * @author cyu (12-06-2017) * * @see "[MIG-40] GUI: collective signature" */ public class SignatureBundleListForm extends SuperForm{ private static Log log = LogFactory.getLog(SignatureBundleListForm.class); private DefaultListWidget listWidget; protected ActionCtrl signButton = null; private List checkedJobList = new ArrayList(); /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create sign action signButton = addActionCtrl(false, true, 1, "onSignPressed"); //$NON-NLS-1$ saveButton.setVisible(false); listWidget = new DefaultListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); //0xAARRGGBB listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.addView(listWidget); return view; } @Override public ApplicationEvent onFormShow() { this.setFormTitle(ServiceMessages.getString("collectiveSignature")); //$NON-NLS-1$ loadTable(); signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_WHITE, CommonConstants.Images.IMAGE_DPI))); boolean validSelection = isJobSelectionValid(); if (validSelection) { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_WHITE, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(true); } else { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(false); } return null; } private void loadTable() { listWidget.clean(); checkedJobList.clear(); List reportList = app.dbutil.selectReportListOfSignBundle(); ArrayList items = new ArrayList(); for (int i = 0; i < reportList.size(); i++) { final Report report = reportList.get(i); final Job job = app.dbutil.selectJobByJobIdAndJobType(report.getJobNumber(), report.getJobType().getCode()); job.loadAddresses(app.dbutil); final DefaultListWidgetItem item = new DefaultListWidgetItem(); item.setStatusColor(job.getStatusColor()); item.setStatusType(job.getStatusType()); item.setButtonImage(null); Address objAddress = job.getObjectAddress(); item.setTitleText(app.getAddressTitle(objAddress)); String lint1 = objAddress.getStreet(); lint1 += ", " + objAddress.getPostalCode(); //$NON-NLS-1$ lint1 += " " + objAddress.getCity(); //$NON-NLS-1$ item.setStringLine1(lint1); item.setStringLine2(objAddress.getLocation()); if(report.isSignatureFlag()) { // MIG-240 Signed jobs in GUI "collective signature" // item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { item.isShowCheckBox(true); item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { item.setCheck(((CheckBox) v).isChecked()); if(((CheckBox) v).isChecked()) { checkedJobList.add(job); } else { checkedJobList.remove(job); } boolean validSelection = isJobSelectionValid(); if (validSelection) { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_WHITE, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(true); } else { signButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SIGNATURE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); signButton.setEnabled(false); } } } }); items.add(item); } } listWidget.addItems(items); } private boolean isJobSelectionValid() { boolean isValid = true; // --> 19.4.11 bep: Check is no longer a prerequisite to sign reports HashSet vbeln = new HashSet(); // Check if at least one job is selected if (!checkedJobList.isEmpty()) { // Check if all jobs have current report which is not signed yet for (int i = 0; i < checkedJobList.size(); i++) { Job job = checkedJobList.get(i); job.loadReports(app.dbutil); Report report = job.getLatestReport(); if (!report.getReportStatus().isInitial()) { // --> 19.4.11 bep: Check is no longer a prerequisite to sign reports // vbeln.add(report.getCommissionNumber()); log.info("CommissionNumber " +report.getCommissionNumber()); //$NON-NLS-1$ if (report.isSignatureFlag()) { isValid = false; } } else { isValid = false; } } // Check if all jobs belong to the same installation (VBELN) // --> 19.4.11 bep: Check is no longer a prerequisite to sign reports if (vbeln.size() > 1) { isValid = false; } } else { isValid = false; } return isValid; } public ApplicationEvent onSignPressed() { return app.callForm(SignatureForm.class, new SignatureForm.Arguments(checkedJobList, true)); } @Override public ApplicationEvent onBackPressed() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobListForm.class); } }, false); return null; } }     service/src/ch/mfiles/kaba/kolibri/service/forms/SignatureForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDDialog; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.SignatureUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.ui.SignatureView; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.LayoutHelper; import ch.mfiles.kolibri.util.ProgressMonitor; /** * @author nop (05-06-2017) * * @see "[MIG-41 GUI] report signature / view" */ public class SignatureForm extends SuperForm { private static Log log = LogFactory.getLog(SignatureForm.class); private List jobList; private boolean isCollectiveSignature; private SignatureView signatureView; private Integer signatureSelected = null; List signatureValues = new ArrayList(); List signatureKeys = new ArrayList(); private MDEditText name; private TextView nameLengthView; private int maxTextLength = CommonConstants.MaxLength.ONE_HUNDRED_AND_FIFTY; private CardView signatureCard = null; private CardView messageCard = null; protected Context context; @Override public void onFormCall(Object argument) { if (argument instanceof Arguments) { Arguments formArguments = (Arguments) argument; jobList = formArguments.getJobList(); isCollectiveSignature = formArguments.isCollectiveSignature(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(ServiceMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); setScreenOrientation(ScreenOrientation.PORTRAIT); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return appman.getActiveApplication().closeForm(); } }, false); } }); // create report view action ActionCtrl reportViewAction = addActionCtrl(false, false, 1, "reportViewAction"); //$NON-NLS-1$ reportViewAction.setTitle(ServiceMessages.getString("reportView")); //$NON-NLS-1$ reportViewAction.setImage(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.PAGE_VIEW_WHITE, CommonConstants.Images.IMAGE_DPI))); // create no signature action ActionCtrl noSignatureAction = addActionCtrl(false, false, 1, "noSignatureAction"); //$NON-NLS-1$ noSignatureAction.setTitle(ServiceMessages.getString("noSignature")); //$NON-NLS-1$ noSignatureAction.setImage(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_DPI))); // create delete action ActionCtrl deleteAction = addActionCtrl(false, false, 1, "deleteAction"); //$NON-NLS-1$ deleteAction.setTitle(ServiceMessages.getString("delete")); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable( app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); relativeLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); LinearLayout cardLinearLayout = new LinearLayout(context); cardLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); cardLinearLayout.setOrientation(LinearLayout.VERTICAL); cardLinearLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); int height = LayoutParams.MATCH_PARENT; if (LayoutHelper.getDisplayMetrics().widthPixels > SignatureUtil.TARGET_WIDTH) { height = (int) (LayoutHelper.getDisplayMetrics().widthPixels * SignatureUtil.ASPECT_RATIO); } signatureView = new SignatureView(context); signatureCard = createCard(context, signatureView, height); ((LayoutParams) signatureCard.getLayoutParams()).bottomMargin = 30; cardLinearLayout.addView(signatureCard); messageCard = createNameCard(context); cardLinearLayout.addView(messageCard); CardView cardView = new CardView(context); RelativeLayout.LayoutParams cardViewParams = new RelativeLayout.LayoutParams(0, 0); cardViewParams.width = LayoutParams.MATCH_PARENT; cardViewParams.height = LayoutParams.WRAP_CONTENT; cardViewParams.addRule(RelativeLayout.CENTER_IN_PARENT); cardViewParams.setMargins(0, 0, 0, 0); cardView.setLayoutParams(cardViewParams); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.addView(cardLinearLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); cardView.addView(linearLayout); relativeLayout.addView(cardView); view.addView(relativeLayout); return view; } private CardView createNameCard(Context context) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(2, 2, 2, 10); name = MDEditText.createDefaultEditText(contentLinearLayout, "Name", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, false); //$NON-NLS-1$ name.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxTextLength)}); name.setSingleLine(false); name.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void afterTextChanged(Editable paramEditable) { if (name.isRequired() && name.getError() != null) { name.clearError(); } nameLengthView.setText(paramEditable.length() + "/" + maxTextLength); //$NON-NLS-1$ } }); nameLengthView = CommonUtilForm.getTextView(context, "0/" + maxTextLength); //$NON-NLS-1$ LinearLayout.LayoutParams nameLengthViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); nameLengthViewParams.gravity = Gravity.CENTER | Gravity.RIGHT; nameLengthView.setLayoutParams(nameLengthViewParams); nameLengthView.setPadding(0, 0, 10, 0); contentLinearLayout.addView(nameLengthView); return createCard(context, contentLinearLayout); } private static CardView createCard(Context context, View view, int height) { CardView cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardViewParams.setMargins(0, 0, 0, 0); cardViewParams.width = LayoutParams.MATCH_PARENT; if (height > 0) { cardViewParams.height = height; } cardView.setLayoutParams(cardViewParams); cardView.setPadding(0, 0, 0, 30); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(view); cardView.addView(linearLayout); return cardView; } private static CardView createCard(Context context, View view) { return createCard(context, view, 0); } private String getName() { return name.getText().toString(); } @Override public ApplicationEvent onFormShow() { super.onFormShow(); // set dialog's title setFormTitle(Messages.getString("signature")); //$NON-NLS-1$ name.setText(""); name.clearFocus(); name.clearError(); name.setEnabled(true); if (!jobList.isEmpty()) { name.setRequired(jobList.get(0).getJobType().isMON()); } if(isCollectiveSignature) { app.showMessage(MessageFormat.format(ServiceMessages.getString("YouAreSingingNReport"), new Object[] { jobList.size()})); } loadSignature(); return null; } @Override public ApplicationEvent onBackPressed() { return appman.getActiveApplication().closeForm(); } private void loadSignature() { // integrity of selected reports means all reports have got the same (or // no) signature. // --> it doesn't matter which of the pictures is shown. if (checkSelectionIntegrity()) { Report report = jobList.get(0).getLatestReport(); if (report.isSignatureFlag() && !report.isSignatureInfo() && StringUtil.isNotEmpty(report.getSignature())) { // Load file name an generate path for the signature file String imageName = report.getSignature(); String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, imageName, false); name.setEnabled(true); name.setText(report.getSignatureName()); if (log.isDebugEnabled()) log.debug("Load signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ try { signatureView.load(SignatureUtil.getOriginalSignatureFileName(imagePath)); signatureView.lock(); name.setEnabled(false); } catch (IOException e) { log.error("Found IOException:", e); //$NON-NLS-1$ app.showMessageBox(ServiceMessages.getString("signatureCanNotBeLoadedFromFile"), //$NON-NLS-1$ ServiceMessages.getString("error"), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_ERROR); } } else { signatureView.clear(); } } else { signatureView.clear(); } } protected ApplicationEvent reportViewAction() { return app.callForm(ReportSummaryForm.class, new Arguments(jobList, false)); } protected ApplicationEvent noSignatureAction() { signatureValues.clear(); signatureKeys.clear(); Iterator> itr = app.enumUtil.noSignatureReasonEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); signatureValues.add((String) entry.getValue()); signatureKeys.add((String) entry.getKey()); } signatureSelected = 0; MDDialog alertDialog = MDDialog.createDefaultSpinner(ServiceMessages.getString("noSignature"), //$NON-NLS-1$ ServiceMessages.getString("cancel")); //$NON-NLS-1$ // CustomArrayAdapter customArrayAdapter = new // CustomArrayAdapter(context, // android.support.v7.appcompat.R.layout.select_dialog_singlechoice_material, // signatureValues); alertDialog.setSingleChoiceItems(signatureValues.toArray(new String[0]), signatureSelected, new OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { signatureSelected = which; } }); alertDialog.setPositiveButton(ServiceMessages.getString("ok"), new OnClickListener() { //$NON-NLS-1$ @Override public void onClick(android.content.DialogInterface dialog, int which) { if (signatureSelected > 0) { saveSignInfo(); dialog.dismiss(); } } }); alertDialog.show(); return null; } private void saveSignInfo() { // If more than one report is signed, get the GUID of the master report // (-> 1st in the list) and save it as sign-GUID String signGuid = ""; //$NON-NLS-1$ if (jobList.size() > 1) { signGuid = jobList.get(0).getLatestReport().getGuId(); } // Update current report of all selected jobs Iterator itr = jobList.iterator(); while (itr.hasNext()) { Report report = itr.next().getLatestReport(); app.deleteSignatureFile(report.getSignature()); updateSignatureAttributes(report, signGuid, true, signatureValues.get(signatureSelected), "", getName()); //$NON-NLS-1$ signatureView.clear(); } app.showMessage(ServiceMessages.getString("noSignatureReasonSaved")); //$NON-NLS-1$ } protected ApplicationEvent deleteAction() { new AsyncTask(this) { private boolean isDelete; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (signatureView == null) { return null; } if (signatureView.isDirty() || signatureView.isLocked()) { // inform user he's going to delete the signature for more than // one report (from requirement mail 17.4.2012) if (isCollectiveSignature) { Object[] arguments = new Object[] { String.valueOf(jobList.size()) }; String warningMsg = MessageFormat .format(ServiceMessages.getString("signatureBelongsToJobsDoYouWanToDeleteIt"), arguments); //$NON-NLS-1$ if (app.showMessageBox(warningMsg, ServiceMessages.getString("collectiveSignature"), //$NON-NLS-1$ Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) isDelete = true; } else { if (app.showMessageBox(ServiceMessages.getString("doYouWantToDeleteThisSignature"), //$NON-NLS-1$ ServiceMessages.getString("Signature"), Application.MBOX_BUTTON_OK_CANCEL, //$NON-NLS-1$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { isDelete = true; } } } return null; } @Override public void runOnUIThread() { if (signatureView == null) { return; } if (isDelete) { signatureView.clear(); name.setText(""); name.setEnabled(true); Iterator itr = jobList.iterator(); while (itr.hasNext()) { Job job = itr.next(); Report report = job.getLatestReport(); if (report.isSignatureFlag() && !report.isSignatureInfo() && StringUtil.isNotEmpty(report.getSignature())) { app.deleteSignatureFile(report.getSignature()); updateSignatureAttributes(report, "", false, "", "", getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } app.showMessage(ServiceMessages.getString("signatureDeleted")); //$NON-NLS-1$ } } }; return null; } protected static void updateSignatureAttributes(Report report, String guiId, boolean signFlag, String signInfo, String signature, String name) { report.setSignatureGuId(guiId); report.setSignatureFlag(signFlag); report.setSignatureInfo(signInfo); report.setSignature(signature); report.setSignatureName(name); app.dbutil.updateReport(report); } @Override public void onFormReset() { super.onFormReset(); signatureView.clear(); } /** * -> A file is created for the report of the first entry in the job list -> * The file name is generated according to the previous pattern -> The * co-signed rapporteurs receive a reference to the signed report (also * asbefore) */ @Override protected boolean onSave() { if (jobList.get(0).getJobType().isMON()) { if (name.isRequired() && name.getText().toString().isEmpty()) { name.setError(Messages.getString("pleaseProvideValue")); return true; } } if (signatureView.isLocked()) app.showMessage(ServiceMessages.getString("signatureAlreadySaved")); //$NON-NLS-1$ else if (!signatureView.isDirty()) app.showMessage(ServiceMessages.getString("noSignatureCaptured")); //$NON-NLS-1$ else { saveSignature(); signatureView.lock(); } return true; } private void saveSignature() { String timeStamp = Long.toString(new Date().getTime()); signatureView.stamp(SignatureView.BOTTOM_RIGHT, timeStamp); // If more than one report is signed, get the GUID of the master // report(-> 1st in the list) and save it as sign-GUID String signGuid = ""; //$NON-NLS-1$ if (!jobList.isEmpty()) { if (jobList.size() > 1) { signGuid = jobList.get(0).getLatestReport().getGuId(); } Iterator itr = jobList.iterator(); try { while (itr.hasNext()) { Job job = itr.next(); // Generate file name and path for the signature file String imageName = job.getJobNumber() + "_" + job.getJobType() + "_" + timeStamp + ".bmp"; String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, imageName, true); log.info("image path " + imagePath); if (log.isDebugEnabled()) log.debug("Save signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ String originalImagePath = SignatureUtil.getOriginalSignatureFileName(imagePath); signatureView.save(originalImagePath); signatureView.save(imagePath, SignatureUtil.TARGET_WIDTH, SignatureUtil.TARGET_HEIGHT, SignatureUtil.TARGET_DENSITY); log.info("originalImagePath path " + originalImagePath); // Update current report of all selected jobs updateSignatureAttributes(job.getLatestReport(), signGuid, true, "", imageName, getName()); //$NON-NLS-1$ } } catch (IOException e) { throw new ApplicationException(e); } name.setEnabled(false); app.showMessage(ServiceMessages.getString("signatureSaved")); //$NON-NLS-1$ } else { log.error("User tried to sign a job, but job list is empty!"); //$NON-NLS-1$ } } /** * Checks the integrity of reports in the job list. Integrity is given, if - * Only one job is in the list - No job in the list is signed (signflg = * false) - All jobs are signed (signflg = false) and refer to the same GUID * * @return */ private boolean checkSelectionIntegrity() { if (jobList.size() == 1) return true; HashSet signFlagSet = new HashSet(); HashSet signGuidSet = new HashSet(); Iterator itr = jobList.iterator(); while (itr.hasNext()) { Job job = itr.next(); Report report = job.getLatestReport(); Boolean signFlag = report.isSignatureFlag(); String signGuid = report.getSignatureGuId(); if (signFlagSet.isEmpty()) { signFlagSet.add(signFlag); signGuidSet.add(signGuid); } else if (signFlagSet.contains(signFlag)) { if (!signGuidSet.contains(signGuid)) return false; } else return false; } return true; } public static class Arguments { private List jobList; private boolean isCollectiveSignature; protected Arguments() { } public Arguments(List jobList, boolean isCollectiveSignature) { super(); this.jobList = jobList; this.isCollectiveSignature = isCollectiveSignature; } public List getJobList() { return jobList; } public void setJobList(List jobList) { this.jobList = jobList; } public boolean isCollectiveSignature() { return isCollectiveSignature; } public void setCollectiveSignature(boolean isCollectiveSignature) { this.isCollectiveSignature = isCollectiveSignature; } } }     service/src/ch/mfiles/kaba/kolibri/service/forms/SuperForm.java:   package ch.mfiles.kaba.kolibri.service.forms; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public abstract class SuperForm extends DialogForm { // initialized by the kolibri framework... public static ServiceApplication app; protected Context context; protected LinearLayout view; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image clearImage = imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(clearImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_WHITE); return view; } @Override protected ApplicationEvent onSavePressed() { hideSoftInputFromWindow(); if (isValid()) { onSave(); } return null; } protected boolean isValid() { return true; } /** * Closes the keyboard (if open) */ protected void hideSoftInputFromWindow() { KeyboardUtil.closeKeyboard(appman, getView()); } /** * Clears the error messages. */ protected void clearErrorMessages() { } }     service/src/ch/mfiles/kaba/kolibri/service/NotificationTestMessage.java:   package ch.mfiles.kaba.kolibri.service; //used for testing only public class NotificationTestMessage { public String getContent() { return "AUFTR-12345-REP-BR"; //$NON-NLS-1$ } }     service/src/ch/mfiles/kaba/kolibri/service/ServiceApplication.java:   package ch.mfiles.kaba.kolibri.service; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.zxing.integration.android.IntentResult; import android.media.MediaPlayer; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.MaterialMovement; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionResult.Status; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.FileUtils; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.Notifications; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.forms.ArticleDetailForm; import ch.mfiles.kaba.kolibri.service.forms.ArticleDetailForm.ArticleDetailFormArguments; import ch.mfiles.kaba.kolibri.service.forms.JobListForm; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm; import ch.mfiles.kaba.kolibri.service.forms.JobSearchForm.JobSearchFormArguments; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kaba.kolibri.service.util.SignatureUtil; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.NotificationMessage; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; import ch.mfiles.kolibri.util.SubProgressMonitor; import ch.mfiles.kolibri.util.ZXingBarcodeScanner; /** * Main application class. */ public class ServiceApplication extends Application { public static final Log log = LogFactory.getLog(ServiceApplication.class); public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public EnumUtil enumUtil; public MessageUtil messageUtil; public boolean filterHist; private Notifications notifications; @Override public ApplicationEvent onNotification(NotificationMessage message) { try { if (message.getContent() == null) { // should not happen, not sure if it does log.error("message with no content received"); //$NON-NLS-1$ return null; } // AUFTR-12345-REP-BR if (message.getContent().startsWith(CommonConstants.Prefix.AUFTR)) { // this is a new job -> parse the parameters and fetch it int firstDashPos = message.getContent().indexOf('-', 0); if (firstDashPos <= 0) { return null; } int secondDashPos = message.getContent().indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return null; } int thirdDashPos = message.getContent().indexOf('-', secondDashPos + 1); if (thirdDashPos <= 0) { return null; } final String jobNumber = message.getContent().substring(firstDashPos + 1, secondDashPos); final String orderType = message.getContent().substring(secondDashPos + 1, thirdDashPos); if (dbutil == null) { dbutil = DatabaseUtil.getInstance(); } RemoteTransactionHandler transactionHandler = new RemoteTransactionHandler(); if (transactionHandler.runGetOrder(jobNumber, orderType, dbutil.getUser().getPersonalNumber()).getStatus() == Status.success) { // If this job was already existing in the DB, the // jobStatus has to be // set manually, because the information is not // delivered in the // GET_ORDER transaction String jobNumberLZ = "0000000000".substring(0, 10-jobNumber.length()) + jobNumber; Job newJob = dbutil.selectJobByJobIdAndJobType(jobNumberLZ, orderType); newJob.calculateActiveDate(); if (newJob.getStatus().isForwarded()) { newJob.setStatus(JobStatus.NEW); dbutil.updateJob(newJob); } // Inform user about new job new Notifications(this).newJobNotification(Messages.getString("newJobReceived")); //$NON-NLS-1$ // Inform user about new job (optically) final Form currentForm = this.getCurrentForm(); if (currentForm != null && currentForm instanceof JobListForm) { // update the job list currentForm.runOnUIThread(new Runnable() { @Override public void run() { log.debug("reloading job list"); ((JobListForm) currentForm).loadTable(); } }); } } } if (message.getContent().startsWith(CommonConstants.Prefix.SHORTMSG)) { if (log.isDebugEnabled()) { log.debug("message startsWith SHORTMSG"); //$NON-NLS-1$ } int firstDashPos = message.getContent().indexOf('-', 0); if (firstDashPos <= 0) { return null; } int secondDashPos = message.getContent().indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return null; } final String pernr = message.getContent().substring(firstDashPos + 1, secondDashPos); final String tdName = message.getContent().substring(secondDashPos + 1, message.getContent().length()); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); if (new RemoteTransactionHandler().runGetShortMSG(Integer.parseInt(pernr), tdName)) { // Inform user about new short message new Notifications(this).shortMessageNotification(Messages.getString("newShortMessageReceived")); //$NON-NLS-1$ } } //MBEW-7F000001018E31C62FAAFCFA0D35797F-CONF if (message.getContent().startsWith(CommonConstants.Prefix.MBEW)) { if (log.isDebugEnabled()) { log.debug("message startsWith MBEW"); //$NON-NLS-1$ } log.info(message.getContent()); if (isServiceActive()) { getIncomingArticle(message.getContent()); } else { Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.INCOMING_ARTICLE_NAME, message.getContent()); } } } } catch (Exception e) { log.error("Found Exception: ", e); } return null; } /** * Called by the framework each time the application is started. * * @param obj * An (optional) object supplied by the application that started * this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); enumUtil = EnumUtil.getInstance(this.dbutil); messageUtil = MessageUtil.getInstance(); notifications = new Notifications(this); // make sure the common plugin exists if (null == appman.getApplicationDescriptor(CommonConstants.Application.COMMON_APP)) { showMessageBox(ServiceMessages.getString("gilgenCommonApplicationIsNotInstalled"), ServiceMessages.getString("startGilgenService"), MBOX_BUTTON_OK, MBOX_ICON_ERROR); //$NON-NLS-1$ //$NON-NLS-2$ return appman.exitApplication(); } // register broadcast receiver notifications.registerBroadcastReceiver(); deleteOldJobs(); deleteFormInstancesNotUsed(); setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { try { getIncomingArticle(reg.getProperty(RegistryProperties.INCOMING_ARTICLE_NAME)); } catch (IllegalArgumentException e) { //No IncomingArticle } } return leaveToForm(JobListForm.class); } /** * Refresh app masterdata. * * @param force Set to true to refresh masterdata even if the regular refresh * already took place. */ public void refreshMasterData(boolean force) { Calendar retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.HOUR_OF_DAY, - ServiceConstants.RETENTION_PERIOD_MASTER_REFRESH); Date lastRefresh = new Date(RegistryUtil.getMasterDataRefreshDateProperty(this)); if (lastRefresh.before(retentionPeriodEnd.getTime()) || force) { //showMessage(ServiceMessages.getString("refreshingMasterData")); //$NON-NLS-1$ new AsyncTask(getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { monitor.begin(5); Person currentUser = dbutil.getUser(); // master data refresh monitor.comment(ServiceMessages.getString("refreshMasterData")); boolean refreshMasterdataSuccessful = new RemoteTransactionHandler() .runRefreshMasterdata(currentUser.getPersonalNumber(), "", "X", new SubProgressMonitor(monitor, 3)); //$NON-NLS-1$ //$NON-NLS-2$ if (refreshMasterdataSuccessful) { showMessage(ServiceMessages.getString("masterDataSuccessfullyRefreshed")); //$NON-NLS-1$ } else { showMessage(ServiceMessages.getString("refreshingMasterDataFailed")); //$NON-NLS-1$ } // stock data refresh monitor.comment(ServiceMessages.getString("refreshingStock")); boolean getInventryStockSuccessful = new RemoteTransactionHandler() .runGetInventryStock(currentUser.getPersonalNumber(), currentUser.getWarehouseNumber(), currentUser.getLanguage()); monitor.worked(1); // order synchronization monitor.comment(ServiceMessages.getString("synchronizingOrders")); boolean syncOrderSuccessful = new RemoteTransactionHandler().runSyncOrder(currentUser.getPersonalNumber()); monitor.worked(1); if (refreshMasterdataSuccessful && getInventryStockSuccessful && syncOrderSuccessful) { Calendar nextRefresh = DateTimeUtil.getToday(); nextRefresh.add(Calendar.HOUR_OF_DAY, ServiceConstants.RETENTION_PERIOD_MASTER_REFRESH); RegistryUtil.setMasterDataRefreshDateProperty(ServiceApplication.this, nextRefresh.getTime().getTime()); } // refresh joblist final Form currentForm = getCurrentForm(); if (currentForm != null && currentForm instanceof JobListForm) { // update the job list currentForm.runOnUIThread(new Runnable() { @Override public void run() { log.debug("reloading job list"); ((JobListForm) currentForm).loadTable(); } }); } return null; } }; } } public void deleteOldJobs() { final int retentionPeriodReport = 1; // Month final String infoMsg1 = "Report from {0} for {1}-Job {2} in status {3} found (current retention period is {4} month"; //$NON-NLS-1$ final String infoMsg2 = "Deleted {0}-Job {1} is older than {2} months"; //$NON-NLS-1$ List finalizedJobList = dbutil.selectFinalizedJobList(); if(!finalizedJobList.isEmpty()){ Calendar retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.MONTH, -retentionPeriodReport); log.info("retentionPeriodEnd = " + retentionPeriodEnd.getTime()); for(int i=0; i < finalizedJobList.size(); i++){ Job finalizedJob = finalizedJobList.get(i); finalizedJob.loadReports(dbutil); Report finalizedReport = finalizedJob.getCurrentReport(); log.info("finalizedReport = " + finalizedReport.getCreateDate()); Object[] argumenst = new Object[] { DateTimeUtil.showDateTime(finalizedReport.getCreateDate()), finalizedJob.getJobType(), finalizedJob.getJobNumber(), finalizedJob.getStatus().getCode(), String.valueOf(retentionPeriodReport) }; log.info(MessageFormat.format(infoMsg1, argumenst)); // Criteria for deleting a job oder than the retention period: // 1. there is no report OR // 2. the latest report is older then the retention period if (finalizedReport.getReportStatus().isInitial() || DateTimeUtil.getTime(finalizedReport.getCreateDate()).getTime().before(retentionPeriodEnd.getTime())) { argumenst = new Object[] { finalizedJob.getJobType(), finalizedJob.getCommissionNumber(), String.valueOf(retentionPeriodReport) }; log.info(MessageFormat.format(infoMsg2, argumenst)); dbutil.deleteJob(finalizedJob); } } } deleteSignatureFilesNotUsed(); } public void deleteFormInstancesNotUsed() { log.info("before delete FormInstance not used " + dbutil.selectCountFromTable("FormInstance", "")); dbutil.deleteFormInstancesWithoutReport(); log.info("after delete FormInstance not used " + dbutil.selectCountFromTable("FormInstance", "")); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { // Unregister broadcast receiver and remove the notification notifications.removeNotification(); notifications.unregisterBroadcastReceiver(); return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { deleteExtractedFiles(); } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // make sure the common plugin exists if (null == appman.getApplicationDescriptor(CommonConstants.Application.COMMON_APP)) { throw new ApplicationException(ServiceMessages.getString("installGilgenCommonApplicationFirst")); //$NON-NLS-1$ } } /** * Called by the framework after the application has been upgraded but * before the upgrade is committed to the database. Additional upgrade * post-processing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade( ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } private void deleteExtractedFiles(){ deleteExtractedDirAndFiles(new File(Runtime.getInstallationFolder() + File.separator + CommonConstants.Application.SERVICE + File.separator)); } private boolean deleteExtractedDirAndFiles(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i usedSignFilenames = dbutil.selectReportListOfSignFiles(); //read all existing filenames for the file system HashMap signFilesMap = getAllSignatureFiles(); //remove files not used anymore in a report Iterator itr = usedSignFilenames.iterator(); while (itr.hasNext()) { String usedSignFilename = itr.next(); if (signFilesMap.containsKey(usedSignFilename)) signFilesMap.remove(usedSignFilename); if (signFilesMap.containsKey(SignatureUtil.getOriginalSignatureFileName(usedSignFilename))) signFilesMap.remove(SignatureUtil.getOriginalSignatureFileName(usedSignFilename)); } Iterator> itrSignature = signFilesMap.entrySet().iterator(); while (itrSignature.hasNext()) { Map.Entry entry = itrSignature.next(); String filename = (String) entry.getKey(); deleteSignatureFile(filename); } } private HashMap getAllSignatureFiles(){ HashMap signFilesMap = new HashMap(); String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, "", false); //$NON-NLS-1$ File signFileFolder = new File(imagePath); if (signFileFolder.exists()) { File[] signFileArray = signFileFolder.listFiles(new BitmapsOnly()); for (int n=0; n < signFileArray.length; n++) { signFilesMap.put(signFileArray[n].getName(), signFileArray[n]); } } else { log.error("Expected signature file not found: " + imagePath); //$NON-NLS-1$ } return signFilesMap; } public boolean deleteFile(String filePath) { if(log.isDebugEnabled()) log.debug("Delete file: filePath /" + filePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ File fFile = new File(filePath); if (fFile.exists()) { if (fFile.delete()) { log.info("File deleted successfully: "); //$NON-NLS-1$ return true; } else { log.error("Was not able to delete file: " + filePath); //$NON-NLS-1$ return false; } } else { log.error("Expected file not found: " + filePath); //$NON-NLS-1$ return false; } } public boolean deleteSignatureFile(String filename) { String imagePath = FileUtils.getAbsoluteFilePathName(CommonConstants.Application.SERVICE, SignatureUtil.FILE_PATH, filename, true); if(log.isDebugEnabled()) log.debug("Delete signature file: imageName /" + imagePath + "/"); //$NON-NLS-1$ //$NON-NLS-2$ File signFile = new File(imagePath); if (signFile.exists()) { if (signFile.delete()) { deleteOriginaSignatureFile(imagePath); log.info("Signature file deleted successfully: " + filename); //$NON-NLS-1$ return true; } else { log.error("Was not able to delete signature file: " + imagePath); //$NON-NLS-1$ return false; } } else { log.error("Expected signature file not found: " + imagePath); //$NON-NLS-1$ return false; } } private void deleteOriginaSignatureFile(String imagePath) { String originalFileName = SignatureUtil.getOriginalSignatureFileName(imagePath); File originaFile = new File(originalFileName); if (originaFile.exists() && originaFile.delete()) { log.info("Signature file deleted successfully: " + originaFile.getName()); } } private class BitmapsOnly implements FilenameFilter { private String suffix; public BitmapsOnly() { this.suffix = ".bmp"; //$NON-NLS-1$ } @Override public boolean accept(File dir, String fileName) { return fileName.endsWith(this.suffix); } } public void injectAndLeaveToForm(final Class formTo, final Object argument) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return leaveToForm(formTo, argument); } }, false); } public void showWarningMessageBox(final String warningMessage){ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { showMessageBox(warningMessage, ServiceMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } public void showMessage(String message) { messageUtil.showMessage(message); } public void showMessage(String message, boolean forceClear) { messageUtil.showMessage(message, forceClear); } public void clearMessage() { messageUtil.clearMessage(); } public String getAddressTitle(Address address) { String title = enumUtil.titelEnum.get(address.getTitle()); String name = ""; if (StringUtil.isNotEmpty(title)) { name = title + " " + address.getName1(); //$NON-NLS-1$ } else { name = address.getName1(); } log.info("Title " + title + " Name1 " + address.getName1() + " Name2 " + address.getName2()); if (address.isPrivate()) { // b) personal address // ZKDMOBADR.TITEL // ZKDMOBADR.NAME1 // ZKDMOBADR.NAME2 return name + " " + address.getName2(); //$NON-NLS-1$ } else { // a) company address // ZKDMOBADR.TITEL // ZKDMOBADR.NAME1 return name; } } public boolean isJobAndReportComplete(Job job) { boolean result = false; Person currentUser = dbutil.getUser(); Report report = job.getCurrentReport(); JobReportTime time = null; if (currentUser != null && !report.getReportStatus().isInitial()) { time = dbutil.selectJobReportTimeByGuid(job.getCurrentReportGuId(dbutil)); if (report.getReportStatus().isNew()){ result = true; if (time != null && time.getStopTime().equals(new Date(0))) { result = false; } } } return result; } public boolean showConfirmDeleteDialog() { return showMessageBox(ServiceMessages.getString("doYouWantToDeleteJob"), ServiceMessages.getString("warning"), //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_YES; } public void scanSavJob() { new AsyncTask(getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String jobNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ return null; } else { showMessage(result.toString()); jobNumber = result.getContents(); StringBuilder builder = new StringBuilder(); if(jobNumber.length() < 10) { for (int i = 0; i < 10 - jobNumber.length(); i++) { builder.append("0"); } jobNumber = builder.toString() + jobNumber; } log.info("scan result -> " + jobNumber); //$NON-NLS-1$ } if (!ServiceJobUtil.isValidJobNumber(jobNumber)) { showMessage(ServiceMessages.getString("invalidJobNumber")); //$NON-NLS-1$ return null; } // call SAP if (new RemoteTransactionHandler().runGetOrder(jobNumber, "SAV", dbutil.getUser().getPersonalNumber()).getStatus() == RemoteTransactionResult.Status.success) { Job job = dbutil.selectJobByJobIdAndJobType(jobNumber, "SAV"); job.calculateActiveDate(); new RemoteTransactionHandler().updateStatus(db, job, JobStatus.RECEIVED, JobStatus.SAP_Confirmed, ""); } return leaveToForm(JobListForm.class); } }; } public void scanCommissionNumber() { new AsyncTask(getCurrentForm()) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { String commissionNumber; ZXingBarcodeScanner s = new ZXingBarcodeScanner(getCurrentForm()); // this instanceof calling Form IntentResult result = s.initiateScan(); // this will block if (result == null) { showMessage(ServiceMessages.getString("aborted")); //$NON-NLS-1$ return null; } else { showMessage(result.toString()); commissionNumber = result.getContents(); log.info("scan result -> " + commissionNumber); //$NON-NLS-1$ } return callForm(JobSearchForm.class, new JobSearchFormArguments(null)); } }; } public boolean play(String path) { MediaPlayer mPlayer = new MediaPlayer(); try { log.info("Playing .. " + path); FileInputStream inputStream = new FileInputStream(path); mPlayer.setDataSource(inputStream.getFD()); inputStream.close(); mPlayer.prepare(); mPlayer.start(); } catch (IOException e){ log.error("IOException" + e.getMessage()); return false; } return true; } private boolean isServiceActive() { return Runtime.getApplicationManager().getActiveApplication().getApplicationDescriptor().getApplication().equalsIgnoreCase(CommonConstants.Application.SERVICE_APP); } public void getIncomingArticle(String message) { // Prefix: "MBEW" // Content: // Suffix: "CONF" int firstDashPos = message.indexOf('-', 0); if (firstDashPos <= 0) { return; } int secondDashPos = message.indexOf('-', firstDashPos + 1); if (secondDashPos <= 0) { return; } final String guid = message.substring(firstDashPos + 1, secondDashPos); final String conf = message.substring(secondDashPos + 1, message.length()); if (dbutil == null) dbutil = DatabaseUtil.getInstance(); int pernr = dbutil.getUser().getPersonalNumber(); if (new RemoteTransactionHandler().runGetMaterialMoveMent(guid, pernr, new Date())) { Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.deleteProperty(RegistryUtil.RegistryProperties.INCOMING_ARTICLE_NAME); } MaterialMovement materialMovement = dbutil.selectMaterialMovement(guid); if (materialMovement != null) { // Inform user about new MBEW new Notifications(this).IncomingArticleNotification(Messages.getString("newVehicleInventoryReceived")); dbutil.deleteMaterialMovement(materialMovement); injectAndLeaveToForm(ArticleDetailForm.class, new ArticleDetailFormArguments(materialMovement)); } } } }     service/src/ch/mfiles/kaba/kolibri/service/test/LongTaskForm.java:   package ch.mfiles.kaba.kolibri.service.test; import android.content.Context; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm.DialogInterface; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; public class LongTaskForm extends Form implements OnMenuItemClickListener { public static ServiceApplication app; /** * Derive the dialog's interface from base interface and add dialog specific * content. * * @author joerg * */ public static class SampleDialogInterface extends DialogInterface { private String text; public String getText() { return text; } public SampleDialogInterface(String text) { this.text = text; } } private EditText m_text; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample NavView"); //$NON-NLS-1$ // prepare toolbar getToolbar().setBackgroundColor(Color.BLUE); // don't set a navigation icon since it is provided by // ActionBarDrawerToggle further below automatically // create content including navigation view DrawerLayout drawer = new DrawerLayout(context); drawer.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always // show below toolbar drawer.setBackgroundColor(Color.WHITE); // create the dialog's view hierarchy, one may use inflation instead LinearLayout contentView = new LinearLayout(context); contentView.setOrientation(LinearLayout.VERTICAL); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); m_text = new EditText(context); m_text.setHint(""); //$NON-NLS-1$ m_text.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); m_text.setTextColor(Color.BLACK); m_text.setHintTextColor(Color.GRAY); contentView.addView(m_text); // create NavigationView NavigationView navigationView = new NavigationView(context); navigationView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); navigationView.setBackgroundColor(Color.LTGRAY); // populate menu Menu menu = navigationView.getMenu(); menu.setGroupCheckable(Menu.CATEGORY_CONTAINER, false, true); menu.add(Menu.NONE, 1, 1, "Test Item 1").setOnMenuItemClickListener(this); //$NON-NLS-1$ menu.add(Menu.NONE, 2, 2, "Test Item 2").setChecked(true); //$NON-NLS-1$ menu.add(Menu.NONE, 3, 3, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.NONE, 4, 4, "Test Item 1"); //$NON-NLS-1$ // link toolbar to drawer layout (creationg left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null, drawer, getToolbar(), 0, 0); drawer.addDrawerListener(drawerToggle); drawerToggle.syncState(); // add views to drawer drawer.addView(contentView); drawer.addView(navigationView); return drawer; } private class DialogTask extends AsyncTask { public DialogTask() { super(LongTaskForm.this); } @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { app.showMessageBox("test", "test", Application.MBOX_BUTTON_YES_NO_CANCEL, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ app.inform("weiter geht's..."); //$NON-NLS-1$ return null; } } @Override public boolean onMenuItemClick(MenuItem item) { new DialogTask(); return true; } }     service/src/ch/mfiles/kaba/kolibri/service/test/SampleCallingForm.java:   package ch.mfiles.kaba.kolibri.service.test; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm.DialogInterface; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.test.SampleDialogForm.SampleDialogInterface; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.Form; /** * A Form calling a dialog. */ public class SampleCallingForm extends Form { public static ServiceApplication app; private DialogInterface m_calledDialogInterface = null; // ... /** Calls SampleDialogForm */ @SuppressWarnings("unused") private ApplicationEvent actionCallDialog() { // example for calling the sample dialog (on AM thread) m_calledDialogInterface = new SampleDialogInterface(""); //$NON-NLS-1$ return app.callForm(SampleDialogForm.class, m_calledDialogInterface); } @Override public ApplicationEvent onFormShow() { // check if we are shown after a dialog was dismissed if (m_calledDialogInterface != null) { DialogInterface dInt = m_calledDialogInterface; m_calledDialogInterface = null; return onReturnFromDialog(dInt); } // normal onFormShow() processing... // ... return null; } private ApplicationEvent onReturnFromDialog(DialogInterface dInt) { if (dInt.isCancelled()) // do nothing if dialog was cancelled return null; if (dInt instanceof SampleDialogInterface) return onReturnFromSampleDialog((SampleDialogInterface) dInt); // dispatch to further dialog returns... // ... throw new ApplicationException("Returning from unknown dialog!?"); //$NON-NLS-1$ } /** Processes return from SampleDialogForm */ private ApplicationEvent onReturnFromSampleDialog(SampleDialogInterface dInt) { // ... return null; } }     service/src/ch/mfiles/kaba/kolibri/service/test/SampleDialogForm.java:   package ch.mfiles.kaba.kolibri.service.test; import android.content.Context; import android.graphics.Color; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.ui.LayoutInflater; public class SampleDialogForm extends DialogForm { public static ServiceApplication app; /** * Derive the dialog's interface from base interface and add dialog specific * content. * * @author joerg * */ public static class SampleDialogInterface extends DialogInterface { private String text; public String getText() { return text; } public SampleDialogInterface(String text) { this.text = text; } } private EditText m_text; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample Dialog"); //$NON-NLS-1$ // create the dialog's view hierarchy, one may use inflation instead LinearLayout view = new LinearLayout(context); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(Color.WHITE); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); m_text = new EditText(context); m_text.setHint(""); //$NON-NLS-1$ m_text.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); m_text.setTextColor(Color.BLACK); m_text.setHintTextColor(Color.GRAY); view.addView(m_text); return view; } private SampleDialogInterface m_dialogInterface; @Override public void onFormCall(Object parameter) { super.onFormCall(parameter); // retrieve and set the dialog content from the dialog's interface m_dialogInterface = (SampleDialogInterface) parameter; if (m_dialogInterface.text != null) m_text.setText(m_dialogInterface.text); } @Override protected ValidationResult validate() { // implement content validation, exit on first validation error while // checking for validity from top to bottom and left to right... String text = m_text.getText().toString(); if (text.length() == 0) return new ValidationResult(m_text, "Enter a text!"); //$NON-NLS-1$ // success return null; } @Override protected boolean onSave() { // update dialog's interface, return false in case of // errors while saving e.g. to database... but should be better handelt // by the dialog's validation method. Errors could be presented by a // SnackBar or app.showMessageBox() m_dialogInterface.text = m_text.getText().toString(); return super.onSave(); } }     service/src/ch/mfiles/kaba/kolibri/service/test/SampleNavigationViewForm.java:   package ch.mfiles.kaba.kolibri.service.test; import android.content.Context; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm.DialogInterface; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.LayoutInflater; public class SampleNavigationViewForm extends Form { public static ServiceApplication app; /** * Derive the dialog's interface from base interface and add dialog specific * content. * * @author joerg * */ public static class SampleDialogInterface extends DialogInterface { private String text; public String getText() { return text; } public SampleDialogInterface(String text) { this.text = text; } } private EditText m_text; @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample NavView"); //$NON-NLS-1$ // prepare toolbar getToolbar().setBackgroundColor(Color.BLUE); // don't set a navigation icon since it is provided by // ActionBarDrawerToggle further below automatically // create content including navigation view DrawerLayout drawer = new DrawerLayout(context); drawer.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always show below toolbar drawer.setBackgroundColor(Color.WHITE); // create the dialog's view hierarchy, one may use inflation instead LinearLayout contentView = new LinearLayout(context); contentView.setOrientation(LinearLayout.VERTICAL); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); m_text = new EditText(context); m_text.setHint(""); //$NON-NLS-1$ m_text.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); m_text.setTextColor(Color.BLACK); m_text.setHintTextColor(Color.GRAY); contentView.addView(m_text); // create NavigationView NavigationView navigationView = new NavigationView(context); navigationView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); navigationView.setBackgroundColor(Color.LTGRAY); // populate menu Menu menu = navigationView.getMenu(); menu.add(Menu.CATEGORY_CONTAINER, 1, 1, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.CATEGORY_CONTAINER, 2, 2, "Test Item 2").setChecked(true); //$NON-NLS-1$ menu.add(Menu.CATEGORY_CONTAINER, 3, 3, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.CATEGORY_CONTAINER, 4, 4, "Test Item 1"); //$NON-NLS-1$ menu.setGroupCheckable(Menu.CATEGORY_CONTAINER, false, true); // link toolbar to drawer layout (creationg left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null, drawer, getToolbar(), 0, 0); drawer.addDrawerListener(drawerToggle); drawerToggle.syncState(); // add views to drawer drawer.addView(contentView); drawer.addView(navigationView); return drawer; } }     service/src/ch/mfiles/kaba/kolibri/service/test/SampleTabForm.java:   package ch.mfiles.kaba.kolibri.service.test; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.CardView; import android.text.InputType; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.LayoutInflater; /** * Sample Form with tabbed content following Material design guidelines. * * @author joerg * */ public class SampleTabForm extends Form { public static ServiceApplication app; /** * A PagerAdapter providing a static number of views. * * @author joerg * */ private static class ViewPageAdapter extends PagerAdapter { private static class Page { String title; View view; Page(String title, View view) { this.view = view; this.title = title; } } private List viewPages = new ArrayList(); public void addPage(String title, View pageView) { viewPages.add(new Page(title, pageView)); notifyDataSetChanged(); } @Override public Object instantiateItem(ViewGroup container, int position) { View pageView = viewPages.get(position).view; container.addView(pageView); return pageView; } @Override public CharSequence getPageTitle(int position) { return viewPages.get(position).title; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return viewPages.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } @Override public View onFormLoad(Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); // set dialog's title setFormTitle("Sample Tabbed View"); //$NON-NLS-1$ // prepare toolbar getToolbar().setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // create content including navigation view DrawerLayout drawer = new DrawerLayout(context); drawer.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.MATCH_PARENT)); // drawer.setFitsSystemWindows(true); // doesn't work; view will always // show below toolbar drawer.setBackgroundColor(Color.WHITE); // create the dialog's view hierarchy, one may use inflation instead View contentView = createTabContentView(context); // create NavigationView NavigationView navigationView = createNavigationView(context); // link toolbar to drawer layout (creating left toolbar icon) ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(null, drawer, getToolbar(), 0, 0); drawer.addDrawerListener(drawerToggle); drawerToggle.syncState(); // add views to drawer drawer.addView(contentView); drawer.addView(navigationView); return drawer; } private NavigationView createNavigationView(Context context) { NavigationView navigationView = new NavigationView(context); navigationView.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, Gravity.START)); navigationView.setBackgroundColor(Color.LTGRAY); // populate menu Menu menu = navigationView.getMenu(); menu.setGroupCheckable(Menu.CATEGORY_CONTAINER, false, true); menu.add(Menu.NONE, 1, 1, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.NONE, 2, 2, "Test Item 2").setChecked(true); //$NON-NLS-1$ menu.add(Menu.NONE, 3, 3, "Test Item 1"); //$NON-NLS-1$ menu.add(Menu.NONE, 4, 4, "Test Item 1"); //$NON-NLS-1$ return navigationView; } private View createTabContentView(Context context) { // create vertical linear view to hold TabLayout and ViewPager LinearLayout contentView = new LinearLayout(context); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); contentView.setOrientation(LinearLayout.VERTICAL); // create TabLayout TabLayout tabLayout = new TabLayout(context); LinearLayout.LayoutParams tabLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); tabLayout.setLayoutParams(tabLayoutParams); tabLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); tabLayout.setTabTextColors(LayoutUtils.DEFAULT_TAB_TEXT_COLOR, LayoutUtils.DEFAULT_TAB_SELECTED_TEXT_COLOR); contentView.addView(tabLayout); // create 3 simple pages and add them to a page adapter ViewPageAdapter pagerAdapter = new ViewPageAdapter(); LinearLayout viewPage1 = new LinearLayout(context); CardView cardView = new CardView(context); cardView.setRadius(20); cardView.setCardElevation(2); LinearLayout.LayoutParams cardLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); cardLayoutParams.topMargin = 20; cardView.setLayoutParams(cardLayoutParams); cardView.setUseCompatPadding(true); viewPage1.addView(cardView); EditText text1 = MDEditText.createDefaultEditText(cardView, "Obligatory Text1", InputType.TYPE_CLASS_TEXT, //$NON-NLS-1$ true); pagerAdapter.addPage("Tab1", viewPage1); //$NON-NLS-1$ LinearLayout viewPage2 = new LinearLayout(context); EditText text2 = MDEditText.createDefaultEditText(viewPage2, "Obligatory Text2", InputType.TYPE_CLASS_TEXT, //$NON-NLS-1$ true); pagerAdapter.addPage("Tab2", viewPage2); //$NON-NLS-1$ LinearLayout viewPage3 = new LinearLayout(context); EditText text3 = MDEditText.createDefaultEditText(viewPage3, "Obligatory Text3", InputType.TYPE_CLASS_TEXT, //$NON-NLS-1$ true); pagerAdapter.addPage("Tab3", viewPage3); //$NON-NLS-1$ // ViewPager for PageAdapter ViewPager viewPager = new ViewPager(context); viewPager.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); contentView.addView(viewPager); viewPager.setAdapter(pagerAdapter); // link TabLayout to ViewPager tabLayout.setupWithViewPager(viewPager); // to add images to the pager's tabs (if required): // contentView.getTabAt(0).setIcon(...); return contentView; } }     service/src/ch/mfiles/kaba/kolibri/service/ui/widgets/FormImageLayout.java:   package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.R.color; import android.content.Context; import android.graphics.Bitmap; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; public class FormImageLayout extends LinearLayout { private Context context; private String label; private boolean isRequire; private OnClickListener onClickListener; private Bitmap imageBitmap; private LinearLayout imageTextLayout; private ImageView deleteIcon; private ActionUtil actionUtil; public FormImageLayout(Context context) { super(context); this.context = context; } public FormImageLayout createFormImageLayout(ServiceApplication app, ViewGroup parent, String label, boolean required, OnClickListener onClickListener) { if (parent == null) { return null; } Context context = parent.getContext(); FormImageLayout formImageLayout = createFormImageLayout(app, label, required, onClickListener); LinearLayout textInputLinearLayout = new LinearLayout(context); textInputLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); textInputLinearLayout.addView(formImageLayout); parent.addView(textInputLinearLayout); return formImageLayout; } public FormImageLayout createFormImageLayout(ServiceApplication app, String label, boolean required, OnClickListener clickListener) { this.label = label; this.isRequire = required; this.actionUtil = new ActionUtil(app); this.onClickListener = clickListener; LinearLayout contentLayout = new LinearLayout(context); contentLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLayout.setOrientation(LinearLayout.HORIZONTAL); contentLayout.setBackgroundColor(color.white); contentLayout.setPadding(0, 0, 0, 0); TextView formName = new TextView(context); formName.setGravity(Gravity.CENTER_VERTICAL); if (required) { label += "*"; } formName.setText(label); formName.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); LinearLayout.LayoutParams formNameTextParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); formNameTextParams.width = 0; formNameTextParams.weight = 0.25f; formNameTextParams.gravity = Gravity.CENTER_VERTICAL; formName.setLayoutParams(formNameTextParams); contentLayout.addView(formName); imageTextLayout = new LinearLayout(context); imageTextLayout.setOrientation(LinearLayout.HORIZONTAL); imageTextLayout.setPadding(0, 0, 0, 0); LinearLayout.LayoutParams imageTextDescParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); imageTextDescParams.width = 0; imageTextDescParams.weight = 0.45f; imageTextDescParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; imageTextLayout.setLayoutParams(imageTextDescParams); contentLayout.addView(imageTextLayout); LinearLayout buttonLinearLayout = new LinearLayout(context); buttonLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams buttonLinearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); buttonLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; buttonLinearLayoutParams.height = 80; buttonLinearLayoutParams.width = 0; buttonLinearLayoutParams.weight = 0.30f; buttonLinearLayoutParams.topMargin = 20; buttonLinearLayoutParams.bottomMargin = 20; buttonLinearLayout.setLayoutParams(buttonLinearLayoutParams); deleteIcon = new ImageView(context); LinearLayout.LayoutParams deleteIconParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); deleteIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; deleteIconParams.height = 80; deleteIconParams.width = 80; deleteIcon.setLayoutParams(deleteIconParams); deleteIcon.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); deleteIcon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setBitmap(null); } }); buttonLinearLayout.addView(deleteIcon); ImageView galleryIcon = new ImageView(context); LinearLayout.LayoutParams galleryIconParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); galleryIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; galleryIconParams.height = 80; galleryIconParams.width = 80; galleryIconParams.leftMargin = 30; galleryIcon.setLayoutParams(galleryIconParams); galleryIcon.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.PHOTO_LIBRARY_BLACK, CommonConstants.Images.IMAGE_DPI))); galleryIcon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickListener.onClick(v); actionUtil.actionGallery(new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { setBitmap(bitmap); } }); } }); buttonLinearLayout.addView(galleryIcon); ImageView addPhotoicon = new ImageView(context); LinearLayout.LayoutParams addPhotoIconParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); addPhotoIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; addPhotoIconParams.height = 80; addPhotoIconParams.width = 80; addPhotoIconParams.leftMargin = 30; addPhotoicon.setLayoutParams(addPhotoIconParams); addPhotoicon.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_PHOTO_BLACK, CommonConstants.Images.IMAGE_DPI))); addPhotoicon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickListener.onClick(v); actionUtil.actionCamera(new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { setBitmap(bitmap); } }); } }); buttonLinearLayout.addView(addPhotoicon); contentLayout.addView(buttonLinearLayout); contentLayout.setOnContextClickListener(new OnContextClickListener() { @Override public boolean onContextClick(View v) { // TODO Auto-generated method stub return false; } }); setBitmap(imageBitmap); FormImageLayout formImageLayout = new FormImageLayout(context); formImageLayout.setOrientation(LinearLayout.VERTICAL); formImageLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); formImageLayout.setBackgroundColor(color.white); formImageLayout.setPadding(0, 0, 0, 0); formImageLayout.addView(contentLayout); formImageLayout.addView(new DividerView(context)); return formImageLayout; } public void setRequire(Boolean isRequire) { this.isRequire = isRequire; } public boolean isRequire() { return this.isRequire; } public Bitmap getImageBitmap() { return this.imageBitmap; }; public String getErrorMessage() { return label + " " + ServiceMessages.getString("notAdded"); } public void setBitmap(Bitmap imageBitmap) { this.imageBitmap = imageBitmap; imageTextLayout.removeAllViews(); if (imageBitmap == null) { TextView imageText = new TextView(context); imageText.setText(ServiceMessages.getString("notAdded")); imageText.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); if (isRequire) { imageText.setTextColor(LayoutUtils.DEFAULT_ERROR_COLOR); } LinearLayout.LayoutParams imageTextParams = LayoutUtils.DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT(); imageTextParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; imageText.setLayoutParams(imageTextParams); imageTextLayout.addView(imageText); deleteIcon.setVisibility(View.INVISIBLE); } else { int height = 160; int width = 240; FrameLayout imageFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams overlayParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_AND_MATCH_PARENT()); overlayParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; overlayParams.height = height; overlayParams.width = width; overlayParams.topMargin = 20; overlayParams.bottomMargin = 20; imageFrameLayout.setLayoutParams(overlayParams); ImageView image = new ImageView(context); image.setAdjustViewBounds(true); image.setScaleType(ScaleType.FIT_START); image.setMinimumHeight(height); image.setMaxHeight(height); image.setMaxWidth(width); image.setImageBitmap(imageBitmap); imageFrameLayout.addView(image); imageTextLayout.addView(imageFrameLayout); deleteIcon.setVisibility(View.VISIBLE); imageTextLayout.requestFocus(); } } }     service/src/ch/mfiles/kaba/kolibri/service/ui/widgets/FormListItemWidget.java:   package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.R.color; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnContextClickListener; import android.widget.AbsListView; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; import ch.mfiles.kaba.kolibri.common.businessobjects.Form; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; public class FormListItemWidget { private ServiceApplication app; private Context context; private Form form; private OnClickListener clickListener; private boolean checked; public FormListItemWidget(ServiceApplication app, Form form, OnClickListener clickListener) { this.app = app; this.context = app.appman.getContext(); this.form = form; this.clickListener = clickListener; } public View getView() { LinearLayout rootLinearLayout = new LinearLayout(context); rootLinearLayout.setOrientation(LinearLayout.VERTICAL); rootLinearLayout.setClickable(true); LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); contentItemLayout.setBackgroundColor(color.white); contentItemLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MIN_PADDING); LinearLayout leftIconLinearLayout = new LinearLayout(context); leftIconLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0,0); leftIconLinearLayoutParams.gravity = Gravity.CENTER | Gravity.LEFT; leftIconLinearLayoutParams.width = 0; leftIconLinearLayoutParams.height = LayoutParams.FILL_PARENT; leftIconLinearLayoutParams.weight = 0f; leftIconLinearLayout.setLayoutParams(leftIconLinearLayoutParams); // if (leftView != null) { // leftIconLinearLayoutParams.weight = 0.55f; // leftIconLinearLayout.addView(leftView); // } contentItemLayout.addView(leftIconLinearLayout); // if (middleView != null) { // contentItemLayout.addView(middleView); // } else { contentItemLayout.addView(createMiddleLayout()); // } LinearLayout buttonLinearLayout = new LinearLayout(context); buttonLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams buttonLinearLayoutParams = new LinearLayout.LayoutParams(LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); buttonLinearLayoutParams.gravity = Gravity.CENTER | Gravity.RIGHT; buttonLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; buttonLinearLayout.setLayoutParams(buttonLinearLayoutParams); // if (rightView != null) { // buttonLinearLayout.addView(rightView); // } else { FrameLayout endFrameLayout = new FrameLayout(context); FrameLayout.LayoutParams backgroundIconParams = new FrameLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 45), LayoutUtils.convertDpToPixel(context, 45)); backgroundIconParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL ; LinearLayout.LayoutParams endFrameParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); endFrameParams.gravity = Gravity.RIGHT | Gravity.CENTER_HORIZONTAL; endFrameLayout.setLayoutParams(endFrameParams); ImageButton imageButton = new ImageButton(context); imageButton.setLayoutParams(backgroundIconParams); imageButton.setImageDrawable(app.getCurrentForm().getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EDIT, CommonConstants.Images.IMAGE_DPI))); // imageButton.setId(ID_BUTTON); endFrameLayout.addView(imageButton); buttonLinearLayout.addView(endFrameLayout); // } contentItemLayout.addView(buttonLinearLayout); rootLinearLayout.addView(contentItemLayout); // LinearLayout contentItemLayout = new LinearLayout(context); // contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); // // contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); //// contentItemLayout.setPadding(0 //// , LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING //// , LayoutUtils.DEFAULT_MIN_PADDING); // // // Generate bottom border only // LayerDrawable bottomBorder = getBorders( // Color.WHITE, // Background color // Color.LTGRAY, // Border color // 0, // Left border in pixels // 0, // Top border in pixels // 0, // Right border in pixels // 2 // Bottom border in pixels // ); // contentItemLayout.setBackground(bottomBorder); // // FrameLayout.LayoutParams checkBoxParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); // checkBoxParams.gravity = Gravity.LEFT ; // // CheckBox checkBox = new CheckBox(context); //// checkBox.setId(ID_CHECK); // checkBox.setPadding(0, 0, 8, 0); // checkBox.setLayoutParams(checkBoxParams); // contentItemLayout.addView(checkBox); // // TextView measureTextView = new TextView(context); //// measureTextView.setId(ID_MEASURE); // measureTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // measureTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); // LinearLayout.LayoutParams measureTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // measureTextParams.width = 0; // measureTextParams.weight = 0.42f; // measureTextView.setLayoutParams(measureTextParams); // // contentItemLayout.addView(measureTextView); // // TextView fDymTextView = new TextView(context); //// fDymTextView.setId(ID_FDYM); // fDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // fDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); // // LinearLayout.LayoutParams fDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // fDymTextParams.width = 0; // fDymTextParams.weight = 0.2f; // fDymTextView.setLayoutParams(fDymTextParams); // // contentItemLayout.addView(fDymTextView); // // TextView tDymTextView = new TextView(context); //// tDymTextView.setId(ID_TDYM); // tDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // tDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); // // // LinearLayout.LayoutParams tDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // tDymTextParams.width = 0; // tDymTextParams.weight = 0.20f; // tDymTextView.setLayoutParams(tDymTextParams); // contentItemLayout.addView(tDymTextView); // // TextView fEneTextView = new TextView(context); //// fEneTextView.setId(ID_FEND); // // fEneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); // fEneTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); // // LinearLayout.LayoutParams fEneTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); // fEneTextParams.width = 0; // fEneTextParams.weight = 0.18f; // fEneTextView.setLayoutParams(fEneTextParams); // contentItemLayout.addView(fEneTextView); // // // checkBox.setOnClickListener(clickListener); // checkBox.setFocusable(false); // checkBox.setChecked(checked); // // System.out.println("getView set checked " + checkBox.isChecked()); //// measureTextView.setText(measurement.getMeasurement()); //// fDymTextView.setText(measurement.getDynamicPowerPeakValue()); //// tDymTextView.setText(measurement.getDynamicTime()); //// fEneTextView.setText(measurement.getStaticEndPower());; // // measureTextView.setEllipsize(TruncateAt.END); rootLinearLayout.setOnContextClickListener(new OnContextClickListener() { @Override public boolean onContextClick(View v) { // TODO Auto-generated method stub return false; } }); rootLinearLayout.addView(new DividerView(context)); return rootLinearLayout; } private LinearLayout createMiddleLayout() { LinearLayout midLinearLayout = new LinearLayout(context); midLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams midLinearLayoutParams = new LinearLayout.LayoutParams(0,0); midLinearLayoutParams.gravity = Gravity.CENTER; midLinearLayoutParams.width = 0; midLinearLayoutParams.height = LayoutParams.WRAP_CONTENT; midLinearLayoutParams.weight = 3f; midLinearLayout.setLayoutParams(midLinearLayoutParams); midLinearLayout.setPadding(25, 0, 0, 0); TextView titleTextView = new TextView(context); titleTextView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); titleTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); titleTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); titleTextView.setText(form.getName()); midLinearLayout.addView(titleTextView); TextView textLineOneTextView = new TextView(context); textLineOneTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineOneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineOneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineOneTextView.setEllipsize(TruncateAt.END); textLineOneTextView.setMaxLines(1); textLineOneTextView.setSingleLine(); textLineOneTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textLineOneTextView.setText(form.getDescription()); midLinearLayout.addView(textLineOneTextView); TextView textLineTwoTextView = new TextView(context); textLineTwoTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textLineTwoTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textLineTwoTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); textLineTwoTextView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textLineTwoTextView.setText(String.valueOf(form.getVersion())); midLinearLayout.addView(textLineTwoTextView); return midLinearLayout; } protected LayerDrawable getBorders(int bgColor, int borderColor, int left, int top, int right, int bottom){ // Initialize new color drawables ColorDrawable borderColorDrawable = new ColorDrawable(borderColor); ColorDrawable backgroundColorDrawable = new ColorDrawable(bgColor); // Initialize a new array of drawable objects Drawable[] drawables = new Drawable[] { borderColorDrawable, backgroundColorDrawable }; // Initialize a new layer drawable instance from drawables array LayerDrawable layerDrawable = new LayerDrawable(drawables); // Set padding for background color layer layerDrawable.setLayerInset(1, // Index of the drawable to adjust [background color layer] left, // Number of pixels to add to the left bound [left border] top, // Number of pixels to add to the top bound [top border] right, // Number of pixels to add to the right bound [right border] bottom // Number of pixels to add to the bottom bound [bottom border] ); // Finally, return the one or more sided bordered background drawable return layerDrawable; } public Form getForm() { return form; } public void setChecked(Boolean checked) { this.checked = checked; } public boolean isChecked() { return checked; } }     service/src/ch/mfiles/kaba/kolibri/service/ui/widgets/GridLayoutForm.java:   package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.CardView; import android.support.v7.widget.GridLayout; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.Address; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.forms.JobDetailAddressEditForm; import ch.mfiles.kaba.kolibri.service.forms.JobDetailAddressForm; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; /** * @author nop (15-02-2017) * @see "MIG-27 investigate if we can have icons (and callback listeners) if we put HTML in android.text.Html Update: use data tables" */ public abstract class GridLayoutForm extends Form { protected CardView cardView; protected Context context; protected ServiceApplication app; public GridLayoutForm(Context context, ServiceApplication app) { super(); this.app = app; this.context = context; } /** * Creates grid parent layout. * * @param title */ protected GridLayout createGridLayout(String title) { return createGridLayout(title, null, null); } /** * Creates grid parent layout. * * @param title * @param job */ protected GridLayout createGridLayout(String title, final Job job, final Address address) { cardView = new CardView(context); LinearLayout.LayoutParams cardViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, 0, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING,LayoutUtils.DEFAULT_MAX_PADDING); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); gradientDrawable.setCornerRadius(7f); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_CARD_VIEW_SHADOW_COLOR); cardView.setBackground(gradientDrawable); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); linearLayout.setOrientation(LinearLayout.VERTICAL); RelativeLayout relativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams relativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); relativeLayoutParams.rightMargin = LayoutUtils.convertDpToPixel(context, 25); relativeLayout.setLayoutParams(relativeLayoutParams); TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_HERDER_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); textView.setLayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); textView.setPadding(5, 10, 5, 5); textView.setText(title); textView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); relativeLayout.addView(textView); if (job != null && !job.getStatus().isFinalized()) { ImageView imageView = new ImageView(context); RelativeLayout.LayoutParams imageViewParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); imageViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); imageView.setLayoutParams(imageViewParams); imageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.EDIT, CommonConstants.Images.IMAGE_DPI))); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(JobDetailAddressEditForm.class, new JobDetailAddressForm.AddressFormArguments(job, address)); } }, false); } }); relativeLayout.addView(imageView); } GridLayout gridLayout = new GridLayout(context); RelativeLayout.LayoutParams gridLayoutParams = new RelativeLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); gridLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); gridLayout.setLayoutParams(gridLayoutParams); gridLayout.setColumnCount(2); gridLayout.setUseDefaultMargins(true); linearLayout.addView(relativeLayout); linearLayout.addView(gridLayout); cardView.addView(linearLayout); return gridLayout; } protected View getParrentView() { return getParentView(null); } protected View getParentView(View v) { FrameLayout frameLayout = new FrameLayout(context); frameLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); RelativeLayout relativeLayout = new RelativeLayout(context); LinearLayout.LayoutParams relativeLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); relativeLayout.setLayoutParams(relativeLayoutParams); LinearLayout linearLayout = new LinearLayout(context); LinearLayout.LayoutParams linearLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); linearLayout.setLayoutParams(linearLayoutParams); linearLayout.setOrientation(LinearLayout.VERTICAL); if (v == null) { linearLayout.addView(cardView); } else { linearLayout.addView(v); } relativeLayout.addView(linearLayout); frameLayout.addView(relativeLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(frameLayout); return scrollView; } /** * Creates no content available layout. * * @param message */ protected View createNoContentAvailableLayout(String message) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setOrientation(LinearLayout.VERTICAL); TextView textView = new TextView(context); textView.setText(message); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, CommonConstants.Font.DEFAULT_FONT_SIZE); textView.setTypeface(CommonConstants.Font.getDefaultRegularFont()); textView.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); linearLayout.addView(textView); return linearLayout; } }     service/src/ch/mfiles/kaba/kolibri/service/ui/widgets/MeasurementListItemWidget.java:   package ch.mfiles.kaba.kolibri.service.ui.widgets; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.text.TextUtils.TruncateAt; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class MeasurementListItemWidget { private Context context; private ReportMeasurement measurement; private OnClickListener clickListener; private boolean checked; public MeasurementListItemWidget(Context context, ReportMeasurement measurement, OnClickListener clickListener) { this.context = context; this.measurement = measurement; this.clickListener = clickListener; } public View getView() { LinearLayout contentItemLayout = new LinearLayout(context); contentItemLayout.setOrientation(LinearLayout.HORIZONTAL); contentItemLayout.setLayoutParams(new AbsListView.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS())); // contentItemLayout.setPadding(0 // , LayoutUtils.DEFAULT_MIN_PADDING, LayoutUtils.DEFAULT_MAX_PADDING // , LayoutUtils.DEFAULT_MIN_PADDING); // Generate bottom border only LayerDrawable bottomBorder = getBorders( Color.WHITE, // Background color Color.LTGRAY, // Border color 0, // Left border in pixels 0, // Top border in pixels 0, // Right border in pixels 2 // Bottom border in pixels ); contentItemLayout.setBackground(bottomBorder); FrameLayout.LayoutParams checkBoxParams = new FrameLayout.LayoutParams(LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS()); checkBoxParams.gravity = Gravity.LEFT ; CheckBox checkBox = new CheckBox(context); // checkBox.setId(ID_CHECK); checkBox.setPadding(0, 0, 8, 0); checkBox.setLayoutParams(checkBoxParams); contentItemLayout.addView(checkBox); TextView measureTextView = new TextView(context); // measureTextView.setId(ID_MEASURE); measureTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); measureTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); LinearLayout.LayoutParams measureTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); measureTextParams.width = 0; measureTextParams.weight = 0.42f; measureTextView.setLayoutParams(measureTextParams); contentItemLayout.addView(measureTextView); TextView fDymTextView = new TextView(context); // fDymTextView.setId(ID_FDYM); fDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout.LayoutParams fDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fDymTextParams.width = 0; fDymTextParams.weight = 0.2f; fDymTextView.setLayoutParams(fDymTextParams); contentItemLayout.addView(fDymTextView); TextView tDymTextView = new TextView(context); // tDymTextView.setId(ID_TDYM); tDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); tDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout.LayoutParams tDymTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); tDymTextParams.width = 0; tDymTextParams.weight = 0.20f; tDymTextView.setLayoutParams(tDymTextParams); contentItemLayout.addView(tDymTextView); TextView fEneTextView = new TextView(context); // fEneTextView.setId(ID_FEND); fEneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fEneTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout.LayoutParams fEneTextParams = new LinearLayout.LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fEneTextParams.width = 0; fEneTextParams.weight = 0.18f; fEneTextView.setLayoutParams(fEneTextParams); contentItemLayout.addView(fEneTextView); checkBox.setOnClickListener(clickListener); checkBox.setFocusable(false); checkBox.setChecked(checked); System.out.println("getView set checked " + checkBox.isChecked()); measureTextView.setText(measurement.getMeasurement()); fDymTextView.setText(measurement.getDynamicPowerPeakValue()); tDymTextView.setText(measurement.getDynamicTime()); fEneTextView.setText(measurement.getStaticEndPower());; measureTextView.setEllipsize(TruncateAt.END); return contentItemLayout; } protected LayerDrawable getBorders(int bgColor, int borderColor, int left, int top, int right, int bottom){ // Initialize new color drawables ColorDrawable borderColorDrawable = new ColorDrawable(borderColor); ColorDrawable backgroundColorDrawable = new ColorDrawable(bgColor); // Initialize a new array of drawable objects Drawable[] drawables = new Drawable[] { borderColorDrawable, backgroundColorDrawable }; // Initialize a new layer drawable instance from drawables array LayerDrawable layerDrawable = new LayerDrawable(drawables); // Set padding for background color layer layerDrawable.setLayerInset(1, // Index of the drawable to adjust [background color layer] left, // Number of pixels to add to the left bound [left border] top, // Number of pixels to add to the top bound [top border] right, // Number of pixels to add to the right bound [right border] bottom // Number of pixels to add to the bottom bound [bottom border] ); // Finally, return the one or more sided bordered background drawable return layerDrawable; } public ReportMeasurement getMeasurement() { return measurement; } public void setChecked(Boolean checked) { this.checked = checked; } public boolean isChecked() { return checked; } }     service/src/ch/mfiles/kaba/kolibri/service/ui/widgets/MeasurementTable.java:   package ch.mfiles.kaba.kolibri.service.ui.widgets; import java.util.ArrayList; import java.util.List; import com.journeyapps.barcodescanner.camera.CenterCropStrategy; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.widgets.DividerView; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.ui.Image; public class MeasurementTable { private Form form; private ServiceApplication app; private Context context; private LinearLayout table; private LinearLayout emptyMessageView; private LinearLayout headerTable; private LinearLayout tableContent; private ImageView checkImageView; private List measurementList; private List checkedList; private List itemWidgets; private String measurementPoint; public MeasurementTable(Form form, ServiceApplication app, String measurementPoint) { this.form = form; this.app = app; this.context = app.appman.getContext(); this.table = createMeasurementTable(); this.measurementPoint = measurementPoint; } public View getTable() { return table; } public List getCheckedList() { return checkedList; } public List getList() { return measurementList; } public String getMeasurementPoint() { return measurementPoint; } private LinearLayout createMeasurementTable() { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(0, 0, 5, 5); headerTable = createHeader(ServiceMessages.getString("Measurement"), "Fdyn","Tdyn","Fend"); linearLayout.addView(headerTable); tableContent = new LinearLayout(context); tableContent.setOrientation(LinearLayout.HORIZONTAL); tableContent.setPadding(0, LayoutUtils.DEFAULT_MAX_PADDING, 0, LayoutUtils.DEFAULT_MIN_PADDING); linearLayout.addView(tableContent); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.addView(emptyMessageView); checkedList = new ArrayList(); itemWidgets = new ArrayList(); return linearLayout; } public interface ClickedResult { void onClicked(boolean isChecked); } private LinearLayout createHeader(String measure, String fdym, String tdym, String fend) { LinearLayout headerLayout = new LinearLayout(context); headerLayout.setOrientation(LinearLayout.HORIZONTAL); headerLayout.setPadding(0, LayoutUtils.DEFAULT_MAX_PADDING, 0, 0); headerLayout.addView(new DividerView(context)); checkImageView = new ImageView(context); checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_UNCHECKED, CommonConstants.Images.IMAGE_DPI))); LinearLayout.LayoutParams buttonRelativeLayoutParams = new LinearLayout.LayoutParams( LayoutUtils.convertDpToPixel(context, 26), LayoutUtils.convertDpToPixel(context, 26)); buttonRelativeLayoutParams.gravity = Gravity.CENTER_VERTICAL; buttonRelativeLayoutParams.leftMargin = 8; buttonRelativeLayoutParams.bottomMargin = 10; checkImageView.setLayoutParams(buttonRelativeLayoutParams); checkImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("Check clicked"); boolean checkAll = false; if (checkedList.size() == itemWidgets.size()) { System.out.println("remvoe all cheked"); checkAll = false; checkedList.clear(); for (int i = 0; i < itemWidgets.size(); i++) { itemWidgets.get(i).setChecked(false); } } else { System.out.println("check all"); checkAll = true; checkedList.clear(); checkedList.addAll(measurementList); } for (int i = 0; i < itemWidgets.size(); i++) { itemWidgets.get(i).setChecked(checkAll); } tableContent.removeAllViews(); tableContent.addView(generateTableContent(itemWidgets)); resetHeaderCheckBox(); } }); headerLayout.addView(checkImageView); TextView measureTextView = new TextView(context); measureTextView.setGravity(Gravity.CENTER_VERTICAL); measureTextView.setText(measure); measureTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); measureTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); LinearLayout.LayoutParams measureTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); measureTextParams.width = 0; measureTextParams.weight = 0.42f; measureTextView.setLayoutParams(measureTextParams); headerLayout.addView(measureTextView); TextView fDymTextView = new TextView(context); LinearLayout.LayoutParams fDymTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fDymTextParams.width = 0; fDymTextParams.weight = 0.2f; fDymTextView.setLayoutParams(fDymTextParams); fDymTextView.setText(fdym); fDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fDymTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); headerLayout.addView(fDymTextView); TextView tDymTextView = new TextView(context); LinearLayout.LayoutParams tDymTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); tDymTextParams.width = 0; tDymTextParams.weight = 0.2f; tDymTextView.setLayoutParams(tDymTextParams); tDymTextView.setText(tdym); tDymTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); tDymTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); tDymTextView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END); headerLayout.addView(tDymTextView); TextView fEneTextView = new TextView(context); LinearLayout.LayoutParams fEneTextParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); fEneTextParams.width = 0; fEneTextParams.weight = 0.18f; fEneTextView.setLayoutParams(fEneTextParams); fEneTextView.setText(fend); fEneTextView.setTextColor(LayoutUtils.DEFAULT_LABEL_COLOR); fEneTextView.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); headerLayout.addView(fEneTextView); return headerLayout; } private Drawable getBitmanDrawable(Image image) { return form.getBitmanDrawable(image); } private void resetHeaderCheckBox() { if (checkedList != null) { if (checkedList.size() == 0) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_UNCHECKED, CommonConstants.Images.IMAGE_DPI))); } else if (checkedList.size() < itemWidgets.size()) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_SOME, CommonConstants.Images.IMAGE_DPI))); } else if (checkedList.size() == itemWidgets.size()) { checkImageView.setImageDrawable(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.CHECK_CHECKED, CommonConstants.Images.IMAGE_DPI))); } else { throw new RuntimeException("Checked item more than item in the list."); } checkedChange.onCheckedChange(getCheckedList()); } } public void loadTable (List measurements) { checkedList.clear(); this.measurementList = measurements; itemsChange.onItemsChange(); resetHeaderCheckBox(); itemWidgets.clear(); tableContent.removeAllViews(); if (!measurements.isEmpty()) { emptyMessageView.setVisibility(View.GONE); for (int i = 0; i < measurements.size(); i++) { final ReportMeasurement measurement = measurements.get(i); MeasurementListItemWidget listItemWidget = new MeasurementListItemWidget(context, measurement, new OnClickListener() { @Override public void onClick(View v) { if (v instanceof CheckBox) { if(((CheckBox) v).isChecked()) { checkedList.add(measurement); } else { checkedList.remove(measurement); } resetHeaderCheckBox(); } } }); itemWidgets.add(listItemWidget); if(emptyMessageView.getChildCount() > 0) emptyMessageView.removeAllViewsInLayout(); } tableContent.addView(generateTableContent(itemWidgets)); } else { if(emptyMessageView.getChildCount() > 0) emptyMessageView.removeAllViewsInLayout(); emptyMessageView.setVisibility(View.VISIBLE); TextView textView = CommonUtilForm.getTextView(context, ServiceMessages.getString("noDataAvailable")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); } } private LinearLayout generateTableContent(List itemWidgets) { LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams contentLinearLayoutParams = new LayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setLayoutParams(contentLinearLayoutParams); for (int i = 0; i < itemWidgets.size(); i++) { MeasurementListItemWidget listItemWidget = itemWidgets.get(i); contentLinearLayout.addView(listItemWidget.getView()); } return contentLinearLayout; } public interface OnCheckedChange { void onCheckedChange(List checkedList); } private OnCheckedChange checkedChange; public void onCheckedChange(OnCheckedChange checkedChange) { this.checkedChange = checkedChange; checkedChange.onCheckedChange(getCheckedList()); } public interface OnEnabledChange { void onEnabledChange(boolean enabled); } private OnEnabledChange enabledChange; public void onEnabledChange(OnEnabledChange enabledChange) { this.enabledChange = enabledChange; enabledChange.onEnabledChange(enabled); } private boolean enabled = true; public void setEnabled(boolean enabled) { this.enabled = enabled; enabledChange.onEnabledChange(enabled); } public interface OnItemsChange { void onItemsChange(); } private OnItemsChange itemsChange; public void onItemsChange(OnItemsChange itemsChange) { this.itemsChange = itemsChange; itemsChange.onItemsChange(); } }     service/src/ch/mfiles/kaba/kolibri/service/util/ReportUtil.java:   package ch.mfiles.kaba.kolibri.service.util; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceApplication; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.forms.JobListForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; public class ReportUtil { private static Log log = LogFactory.getLog(ReportUtil.class); private Form form; private ServiceApplication app; public ReportUtil(Form form, ServiceApplication app) { this.form = form; this.app = app; } /** * Handles on click event for sending report. * * @return */ public ApplicationEvent onSendingReport(final Job job) { job.loadReports(app.dbutil); final Report report = job.getLatestReport(); // Load stamping report.loadTimes(app.dbutil); List jobReportTimeList = report.getTimes(); // Check if there are times if (jobReportTimeList.isEmpty()) { app.showMessage(ServiceMessages.getString("noTimesheetEntriesReportCannotBeSent")); //$NON-NLS-1$ return null; } // Determine whether a type of work is specified for all stamps (MON order only) else if (job.getJobType().isMON() && !checkArba(jobReportTimeList)) { app.showMessage(ServiceMessages.getString("thereAreTimeStampsWithoutWorkType")); //$NON-NLS-1$ return null; } else { report.setCreateDate((jobReportTimeList.get(0)).getStartTime()); app.dbutil.updateReport(report); } if(!report.isNoMaterial() && report.getParts().isEmpty()) { app.showMessage(ServiceMessages.getString("noMaterialPresent")); //$NON-NLS-1$ return null; } List formDescList = ServiceJobUtil.isReportDocsComplete(job); String warningMessage = ""; for (String formDesc : formDescList) { if (!warningMessage.isEmpty()) { warningMessage += "\n"; } if (formDesc.equalsIgnoreCase(ServiceConstants.ModernisationNecessary)) { warningMessage += MessageFormat.format(ServiceMessages.getString("noFormDescImagePresent"), new Object[] { app.dbutil.selectJobFormDescByFormDesc(formDesc).getText()}); } else { warningMessage += MessageFormat.format(ServiceMessages.getString("noFormDescPresent"), new Object[] { app.dbutil.selectJobFormDescByFormDesc(formDesc).getText()}); } } if (!warningMessage.isEmpty()) { warningMessage = warningMessage + "\n" + ServiceMessages.getString("reportCannotBeSent"); app.showWarningMessageBox(warningMessage); return null; } if (ServiceJobUtil.isJobRequireReportMessageToCustomer(job)) { String message = MessageFormat.format(ServiceMessages.getString("reportMessageToCustomer"), //$NON-NLS-1$ new Object[] { job.getJobType().getCode() }); app.showMessage(message); //$NON-NLS-1$ return null; } if (!ServiceJobUtil.isReportImageComplete(job) ) { app.showMessage(ServiceMessages.getString("noImagesEntriesReportCannotBeSent")); return null; } if (!ServiceJobUtil.isInstallationWorkTypeComplete(job) ) { app.showMessage(MessageFormat.format(ServiceMessages.getString("AtLeastXImagesNecessary") , new Object[] { ServiceConstants.REQUIRE_IMAGE})); return null; } job.getLatestReport().loadMeasurements(app.dbutil); if (ServiceJobUtil.isTooMuchMeasurementAreMadeForOnemeasurePoint(report.getMeasurements())) { app.showMessage(ServiceMessages.getString("tooManyMeasurements")); //$NON-NLS-1$ return null; } if (!report.isSignatureFlag()) { app.showMessage(ServiceMessages.getString("noSignaturePresent")); //$NON-NLS-1$ //For jobs with type MON, the user only have to let sign the report, if the report time has work type "Installation" (ZARBEITSART = 32). if (job.getJobType().isMON() && ServiceJobUtil.isMandatoryByReportTime(job)) { return null; } return null; } //IBS checklist have to be mandatory when working type is code 32 if (!ServiceJobUtil.isChecklistComplete(job)) { app.showMessage(ServiceMessages.getString("noChecklistPresent")); return null; } //If working type "98" (ZKDMOBREP.ARBA = 98) is selected in report, a specific form is mandatory //If ZKDMOBREP.ARBA = 98, FORM.ID = VD10 is mandatory and have to be saved and added to report. if (!ServiceJobUtil.isReportFormVonoviaComplete(job)) { app.showMessage(ServiceMessages.getString("noVonoviaFormPresent")); return null; } runSaveReport(job, report); return null; } private void runSaveReport(final Job job, final Report report) { app.appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (report.isPartialRepair() && !report.isFinalRepair()) { confirmSendingReport(job, ServiceMessages.getString("sendReport"), true); //$NON-NLS-1$ } else { if (log.isDebugEnabled()) { log.debug("last report, no new GUID generated"); //$NON-NLS-1$ } confirmSendingReport(job, ServiceMessages.getString("JobFinishedSendReport"), false); //$NON-NLS-1$ } return null; } }, false); } private ApplicationEvent confirmSendingReport(Job job, String label, boolean isPartialRepair) { GuidGenerator generator = new GuidGenerator(); try { if (app.showMessageBox(label, ServiceMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_QUESTION) == Application.MBOX_RESULT_NO) { //$NON-NLS-1$ return null; } else { if (isPartialRepair) { job.setCurrentReportGuId(generator.generate()); } if (new RemoteTransactionHandler().saveReport(form.db, job, SignatureUtil.FILE_PATH)) { if (isPartialRepair) { app.dbutil.insertReplaceReport(new Report(job.getJobNumber(), job.getJobType(), job.getCurrentReportGuId(app.dbutil), job.getNextReportIdx(app.dbutil), job.isCycleOfInstallationFlag())); job.loadReports(app.dbutil); app.dbutil.updateJob(job); } app.injectAndLeaveToForm(JobListForm.class, null); } else { return null; } } } catch (UnknownHostException | NoSuchAlgorithmException e) { throw new ApplicationException(e); } return null; } /** * @param jobReportTimeList List with time elements * @return true if check is successful, false if problems have been found */ private boolean checkArba(List jobReportTimeList) { boolean result = true; for (int i = 0; i < jobReportTimeList.size(); i++) { String arba = jobReportTimeList.get(i).getWorkTypeCode(); if (arba == null || StringUtil.isEmpty(arba) || CommonConstants.PLEASE_SELECT.equalsIgnoreCase(arba)) { //$NON-NLS-1$ result = false; } } return result; } }     service/src/ch/mfiles/kaba/kolibri/service/util/ServiceConstants.java:   package ch.mfiles.kaba.kolibri.service.util; public class ServiceConstants { ServiceConstants() { } public static final int COMPANY_TITLE_CODE = 0003; public static final int PERMISSION_REQUEST_CODE = 200; public static final int RETENTION_PERIOD_MASTER_REFRESH = 24; // Hours public static final int MAX_DOWNLOAD = 30; public static final int MAX_COMFIRM_DOWNLOAD = 10; public static final String InstallationWorkType = "05"; public static final String ModernisationNecessary = "01"; public static final String OfferModernisation = "02"; public static final String SecurityReport = "06"; public static final int MAX_MEASUREMENT_FOR_ONE_POINT = 1; public static final String MATERIAL_BILLING_NEW_PRICE = "01"; public static final int REQUIRE_IMAGE = 5; public static final class Index { Index() { } public static final Integer NULL = null; public static final Integer ZERO = 0; public static final Integer ONE = 1; public static final Integer TWO = 2; public static final Integer THREE = 3; public static final Integer FOUR = 4; public static final Integer FIVE = 5; public static final Integer SIX = 6; public static final Integer SEVEN = 7; public static final Integer EIGHT = 8; public static final Integer NINE = 9; } public static final class MatUnit { MatUnit() { } public static final String M = "M"; public static final String MM = "MM"; public static final String KG = "KG"; public static final String ST = "ST"; } public static final class KMaterialNumber { KMaterialNumber() { } public static final String K_Material = "K-Material"; public static final String K_11 = "K-11"; public static final String K_12 = "K-12"; public static final String K_13 = "K-13"; public static final String K_14 = "K-14"; } }     service/src/ch/mfiles/kaba/kolibri/service/util/ServiceFormUtil.java:   package ch.mfiles.kaba.kolibri.service.util; import java.util.List; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.FormItem; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil.Images; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; public class ServiceFormUtil { public static boolean isFormEdited(List formInstances) { if (formInstances.isEmpty()) { return false; } return true; } public static boolean isFormInComplete(List formItemLis, List formInstances) { return !isFormDone(formItemLis, formInstances); } public static boolean isFormDone(List formItemLis, List formInstances) { if (formItemLis.size() == formInstances.size()) { return true; } return false; } /** * If a form was edited or done: Check Box * If no form was edited or done: Check Box Outline Blank * If a form has errors or is incomplete: Indeterminate Check Box * @param formItemLis * @param formInstances * @return image as integer */ public static Images getCheckImageStatus(List formItemLis, List formInstances) { Images result = ImagesUtil.Images.CHECK_UNCHECKED; if (isFormEdited(formInstances)) { //If a form was edited or done: "", text black, Icon: Check Box if (isFormDone(formItemLis, formInstances)) { result = ImagesUtil.Images.CHECK_CHECKED; } else { //If a form has errors or is incomplete: "", text red, Icon: Indeterminate Check Box result = ImagesUtil.Images.CHECK_SOME; } } else { //If no form was edited or done: "Kein Formular erfasst." text grey, Icon: Check Box Outline Blank if (isFormDone(formItemLis, formInstances)) { result = ImagesUtil.Images.CHECK_UNCHECKED; } } return result; } /** * If a form was edited or done: text black * If no form was edited or done: text grey * If a form has errors or is incomplete: text red * * @param formItemLis * @param formInstances * @return */ public static int getTextColor(List formItemLis, List formInstances) { int result = LayoutUtils.DEFAULT_TEXT_COLOR; switch (getCheckImageStatus(formItemLis, formInstances)) { case CHECK_UNCHECKED: result = LayoutUtils.DEFAULT_DARK_GRAY; break; case CHECK_CHECKED: result = LayoutUtils.DEFAULT_TEXT_COLOR; break; case CHECK_SOME: result = LayoutUtils.DEFAULT_ERROR_COLOR; break; default: result = LayoutUtils.DEFAULT_TEXT_COLOR; break; } return result; } }     service/src/ch/mfiles/kaba/kolibri/service/util/ServiceJobUtil.java:   package ch.mfiles.kaba.kolibri.service.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMeasurement; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.service.ServiceMessages; public class ServiceJobUtil { private static Log log = LogFactory.getLog(ServiceJobUtil.class); ServiceJobUtil() { } /** * Checks whether the remaining report requires the job to return to partly * done after a newer report was deleted. * * @param job job whose reports have already been reloaded after deletion * @return {@code true} when the latest remaining report was sent as partial */ public static boolean shouldRestorePartlyDoneAfterReportDeletion(Job job) { Report report = job.getLatestReport(); return report != null && report.getReportStatus().isReceived() && report.isPartialRepair(); } /** * Checks Is Job Acceptable. * * @param job * @return */ public static boolean isJobAcceptable(Job job) { return job.getStatus().isNew(); } /** * Checks Is Job Forwardable. * * To send a job forward to a partner, the job have to be in status NEW or RECEIVED or PARTLY_DONE; * forward a job to a partner isn't possible with another job status or job type REP. * The job cannot be forwarded too, if there is any report things added by user (time, material, report itself, messages). * * Forward of a job is new only possible for job type REP. * * A job cannot be forwarded if the user already have done followed inputs: * - Create a report * - Add report time * - Add report material * - Add report messages * @param job * @return */ public static boolean isJobForwardable(Job job) { return job.getJobType().isREP() && (job.getStatus().isNew() || job.getStatus().isPartlyDone() || (job.getStatus().isReceived() && isEmptyReportContent(job))); } /** * Checks Is Job can Delete. * * Check whether the order can be deleted: * - NEW -> delete (with SAP status 16 update) * - Accept -> delete (with SAP status 16 update) * - No times on the akt. rapport * - No unsolicited report * - REPEATED -> there is not * - RELEASED -> delete (without SAP status update) * - IN WORK -> do not delete * - COMPLETED -> delete (without SAP status update) * - PARTLED -> delete (with SAP status 16 update) * (if a report has already been sent, no more has opened and no time is running) * * A job cannot be deleted if the user already have done followed inputs: * - Create a report * - Add report time * - Add report material * - Add report messages * @param job * @return */ public static boolean isJobDeletable(Job job) { // Check whether the order can be deleted: // - NEW -> delete (with SAP status 16 update) // - Accept -> delete (with SAP status 16 update) // - No times on the akt. rapport // - No unsolicited report // - REPEATED -> there is not // - RELEASED -> delete (without SAP status update) // - IN WORK -> do not delete // - COMPLETED -> delete (without SAP status update) // - PARTLED -> delete (with SAP status 16 update) (if a report has already been sent, no more has opened and no time is running) boolean isJobDeletable = true; isJobDeletable = job.getStatus().isNew() || (job.getStatus().isReceived() && job.getCurrentReport().getReportStatus().isInitial()) || job.getStatus().isRejected() || job.getStatus().isForwarded() || job.getStatus().isFinalized() || (job.getStatus().isPartlyDone() && job.getCurrentReport().getReportStatus().isInitial()) || job.getStatus().isDeleted() ; return isJobDeletable && isEmptyReportContent(job); } public static boolean isEmptyReportContent(Job job) { List reportMatList = job.getLatestReport().getParts(); List reportTextList = job.getLatestReport().getMessages(); List reportTimeList = job.getLatestReport().getTimes(); boolean isEmptyMessage = true; for (int i = 0; i < reportTextList.size(); i++) { JobMessage jobMessage = reportTextList.get(i); if (!"".equals(jobMessage.getMessageId()) || !jobMessage.getFullText().isEmpty()) { isEmptyMessage = false; } } String jobContent = job.getJobNumber() + " " + job.getObjectAddress().getPostalCode(); if (job.getJobType().isMON()) { jobContent += " " + StringUtil.removeAllLeadingZero(job.getJobNumber()); } else { jobContent += " " + job.getCommissionNumber(); } boolean isEmptyReportContent = false; isEmptyReportContent = !job.getLatestReport().getReportStatus().isNew()/*new report*/ && reportMatList.isEmpty() && isEmptyMessage && (reportTimeList.isEmpty() || job.getLatestReport().getReportStatus().isReceived()); log.debug(jobContent + " time " + reportTimeList.size() + " report status " + job.getLatestReport().getReportStatus().toString() + " isEmptyReportContent " + isEmptyReportContent + " material " + reportMatList.size() + " isEmptyMessage " + isEmptyMessage); return isEmptyReportContent; } /** * Checks is job start time able. * * @param job * @return */ public static boolean isJobStartTimeable(Job job) { return (job.getStatus().isReceived() || job.getStatus().isPartlyDone() || job.getStatus().isInProgress()); } /** * Checks Is Max Download. * * @param list * @return */ public static boolean isMaxDownload(List list) { return (list != null && list.size() > ServiceConstants.MAX_DOWNLOAD); } /** * Checks Is Max Confirm To Download. * * @param list * @return */ public static boolean isMaxConfirmDownload(List list) { return (list != null && list.size() > ServiceConstants.MAX_COMFIRM_DOWNLOAD); } /** * Checks Is valid job number. * * @see "[MIG-88] Integrate of SCAN-button in joblist" * * @param jobNumber * @return */ public static boolean isValidJobNumber(String jobNumber) { return StringUtil.isNotEmpty(jobNumber) && jobNumber.length() == 10; } /** * Checks Is job Editable. * * @see "[MIG-135] Edit of job informations is only possible by self created jobs" * * @param job * @return */ public static boolean isJobEditable(Job job) { return (job.isLocalJob() && job.getJobType().isREP()); } /** * Checks Is job can reschedule. * * @see "[MIG-349] Rescheduling of jobs" * * - RECEIVED\n * - PARTLY_DONE\n * @param job * @return */ public static boolean isJobRescheduleable(Job job) { return (job.getStatus().isReceived() || job.getStatus().isPartlyDone()); } /** * Checks Is valid ZIP. * * @see "[MIG-127] Validation of ZIP (PLZ)" * * @param zip * @return */ public static boolean isValidZIP(String zip) { return StringUtil.isNotEmpty(zip) && StringUtil.isNumeric(zip) && zip.length() == 5; } public static boolean isJobActive(Job job) { boolean isAppointmentDateInActive = false; Date today = new Date(); Calendar appointmentDateCalendar = Calendar.getInstance(); appointmentDateCalendar.setTime(job.getAppointmentDate()); if(job.getJobType().isSAV()) { appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(!appointmentDateCalendar.getTime().after(today)) { isAppointmentDateInActive = true; } appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, 90); if ((job.getStatus().isNew() || job.getStatus().isPartlyDone()) && !appointmentDateCalendar.before(today)) { isAppointmentDateInActive = true; } } else { appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(!appointmentDateCalendar.getTime().after(today)) { isAppointmentDateInActive = true; } appointmentDateCalendar.add(Calendar.DAY_OF_YEAR, 3); if ((job.getStatus().isNew() || (job.getStatus().isPartlyDone()) && !appointmentDateCalendar.getTime().after(today))) { isAppointmentDateInActive = true; } } boolean isActiveJobDateInActive = false; Calendar activeDateCalendar = Calendar.getInstance(); activeDateCalendar.setTime(job.getActiveJobDate()); if(job.getJobType().isSAV()) { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(!activeDateCalendar.getTime().after(today)) { isActiveJobDateInActive = true; } } else { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(!activeDateCalendar.getTime().after(today)) { isActiveJobDateInActive = true; } } boolean isJobStatusActive = false; JobStatus status = job.getStatus(); isJobStatusActive = status.isNew() || status.isReceived() || status.isInProgress() || status.isPartlyDone(); log.info("isJobStatusActive " + isJobStatusActive + " isEdateInActive " + isAppointmentDateInActive + " isActiveJobDateInActive " + isActiveJobDateInActive); isJobStatusActive = isJobStatusActive && (isAppointmentDateInActive && isActiveJobDateInActive) || (!isEmptyReportContent(job) && isJobStatusActive); log.info("This job is in Active -> " + isJobStatusActive); return isJobStatusActive; } public static boolean isJobInPlanned(Job job) { boolean isEdateInPlaned = false; Date today = new Date(); Calendar edateCalendar = Calendar.getInstance(); edateCalendar.setTime(job.getAppointmentDate()); if(job.getJobType().isSAV()) { edateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(edateCalendar.getTime().getTime() >= today.getTime()) { isEdateInPlaned = true; } } else { edateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(edateCalendar.getTime().getTime() >= today.getTime()) { isEdateInPlaned = true; } } boolean isActiveJobDateInPlaned = false; Calendar activeDateCalendar = Calendar.getInstance(); activeDateCalendar.setTime(job.getActiveJobDate()); if(job.getJobType().isSAV()) { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -90); if(activeDateCalendar.getTime().getTime() >= today.getTime()) { isActiveJobDateInPlaned = true; } } else { activeDateCalendar.add(Calendar.DAY_OF_YEAR, -3); if(activeDateCalendar.getTime().getTime() >= today.getTime()) { isActiveJobDateInPlaned = true; } } boolean isJobStatusPlanned = false; JobStatus status = job.getStatus(); isJobStatusPlanned = status.isReceived() || status.isPartlyDone(); log.info("isJobStatusPlaned " + isJobStatusPlanned + " isEdateInPlaned " + isEdateInPlaned + " isActiveJobDateInPlaned " + isActiveJobDateInPlaned); isJobStatusPlanned = isJobStatusPlanned && (isEdateInPlaned || isActiveJobDateInPlaned) && isEmptyReportContent(job); log.info("This job is in planned -> " + isJobStatusPlanned); if (!isJobStatusPlanned) { log.info("EDATE -> " + DateTimeUtil.showDate(job.getAppointmentDate())); log.info("ACTIVE_DATE -> " + DateTimeUtil.showDate(job.getActiveJobDate())); log.info("today-------" + DateTimeUtil.showDate(today) ); log.info("edate-------" + DateTimeUtil.showDate(edateCalendar.getTime()) ); log.info("active date-" + DateTimeUtil.showDate(activeDateCalendar.getTime()) ); } return isJobStatusPlanned; } public static boolean isJobFinalized(Job job) { return job.getStatus().isForwarded() || job.getStatus().isFinalized(); } /** * Checks is JobReportTime overlapping * * * @param jobReportTimeList * @param newJobReportTime * @return */ public static List isJobTimesheetOverlapping(List jobReportTimeList, String start, String stop) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setStartTime(DateTimeUtil.parseDateFromHHmm(start, DateTimeUtil.getToday().getTime())); newJobTime.setStopTime(DateTimeUtil.parseDateFromHHmm(stop, DateTimeUtil.getToday().getTime())); return isJobTimesheetOverlapping(jobReportTimeList, newJobTime); } /** * Checks is JobReportTime overlapping * * * @param jobReportTimeList * @param newJobReportTime * @return */ public static List isJobTimesheetOverlapping(List jobReportTimeList, JobReportTime newJobReportTime) { List overlappingJobReportTimeList = new ArrayList(); for (JobReportTime jobReportTime : jobReportTimeList) { boolean isStartBefor = newJobReportTime.getStartTime().before(jobReportTime.getStartTime()); boolean isStopAfter = newJobReportTime.getStopTime().after(jobReportTime.getStopTime()); boolean isStartOverlapping = (newJobReportTime.getStartTime().compareTo(jobReportTime.getStartTime()) > 0) && (newJobReportTime.getStartTime().compareTo(jobReportTime.getStopTime()) < 0); boolean isStopOverlapping = (newJobReportTime.getStopTime().compareTo(jobReportTime.getStopTime()) < 1) && (newJobReportTime.getStopTime().compareTo(jobReportTime.getStartTime()) > 0);; if (isStartOverlapping || isStopOverlapping) { overlappingJobReportTimeList.add(jobReportTime); } if (isStartBefor && isStopAfter) { overlappingJobReportTimeList.add(jobReportTime); } } if (overlappingJobReportTimeList.size() > 0) { Object[] arguments = new Object[] { DateTimeUtil.showTime(newJobReportTime.getStartTime()) + " - " + DateTimeUtil.showTime(newJobReportTime.getStopTime()) , DateTimeUtil.showTime(overlappingJobReportTimeList.get(0).getStartTime()) + " - " + DateTimeUtil.showTime(overlappingJobReportTimeList.get(0).getStopTime())}; log.info(MessageFormat.format(Messages.getString("overlapping"), arguments)); } return overlappingJobReportTimeList; } /** * Checks If report has doc that require for job. * * @param job * @param jobFileList * @param reportImageAttachmentsList * * @return list of formDesc code that require for the job, report. */ public static List isReportDocsComplete(Job job) { boolean isFormDesc1Valid = false; boolean isFormDesc2Valid = false; boolean isFormDesc3Valid = false; boolean isSecurityReportValid = false; boolean isModernisationNecessaryValid = false; boolean isSecurityReportRequire = false; boolean isModernisationNecessaryRequire = false; isModernisationNecessaryRequire = isMandatoryByReportMessage(job); isModernisationNecessaryValid = !isModernisationNecessaryRequire; isSecurityReportRequire = job.getLatestReport().isSafetyReport(); isSecurityReportValid = !isSecurityReportRequire; log.info("comNo " + job.getCommissionNumber() + " FormDesc1 " + job.getFormDesc1() + " FormDesc2 " + job.getFormDesc2() + " FormDesc3 " + job.getFormDesc3()); Map> documentFormDescMap = job.getLatestReport().getDocumentFormDescMap(); if (documentFormDescMap.containsKey(ServiceConstants.ModernisationNecessary)) { if (isModernisationNecessaryRequire) { isModernisationNecessaryValid = true; } } if (documentFormDescMap.containsKey(job.getFormDesc1())) { if (isDocumentOrNoFormValid(job.getFormDesc1(), documentFormDescMap.get(job.getFormDesc1()), job.getLatestReport().getNoForm1())) { isFormDesc1Valid = true; } } if (documentFormDescMap.containsKey(job.getFormDesc2())) { if (isDocumentOrNoFormValid(job.getFormDesc2(), documentFormDescMap.get(job.getFormDesc2()), job.getLatestReport().getNoForm2())) { isFormDesc2Valid = true; } } if (documentFormDescMap.containsKey(job.getFormDesc3())) { if (isDocumentOrNoFormValid(job.getFormDesc3(), documentFormDescMap.get(job.getFormDesc3()), job.getLatestReport().getNoForm3())) { isFormDesc3Valid = true; } } if (documentFormDescMap.containsKey(ServiceConstants.SecurityReport)) { if (isSecurityReportRequire) { isSecurityReportValid = true; } } for (FormInstance formInstance : job.getCurrentReport().getFormInstances()) { if (isGenericFormValid(ServiceConstants.ModernisationNecessary, formInstance) && !isModernisationNecessaryValid) { isModernisationNecessaryValid = true; } if (isGenericFormValid(job.getFormDesc1(), formInstance) && !isFormDesc1Valid) { isFormDesc1Valid = true; } if (isGenericFormValid(job.getFormDesc2(), formInstance) && !isFormDesc2Valid) { isFormDesc2Valid = true; } if (isGenericFormValid(job.getFormDesc3(), formInstance) && !isFormDesc3Valid) { isFormDesc3Valid = true; } if (isGenericFormValid(ServiceConstants.SecurityReport, formInstance) && !isSecurityReportValid) { isSecurityReportValid = true; } } List result = new ArrayList(); if (!isModernisationNecessaryValid) { if (!result.contains(ServiceConstants.ModernisationNecessary)) result.add(ServiceConstants.ModernisationNecessary); } if (isJobRequireFormDesc(job.getFormDesc1()) && !isFormDesc1Valid) { result.add(job.getFormDesc1()); } if (isJobRequireFormDesc(job.getFormDesc2()) && !isFormDesc2Valid) { result.add(job.getFormDesc2()); } if (isJobRequireFormDesc(job.getFormDesc3()) && !isFormDesc3Valid) { result.add(job.getFormDesc3()); } if (!isSecurityReportValid) { result.add(ServiceConstants.SecurityReport); } if (!result.isEmpty()) log.info("result " + result); return result; } public static boolean isGenericFormValid(String formDesc, FormInstance formInstance) { if (isJobRequireFormDesc(formDesc) && formInstance.getFormId().substring(1, 3).contains(formDesc)) { return true; } return false; } public static boolean isDocumentOrNoFormValid(String formDesc, List documentImages, String noForm) { if (!documentImages.isEmpty() && isFormDescFileOrNoFormValid(formDesc, documentImages.get(0).getFormDesc(), noForm)) { return true; } else { return false; } } public static boolean isFormDescFileOrNoFormValid(String formDesc, String formDescFile, String noForm) { if (isJobRequireFormDesc(formDesc) && (formDesc.equalsIgnoreCase(formDescFile) || !noForm.isEmpty())) { return true; } return false; } private static boolean isJobRequireFormDesc(String formDesc) { if (!formDesc.isEmpty() && !formDesc.equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { return true; } return false; } public static boolean isJobRequireFormDesc(Job job) { if (isJobRequireFormDesc(job.getFormDesc1())) { return true; } if (isJobRequireFormDesc(job.getFormDesc2())) { return true; } if (isJobRequireFormDesc(job.getFormDesc3())) { return true; } return false; } public static boolean isJobRequireReportMessageToCustomer(Job job) { if (job.getJobType().isMON() || job.getJobType().isSAV()) { if (job.getLatestReport().getMessages().isEmpty()) { return true; } boolean isSavRequireReportMessage = true; for (JobMessage jobMessage : job.getLatestReport().getMessages()) { if (jobMessage.getMessageId().equalsIgnoreCase(CommonConstants.Message.CUSTOMER)) { log.info("MessageId " + jobMessage.getMessageId()); log.info("MessageCode " + jobMessage.getMessageCode() + " FullText " + jobMessage.getFullText()); if (job.getJobType().isMON()) { if (jobMessage.getMessageCode().isEmpty() && jobMessage.getFullText().isEmpty()) { return true; } return false; } else if (job.getJobType().isSAV()) { //ZKDCMSGC.KND = 1, ZKDMOBMSGC.TXT = 18 or 19 or 20 for job type (ZKDMOB.AUART) 'SAV' if (jobMessage.getMessageCode().equalsIgnoreCase(CommonConstants.Message.SYSTEM_IS_SAVE) || jobMessage.getMessageCode().equalsIgnoreCase(CommonConstants.Message.SYSTEM_WITH_MINOR_DEFECTS) || jobMessage.getMessageCode().equalsIgnoreCase(CommonConstants.Message.SYSTEM_EXHIBITS_DEFECTS)) { isSavRequireReportMessage = false; } } } } return isSavRequireReportMessage; } return false; } public static boolean isMandatoryByReportTime(Job job) { if (job.getJobType().isMON() && !job.getLatestReport().getTimes().isEmpty()) { for (JobReportTime jobReportTime : job.getLatestReport().getTimes()) { if (jobReportTime.getWorkTypeCode().equalsIgnoreCase(CommonConstants.Report.WORKTYPE_INSTALLATION)) { return true; } } } return false; } public static boolean isInstallationWorkTypeComplete(Job job) { if (isMandatoryByReportTime(job)) { if (job.getLatestReport().getImageAttachments().size() >= ServiceConstants.REQUIRE_IMAGE) { return true; } } else { return true; } return false; } public static boolean isChecklistComplete(Job job) { if (isMandatoryByReportTime(job)) { if (job.getLatestReport().isChedklistEdited()) { return true; } } else { return true; } return false; } public static boolean isMandatoryByReportMessage(Job job) { if (job.getJobType().isREP() || job.getJobType().isSAV()) { for (JobMessage jobMessage : job.getLatestReport().getMessages()) { log.info("MessageCode " + jobMessage.getMessageCode() + " FullText " + jobMessage.getFullText()); if ((jobMessage.getMessageCode().equalsIgnoreCase(ServiceConstants.ModernisationNecessary) || jobMessage.getMessageCode().equalsIgnoreCase(ServiceConstants.OfferModernisation))) { if (!jobMessage.getMessageCode().isEmpty() || !jobMessage.getFullText().isEmpty()) { return true; } } } } return false; } /** * Only the document type 01 and 02 and Job type 'SAV' and 'REP' needs images * * @param job * @return */ public static boolean isReportImageComplete(Job job) { log.info("isReportImageComplete "); boolean isReportImageRequireisByReportMessage = isMandatoryByReportMessage(job); boolean isReportImageRequireisByReportTime = isMandatoryByReportTime(job); log.info("isReportImageRequireisByReportMessage " + isReportImageRequireisByReportMessage); log.info("isReportImageRequireisByReportTime " + isReportImageRequireisByReportTime); log.info("isReportDocsComplete " + isReportDocsComplete(job)); if (!isReportDocsComplete(job).isEmpty()) { if (isReportDocsComplete(job).contains(ServiceConstants.ModernisationNecessary) || isReportDocsComplete(job).contains(ServiceConstants.OfferModernisation)) { isReportImageRequireisByReportMessage = true; } } log.info("isReportImageRequire " + isReportImageRequireisByReportMessage); log.info("ImageAttachments " + job.getLatestReport().getImageAttachments().size()); if (isReportImageRequireisByReportMessage) { if (!job.getLatestReport().getImageAttachments().isEmpty()) { return true; } } else { return true; } return false; } /** * The application have to check if there are more than 3 measurements in a measuring point. * @param reportMeasurementList * @return */ public static boolean isTooMuchMeasurementAreMadeForOnemeasurePoint(List reportMeasurementList) { Map> measurementMap = new HashMap>(); for (ReportMeasurement reportMeasurement : reportMeasurementList) { if (measurementMap.containsKey(reportMeasurement.getMeasurementPoint())) { measurementMap.get(reportMeasurement.getMeasurementPoint()).add(reportMeasurement); } else { measurementMap.put(reportMeasurement.getMeasurementPoint(), new ArrayList()); measurementMap.get(reportMeasurement.getMeasurementPoint()).add(reportMeasurement); } } for (List reportMeasurement : measurementMap.values()) { log.info("reportMeasurement size " + reportMeasurement.size()); if (reportMeasurement.size() > ServiceConstants.MAX_MEASUREMENT_FOR_ONE_POINT) { return true; } } return false; } public static String getTooMuchMeasurementAreMadeForOnemeasurePointMessage() { return MessageFormat.format(ServiceMessages.getString("MeasurementMaximum"), new Object[] { ServiceConstants.MAX_MEASUREMENT_FOR_ONE_POINT}); } public static boolean isReportFormVonoviaComplete(Job job) { if (job.getLatestReport().getWorkType().equalsIgnoreCase(CommonConstants.Report.WORK_TYPE_RECORDING_MAINTENANCE_VONOVIA)) { for (FormInstance formInstance : job.getLatestReport().getFormInstances()) { if (formInstance.getFormId().equalsIgnoreCase(CommonConstants.Report.FORM_VONOVIA)) { return true; } } return false; } else { return true; } } }     service/src/ch/mfiles/kaba/kolibri/service/util/SignatureUtil.java:   package ch.mfiles.kaba.kolibri.service.util; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.CardView; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kolibri.ui.SignatureView; import ch.mfiles.kolibri.util.LayoutHelper; public class SignatureUtil { public static final String FILE_PATH = "images"; //$NON-NLS-1$ public static final int TARGET_WIDTH = 240; public static final int TARGET_HEIGHT = 216; public static final int TARGET_DENSITY = 75; public static final float ASPECT_RATIO = 1.11f; public static String getOriginalSignatureFileName(String fileName) { String newFilename = ""; int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { newFilename = fileName.substring(0, i - 1) + "_Original" + fileName.substring(i).toLowerCase(); } return newFilename; } public static View flexibleSignatureView(Context context, SignatureView signatureView) { RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); relativeLayout.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); CardView cardView = new CardView(context); RelativeLayout.LayoutParams cardViewParams = new RelativeLayout.LayoutParams(0, 0); cardViewParams.width = LayoutParams.MATCH_PARENT; if (LayoutHelper.getDisplayMetrics().widthPixels > TARGET_WIDTH) { cardViewParams.height = (int) (LayoutHelper.getDisplayMetrics().widthPixels * ASPECT_RATIO); } else { cardViewParams.height = LayoutParams.MATCH_PARENT; } cardViewParams.addRule(RelativeLayout.CENTER_IN_PARENT); cardViewParams.setMargins(LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN, LayoutUtils.DEFAULT_MAX_MARGIN); cardView.setLayoutParams(cardViewParams); cardView.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING, LayoutUtils.DEFAULT_MAX_PADDING); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); gradientDrawable.setCornerRadius(7f); gradientDrawable.setStroke(2, LayoutUtils.DEFAULT_CARD_VIEW_SHADOW_COLOR); cardView.setBackgroundDrawable(gradientDrawable); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); linearLayout.setPadding(LayoutUtils.DEFAULT_MAX_PADDING, 0, 0, 0); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.addView(signatureView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); cardView.addView(linearLayout); relativeLayout.addView(cardView); return relativeLayout; } }     service/test/ch/mfiles/kaba/kolibri/service/forms/util/ReportDeletionStateTest.java:   package ch.mfiles.kaba.kolibri.service.forms.util; import java.util.Arrays; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import junit.framework.TestCase; public class ReportDeletionStateTest extends TestCase { /** * @see "MIG-998 Job resp. Report is sometimes in an invalid state after deleting the report" */ @Test public void testRestorePartlyDoneAfterDeletingNewerReport() { Job job = new Job(); job.setJobNumber("0000434704"); job.setJobType(JobType.SAV); Report sentPartialReport = new Report(job.getJobNumber(), job.getJobType(), "first-report-guid", 1, false); sentPartialReport.setReportStatus(ReportStatus.RECEIVED); sentPartialReport.setPartialRepair(true); Report reportToDelete = new Report(job.getJobNumber(), job.getJobType(), "second-report-guid", 2, false); reportToDelete.setReportStatus(ReportStatus.NEW); reportToDelete.setFinalRepair(true); job.setReports(Arrays.asList(reportToDelete, sentPartialReport)); assertFalse(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); job.setReports(Arrays.asList(sentPartialReport)); assertTrue(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); assertFalse(sentPartialReport.getGuId().equals(reportToDelete.getGuId())); } @Test public void testDoNotRestorePartlyDoneWithoutReceivedPartialReport() { Job job = new Job(); job.setJobNumber("0000434704"); job.setJobType(JobType.SAV); Report report = new Report(job.getJobNumber(), job.getJobType(), "report-guid", 1, false); job.setReports(Arrays.asList(report)); report.setReportStatus(ReportStatus.RECEIVED); report.setPartialRepair(false); assertFalse(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); report.setPartialRepair(true); report.setReportStatus(ReportStatus.NEW); assertFalse(ServiceJobUtil.shouldRestorePartlyDoneAfterReportDeletion(job)); } }     service/test/ch/mfiles/kaba/kolibri/service/forms/util/ReportTest.java:   package ch.mfiles.kaba.kolibri.service.forms.util; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.FormInstance; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobFile; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.types.FormType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.service.ServiceMessages; import ch.mfiles.kaba.kolibri.service.util.ServiceConstants; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.util.DateUtils; import junit.framework.TestCase; public class ReportTest extends TestCase { public ReportTest(String name) { super(name); } /** * @see "(MIG-415) Incomplete report can be saved" */ @Test public void testSaveReport() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(""); // empty assertTrue(report.getCustomerSupportText().isEmpty()); //$NON-NLS-1$ // fax report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_FAX); report.setCustomerSupportText("012345678"); assertFalse(report.getCustomerSupportText().isEmpty()); // eMail report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_EMAIL); report.setCustomerSupportText("abc@a.ch"); assertFalse(report.getCustomerSupportText().isEmpty()); // formula report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_FOMULAR); report.setCustomerSupportText(report.getJobNumber()); assertFalse(report.getCustomerSupportText().isEmpty()); // waiver report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); report.setCustomerSupportText(""); assertTrue(report.isValid()); //$NON-NLS-1$ } /** * @see "MIG-419 Report cannot be saved if "Verzicht" (waiver) in "Send report to:" is selected" */ @Test public void testSaveReport2() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ } /** * @see "MIG-459 CHANGE: New flag for cycles of an installation" */ @Test public void testSaveReport3() { Job job = getJobObjectByStatus(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ report.setIdx(1); report.setPersonalNumber(job.getPersonalNumber()); report.setCommissionNumber(job.getCommissionNumber()); report.setReportStatus(ReportStatus.INITIAL); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ job.setCycleOfInstallationFlag(true); report = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 2, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ report.setIdx(2); report.setPersonalNumber(job.getPersonalNumber()); report.setCommissionNumber(job.getCommissionNumber()); report.setReportStatus(ReportStatus.INITIAL); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertFalse(report.isValid()); //$NON-NLS-1$ report.setCycleOfInstallation("24"); assertTrue(report.isValid()); //$NON-NLS-1$ } private Job getJobObjectByStatusWithReport(String JobStatus) { Job job = new Job(); job.setJobNumber("0000434704"); //$NON-NLS-1$ job.setJobType(JobType.REP); job.setPersonalNumber(9998); job.setStatus(JobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); Report report = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ report.setIdx(1); report.setPersonalNumber(job.getPersonalNumber()); report.setCommissionNumber(job.getCommissionNumber()); report.setReportStatus(ReportStatus.INITIAL); ArrayList reports = new ArrayList(); reports.add(report); job.setReports(reports); return job; } private Job getJobObjectByStatus(String JobStatus) { Job job = new Job(); job.setJobNumber("0000434704"); //$NON-NLS-1$ job.setJobType(JobType.REP); job.setPersonalNumber(9998); job.setStatus(JobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); return job; } /** * @see "MIG-454 Documents as attachment" */ @Test public void testSaveImageJobFile() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("I"); jobFile.setSignPicAt("test"); assertTrue(jobFile.isValid()); } /** * @see "MIG-454 Documents as attachment" */ @Test public void testSaveDocJobFile() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(report.isValid()); //$NON-NLS-1$ JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormType(new FormType(FormType.JPG)); assertTrue(jobFile.isValid()); } /** * @see "MIG-461 Required documents in ZKDMOB for documents as attachment" */ @Test public void testValidateReportDocFromJob() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.setJobType(JobType.MON); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); newJobTime.setWorkTypeCode(CommonConstants.Report.WORKTYPE_INSTALLATION); job.getCurrentReport().getTimes().add(newJobTime); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setSafetyReport(true); assertEquals(2, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("02"); job.setFormDesc2("03"); job.setFormDesc3("04"); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals(5, ServiceJobUtil.isReportDocsComplete(job).size()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("05"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertEquals(4, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm2("03"); JobFile NoForm2 = new JobFile(); date = new Date(); NoForm2.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm2()); NoForm2.setGuid(job.getLatestReport().getGuId()); NoForm2.setJobNumber(job.getJobNumber()); NoForm2.setJobType(job.getJobType()); NoForm2.setType("F"); NoForm2.setFormDesc("03"); job.getLatestReport().getDocumentAttachments().add(NoForm2); assertEquals(3, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm3("04"); JobFile NoForm3 = new JobFile(); date = new Date(); NoForm3.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm3()); NoForm3.setGuid(job.getLatestReport().getGuId()); NoForm3.setJobNumber(job.getJobNumber()); NoForm3.setJobType(job.getJobType()); NoForm3.setType("F"); NoForm3.setFormDesc("04"); job.getLatestReport().getDocumentAttachments().add(NoForm3); assertEquals(2, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm1("02"); JobFile NoForm1 = new JobFile(); date = new Date(); NoForm1.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm1()); NoForm1.setGuid(job.getLatestReport().getGuId()); NoForm1.setJobNumber(job.getJobNumber()); NoForm1.setJobType(job.getJobType()); NoForm1.setType("F"); NoForm1.setFormDesc("02"); job.getLatestReport().getDocumentAttachments().add(NoForm1); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setSafetyReport(false); assertEquals(0, ServiceJobUtil.isReportDocsComplete(job).size()); } /** * @see "MIG-484 CHANGE: Mandatory of document, if specific report messages are chosen" * */ @Test public void testReportMessageMandatoryOfDocument() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode(ServiceConstants.ModernisationNecessary); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setFormType(new FormType(FormType.JPG)); job.getCurrentReport().getDocumentAttachments().add(jobFile); JobFile jobImage = new JobFile(); job.getCurrentReport().getImageAttachments().add(jobImage); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); } /** * @see "MIG-511 Mandatories doesn't work if the user stamps 2 times at one report" * */ @Test public void testReportTimeMandatoryOfDocument() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.MON); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateTimeUtil.getNow().getTime()); newJobTime.setWorkTypeCode("30"); job.getCurrentReport().getTimes().add(newJobTime); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(1); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateTimeUtil.getNow().getTime()); newJobTime.setWorkTypeCode(CommonConstants.Report.WORKTYPE_INSTALLATION); job.getCurrentReport().getTimes().add(newJobTime); // job.getCurrentReport().setSafetyReport(false); // assertFalse(ServiceJobUtil.isReportDocsComplete(job, jobImages, jobFiles).isEmpty()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setJobNumber(job.getJobNumber()); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); JobFile jobFile2 = new JobFile(); jobFile2.setJobNumber(job.getJobNumber()); Date date2 = DateTimeUtil.getNow().getTime(); jobFile2.setJobFileId(DateTimeUtil.fileNameDate(date2) + "_" + DateTimeUtil.fileNameTime(date2) + ".jpg"); jobFile2.setType("F"); jobFile2.setSignPicAt("test"); jobFile2.setFormDesc("05"); jobFile2.setJobNumber(job.getJobNumber()); jobFile2.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile2); assertEquals(0, ServiceJobUtil.isReportDocsComplete(job).size()); } /** * @see "MIG-540 Required documents aren't checked by app" * */ @Test public void testRequireOfDocument() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); Report report = job.getLatestReport(); report.setWorkType("01"); report.setPartialRepair(true); report.setCustomerSupport(CommonConstants.Report.CUSTOMER_SUPPORT_WAIVER); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.setFormDesc1("00"); job.setFormDesc2("00"); job.setFormDesc3("00"); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.setFormDesc1("00"); job.setFormDesc2("03"); job.setFormDesc3("04"); assertEquals(2, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("02"); job.setFormDesc2("00"); job.setFormDesc3("00"); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("00"); job.setFormDesc2("00"); job.setFormDesc3("04"); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.setFormDesc1("00"); job.setFormDesc2("03"); job.setFormDesc3("00"); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("05"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertEquals(1, ServiceJobUtil.isReportDocsComplete(job).size()); job.getLatestReport().setNoForm2("03"); JobFile NoForm2 = new JobFile(); date = new Date(); NoForm2.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + job.getLatestReport().getNoForm2()); NoForm2.setGuid(job.getLatestReport().getGuId()); NoForm2.setJobNumber(job.getJobNumber()); NoForm2.setJobType(job.getJobType()); NoForm2.setType("F"); NoForm2.setFormDesc("03"); job.getLatestReport().getDocumentAttachments().add(NoForm2); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); } /** * @see "MIG-549 Report can be send without report image if user chooses report message "Modernisation"" * */ @Test public void testRequireOfImage() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode(ServiceConstants.ModernisationNecessary); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertFalse(ServiceJobUtil.isReportImageComplete(job)); JobFile imageFile = new JobFile(); assertFalse(imageFile.isValid()); imageFile.setJobNumber(job.getJobNumber()); date = DateTimeUtil.getNow().getTime(); imageFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); imageFile.setType("I"); imageFile.setSignPicAt("test"); imageFile.setDescription("desc"); imageFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getImageAttachments().add(imageFile); assertTrue(ServiceJobUtil.isReportImageComplete(job)); } /** * @see "MIG-999 Wrong mandatories for report document in job type MON" * * ZKMDOB.AUART = 'MON' ZKDMONMONTXT = '01' or ZKDMONMONTXT = '02' * no document or generic form is required as mandatory. */ @Test public void testJobMonRequireOfImage() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.MON); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode("01"); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); job.getLatestReport().getMessages().get(0).setMessageCode("02"); assertFalse(ServiceJobUtil.isReportImageComplete(job)); } /** * @see "MIG-751 Check for document doesn't work" * "MIG-745 New check for report document" * "MIG-735 When a document is required with job, we have to check if there's a generic form" * */ @Test public void testRequireOfForm() { Job job = getJobObjectByStatusWithReport(JobStatus.RECEIVED); job.setJobType(JobType.REP); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // Document is required with job // When a document is required with the job (ZKDMOB.FORDMESC1, ZKDMOB.FORMDESC2, ZKDMOB.FORMDESC3), we should check: // 1. // ZKDMOB.FORMDESC1 = 01 (document required as mandatory for user to add an attachment or a generic form to report) job.setFormDesc1("01"); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // 2. // Now check FORM.ID (CHAR4) the 2nd and 3rd digit // -> If those digits of FORM.ID (for example F010) are the same as in ZKKDMOB.FORMDESC1 (in this case 01), // the user has to add this generic form or has to add an document attachment (ZKDMOBMV.FORMTYPE = 01 // add generic form FormInstance formInstance = new FormInstance(); formInstance.setFormId("F010"); job.getLatestReport().getFormInstances().add(formInstance); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // clear generic form job.getLatestReport().getFormInstances().clear(); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // add document JobFile jobFile = new JobFile(); assertFalse(jobFile.isValid()); jobFile.setJobNumber(job.getJobNumber()); Date date = DateTimeUtil.getNow().getTime(); jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + ".jpg"); jobFile.setType("F"); jobFile.setSignPicAt("test"); jobFile.setFormDesc("01"); jobFile.setFormType(new FormType(FormType.JPG)); job.getLatestReport().getDocumentAttachments().add(jobFile); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // clear document job.getLatestReport().getDocumentAttachments().clear(); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // or can choose to ad no form to report (ZKDMOBREP.NO_FORM) jobFile.setJobFileId(DateTimeUtil.fileNameDate(date) + "_" + DateTimeUtil.fileNameTime(date) + "NO_FORM" + "01"); job.getLatestReport().getDocumentAttachments().add(jobFile); job.getLatestReport().setNoForm1("01"); ServiceJobUtil.isReportDocsComplete(job); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // remove no form job.getLatestReport().setNoForm1(""); // clear no form job.getLatestReport().getDocumentAttachments().clear(); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // clear FormDesc job.setFormDesc1(""); // 3. // One of these points must be added to report, otherwise the user can't send the report assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); // Document is required according to report message // In a 2nd case, a document is required when the user adds a report message to report: // If any of the report messages is ZKDMOBMSGC.MSGC = 01 and/or 02, then a modernisation document (ZKDMOBMV.FORMDESC = 01) is necessary. // In this case, the same logic as above have to be implemented JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode(ServiceConstants.ModernisationNecessary); jobMessage.setMessageId(CommonConstants.Message.KDZ1); jobMessage.setFullText("Test message"); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); // remove message job.getLatestReport().getMessages().clear(); assertTrue(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); jobMessage.setMessageCode(ServiceConstants.OfferModernisation); job.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isReportDocsComplete(job).isEmpty()); assertEquals("01",ServiceJobUtil.isReportDocsComplete(job).get(0)); } }     service/test/ch/mfiles/kaba/kolibri/service/forms/util/ServiceJobUtilTest.java:   package ch.mfiles.kaba.kolibri.service.forms.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.Job; import ch.mfiles.kaba.kolibri.common.businessobjects.JobMessage; import ch.mfiles.kaba.kolibri.common.businessobjects.JobReportTime; import ch.mfiles.kaba.kolibri.common.businessobjects.Report; import ch.mfiles.kaba.kolibri.common.businessobjects.ReportMaterial; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobStatus; import ch.mfiles.kaba.kolibri.common.businessobjects.types.JobType; import ch.mfiles.kaba.kolibri.common.businessobjects.types.ReportStatus; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil.JobStatusFilter; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.GuidGenerator; import ch.mfiles.kaba.kolibri.service.util.ServiceJobUtil; import ch.mfiles.kolibri.util.DateUtils; import junit.framework.TestCase; public class ServiceJobUtilTest extends TestCase { public ServiceJobUtilTest(String name) { super(name); } @Test public void testIsJobAcceptable() { // new assertEquals(true, ServiceJobUtil.isJobAcceptable(getJobObjectByStatus(JobStatus.NEW))); } @Test public void testIsJobForwardable() { Job newJob = getJobObjectByStatus(JobStatus.NEW); newJob.setJobType(JobType.REP); // new assertEquals(true, ServiceJobUtil.isJobForwardable(newJob)); newJob.setStatus(JobStatus.RECEIVED); // received assertEquals(true, ServiceJobUtil.isJobForwardable(newJob)); } @Test public void testIsJobDeletable() { // new assertEquals(true, ServiceJobUtil.isJobDeletable(getJobObjectByStatus(JobStatus.NEW))); // received assertEquals(true, ServiceJobUtil.isJobDeletable(getJobObjectByStatus(JobStatus.RECEIVED))); // partly done assertEquals(true, ServiceJobUtil.isJobDeletable(getJobObjectByStatus(JobStatus.PARLTY_DONE))); } @Test public void testIsJobStartTimeable() { // received assertEquals(true, ServiceJobUtil.isJobStartTimeable(getJobObjectByStatus(JobStatus.RECEIVED))); // in progress assertEquals(true, ServiceJobUtil.isJobStartTimeable(getJobObjectByStatus(JobStatus.IN_PROGRESS))); // partly done assertEquals(true, ServiceJobUtil.isJobStartTimeable(getJobObjectByStatus(JobStatus.PARLTY_DONE))); } @Test public void testIsMaxDownload() { assertEquals(true, ServiceJobUtil.isMaxDownload(getSelectedList())); assertEquals(false, ServiceJobUtil.isMaxDownload(new ArrayList())); } @Test public void testIsMaxConfirmDownload() { assertEquals(true, ServiceJobUtil.isMaxConfirmDownload(getSelectedList())); assertEquals(false, ServiceJobUtil.isMaxConfirmDownload(new ArrayList())); } /** * @see "[MIG-88] Integrate of SCAN-button in joblist" */ @Test public void testIsValidJobNumber() { String jobNumber = "0000434704"; //$NON-NLS-1$ // empty assertEquals(false, ServiceJobUtil.isValidJobNumber("")); //$NON-NLS-1$ // null assertEquals(false, ServiceJobUtil.isValidJobNumber(null)); // when the length < 10 assertEquals(9, jobNumber.substring(1).length()); assertEquals(false, ServiceJobUtil.isValidJobNumber(jobNumber.substring(1))); // when the length > 10 assertEquals(11, (jobNumber + "7").length()); //$NON-NLS-1$ assertEquals(false, ServiceJobUtil.isValidJobNumber(jobNumber + "7")); //$NON-NLS-1$ // valid job number, length == 10 assertEquals(10, jobNumber.length()); assertEquals(true, ServiceJobUtil.isValidJobNumber(jobNumber)); } /** * @see "[MIG-135] Edit of job informations is only possible by self created jobs" */ @Test public void testIsJobEditable() { Job newJob = getJobObjectByStatus(JobStatus.NEW); newJob.setJobNumber("$0000434704"); //$NON-NLS-1$ newJob.setJobType(JobType.REP); //self created jobs with the type REP. assertEquals(true, ServiceJobUtil.isJobEditable(newJob)); Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); //Isn't the job self created and/or has the type SAV / MON receivedJob.setJobType(JobType.SAV); assertEquals(false, ServiceJobUtil.isJobEditable(receivedJob)); receivedJob.setJobType(JobType.MON); assertEquals(false, ServiceJobUtil.isJobEditable(receivedJob)); receivedJob.setJobType(JobType.REP); assertEquals(false, ServiceJobUtil.isJobEditable(receivedJob)); } /** * @see "[MIG-150] Report edit, commission number: Show the comission number" */ @Test public void testReportCommissionNumberType() { Job job = getJobObjectByStatus(JobStatus.RECEIVED); Report report = job.getLatestReport(); // job commission number and report commission number are not the same. assertSame(CommonConstants.CommissionNumber.Type.INVALID, job.getReportCommissionNumberType()); report.setCommissionNumber(CommonConstants.CommissionNumber.DEFAULT); assertSame(CommonConstants.CommissionNumber.Type.UNKNOWN, job.getReportCommissionNumberType()); // job commission number and commission number are the same. report.setCommissionNumber(job.getCommissionNumber()); assertSame(CommonConstants.CommissionNumber.Type.CORRECT, job.getReportCommissionNumberType()); } private Job getJobObjectByStatus(String jobStatus) { Random random = new Random(); Job job = new Job(); job.setJobNumber(getSelectedList().get(random.nextInt(getSelectedList().size()))); //$NON-NLS-1$ job.setJobType(JobType.SAV); job.setPersonalNumber(99998); job.setStatus(jobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); Report reoprt = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ reoprt.setIdx(1); reoprt.setPersonalNumber(job.getPersonalNumber()); reoprt.setReportStatus(ReportStatus.INITIAL); ArrayList reports = new ArrayList(); reports.add(reoprt); job.setReports(reports); if(jobStatus == JobStatus.IN_PROGRESS) { job.getLatestReport().setReportStatus(ReportStatus.NEW); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); } if(jobStatus == JobStatus.PARLTY_DONE) { job.getCurrentReport().setReportStatus(ReportStatus.INITIAL); job.setStatus(JobStatus.PARLTY_DONE); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } if(jobStatus == JobStatus.FINALIZED) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); job.getCurrentReport().setCreateDate((job.getCurrentReport().getTimes().get(0)).getStartTime()); job.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); job.setStatus(JobStatus.FINALIZED); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } return job; } private List getSelectedList() { String[] data = {"0000434704","0000436584","0000436138","0000434318","0000434324" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000433101","0000436565","0000434729","0000757569","0000757825" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000757825","0000757826","0000434324","0000434324","0000434704" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000434704","0000757569","0000757569","0000434728","0000434729" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000436584","0000436585","0000436138","0000436139","0000434318" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000434319","0000776941","0000776942","0000776943","0000776944" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ ,"0000776945","0000776946","0000776947","0000776948","0000776949"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ return Arrays.asList(data); } /** * @see "[MIG-167] Every job is displayed in the list for collective signature" */ @Test public void testCollectiveSignature() { List reportList = new ArrayList(); for (int i = 0; i < 6; i++) { Job newJob = getJobObjectByStatus(JobStatus.NEW); newJob.setJobNumber(getSelectedList().get(i)); //$NON-NLS-1$ Report report = newJob.getLatestReport(); if(i == 2 || i == 4) { report.setSignatureFlag(true); } reportList.add(report); } int singnatureCollectiveToShow = 0; for (Report report : reportList) { if(report.isSignatureFlag()) { singnatureCollectiveToShow ++; } } assertEquals(false, singnatureCollectiveToShow == 0); assertEquals(true, singnatureCollectiveToShow == 2); assertEquals(false, singnatureCollectiveToShow == reportList.size()-1); } /** * @see "[MIG-127] Validation of ZIP (PLZ)" */ @Test public void testIsValidZIP() { String zip = "12345"; //$NON-NLS-1$ // empty assertEquals(false, ServiceJobUtil.isValidZIP("")); //$NON-NLS-1$ // null assertEquals(false, ServiceJobUtil.isValidZIP(null)); // when the length < 5 assertEquals(4, zip.substring(1).length()); assertEquals(false, ServiceJobUtil.isValidZIP(zip.substring(1))); // when the length > 5 assertEquals(6, (zip + "5").length()); //$NON-NLS-1$ assertEquals(false, ServiceJobUtil.isValidZIP(zip + "5")); //$NON-NLS-1$ // valid job number, length == 5 assertEquals(5, zip.length()); assertEquals(true, ServiceJobUtil.isValidZIP(zip)); } /** * @see "[MIG-437] REP jobs disappears, if you start the report time while they're in filter "planned"" */ @Test public void testPlanedJob() { List jobList = getPlannedJobList(); for (int i = 0; i < jobList.size(); i++) { final Job job = jobList.get(i); assertTrue("This job is not in planned", ServiceJobUtil.isJobInPlanned(job)); } // Partly_Done and Active_Date => current date with report data Job job = jobList.get(jobList.size() -1); job.getCurrentReport().getParts().add(new ReportMaterial()); assertFalse("This job is still in planned", ServiceJobUtil.isJobInPlanned(job)); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); // 1. The user downloads a job and rescheduled it in the future. // -> The job stays with status received, but is now displayed in planned // 2. The user goes to planned filter and starts the report time // -> The status is changed from received to in_progress // -> Now the job is displayed in active // 3. He stops the time // -> The status is changed from in_progress to received (but with report data) // -> The job is still displayed in active // Received and Edate => current date Job planjob1 = getJobObjectByStatus(JobStatus.RECEIVED); planjob1.setJobType(JobType.REP); Calendar edateCalendar = DateTimeUtil.getTimestamp(); edateCalendar.add(Calendar.DAY_OF_YEAR, +4); planjob1.setActiveJobDate(edateCalendar.getTime()); assertFalse("This job is still in planned", ServiceJobUtil.isJobInPlanned(job)); Job receivedJob = jobList.get(jobList.size() -1); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(receivedJob.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); receivedJob.getCurrentReport().getTimes().add(newJobTime); // With started time assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); // Stopped job time receivedJob.getCurrentReport().getTimes().get(receivedJob.getCurrentReport().getTimes().size() - 1).setStopTime(DateTimeUtil.getNow().getTime()); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); // 1. The user downloads a job and send a report with "partly_done" to backend // -> The job changed the status from received / in_progress to partly_done // 2. The user rescheduled the job // -> The job stays in status partly_done and is displayed in planned // 3. Now the user starts the time from this job // -> The status is changed from partly_done to in_progress // -> It is displayed in active // 4. The user now stops the time // -> The status is changed from in_progress to partly_done (but with report data) // -> The job is still displayed in active // send report receivedJob.getCurrentReport().setCreateDate((receivedJob.getCurrentReport().getTimes().get(0)).getStartTime()); receivedJob.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); receivedJob.setStatus(JobStatus.PARLTY_DONE); receivedJob.setStatusEdit(new Date()); edateCalendar.add(Calendar.DAY_OF_YEAR, +4); receivedJob.setActiveJobDate(edateCalendar.getTime()); assertTrue("Job status not Partly done", receivedJob.getStatus().isPartlyDone()); assertFalse("This job is still in planned", ServiceJobUtil.isJobInPlanned(job)); newJobTime.setGuid(receivedJob.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); receivedJob.getCurrentReport().getTimes().add(newJobTime); receivedJob.getCurrentReport().setCreateDate((receivedJob.getCurrentReport().getTimes().get(receivedJob.getCurrentReport().getTimes().size()-1)).getStartTime()); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); receivedJob.getCurrentReport().getTimes().get(receivedJob.getCurrentReport().getTimes().size() - 1).setStopTime(DateTimeUtil.getNow().getTime()); assertTrue("Job status not Partly done", receivedJob.getStatus().isPartlyDone()); assertTrue("This job is not in active", ServiceJobUtil.isJobActive(job)); } private List getPlannedJobList() { List result = new ArrayList(); Calendar edateCalendar = DateTimeUtil.getTimestamp(); edateCalendar.add(Calendar.DAY_OF_YEAR, +4); // Received and Edate => current date Job planjob1 = getJobObjectByStatus(JobStatus.RECEIVED); planjob1.setJobType(JobType.REP); planjob1.setAppointmentDate(edateCalendar.getTime()); result.add(planjob1); // Received and Active_Date => current date Job planjob2 = getJobObjectByStatus(JobStatus.RECEIVED); planjob2.setJobType(JobType.REP); planjob2.setActiveJobDate(edateCalendar.getTime()); result.add(planjob2); // Partly_Done and Active_Date => current date Job planjob3 = getJobObjectByStatus(JobStatus.PARLTY_DONE); planjob3.setJobType(JobType.REP); planjob3.setActiveJobDate(edateCalendar.getTime()); result.add(planjob3); return result; } /** * * @param jobType * @param jobStatus * @param idleTimeFlag * @param isReschedule * @param isNewReport * @param isReportSent * @param jobStatusFilter */ public void checkJobFilter(String jobType, String jobStatus , boolean idleTimeFlag , boolean isReschedule , boolean isNewReport , boolean isReportSent , JobStatusFilter jobStatusFilter) { Random random = new Random(); Job job = new Job(); job.setJobNumber(getSelectedList().get(random.nextInt(getSelectedList().size()))); //$NON-NLS-1$ job.setJobType(jobType); job.setPersonalNumber(99998); job.setStatus(jobStatus); job.setJobForward(00); job.setCommissionNumber("0347129-00"); //$NON-NLS-1$ job.setStaffName("HBA"); //$NON-NLS-1$ job.setAppointmentDate(DateTimeUtil.getTimestamp().getTime()); job.setNewJobDate(DateTimeUtil.getToday().getTime()); Calendar idleTime = DateTimeUtil.getTimestamp(); int idleTimeDays =0; if(jobType == JobType.SAV ) { if (idleTimeFlag) { idleTimeDays = 91; // idleTime.add(Calendar.DAY_OF_YEAR, +90); } else { idleTimeDays = -90; // idleTime.add(Calendar.DAY_OF_YEAR, -90); } } else { if (idleTimeFlag) { idleTimeDays = 4; // idleTime.add(Calendar.DAY_OF_YEAR, +3); } else { idleTimeDays = -3; // idleTime.add(Calendar.DAY_OF_YEAR, -3); } } idleTime.add(Calendar.DAY_OF_YEAR, idleTimeDays); if(isReschedule) { job.setJobRescheduleDate(idleTime.getTime()); job.setJobRescheduleTime(idleTime.getTime()); job.setAppointmentDate(idleTime.getTime()); job.calculateActiveDate(); } else { job.setAppointmentDate(idleTime.getTime()); } Report reoprt = new Report(job.getJobNumber(), job.getJobType(), new GuidGenerator().toString(), 1, job.isCycleOfInstallationFlag()); //$NON-NLS-1$ reoprt.setIdx(1); reoprt.setPersonalNumber(job.getPersonalNumber()); reoprt.setReportStatus(ReportStatus.INITIAL); ArrayList reports = new ArrayList(); reports.add(reoprt); job.setReports(reports); if(jobStatus == JobStatus.RECEIVED) { job.calculateActiveDate(); } if(jobStatus == JobStatus.IN_PROGRESS) { job.getLatestReport().setReportStatus(ReportStatus.NEW); JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); } if(isNewReport) { job.getLatestReport().setReportStatus(ReportStatus.NEW); } if(isReportSent) { if(jobStatus == JobStatus.PARLTY_DONE) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); job.getCurrentReport().setCreateDate((job.getCurrentReport().getTimes().get(0)).getStartTime()); job.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); job.setStatus(JobStatus.PARLTY_DONE); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } if(jobStatus == JobStatus.FINALIZED) { JobReportTime newJobTime = new JobReportTime(); newJobTime.setGuid(job.getCurrentReport().getGuId()); newJobTime.setDate(DateTimeUtil.getToday().getTime()); newJobTime.setIdx(0); newJobTime.setStartTime(DateTimeUtil.getNow().getTime()); newJobTime.setStopTime(DateUtils.getInitialDateTime()); job.getCurrentReport().getTimes().add(newJobTime); job.getCurrentReport().setCreateDate((job.getCurrentReport().getTimes().get(0)).getStartTime()); job.getCurrentReport().setReportStatus(ReportStatus.RECEIVED); job.setStatus(JobStatus.FINALIZED); job.setStatusEdit(new Date()); job.getCurrentReport().setNoMaterial(true); } } String resultMessage = "Job " + job.getJobNumber() + ", job type -> " + jobType + ", State -> " + jobStatus + ", idle time " + idleTimeDays + " days " + ", Rescheduled -> " + (isReschedule == true ?"YES":"NO") + ", Report -> " + (isNewReport == true ?"YES":"NO") + ", Sent -> " + (isReportSent == true ?"YES":"NO"); switch (jobStatusFilter) { case active: resultMessage += " --> Job filter -> ACTIVE."; assertTrue(resultMessage, ServiceJobUtil.isJobActive(job)); break; case planned: resultMessage += " --> Job filter -> PLANNED."; assertTrue(resultMessage, ServiceJobUtil.isJobInPlanned(job)); break; case finalized: resultMessage += " --> Job filter -> FINALIZED."; assertTrue(resultMessage, ServiceJobUtil.isJobFinalized(job)); break; default: break; } System.out.println(resultMessage); } /** * @see "[MIG-437] REP jobs disappears, if you start the report time while they're in filter "planned"" * * https://dev.mfiles.ch/confluence/gilgen/pages/viewpage.action?pageId=106299428 */ @Test public void testFilterJobs() { filterJobsByJobType(JobType.REP); filterJobsByJobType(JobType.MON); filterJobsByJobType(JobType.SAV); } private void filterJobsByJobType(String jobType) { boolean less = false; boolean more = true; boolean yes = true; boolean no = false; checkJobFilter(jobType, JobStatus.NEW, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.NEW, more, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, more, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, more, yes, no, no, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.RECEIVED, more, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.RECEIVED, more, no, no, no, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.IN_PROGRESS, more, no, no, no, JobStatusFilter.active); // checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, yes, yes, yes, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, yes, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, no, yes, yes, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, less, no, no, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, yes, yes, yes, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, yes, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, yes, no, no, JobStatusFilter.planned); // checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, no, yes, yes, JobStatusFilter.active); not exist checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, no, yes, no, JobStatusFilter.active); checkJobFilter(jobType, JobStatus.PARLTY_DONE, more, no, no, no, JobStatusFilter.planned); checkJobFilter(jobType, JobStatus.FINALIZED, less, yes, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FINALIZED, less, no, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FINALIZED, more, yes, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FINALIZED, more, no, yes, yes, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, less, yes, no, no, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, less, no, no, no, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, more, yes, no, no, JobStatusFilter.finalized); checkJobFilter(jobType, JobStatus.FORWARDED, more, no, no, no, JobStatusFilter.finalized); } /** * @see "[MIG-445] User cannot edit a report time (always overlapping)" * */ @Test public void testJobReportTimeOverlapping() { Job newJob = getJobObjectByStatus(JobStatus.RECEIVED); Calendar todayCalendar = DateTimeUtil.getToday(); JobReportTime jobTime = new JobReportTime(); jobTime.setGuid(newJob.getCurrentReport().getGuId()); jobTime.setDate(todayCalendar.getTime()); jobTime.setIdx(0); todayCalendar.set(Calendar.HOUR_OF_DAY, 8); jobTime.setStartTime(todayCalendar.getTime()); todayCalendar.set(Calendar.HOUR_OF_DAY, 9); jobTime.setStopTime(todayCalendar.getTime()); newJob.getCurrentReport().getTimes().add(jobTime); testTimeOverlapping(newJob, "07:50", "08:10", true); testTimeOverlapping(newJob, "08:50", "09:10", true); testTimeOverlapping(newJob, "08:10", "08:50", true); testTimeOverlapping(newJob, "07:50", "09:10", true); testTimeOverlapping(newJob, "01:35", "01:36", false); testTimeOverlapping(newJob, "07:00", "08:00", false); testTimeOverlapping(newJob, "08:00", "08:10", true); testTimeOverlapping(newJob, "09:00", "09:30", false); } private void testTimeOverlapping(Job newJob, String start, String stop, boolean isOverlap) { Object[] arguments = new Object[] { start + " - " + stop , DateTimeUtil.showTime(newJob.getCurrentReport().getTimes().get(0).getStartTime()) + " - " + DateTimeUtil.showTime(newJob.getCurrentReport().getTimes().get(0).getStopTime())}; String errorMessage = MessageFormat.format(Messages.getString("overlapping"), arguments); String resultMessage = errorMessage ; boolean isJobTimesheetOverlapping = ServiceJobUtil.isJobTimesheetOverlapping(newJob.getCurrentReport().getTimes(), start, stop).size() > 0; if(isOverlap) { assertTrue(resultMessage, isJobTimesheetOverlapping); } else { assertFalse(resultMessage, isJobTimesheetOverlapping); } } /** * @see "MIG-466 Report message to client is now mandatory for job type MON" * */ @Test public void testReportMessageForMONJob() { Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); receivedJob.setJobType(JobType.MON); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode("02"); jobMessage.setMessageId(CommonConstants.Message.CUSTOMER); jobMessage.setFullText("Test message"); receivedJob.getLatestReport().getMessages().add(jobMessage); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); } /** * @see "MIG-993 New mandatory for report message for job type 'SAV'" * */ @Test public void testReportMessageForSAVJob() { Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); receivedJob.setJobType(JobType.SAV); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); JobMessage customerMessage = new JobMessage(); customerMessage.setMessageCode("02"); customerMessage.setMessageId(CommonConstants.Message.CUSTOMER); customerMessage.setFullText("Test message"); receivedJob.getLatestReport().getMessages().add(customerMessage); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); customerMessage.setMessageCode(CommonConstants.Message.SYSTEM_IS_SAVE); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); customerMessage.setMessageCode(CommonConstants.Message.SYSTEM_WITH_MINOR_DEFECTS); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); customerMessage.setMessageCode(CommonConstants.Message.SYSTEM_EXHIBITS_DEFECTS); assertFalse(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); JobMessage supervisorMessage = new JobMessage(); supervisorMessage.setMessageId(CommonConstants.Message.HEAD_OF_DEPARTMENT); supervisorMessage.setMessageCode(CommonConstants.Message.SYSTEM_IS_SAVE); supervisorMessage.setFullText("Test message 2"); receivedJob.getLatestReport().getMessages().add(supervisorMessage); customerMessage.setMessageCode("17"); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); } /** * @see "MIG-545 If user chooses ZKDMOBMONTXT.MONTXT = 01 the app is requiring a document incorrectly" * */ @Test public void testModernisationNecessaryFormDescRequire() { Job receivedJob = getJobObjectByStatus(JobStatus.RECEIVED); receivedJob.setJobType(JobType.MON); assertTrue(ServiceJobUtil.isJobRequireReportMessageToCustomer(receivedJob)); receivedJob.setJobType(JobType.SAV); JobMessage jobMessage = new JobMessage(); jobMessage.setMessageCode("02"); jobMessage.setMessageId(CommonConstants.Message.CUSTOMER); jobMessage.setFullText("Test message"); receivedJob.getLatestReport().getMessages().add(jobMessage); assertTrue(ServiceJobUtil.isMandatoryByReportMessage(receivedJob)); receivedJob.getLatestReport().getMessages().get(0).setMessageCode("01"); assertTrue(ServiceJobUtil.isMandatoryByReportMessage(receivedJob)); receivedJob.setJobType(JobType.MON); assertFalse(ServiceJobUtil.isMandatoryByReportMessage(receivedJob)); } }     settings.gradle.kts:   rootProject.name = "gilgen2020" include("common", "login", "material", "service", "timeSheet", "apk-customizer")     timeSheet/AndroidManifest.xml:       timeSheet/application.dtd:       timeSheet/application.xml:       timeSheet/build.gradle.kts:   plugins { id("ch.mfiles.kolibri-application") } sourceSets { test { java { srcDir("test") } } } repositories { mavenCentral() } val junitConfiguration: Configuration by configurations.creating dependencies { implementation(project(":common")) junitConfiguration("junit:junit:4.12") junitConfiguration("commons-logging:commons-logging:1.2") testImplementation(junitConfiguration) } tasks.named("compileTestJava", JavaCompile::class).configure { classpath = junitConfiguration + classpath } tasks.named("test", Test::class).configure { classpath = junitConfiguration + classpath }     timeSheet/build.xml:       timeSheet/i18n/ch/mfiles/kaba/kolibri/timesheet/Messages.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Generated by Eclipse Messages Editor (Eclipse Babel) NoTimeSheet = No time entered. The Timesheet/Expensesheet cannot be sent to the server ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = There are some invalid data. Are you sure you want to close and dismiss the changes? amount = Amount Amount = Amount areYouSureThatYouWantToDeleteAllRecords = Are you sure that you want to delete all records? areYouSureThatYouWantToDeleteRecord = Are you sure that you want to delete this record? calendar = Calendar cannotTransmissonToServerThereIsUnsavedPersonalTimeData = There are some invalid data. The Timesheet/Expensesheet cannot be sent to the server. carMilage = Car milage changesWillBeLost = Changes will be lost, are you sure that you want to continue? clear = Clear clock = O'clock compensation = Compensation dailyExpense = Daily expense date = Date day = Day deduction = Deduction delete = Delete employee = Employee enteredValueIsInTheFuture = The entered value is in the future! Please enter a valid time enteredValueIsInTheFuturePleaseEnterValidTime = The entered value is in the future! Please enter a valid time exit = Exit expense = Expense expenseSheetCouldNotBeSaved = Expense sheet could not be saved. Please try again. fr = CHF from = From fromTo = From - to hours = Hours ia = IA image = Image internalTypeOfWork = Internal type of work internalWorkType = Internal Work type listIsEmptyNoTimeEntryToDelete = List is empty, no time entry to delete miscExpense = Misc. expense newTimeEntryConfictsWithExistingOne = New time entry conficts with existing one: {0} - {1} noExpenses = No expenses noExpensesFoundForThisDate = No expenses found for this date noPresentCannotBeSent = No {0} present for {1}, {2} cannot be sent. noReportAvailable = No report available noTimeEntrySelected = No time entry selected non = non onCall = On-call opHrs = Op.Hrs. p = P payment = Payment personalTime = Personal time personalTimeAndExpensesNotSent = Personal time and expenses aren't sent yet! pikett = Pikett pikettExpenses = Pikett expenses pleaseAdjustBeforeSendToServer = Entry past midnight detected, please adjust it before send to server. pleaseEnterTime = Please enter a time pleaseEnterValidTime = Please enter a valid time pleaseEnterWorkType = Please enter a work type removingOldTimesheets = Removing old time sheets: save = Save send = Send startTimeAlreadyExists = Entry with identical start time {0} already exists. startingTime = Starting time state = State time = Time timeIsRumming = Time is running timeSheet = TimeSheet timeSheetNotSentOlderThanThirTyDays = Timesheet from: {0} refered on the timesheet, that wasn't sent since 30 days. timesheet = Timesheet timesheetAlreadySent = Timesheet already sent. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = The Timesheet/Expensesheet cannot be edited anymore after transmisson to the server.\nAre you sure that you want to transmit the Timesheet together with the Expensesheet? timesheetSent = Timesheet sent. to = To total = Total variousExpenses = Various Expenses vehicleKilometers = Vehicle kilometers warning = Warning! wrongFormArgument = Wrong form argument class found in form     timeSheet/i18n/ch/mfiles/kaba/kolibri/timesheet/Messages_de.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface NoTimeSheet = Es wurde keine Zeit eingegeben. Das Zeiterfassungs-/Spesen-Blatt kann nicht an den Server gesandt werden. ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = Einige der Daten sind ung\u00FCltig. Sind Sie sicher, dass Sie schliessen und die \u00C4nderungen verwerfen wollen? amount = Anzahl Amount = Betrag areYouSureThatYouWantToDeleteAllRecords = Sind Sie sicher, dass Sie alle Datens\u00E4tze l\u00F6schen m\u00F6chten? areYouSureThatYouWantToDeleteRecord = Soll der Eintrag gel\u00F6scht werden? calendar = Kalender cannotTransmissonToServerThereIsUnsavedPersonalTimeData = Einige der Daten sind ung\u00FCltig. Das Zeiterfassungs-/Spesen-Blatt kann nicht an den Server gesandt werden. carMilage = Fz. km changesWillBeLost = \u00C4nderungen gehen verloren, weiterfahren? clear = Reset clock = Uhr compensation = Verg\u00FCtung dailyExpense = Tagesspesen date = Datum day = Tag deduction = Abzug delete = L\u00F6schen employee = Mitarbeiter enteredValueIsInTheFuture = Der eingegebene Wert liegt in der Zukunft. Bitte geben Sie einen g\u00FCltigen Wert ein. enteredValueIsInTheFuturePleaseEnterValidTime = Der eingegebene Wert liegt in der Zukunft. Bitte geben Sie einen g\u00FCltigen Wert ein. exit = Beenden expense = Spesen expenseSheetCouldNotBeSaved = Spesen konnten nicht gespeichert werden. Bitte nochmals probieren. fr = CHF from = Von fromTo = Von - Bis hours = Std ia = IA image = Bild internalTypeOfWork = Interne Arbeitsart internalWorkType = Interne Arbeitsart listIsEmptyNoTimeEntryToDelete = Liste ist leer, Zeit kann nicht gel\u00F6scht werden miscExpense = Div. Spesen newTimeEntryConfictsWithExistingOne = Neuer Eintrag kollidiert mit Bestehendem: {0} - {1} noExpenses = Keine Spesen noExpensesFoundForThisDate = Keine Spesen f\u00FCr dieses Datum erfasst noPresentCannotBeSent = Kein {0} erstellt f\u00FCr {1}, {2} kann nicht \u00FCbermittelt werden. noReportAvailable = Keinen Rapport gefunden noTimeEntrySelected = Keinen Eintrag gew\u00E4hlt non = keine onCall = Pikett opHrs = Betr. Std. p = P payment = Auszahlung personalTime = Zeit personalTimeAndExpensesNotSent = Zeit und Spesen noch nicht \u00FCbertragen! pikett = Pikett pikettExpenses = Pikettspesen pleaseAdjustBeforeSendToServer = Stempelung \u00FCber Mitternacht entdeckt, bitte korrigieren. pleaseEnterTime = Bitte Zeit eingeben pleaseEnterValidTime = Bitte eine g\u00FCltige Zeit eingeben pleaseEnterWorkType = Bitte Arbeitsart angeben removingOldTimesheets = Alte Timesheets l\u00F6schen: save = Speichern send = Senden startTimeAlreadyExists = Es gibt schon einen Eintrag mit identischer Startzeit: {0} startingTime = Startzeit state = Status time = Zeit timeIsRumming = Zeit laufend timeSheet = Zeiterfassung timeSheetNotSentOlderThanThirTyDays = Timesheet vom {0} wurde noch nicht \u00FCbermittelt. timesheet = Zeiterfassung timesheetAlreadySent = Timesheet wurde bereits gesandt. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = Nach der \u00DCbermittlung k\u00F6nnen Sie die Auftragszeiten und das Spesenformular nicht mehr bearbeiten. Fortfahren? timesheetSent = Timesheet gesendet. to = Bis total = Total variousExpenses = Diverse Spesen vehicleKilometers = Fahrzeugkilometer warning = Warnung! wrongFormArgument = Falscher Form\u00FCbergabeparameter     timeSheet/i18n/ch/mfiles/kaba/kolibri/timesheet/Messages_fr.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface NoTimeSheet = Le temps n'a pas \u00E9t\u00E9 entr\u00E9. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre envoy\u00E9e au serveur. ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = Certaines des donn\u00E9es ne sont pas valables. Voulez-vous vraiment fermer et annuler les modifications? amount = Quantit\u00E9 Amount = Montant areYouSureThatYouWantToDeleteAllRecords = \u00CAtes-vous s\u00FBr de vouloir supprimer tous les enregistrements? areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? calendar = Calendrier cannotTransmissonToServerThereIsUnsavedPersonalTimeData = Certaines des donn\u00E9es ne sont pas valables. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre enfoy\u00E9e au serveur. carMilage = Km v\u00E9hic. changesWillBeLost = Les changements seront perdus. Continuer? clear = Remettre clock = Regarder compensation = Remboursement dailyExpense = Frais du jour date = Date day = Jour deduction = D\u00E9duction delete = Effacer employee = Collaborateur enteredValueIsInTheFuture = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. exit = Terminer expense = Frais expenseSheetCouldNotBeSaved = Impossible de m\u00E9moriser les frais. Veuillez r\u00E9essayer. fr = CHF from = De fromTo = de - \u00E0 hours = Heures ia = IA image = Image internalTypeOfWork = Type de travail interne internalWorkType = Type de travail interne listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible de supprimer le temp miscExpense = Div. frais newTimeEntryConfictsWithExistingOne = Nouvelle entr\u00E9e en collision avec l''entr\u00E9e existante: {0} - {1} noExpenses = Pas de frais noExpensesFoundForThisDate = Pas de frais saisies pour cette date noPresentCannotBeSent = Aucun {0} \u00E9tabli pour f\u00FCr {1}, {2} impossible de transmettre. noReportAvailable = Aucun rapport n'est trouv\u00E9 noTimeEntrySelected = Aucun enregistrement n'est saisi non = aucun onCall = Piquet opHrs = Heures de fonct. p = P payment = Versement personalTime = Temps personnel personalTimeAndExpensesNotSent = Temps n\u00E9cessaire et d\u00E9penses n'ont pas \u00E9t\u00E9 transmis! pikett = Piquet pikettExpenses = Frais d'appel pleaseAdjustBeforeSendToServer = Enregistrement d\u00E9t\u00E9ct\u00E9 apr\u00E9s minuit, s.v.p. corriger. pleaseEnterTime = Veuillez saisir le temps pleaseEnterValidTime = Veuillez saisir un temps valide pleaseEnterWorkType = Veuillez introduire le type de travail removingOldTimesheets = Effacer les vieilles fiches horaires : save = Enregistre send = Envoyer startTimeAlreadyExists = Il y a d\u00E9j\u00E0 un enregistrement avec temps de d\u00E9marrage identique: {0} startingTime = Heure de d\u00E9but state = \u00C9tat time = Temps timeIsRumming = Le temps court timeSheet = Saisie du temps timeSheetNotSentOlderThanThirTyDays = Timesheet de {0} n'a pas encore \u00E9t\u00E9 transmis. timesheet = Saisie du temps timesheetAlreadySent = Feuille de saisie des heures a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9e. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = Impossible d'\u00E9diter les temps de commande et le formulaire des frais apr\u00E9s la transmission. Transmettre? timesheetSent = Feuille de temps envoy\u00E9e. to = \u00E0 total = Total variousExpenses = Various Expenses vehicleKilometers = Kilom\u00E9trage du v\u00E9hicule warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect     timeSheet/i18n/ch/mfiles/kaba/kolibri/timesheet/Messages_it.properties:   #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) # File created by MFiles Kolibri mobileX interface NoTimeSheet = Le temps n'a pas \u00E9t\u00E9 entr\u00E9. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre envoy\u00E9e au serveur. ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit = Certaines des donn\u00E9es ne sont pas valables. Voulez-vous vraiment fermer et annuler les modifications? amount = Quantit\u00E9 Amount = Montant areYouSureThatYouWantToDeleteAllRecords = \u00CAtes-vous s\u00FBr de vouloir supprimer tous les enregistrements? areYouSureThatYouWantToDeleteRecord = Effacer l'entregistrement? calendar = Calendrier cannotTransmissonToServerThereIsUnsavedPersonalTimeData = Certaines des donn\u00E9es ne sont pas valables. La feuille de saisie des heures/d\u00E9penses ne peut pas \u00EAtre enfoy\u00E9e au serveur. carMilage = Km v\u00E9hic. changesWillBeLost = Les changements seront perdus. Continuer? clear = Remettre clock = Regarder compensation = Remboursement dailyExpense = Frais du jour date = Date day = Jour deduction = D\u00E9duction delete = Effacer employee = Collaborateur enteredValueIsInTheFuture = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. enteredValueIsInTheFuturePleaseEnterValidTime = La valeur indiqu\u00E9e se trouve au futur. Veuillez enregister une valeur valide. exit = Terminer expense = Frais expenseSheetCouldNotBeSaved = Impossible de m\u00E9moriser les frais. Veuillez r\u00E9essayer. fr = CHF from = De fromTo = de - \u00E0 hours = Heures ia = IA image = Image internalTypeOfWork = Type de travail interne internalWorkType = Type de travail interne listIsEmptyNoTimeEntryToDelete = La liste est vide, impossible de supprimer le temp miscExpense = Div. frais newTimeEntryConfictsWithExistingOne = Nouvelle entr\u00E9e en collision avec l''entr\u00E9e existante: {0} - {1} noExpenses = Pas de frais noExpensesFoundForThisDate = Pas de frais saisies pour cette date noPresentCannotBeSent = Aucun {0} \u00E9tabli pour f\u00FCr {1}, {2} impossible de transmettre. noReportAvailable = Aucun rapport n'est trouv\u00E9 noTimeEntrySelected = Aucun enregistrement n'est saisi non = aucun onCall = Piquet opHrs = Heures de fonct. p = P payment = Versement personalTime = Temps personnel personalTimeAndExpensesNotSent = Temps n\u00E9cessaire et d\u00E9penses n'ont pas \u00E9t\u00E9 transmis! pikett = Piquet pikettExpenses = Frais d'appel pleaseAdjustBeforeSendToServer = Enregistrement d\u00E9t\u00E9ct\u00E9 apr\u00E9s minuit, s.v.p. corriger. pleaseEnterTime = Veuillez saisir le temps pleaseEnterValidTime = Veuillez saisir un temps valide pleaseEnterWorkType = Veuillez introduire le type de travail removingOldTimesheets = Effacer les vieilles fiches horaires : save = Enregistre send = Envoyer startTimeAlreadyExists = Il y a d\u00E9j\u00E0 un enregistrement avec temps de d\u00E9marrage identique: {0} startingTime = Heure de d\u00E9but state = \u00C9tat time = Temps timeIsRumming = Le temps court timeSheet = Saisie du temps timeSheetNotSentOlderThanThirTyDays = Timesheet de {0} n'a pas encore \u00E9t\u00E9 transmis. timesheet = Saisie du temps timesheetAlreadySent = Feuille de saisie des heures a d\u00E9j\u00E0 \u00E9t\u00E9 envoy\u00E9e. timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer = Impossible d'\u00E9diter les temps de commande et le formulaire des frais apr\u00E9s la transmission. Transmettre? timesheetSent = Feuille de temps envoy\u00E9e. to = \u00E0 total = Total variousExpenses = Various Expenses vehicleKilometers = Kilom\u00E9trage du v\u00E9hicule warning = Avertissement! wrongFormArgument = Param\u00E8tre de remise de la forme incorrect     timeSheet/i18n/ch/mfiles/kaba/kolibri/timesheet/TimeSheetMessages.java:   package ch.mfiles.kaba.kolibri.timesheet; import java.util.MissingResourceException; import java.util.ResourceBundle; public class TimeSheetMessages { private static final String BUNDLE_NAME = "ch.mfiles.kaba.kolibri.timesheet.Messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private TimeSheetMessages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }     timeSheet/project.properties:   # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-23     timeSheet/sonar.xml:       timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/forms/CalendarOverviewForm.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.DatePicker; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ListWidget.OverScrollListener; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarDateRange; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarDateSelection; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarListWindow; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarMonthHeaderPolicy; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarScrollTrigger; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarTimeSheetCache; import ch.mfiles.kaba.kolibri.timesheet.util.CalendarToolbarTitleText; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.impl.android.ui.UIActivity; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; @SuppressWarnings("unused") public class CalendarOverviewForm extends SuperForm { protected static Log log = LogFactory.getLog(CalendarOverviewForm.class); private static final int MAX_CALENDAR_ITEMS = 124; public static TimeSheetApplication app; private Context context; private TimeListWidget listWidget; private ProgressBar loadMoreProgressView; private RelativeLayout mainFormView; private LinearLayout emptyMessageView; private TextView calendarValue; private Date dateSelected = new Date(); private TimeUtil timeUtil; private CalendarTimeSheet mCalendar; private CalendarTimeSheet selectedCalendar; private List calendarList = new ArrayList(); private CalendarTimeSheetCache calendarCache; private CalendarScrollTrigger calendarScrollTrigger = new CalendarScrollTrigger(); private CalendarToolbarTitleText calendarTitleText = new CalendarToolbarTitleText(); private volatile boolean preloadCalendarRunning = false; public void onFormCall(Object argument) { if (argument instanceof CalendarOverviewFormArgument) { mCalendar = ((CalendarOverviewFormArgument) argument).getCALENDAR(); isServiceApp = ((CalendarOverviewFormArgument) argument).isServiceApp(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(TimeSheetMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } /** * This event is received exactly once in the lifetime of a form. It is * called after the framework instantiated and initialized the form and * should be used to further initialize the form's controls and other data * that must only be initialized once. *

*

* This event is received before the {@link #onFormShow()} event is raised. *

* The framework decides, when to load and initialize a new form. This may * happen immediately before the form is used, but it could also happen at * application start to preload often used forms. *

* * @param context * The context to user for creating UI widgets. * * @param inflater * The inflater to use to inflate the application's layouts * from XML resource ids. * * @return The view hierarchy constituting the form's UI. */ @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); this.context = context; timeUtil = new TimeUtil(app, app.dbutil, this); // hide runtime menu items setRuntimeMenuHidden(true); FrameLayout calendarTitleLayout = new FrameLayout(context); LinearLayout.LayoutParams titleLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT(); titleLayoutParams.setMargins(LayoutUtils.convertDpToPixel(context, -4), LayoutUtils.convertDpToPixel(context, -8), 0, 0); calendarTitleLayout.setLayoutParams(titleLayoutParams); calendarValue = new TextView(context); calendarValue.setTextColor(LayoutUtils.DEFAULT_WHITE); calendarValue.setTypeface(CommonConstants.Font.getDefaultRegularFont(Typeface.BOLD)); calendarValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); calendarValue.setSingleLine(); FrameLayout.LayoutParams titleTextLayoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); titleTextLayoutParams.gravity = Gravity.CENTER_VERTICAL; calendarTitleLayout.addView(calendarValue, titleTextLayoutParams); TextView dropdownIndicator = new TextView(context); dropdownIndicator.setText("\u25BE"); dropdownIndicator.setTextColor(LayoutUtils.DEFAULT_WHITE); dropdownIndicator.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); dropdownIndicator.setSingleLine(); FrameLayout.LayoutParams dropdownLayoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); dropdownLayoutParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; calendarTitleLayout.addView(dropdownIndicator, dropdownLayoutParams); OnTouchListener showDatePickerListener = new OnTouchListener() { @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { if (paramMotionEvent.getAction() == MotionEvent.ACTION_UP) { createDatePickerDialog(getPickerDate()).show(); } return true; } }; calendarTitleLayout.setOnTouchListener(showDatePickerListener); calendarValue.setOnTouchListener(showDatePickerListener); dropdownIndicator.setOnTouchListener(showDatePickerListener); Toolbar toolbar = getToolbar(); toolbar.addView(calendarTitleLayout); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return onBackPressed(); } }, false); } }); saveButton.setVisible(false); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget = new TimeListWidget(context); listWidget.setDivider(new ColorDrawable(Color.LTGRAY)); //0xAARRGGBB listWidget.setDividerHeight(1); listWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); listWidget.setOnOverScrollListener(new OverScrollListener() { @Override public void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { if(clampedY) { int trigger = calendarScrollTrigger.getOverScrollTrigger(listWidget.getFirstVisiblePosition(), listWidget.getLastVisiblePosition(), listWidget.getCount(), loadMoreCalendarRunning); if (trigger == CalendarScrollTrigger.PREVIOUS) { loadMoreCalendar(true); return; } if (trigger == CalendarScrollTrigger.NEXT) { loadMoreCalendar(false); return; } } } }); listWidget.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { calendarScrollTrigger.onScrollStateChanged(scrollState != OnScrollListener.SCROLL_STATE_IDLE); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int trigger = calendarScrollTrigger.getTrigger(firstVisibleItem, visibleItemCount, totalItemCount, loadMoreCalendarRunning); if (trigger == CalendarScrollTrigger.PREVIOUS) { loadMoreCalendar(true); return; } if (trigger == CalendarScrollTrigger.NEXT) { loadMoreCalendar(false); return; } updateVisibleCalendarDate(firstVisibleItem, visibleItemCount); } }); ArrayList items = new ArrayList(); listWidget.addItems(items); mainFormView.addView(listWidget); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(emptyMessageView); loadMoreProgressView = new ProgressBar(context); loadMoreProgressView.setIndeterminate(true); RelativeLayout.LayoutParams loadMoreProgressParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); loadMoreProgressParams.addRule(RelativeLayout.CENTER_HORIZONTAL); loadMoreProgressParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); loadMoreProgressParams.bottomMargin = LayoutUtils.convertDpToPixel(context, 16); loadMoreProgressView.setLayoutParams(loadMoreProgressParams); loadMoreProgressView.setVisibility(View.GONE); mainFormView.addView(loadMoreProgressView); linearLayout.addView(mainFormView); view.addView(linearLayout); return view; } private DatePickerDialog createDatePickerDialog(Date initialDate) { Calendar calendar = Calendar.getInstance(); calendar.setTime(initialDate); return new DatePickerDialog(UIActivity.getInstance(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, monthOfYear); cal.set(Calendar.DAY_OF_MONTH, dayOfMonth); cal.set(Calendar.YEAR, year); // Load new calendar object from database mCalendar = app.dbutil.loadCalendar(cal.getTime(), app.dbutil.getUser().getPersonalNumber()); loadTable(); selectCalendar(mCalendar.getDate(), false); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } private Date getPickerDate() { Date visibleDate = mCalendar == null ? null : mCalendar.getDate(); Date selectedDate = selectedCalendar == null ? null : selectedCalendar.getDate(); return CalendarDateSelection.getPickerDate(visibleDate, selectedDate); } /** * This event is received every time the form is shown. This happens if the * form is called by the framework, another form or if reactivated from the * application's form stack. <p/> * * The application developer has to set all member variables (reset the * state of the form) at this point because the framework reuses the forms * (every form is instantiated exactly once during the lifetime of an * application) *

* * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(TimeSheetMessages.getString("calendar")); //$NON-NLS-1$ log.info("calendar " + mCalendar.getDateString()); loadTable(); Date visibleDate = CalendarDateSelection.getVisibleDate(mCalendar.getDate(), selectedCalendar == null ? null : selectedCalendar.getDate()); selectCalendar(visibleDate, false); List capturingDays = app.dbutil.selectCalendarDateWithRunningTimeCapturing(app.dbutil.getUser().getPersonalNumber()); if (!capturingDays.isEmpty()) { Calendar capturingDay = Calendar.getInstance(); capturingDay.setTime(capturingDays.get(0)); if(DateTimeUtil.getToday().get(Calendar.DAY_OF_YEAR) > capturingDay.get(Calendar.DAY_OF_YEAR) && DateTimeUtil.getToday().get(Calendar.YEAR) == capturingDay.get(Calendar.YEAR)) { // stopTime timeUtil.stopWorkTimeCapturing(new RunOnUIThread() { @Override public void runOnUIThread() { // start time timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { loadTable(); } }); } }); } } return null; } private volatile int currentDayPosition; private volatile int selectedDayPosition; /** * UI independent part of table loading... */ private ArrayList loadTableItems() { calendarList.clear(); currentDayPosition = -1; selectedDayPosition = -1; List monthCalendars = getCalendarCache().getMonthItems(mCalendar.getDate()); calendarList.addAll(monthCalendars); return createTableItems(monthCalendars, 0, true); } private ArrayList createTableItems(List calendars, int startIndex, boolean updateSelectionPositions) { int index = startIndex; Date previousDate = startIndex > 0 && startIndex - 1 < calendarList.size() ? calendarList.get(startIndex - 1).getDate() : null; ArrayList items = new ArrayList(); Iterator itr = calendars.iterator(); while (itr.hasNext()) { final CalendarTimeSheet calendar = (CalendarTimeSheet) itr.next(); Calendar date = Calendar.getInstance(); date.setTime(calendar.getDate()); final TimeListWidgetItem item = new TimeListWidgetItem(); if (CalendarMonthHeaderPolicy.shouldShowHeader(calendar.getDate(), previousDate, index)) { item.setHeader(DateTimeUtil.showMonthNameYear(date.getTime())); } previousDate = calendar.getDate(); // status // Colours of line depends on the status of the timesheet itself: // grey = sent // red = validation error // black / orange = active / current date item.setTextColor(getStyleByCalendar(calendar)); String hours = "0.00"; //$NON-NLS-1$ String expns = "0.00"; //$NON-NLS-1$ String opHrs = ""; //$NON-NLS-1$ if (!calendar.getStatus().isINITIAL()) { if (calendar.getDate().after(DateTimeUtil.getToday().getTime())) { calendar.setStatus(CalendarStatus.INITIAL); app.dbutil.deleteCalendarTimeSheet(calendar); } else { hours = getWorkingHours(calendar.getTimeSheets()); expns = getExpens(calendar.getExpense()); opHrs = getOperatingHours(calendar.getExpense()); item.setTitleText(TimeSheetMessages.getString("time") + " " + hours + " Std."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String line1 = TimeSheetMessages.getString("expense") + ": " + expns; //$NON-NLS-1$ //$NON-NLS-2$ item.setStringLine1(line1); } } else { // hours = TimeSheetMessages.getString("timeIsRunning"); } if(DateTimeUtil.getToday().get(Calendar.DAY_OF_YEAR) == date.get(Calendar.DAY_OF_YEAR) && DateTimeUtil.getToday().get(Calendar.YEAR) == date.get(Calendar.YEAR)) { //current date = orange if (updateSelectionPositions) { currentDayPosition = index; } item.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); item.setBackgroundColor(LayoutUtils.DEFAULT_ORANGE); if(calendar.isTimeCapturing()){ item.setTitleText(TimeSheetMessages.getString("startingTime") + ": " + DateTimeUtil.showTime(calendar.getStartTimeCapturing())); //$NON-NLS-1$ item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.STOP_TIME, CommonConstants.Images.IMAGE_DPI))); } else { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.START_TIME, CommonConstants.Images.IMAGE_DPI))); } if(calendar.getStatus().isSENT()) { item.setTextColor(LayoutUtils.DEFAULT_DARK_GRAY); item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.START_TIME_DISABLED, CommonConstants.Images.IMAGE_DPI))); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton) { if(calendar.isTimeCapturing()){ // stopTime timeUtil.stopWorkTimeCapturing(new RunOnUIThread() { @Override public void runOnUIThread() { loadTable(); } }); } else { // start time timeUtil.startWorkTimeCapturing(CommonConstants.PLEASE_SELECT, false, new RunOnUIThread() { //$NON-NLS-1$ @Override public void runOnUIThread() { loadTable(); } }); } } } }); } else { Calendar selectedCal = Calendar.getInstance(); selectedCal.setTime(mCalendar.getDate()); if(selectedCal.get(Calendar.DAY_OF_YEAR) == date.get(Calendar.DAY_OF_YEAR) && selectedCal.get(Calendar.YEAR) == date.get(Calendar.YEAR)) { if (updateSelectionPositions) { selectedDayPosition = index; } } selectedCal.setTime(calendar.getDate()); if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { item.setBackgroundColor(LayoutUtils.DEFAULT_LIGHT_GRAY); if(calendar.getStatus().isSENT()) { item.setTextColor(LayoutUtils.DEFAULT_DARK_GRAY); } } } item.setDateTitle(DateTimeUtil.showDayOfMonth(calendar.getDate())); item.setDateText(DateTimeUtil.showDayOfWeek(calendar.getDate())); items.add(item); index ++; } return items; } /** * UI part of table loading... * @param items */ private void loadTableDataListWidget(ArrayList items) { listWidget.clean(); listWidget.setOnItemClickListener(createOnItemClickListener()); listWidget.addItems(items); if(currentDayPosition>-1) { listWidget.setSelection(currentDayPosition -3); } if(selectedDayPosition>-1) { listWidget.setSelection(selectedDayPosition); } } private void loadTable() { resetCalendarCache(); ArrayList items = loadTableItems(); loadTableDataListWidget(items); preloadAdjacentCalendars(mCalendar.getDate()); } private volatile boolean loadMoreCalendarRunning = false; private void loadMoreCalendar(final boolean isLoadPrevious) { // Problem: the refresh trigger is called multiple times during a // single overscroll gesture, so stop processing events until the // reload has finished if (loadMoreCalendarRunning) return; loadMoreCalendarRunning = true; setLoadMoreProgressVisible(true); final int firstVisibleBeforeLoad = listWidget.getFirstVisiblePosition(); final int firstVisibleTopBeforeLoad = listWidget.getChildCount() > 0 ? listWidget.getChildAt(0).getTop() : 0; final Date boundaryDate = isLoadPrevious ? calendarList.get(0).getDate() : calendarList.get(calendarList.size() - 1).getDate(); final int appendStartIndex = calendarList.size(); new AsyncTask(this) { private volatile List loadedCalendars; private volatile ArrayList items; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if (calendarList.isEmpty()) { return null; } CalendarDateRange.Range range = isLoadPrevious ? CalendarDateRange.previousBefore(boundaryDate) : CalendarDateRange.nextAfter(boundaryDate); loadedCalendars = getCalendarCache().getRangeItems(range.getStartDate(), range.getEndDate()); items = createTableItems(loadedCalendars, isLoadPrevious ? 0 : appendStartIndex, false); return null; } @Override protected void runOnUIThread() { if (loadedCalendars == null || loadedCalendars.isEmpty() || items == null || items.isEmpty()) { loadMoreCalendarRunning = false; setLoadMoreProgressVisible(false); return; } calendarScrollTrigger.suppressTriggerUntilIdle( isLoadPrevious ? CalendarScrollTrigger.PREVIOUS : CalendarScrollTrigger.NEXT); if (isLoadPrevious) { calendarList.addAll(0, loadedCalendars); listWidget.getItems().addAll(0, items); int anchorPosition = firstVisibleBeforeLoad + items.size(); trimCalendarItems(true); updateCalendarHeaders(); listWidget.getAdapter().notifyDataSetChanged(); listWidget.setSelectionFromTop(anchorPosition, firstVisibleTopBeforeLoad); } else { calendarList.addAll(loadedCalendars); listWidget.getItems().addAll(items); int removedFromStart = trimCalendarItems(false); updateCalendarHeaders(); listWidget.getAdapter().notifyDataSetChanged(); if (removedFromStart > 0) { listWidget.setSelectionFromTop( CalendarListWindow.getPositionAfterStartTrim(firstVisibleBeforeLoad, removedFromStart), firstVisibleTopBeforeLoad); } } loadMoreCalendarRunning = false; setLoadMoreProgressVisible(false); } }; } private int trimCalendarItems(boolean removeFromEnd) { int trimCount = CalendarListWindow.getTrimCount(calendarList.size(), MAX_CALENDAR_ITEMS); if (trimCount <= 0) { return 0; } if (removeFromEnd) { int fromIndex = calendarList.size() - trimCount; calendarList.subList(fromIndex, calendarList.size()).clear(); listWidget.getItems().subList(fromIndex, listWidget.getItems().size()).clear(); return 0; } calendarList.subList(0, trimCount).clear(); listWidget.getItems().subList(0, trimCount).clear(); return trimCount; } private void updateCalendarHeaders() { int itemCount = Math.min(calendarList.size(), listWidget.getItems().size()); Date previousDate = null; for (int i = 0; i < itemCount; i++) { CalendarTimeSheet calendar = calendarList.get(i); if (CalendarMonthHeaderPolicy.shouldShowHeader(calendar.getDate(), previousDate, i)) { listWidget.getItems().get(i).setHeader(DateTimeUtil.showMonthNameYear(calendar.getDate())); } else { listWidget.getItems().get(i).setHeader(null); } previousDate = calendar.getDate(); } } private void setLoadMoreProgressVisible(boolean visible) { if (loadMoreProgressView != null) { loadMoreProgressView.setVisibility(visible ? View.VISIBLE : View.GONE); } } private CalendarTimeSheetCache getCalendarCache() { if (calendarCache == null) { calendarCache = new CalendarTimeSheetCache(new CalendarTimeSheetCache.Loader() { @Override public CalendarTimeSheet loadCalendar(Date date, int personalNumber) { return app.dbutil.loadCalendar(date, personalNumber); } }, app.dbutil.getUser().getPersonalNumber()); } return calendarCache; } private void resetCalendarCache() { getCalendarCache().clear(); } private void preloadAdjacentCalendars(final Date focusDate) { if (preloadCalendarRunning) { return; } preloadCalendarRunning = true; final CalendarTimeSheetCache cache = getCalendarCache(); new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { cache.preloadAdjacentMonths(focusDate); return null; } @Override protected void runOnUIThread() { preloadCalendarRunning = false; } }; } private void selectCalendar(Date date) { selectCalendar(date, true); } private void selectCalendar(Date date, boolean smoothScroll) { selectedCalendar = null; for (int i = 0; i < calendarList.size(); i++) { if(CalendarDateSelection.isSameCalendarDay(date, calendarList.get(i).getDate())) { Calendar nextCal = Calendar.getInstance(); nextCal.setTime(calendarList.get(i).getDate()); setDate(nextCal.get(Calendar.YEAR), nextCal.get(Calendar.MONTH), nextCal.get(Calendar.DAY_OF_MONTH)); selectedCalendar = calendarList.get(i); calendarScrollTrigger.suppressUntilIdle(); if (smoothScroll) { listWidget.smoothScrollToPosition(i); } else { listWidget.setSelectionFromTop(i, 0); } return; } } } private void updateVisibleCalendarDate(int firstVisibleItem, int visibleItemCount) { if (calendarList.isEmpty() || firstVisibleItem < 0 || visibleItemCount <= 0) { return; } int visiblePosition = CalendarListWindow.getToolbarTitlePosition(firstVisibleItem, calendarList.size()); CalendarTimeSheet visibleCalendar = calendarList.get(visiblePosition); Calendar nextCal = Calendar.getInstance(); nextCal.setTime(visibleCalendar.getDate()); mCalendar = visibleCalendar; setDate(nextCal.get(Calendar.YEAR), nextCal.get(Calendar.MONTH), nextCal.get(Calendar.DAY_OF_MONTH)); } private OnItemClickListener createOnItemClickListener() { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { selectedCalendar = calendarList.get(position); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(selectedCalendar.getDate(), 0, isServiceApp)); } }, false); } }; } private void setDate(int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, monthOfYear); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); String date = calendarTitleText.updateVisibleMonthTitle(calendar.getTime()); if (date == null) { return; } calendarValue.setText(date); } @Override public ApplicationEvent onBackPressed() { if (isServiceApp) { return appman.leaveToApplication(CommonConstants.Application.SERVICE_APP, null); } else { return appman.exitApplication(); } } private String getOperatingHours(Expenses expense) { String opHrs = ""; //$NON-NLS-1$ if (!expense.isInitial()) { if (StringUtil.isNotEmpty(expense.getOperatingHoursTotal())) { opHrs = expense.getOperatingHoursTotal(); } else if (!(StringUtil.isEmpty(expense.getOperatingHoursOf()) || StringUtil.isEmpty(expense.getOperatingHoursUpTo()))) { Locale locale = Locale.ENGLISH; if (expense.getOperatingHoursOf().contains(",")) { locale = Locale.GERMAN; } try { float vonFloatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(expense.getOperatingHoursOf()))); float bisFloatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(expense.getOperatingHoursUpTo()))); DecimalFormat formater = new DecimalFormat("###.0", new DecimalFormatSymbols(locale)); opHrs = formater.format(bisFloatValue - vonFloatValue); } catch (NumberFormatException e) { opHrs = "--"; } catch (ParseException e) { opHrs = "--"; } } else { opHrs = "--"; //$NON-NLS-1$ } } else { opHrs = "--"; //$NON-NLS-1$ } return opHrs; } private String getExpens(Expenses expense) { String expns = ""; //$NON-NLS-1$ if (!expense.isInitial()) { if (expense.isNoExpenses()) expns = TimeSheetMessages.getString("non"); //$NON-NLS-1$ else { float tgspsn = 0; float divspsn = 0; float pikett = 0; float abzg = 0; Locale locale = Locale.ENGLISH; if (expense.getDailyExpenses().contains(",")) { locale = Locale.GERMAN; } tgspsn = getFloatValue(expense.getDailyExpenses()); divspsn = getFloatValue(expense.getVariousExpenses()); // divspsn = getFloatValue(expense.getVariousExpenses()); pikett = getFloatValue(expense.getPikettExpenses()); abzg = getFloatValue(expense.getDeduction()); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); DecimalFormat format = new DecimalFormat("##0.00", symbols); format.setMaximumFractionDigits(2); expns = format.format(tgspsn + divspsn + pikett - abzg); } } else { expns = "--"; //$NON-NLS-1$ } try { Double.parseDouble(expns); } catch (NumberFormatException e) { expns = "00.00"; //$NON-NLS-1$ } return expns; } private float getFloatValue(String value) { try { Locale locale = Locale.ENGLISH; if (value.contains(",")) { locale = Locale.GERMAN; } float floatValue = Float.valueOf(String.valueOf(NumberFormat.getNumberInstance(locale).parse(value))); return floatValue; } catch (NumberFormatException e) { return 0; } catch (ParseException e) { return 0; } } private String getWorkingHours(TreeSet timeSheets) { long totalTime = 0; Iterator itr = timeSheets.iterator(); while (itr.hasNext()) { TimeSheet timeSheet = (TimeSheet) itr.next(); if (timeSheet.validate().isValid()) totalTime += DateTimeUtil.getTimeDifference(timeSheet.getStopTime(), timeSheet.getStartTime()); // totalTime += zkdmatime.getStopTime().getTime() - zkdmatime.getStartTime().getTime(); } return DateTimeUtil.showTime(totalTime); } private int getStyleByCalendar(CalendarTimeSheet calendar) { int result = LayoutUtils.DEFAULT_TEXT_COLOR; if (calendar.getStatus().isINITIAL() || calendar.getStatus().isSAVED()) result = LayoutUtils.DEFAULT_TEXT_COLOR; else if (calendar.getStatus().isSENT()) result = LayoutUtils.DEFAULT_LIGHT_GRAY; else if (!calendar.isValid()) result = LayoutUtils.DEFAULT_ERROR_COLOR; return result; } public static class CalendarOverviewFormArgument { private CalendarTimeSheet calendar; private boolean isServiceApp; protected CalendarOverviewFormArgument() { } public CalendarOverviewFormArgument(CalendarTimeSheet calendar, boolean isServiceApp) { this.calendar = calendar; this.isServiceApp = isServiceApp; } public CalendarTimeSheet getCALENDAR() { return this.calendar; } public boolean isServiceApp() { return this.isServiceApp; } } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/forms/SuperForm.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import android.content.Context; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import ch.mfiles.kaba.kolibri.common.forms.dlg.DialogForm; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.KeyboardUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetApplication; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; public class SuperForm extends DialogForm { protected Context context; protected LinearLayout view; // initialized by the kolibri framework... public static TimeSheetApplication app; public static boolean isServiceApp; protected ActionCtrl sendButton; @Override public View onFormLoad(Context context, LayoutInflater inflater) { this.context = context; final ImagesUtil imagesUtil = ImagesUtil.getInstance(app); view = new LinearLayout(context); view.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.setOrientation(LinearLayout.VERTICAL); view.setBackgroundColor(LayoutUtils.DEFAULT_CONTENT_AREA_COLOR); view.setFocusable(true); view.setFocusableInTouchMode(true); // hide runtime menu items setRuntimeMenuHidden(true); // customize Toolbar Toolbar toolbar = getToolbar(); // set blue background toolbar.setBackgroundColor(LayoutUtils.DEFAULT_TOOL_BAR_COLOR); // set navigation image and listener Image clearImage = imagesUtil.getImage(ImagesUtil.Images.CLOSE_WHITE, CommonConstants.Images.IMAGE_MIN_DPI); toolbar.setNavigationIcon(getBitmanDrawable(clearImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearErrorMessages(); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); // create save action Image saveImage = imagesUtil.getImage(ImagesUtil.Images.SAVE_WHITE, CommonConstants.Images.IMAGE_DPI); saveButton = addActionCtrl(false, true, 1, "onSavePressed"); //$NON-NLS-1$ saveButton.setTitle(TimeSheetMessages.getString("save")); //$NON-NLS-1$ saveButton.setImage(saveImage); sendButton = addActionCtrl(false, true, 2, "onSendPressed"); //$NON-NLS-1$ sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); // set invisible save button saveButton.setVisible(false); return view; } @Override protected ApplicationEvent onSavePressed() { hideSoftInputFromWindow(); if (isValid()) { onSave(); } return null; } protected boolean isValid() { return true; } /** * Closes the keyboard (if open) */ protected void hideSoftInputFromWindow() { KeyboardUtil.closeKeyboard(appman, getView()); } /** * Clears the error messages. */ protected void clearErrorMessages() { // do nothings } protected ApplicationEvent onSendPressed() { return null; } protected void setSendButtonEnabled(boolean enabled) { sendButton.setEnabled(enabled); if (enabled) { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_WHITE, CommonConstants.Images.IMAGE_DPI))); } else { sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); } } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/forms/TimeSheetDetailForm.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.text.InputFilter; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.InternalWorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.Person; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.VariousExpenses; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.ExpenseMaskEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDRadioButton; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.ViewPageAdapter; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.ExpenseMaskWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.inputmasks.VehicleMaskWatcher; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.ImageListWidgetItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidget; import ch.mfiles.kaba.kolibri.common.forms.widgets.lists.TimeListWidgetItem; import ch.mfiles.kaba.kolibri.common.util.ActionUtil; import ch.mfiles.kaba.kolibri.common.util.ActionUtil.ActionResult; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kaba.kolibri.timesheet.forms.VariousExpensesImageNewEditForm.VariousExpenseFileNewEditFormArguments; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.ActionCtrl; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class TimeSheetDetailForm extends SuperForm implements OnItemSelectedListener, OnCheckedChangeListener { private static Log log = LogFactory.getLog(TimeSheetDetailForm.class); private TimeUtil timeUtil; private CalendarTimeSheet calendar; private Date selectedDate; private RelativeLayout mainView; private ActionCtrl deleteAction; private ActionCtrl addAction; private TabLayout tabLayout; private int pageSelected = 0; /* * Daily routine section */ private TimeListWidget dailyRoutineListWidget; private List timeList; /* * Expense section */ private AppCompatCheckBox noExpensesCheckBox; private ExpenseMaskEditText dailyExpensesEditText; private ExpenseMaskEditText pikettExpensesEditText; private MDSpinner reasonForVariousExpensesValue; private MDEditText freeTextEditText; private ExpenseMaskEditText variousExpensesEditText; private MDEditText deductionEditText; private ExpenseMaskEditText deductionAmountEditText; private MDRadioButton timeRadioButton; private MDRadioButton expensesRadioButton; private MDEditText vehicleFromEditText; private MDEditText vehicleToEditText; /* * Various Expenses section */ private ImageListWidget variousExpenseListWidget; private List variousExpenseList; private LinearLayout emptyMessageView; private ActionUtil utilButton; public void reloadCalendar() { this.calendar = app.dbutil.loadCalendar(selectedDate, app.dbutil.getUser().getPersonalNumber()); } @Override public void onFormCall(Object argument) { if (argument instanceof TimeSheetDetailFormArgument) { TimeSheetDetailFormArgument formArgument = (TimeSheetDetailFormArgument) argument; pageSelected = formArgument.getTabSelected(); selectedDate = formArgument.getDate(); isServiceApp = formArgument.isServiceApp(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(Messages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); timeUtil = new TimeUtil(app, app.dbutil, this); utilButton = new ActionUtil(app); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideSoftInputFromWindow(); onBackPressed(); } }); deleteAction = addActionCtrl(false, true, 1, "actionDelete"); //$NON-NLS-1$ deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setVisible(false); addAction = addActionCtrl(false, true, 1, "actionAdd"); //$NON-NLS-1$ addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setVisible(false); addAction.setEnabled(false); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); view.addView(mainView); return view; } @Override public ApplicationEvent onFormShow() { super.onFormShow(); reloadCalendar(); if(calendar.isValid() && !calendar.getStatus().isSENT()) { setSendButtonEnabled(true); } else { setSendButtonEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); } if (calendar != null) { setFormTitle(DateTimeUtil.showDayOfWeek(calendar.getDate()) + ", " + DateTimeUtil.showDate(calendar.getDate())); //$NON-NLS-1$ } else { setFormTitle(DateTimeUtil.showDayOfWeek(selectedDate) + ", " + DateTimeUtil.showDate(selectedDate)); //$NON-NLS-1$ } if (mainView.getChildCount() > 0) { mainView.removeAllViewsInLayout(); mainView.invalidate(); } View contentView = createTabContentView(context); mainView.addView(contentView); tabLayout.getTabAt(pageSelected).select(); view.invalidate(); loadDailyRoutine(); loadExpense(); // loadVariousExpenses(); Person user = app.dbutil.getUser(); boolean editableCalendar = !calendar.getStatus().isSENT(); boolean editableExpenses = user.getExpensesActive() && editableCalendar && canSaveExpenseForDate(selectedDate, DateTimeUtil.getToday().getTime()); setEnabledControls(editableCalendar); setExpenseControlsEnabled(editableExpenses); if (!user.getExpensesActive()) { noExpensesCheckBox.setChecked(true); vehicleFromEditText.setRequired(false); vehicleToEditText.setRequired(false); } return null; } private void setEnabledControls(boolean enabled) { if(enabled) { deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); if(selectedDate.after(DateTimeUtil.getToday().getTime())) { addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setEnabled(false); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); setSendButtonEnabled(false); enabled = false; } else { addAction.setEnabled(true); addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_WHITE, CommonConstants.Images.IMAGE_DPI))); deleteAction.setEnabled(true); setSendButtonEnabled(true); } } else { deleteAction.setEnabled(false); deleteAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.ADD_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); addAction.setEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); setSendButtonEnabled(false); } } private void setExpenseControlsEnabled(boolean enabled) { noExpensesCheckBox.setEnabled(enabled); setExpenseEnable(enabled); vehicleFromEditText.setEnabled(enabled); vehicleToEditText.setEnabled(enabled); } @Override public ApplicationEvent onBackPressed() { if (isEditedExpense()) { if (validateExpense()) { leaveToCalendarOverview(); } else { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(TimeSheetMessages.getString("ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } else { leaveToCalendarOverview(); } return null; } }, false); } } else { leaveToCalendarOverview(); } return null; } private void leaveToCalendarOverview() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(CalendarOverviewForm.class, new CalendarOverviewForm.CalendarOverviewFormArgument(calendar, isServiceApp)); } }, false); } private boolean validateExpense() { boolean result = true; clearErrorMessages(); if (!noExpensesCheckBox.isChecked()) { if (!timeRadioButton.isChecked() && !expensesRadioButton.isChecked()) { timeRadioButton.setError(Messages.getString("pleaseSelectValue")); //$NON-NLS-1$ result = false; } } if (dailyExpensesEditText.isFocused()) { dailyExpensesEditText.clearFocus(); } if (pikettExpensesEditText.isFocused()) { pikettExpensesEditText.clearFocus(); } if (variousExpensesEditText.isFocused()) { variousExpensesEditText.clearFocus(); } if (deductionAmountEditText.isFocused()) { deductionAmountEditText.clearFocus(); } if (vehicleFromEditText.isFocused()) { vehicleFromEditText.clearFocus(); } if (vehicleToEditText.isFocused()) { vehicleToEditText.clearFocus(); } if(!result) { pageSelected = 1; tabLayout.getTabAt(pageSelected).select(); view.invalidate(); } else { saveExpense(); } return result; } /** * Handles on click event for delete calendar. * * @return */ public ApplicationEvent actionDelete() { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteAllRecords"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } app.dbutil.deleteCalendarTimeSheet(calendar); return appman.getActiveApplication().leaveToForm(CalendarOverviewForm.class, new CalendarOverviewForm.CalendarOverviewFormArgument(calendar, isServiceApp)); } }; return null; } /** * Handles on click event for add action. * * @return */ public ApplicationEvent actionAdd() { if (pageSelected == 2) { utilButton.showPopupMenu(context, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, new ActionResult() { @Override public void onActionResult(Bitmap bitmap) { leaveToImageNewEditForm(bitmap); } }, null); } else { if (isEditedExpense() && !validateExpense()) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { if (app.showMessageBox(TimeSheetMessages.getString("ThereIsUnsavedPersonalTimeDataAreYouSureYouWantToExit"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } else { return appman.getActiveApplication().leaveToForm(TimeSheetForm.class, new TimeSheetForm.TimeSheetFormArgument(calendar, null)); } } }, false); } else { return appman.getActiveApplication().leaveToForm(TimeSheetForm.class, new TimeSheetForm.TimeSheetFormArgument(calendar, null)); } } return null; } private void leaveToImageNewEditForm(final Bitmap bitmap) { if(bitmap == null) return; appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(VariousExpensesImageNewEditForm.class, new VariousExpenseFileNewEditFormArguments(selectedDate, bitmap, null)); } }, false); } /** * Handles on click event for send. * * @return */ @Override public ApplicationEvent onSendPressed() { setSendButtonEnabled(false); sendButton.setImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.SEND_DISABLED_WHITE, CommonConstants.Images.IMAGE_DPI))); if (calendar !=null && calendar.getStatus().isSENT()) { app.showMessage(TimeSheetMessages.getString("timesheetAlreadySent")); //$NON-NLS-1$ log.error(TimeSheetMessages.getString("timesheetAlreadySent")); return null; } boolean isExpenseValid = true; if (!noExpensesCheckBox.isChecked()) { if (StringUtil.isEmpty(dailyExpensesEditText.getText().toString())) { dailyExpensesEditText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ isExpenseValid = false; } } if (vehicleFromEditText.isRequired() && StringUtil.isEmpty(vehicleFromEditText.getText().toString())) { vehicleFromEditText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ isExpenseValid = false; } if (vehicleToEditText.isRequired() && StringUtil.isEmpty(vehicleToEditText.getText().toString())) { vehicleToEditText.setError(Messages.getString("pleaseProvideValue")); //$NON-NLS-1$ isExpenseValid = false; } if (!isExpenseValid) { app.showWarningMessageBox(TimeSheetMessages.getString("cannotTransmissonToServerThereIsUnsavedPersonalTimeData"), new RunOnUIThread() { @Override public void runOnUIThread() { setSendButtonEnabled(true); pageSelected = 1; tabLayout.getTabAt(pageSelected).select(); } }); return null; } if (isEditedExpense()) { if (validateExpense()) { reloadCalendar(); log.info("is Expense valid " + calendar.getExpense().validate().isValid()); log.info("is TimeSheets valid " + !calendar.getTimeSheets().isEmpty()); } } sendCalendar(); return null; } private void sendCalendar() { log.info("is Calendar valid " + calendar.isValid()); if (calendar.isValid()) { new AsyncTask(this) { private CalendarTimeSheet sendCalendar; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { sendCalendar = app.sendTimeSheet(calendar); return null; } @Override protected void runOnUIThread() { if (sendCalendar !=null && sendCalendar.getStatus().isSENT()) { app.showMessage(TimeSheetMessages.getString("timesheetSent")); //$NON-NLS-1$ setSendButtonEnabled(false); reloadCalendar(); loadDailyRoutine(); setEnabledControls(!calendar.getStatus().isSENT()); setExpenseControlsEnabled(false); } else { setSendButtonEnabled(true); } } }; } else { String errorMessage = TimeSheetMessages.getString("cannotTransmissonToServerThereIsUnsavedPersonalTimeData"); if(validateExpense() && calendar.getTimeSheets().isEmpty()) { errorMessage = TimeSheetMessages.getString("NoTimeSheet"); pageSelected = 0; tabLayout.getTabAt(pageSelected).select(); } app.showWarningMessageBox(errorMessage, new RunOnUIThread() { @Override public void runOnUIThread() { setSendButtonEnabled(true); } }); } } private View createTabContentView(Context context) { if (pageSelected != 1) { contextMenuActionState(true); } // create vertical linear view to hold TabLayout and ViewPager LinearLayout contentView = new LinearLayout(context); contentView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentView.setOrientation(LinearLayout.VERTICAL); // create TabLayout tabLayout = new TabLayout(context); LinearLayout.LayoutParams tabLayoutParams = LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS(); tabLayout.setLayoutParams(tabLayoutParams); tabLayout.setBackgroundColor(LayoutUtils.DEFAULT_TAB_COLOR); tabLayout.setTabTextColors(LayoutUtils.DEFAULT_TAB_TEXT_COLOR, LayoutUtils.DEFAULT_TAB_SELECTED_TEXT_COLOR); tabLayout.setSelectedTabIndicatorColor(LayoutUtils.DEFAULT_HIGHLIGHT); contentView.addView(tabLayout); // create 2 simple pages and add them to a page adapter ViewPageAdapter pagerAdapter = new ViewPageAdapter(); // info personal time tab pagerAdapter.addPage(TimeSheetMessages.getString("personalTime"), getDailyRoutineContent()); //$NON-NLS-1$ // address expense tab pagerAdapter.addPage(TimeSheetMessages.getString("expense"), getExpenseContent()); // address expense tab // pagerAdapter.addPage(TimeSheetMessages.getString("variousExpenses"), getVariousExpensesContent()); //$NON-NLS-1$ // ViewPager for PageAdapter ViewPager viewPager = new ViewPager(context); viewPager.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentView.addView(viewPager); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { // reloadCalendar(); if (position == 1) { // personal time contextMenuActionState(false); // loadExpense(); pageSelected = 1; } else { pageSelected = position++; contextMenuActionState(true); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Auto-generated method stub } @Override public void onPageScrollStateChanged(int state) { // Auto-generated method stub } }); viewPager.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { app.showMessage("onFocusChange " + v.getTag() + " focus " + hasFocus); } }); // link TabLayout to ViewPager tabLayout.setupWithViewPager(viewPager); return contentView; } private View getDailyRoutineContent() { RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); dailyRoutineListWidget = new TimeListWidget(context); dailyRoutineListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); dailyRoutineListWidget.setDividerHeight(1); dailyRoutineListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); mainFormView.addView(dailyRoutineListWidget); return mainFormView; } private void loadDailyRoutine() { dailyRoutineListWidget.clean(); if (calendar != null) { ArrayList items = new ArrayList(); timeList = new ArrayList(calendar.getTimeSheets()); for (final TimeSheet timeSheet : timeList) { final TimeListWidgetItem item = new TimeListWidgetItem(); if (calendar.getStatus().isSENT()) { item.setTextColor(LayoutUtils.DEFAULT_LIGHT_GRAY); } else { item.setTextColor(LayoutUtils.DEFAULT_TEXT_COLOR); } InternalWorkType internalWorkType = app.dbutil.selectInternalWorkTypeByWorkTypeCode(timeSheet.getWorkTypeCode()); item.setTitleText(internalWorkType == null ? "":internalWorkType.getText()); if (timeSheet.getStopTime().equals(DateUtils.getInitialDateTime())) { item.setBackgroundColor(LayoutUtils.DEFAULT_ORANGE); item.setStringLine1(TimeSheetMessages.getString("timeIsRumming")); //$NON-NLS-1$ item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.STOP_TIME, CommonConstants.Images.IMAGE_DPI))); item.setButtonImageTag(CommonConstants.Mode.PLAYING); } else { if (calendar.getStatus().isSENT()) { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_DISABLED_BLACK, CommonConstants.Images.IMAGE_DPI))); } else { item.setButtonImage(getBitmanDrawable(app.imagesUtil.getImage(ImagesUtil.Images.DELETE_BLACK, CommonConstants.Images.IMAGE_DPI))); } item.setStringLine1(DateTimeUtil.showTime(timeSheet.getStartTime()) + " - " + DateTimeUtil.showTime(timeSheet.getStopTime()) + " " + TimeSheetMessages.getString("clock")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ item.setButtonImageTag(CommonConstants.Mode.STOP); } item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (v instanceof ImageButton) { if (calendar.getStatus().isSENT()) { return; } if (CommonConstants.Mode.STOP.equals(v.getTag())) { deleteDailyRoutineAction(timeSheet); } else { timeUtil.stopWorkTimeCapturing(new RunOnUIThread() { @Override public void runOnUIThread() { // reload calendar from database reloadCalendar(); loadDailyRoutine(); } }); } } } }); item.setDateTitle(DateTimeUtil.showDayOfMonth(calendar.getDate())); item.setDateText(DateTimeUtil.showDayOfWeek(calendar.getDate())); items.add(item); dailyRoutineListWidget.setOnItemClickListener(createOnItemClickListener(timeList)); } dailyRoutineListWidget.addItems(items); } } private OnItemClickListener createOnItemClickListener(final List timeList) { return new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, final long id) { final TimeSheet timeSheet = timeList.get(position); appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetForm.class, new TimeSheetForm.TimeSheetFormArgument(calendar, timeSheet)); } }, false); } }; } private void deleteDailyRoutineAction(final TimeSheet timeSheet) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteRecord"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, //$NON-NLS-1$ //$NON-NLS-2$ Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } // number the timesheet entries consecutively in chronological // order TreeSet timeSheets = new TreeSet(timeList); Iterator itr = timeSheets.iterator(); int idx = 0; while (itr.hasNext()) { TimeSheet temp = itr.next(); if (temp.getPersonalNumber() == timeSheet.getPersonalNumber() && temp.getStartTime().compareTo(timeSheet.getStartTime()) == 0) { itr.remove(); } else { temp.setIdx(idx); idx++; } } // Save the list of timesheet entries to the current calendar calendar.setTimeSheets(timeSheets); // Save hole CALENDAR Object to the database app.dbutil.saveCALENDAR(calendar); return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); loadDailyRoutine(); } }; } private View getExpenseContent() { RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); // No Expenses noExpensesCheckBox = CommonUtilForm.getCheckBox(context, TimeSheetMessages.getString("noExpenses")); //$NON-NLS-1$ noExpensesCheckBox.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton paramCompoundButton, boolean paramBoolean) { if (paramBoolean) { setExpenseEnable(false); dailyExpensesEditText.getText().clear(); pikettExpensesEditText.getText().clear(); variousExpensesEditText.getText().clear(); deductionEditText.getText().clear(); deductionAmountEditText.getText().clear(); paramCompoundButton.setChecked(paramBoolean); dailyExpensesEditText.clearError(); timeRadioButton.clearError(); } else { setExpenseEnable(true); loadExpense(); paramCompoundButton.setChecked(paramBoolean); } } }); contentLinearLayout.addView(noExpensesCheckBox); LinearLayout dailyLinearLayout = new LinearLayout(context); dailyLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams dailyLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); dailyLinearLayoutParams.gravity = Gravity.CENTER; dailyLinearLayoutParams.width = LayoutParams.MATCH_PARENT; dailyLinearLayoutParams.weight = 1; dailyLinearLayout.setLayoutParams(dailyLinearLayoutParams); dailyExpensesEditText = ExpenseMaskEditText.createDefaultEditText(dailyLinearLayout, TimeSheetMessages.getString("dailyExpense"), true); //$NON-NLS-1$ LinearLayout.LayoutParams dailyExpensesLayoutParams = new LinearLayout.LayoutParams(0, 0); dailyExpensesLayoutParams.gravity = Gravity.CENTER; dailyExpensesLayoutParams.width = 0; dailyExpensesLayoutParams.height = LayoutParams.MATCH_PARENT; dailyExpensesLayoutParams.weight = 0.3f; dailyExpensesEditText.getParentTextInputLayout().setLayoutParams(dailyExpensesLayoutParams); // Pikett Expenses pikettExpensesEditText = ExpenseMaskEditText.createDefaultEditText(dailyLinearLayout, TimeSheetMessages.getString("pikettExpenses"), false); //$NON-NLS-1$ LinearLayout.LayoutParams pikettExpensesLayoutParams = new LinearLayout.LayoutParams(0, 0); pikettExpensesLayoutParams.gravity = Gravity.CENTER; pikettExpensesLayoutParams.width = 0; pikettExpensesLayoutParams.height = LayoutParams.MATCH_PARENT; pikettExpensesLayoutParams.weight = 0.3f; pikettExpensesEditText.getParentTextInputLayout().setLayoutParams(pikettExpensesLayoutParams); contentLinearLayout.addView(dailyLinearLayout); // Misc Expense reasonForVariousExpensesValue = MDSpinner.createDefaultSpinner(contentLinearLayout, TimeSheetMessages.getString("miscExpense"), false); //$NON-NLS-1$ reasonForVariousExpensesValue.setTag("MISC_EXPENSE"); //$NON-NLS-1$ reasonForVariousExpensesValue.setOnItemSelectedListener(this); LinearLayout.LayoutParams underlineLinearLayout = (LinearLayout.LayoutParams) reasonForVariousExpensesValue.getUnderline().getLayoutParams(); underlineLinearLayout.setMargins(0, 0, LayoutUtils.convertDpToPixel(context, 5), LayoutUtils.convertDpToPixel(context, 4)); reasonForVariousExpensesValue.getUnderline().setLayoutParams(underlineLinearLayout); // Misc Display freeTextEditText = MDEditText.createDefaultEditText(contentLinearLayout, "", InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ freeTextEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY_FIVE) }); // Various expenses variousExpensesEditText = ExpenseMaskEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("Amount"), false); //$NON-NLS-1$ // Deduction deductionEditText = MDEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("deduction"), InputType.TYPE_CLASS_TEXT, false); //$NON-NLS-1$ deductionEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.TWENTY_FIVE) }); // Deduction Amount deductionAmountEditText = ExpenseMaskEditText.createDefaultEditText(contentLinearLayout, TimeSheetMessages.getString("Amount"), false); //$NON-NLS-1$ LinearLayout compensationLinearLayout = new LinearLayout(context); compensationLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams compensationLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); compensationLinearLayoutParams.gravity = Gravity.LEFT; compensationLinearLayoutParams.width = LayoutParams.MATCH_PARENT; compensationLinearLayoutParams.weight = 0.7f; compensationLinearLayoutParams.topMargin = LayoutUtils.DEFAULT_MAX_MARGIN; compensationLinearLayoutParams.bottomMargin = LayoutUtils.DEFAULT_MAX_MARGIN; compensationLinearLayout.setLayoutParams(compensationLinearLayoutParams); // Compensation TextView compensationTextView = CommonUtilForm.getTextView(context, TimeSheetMessages.getString("compensation")); //$NON-NLS-1$ LinearLayout.LayoutParams compensationTextViewLayoutParams = new LinearLayout.LayoutParams(0, 0); compensationTextViewLayoutParams.gravity = Gravity.LEFT; compensationTextViewLayoutParams.width = 0; compensationTextViewLayoutParams.height = LayoutParams.MATCH_PARENT; compensationTextViewLayoutParams.weight = 0.3f; compensationTextView.setLayoutParams(compensationTextViewLayoutParams); compensationLinearLayout.addView(compensationTextView); timeRadioButton = MDRadioButton.createDefaultRadioButton(compensationLinearLayout, TimeSheetMessages.getString("time")); //$NON-NLS-1$ timeRadioButton.setTag("TIME"); //$NON-NLS-1$ timeRadioButton.setOnCheckedChangeListener(this); timeRadioButton.setEnabled(false); LinearLayout.LayoutParams timeRadioButtonLayoutParams = new LinearLayout.LayoutParams(0, 0); timeRadioButtonLayoutParams.gravity = Gravity.LEFT; timeRadioButtonLayoutParams.width = 0; timeRadioButtonLayoutParams.height = LayoutParams.MATCH_PARENT; timeRadioButtonLayoutParams.weight = 0.2f; ((LinearLayout) timeRadioButton.getParent()).setLayoutParams(timeRadioButtonLayoutParams); expensesRadioButton = MDRadioButton.createDefaultRadioButton(compensationLinearLayout, TimeSheetMessages.getString("expense")); //$NON-NLS-1$ expensesRadioButton.setTag("EXPENSE"); //$NON-NLS-1$ expensesRadioButton.setOnCheckedChangeListener(this); expensesRadioButton.setEnabled(false); LinearLayout.LayoutParams expensesRadioButtonLayoutParams = new LinearLayout.LayoutParams(0, 0); expensesRadioButtonLayoutParams.gravity = Gravity.LEFT; expensesRadioButtonLayoutParams.width = 0; expensesRadioButtonLayoutParams.height = LayoutParams.MATCH_PARENT; expensesRadioButtonLayoutParams.weight = 0.2f; ((LinearLayout) expensesRadioButton.getParent()).setLayoutParams(expensesRadioButtonLayoutParams); compensationLinearLayout.setVisibility(View.GONE); contentLinearLayout.addView(compensationLinearLayout); // Vehicle Kilometers TextView vehicleKilometerTextView = CommonUtilForm.getTextView(context, TimeSheetMessages.getString("vehicleKilometers")); //$NON-NLS-1$ contentLinearLayout.addView(vehicleKilometerTextView); LinearLayout vehicleLinearLayout = new LinearLayout(context); vehicleLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams vehicleLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); vehicleLinearLayoutParams.gravity = Gravity.CENTER; vehicleLinearLayoutParams.width = LayoutParams.MATCH_PARENT; vehicleLinearLayoutParams.weight = 1; vehicleLinearLayout.setLayoutParams(vehicleLinearLayoutParams); // Vehicle Kilometers From vehicleFromEditText = MDEditText.createDefaultEditText(vehicleLinearLayout, TimeSheetMessages.getString("from"), InputType.TYPE_NUMBER_FLAG_DECIMAL, true); //$NON-NLS-1$ vehicleFromEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.NINE) }); vehicleFromEditText.addTextChangedListener(new VehicleMaskWatcher(vehicleFromEditText)); LinearLayout.LayoutParams vehicleFromLayoutParams = new LinearLayout.LayoutParams(0, 0); vehicleFromLayoutParams.gravity = Gravity.LEFT; vehicleFromLayoutParams.width = 0; vehicleFromLayoutParams.height = LayoutParams.MATCH_PARENT; vehicleFromLayoutParams.weight = 0.3f; vehicleFromEditText.getParentTextInputLayout().setLayoutParams(vehicleFromLayoutParams); // Vehicle Kilometers To vehicleToEditText = MDEditText.createDefaultEditText(vehicleLinearLayout, TimeSheetMessages.getString("to"), InputType.TYPE_NUMBER_FLAG_DECIMAL, true); //$NON-NLS-1$ vehicleToEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CommonConstants.MaxLength.NINE) }); vehicleToEditText.addTextChangedListener(new VehicleMaskWatcher(vehicleToEditText)); LinearLayout.LayoutParams vehicleToLayoutParams = new LinearLayout.LayoutParams(0, 0); vehicleToLayoutParams.gravity = Gravity.LEFT; vehicleToLayoutParams.width = 0; vehicleToLayoutParams.height = LayoutParams.MATCH_PARENT; vehicleToLayoutParams.weight = 0.3f; vehicleToEditText.getParentTextInputLayout().setLayoutParams(vehicleToLayoutParams); contentLinearLayout.addView(vehicleLinearLayout); relativeLayout.addView(contentLinearLayout); ScrollView scrollView = new ScrollView(context); scrollView.addView(relativeLayout); return scrollView; } private void loadExpense() { // resetExpense(); fillExpenseCombo(); // if (!calendar.getTimeSheets().isEmpty()) { expensesRadioButton.setChecked(true); Expenses expenses = calendar.getExpense(); log.info("DailyExpenses :" + expenses.getDailyExpenses() + "\nNoExpenses :" + expenses.getNoExpenses() + "\nExpensesDescription :" + expenses.getExpensesDescription() + "\nPikettExpenses :" + expenses.getPikettExpenses() + "\nVariousExpenses :" + expenses.getVariousExpenses() + "\nDeduction :" + expenses.getDeduction() + "\nDeductionDescription :" + expenses.getDeductionDescription() + "\nOperatingHoursOf :" + expenses.getOperatingHoursOf() + "\nOperatingHoursUpTo :" + expenses.getOperatingHoursUpTo() + "\nOperatingHoursTotal :" + expenses.getOperatingHoursTotal() + "\nCompensation :" + expenses.getCompensation()); log.info("is Initial " + expenses.isInitial()); if (expenses.isInitial()) { if (!calendar.getTimeSheets().isEmpty()) { Expenses lastExpens = app.dbutil.selectLastAvailableBToDate(calendar.getDate(), app.dbutil.getUser().getPersonalNumber()); if (lastExpens != null) { calendar.getExpense().setOperatingHoursOf(lastExpens.getOperatingHoursUpTo()); vehicleFromEditText.setText(lastExpens.getOperatingHoursUpTo()); } } } else { noExpensesCheckBox.setChecked(expenses.isNoExpenses()); dailyExpensesEditText.setText(expenses.getDailyExpenses()); pikettExpensesEditText.setText(expenses.getPikettExpenses()); // If SPNSTXT is empty: No 'Diverese Spesen' exist if (expenses.getExpensesDescription().equalsIgnoreCase("")) { //$NON-NLS-1$ reasonForVariousExpensesValue.setSelection(0); } // If SPNSTXT is part of the combobox stings: A value of the combobox was selected a no free text was used else if (app.enumUtil.variousExpensEnum.containsValue(expenses.getExpensesDescription())) { reasonForVariousExpensesValue.setSelectionByName(expenses.getExpensesDescription()); } // If SPNSTXT is not part of the combobox stings: A free text was entered and the combobox contains the entry "01 Diverses.." else { reasonForVariousExpensesValue.setSelectionById("01"); } variousExpensesEditText.setText(expenses.getVariousExpenses()); deductionEditText.setText(expenses.getDeductionDescription()); deductionAmountEditText.setText(expenses.getDeduction()); if (expenses.isCompensation()) expensesRadioButton.setChecked(true); else timeRadioButton.setChecked(true); if (expenses.getOperatingHoursTotal().length() > 0) { vehicleFromEditText.setText(""); //$NON-NLS-1$ vehicleToEditText.setText(""); //$NON-NLS-1$ } else { vehicleFromEditText.setText(expenses.getOperatingHoursOf()); vehicleToEditText.setText(expenses.getOperatingHoursUpTo()); } } // } else { // noExpensesCheckBox.setChecked(false); // } } private void resetExpense() { noExpensesCheckBox.setChecked(false); dailyExpensesEditText.getText().clear(); pikettExpensesEditText.getText().clear(); reasonForVariousExpensesValue.setSelection(0); freeTextEditText.getText().clear(); variousExpensesEditText.getText().clear(); deductionEditText.getText().clear(); deductionAmountEditText.getText().clear(); vehicleFromEditText.getText().clear(); vehicleToEditText.getText().clear(); } private View getVariousExpensesContent() { RelativeLayout mainFormView = new RelativeLayout(context); mainFormView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); variousExpenseListWidget = new ImageListWidget(context); variousExpenseListWidget.setDivider(new ColorDrawable(Color.LTGRAY)); variousExpenseListWidget.setDividerHeight(1); variousExpenseListWidget.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); emptyMessageView = new LinearLayout(context); emptyMessageView.setOrientation(LinearLayout.VERTICAL); emptyMessageView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); TextView textView = CommonUtilForm.getTextView(context, Messages.getString("noDocumentsRecorded")); //$NON-NLS-1$ LinearLayout.LayoutParams textViewParams = LayoutUtils.DEFAULT_WRAP_CONTENT_PARAMS(); textViewParams.gravity = Gravity.CENTER; textViewParams.topMargin = 20; textView.setLayoutParams(textViewParams); emptyMessageView.addView(textView); mainFormView.addView(variousExpenseListWidget); mainFormView.addView(emptyMessageView); return mainFormView; } private void loadVariousExpenses() { variousExpenseListWidget.clean(); if (calendar != null) { ArrayList items = new ArrayList(); variousExpenseList = app.dbutil.selectVariousExpenses(calendar.getDate(), app.dbutil.getUser().getPersonalNumber()); if(variousExpenseList.isEmpty()) { view.addView(emptyMessageView); emptyMessageView.setVisibility(View.VISIBLE); } else { emptyMessageView.setVisibility(View.GONE); } for (int i = 0; i < variousExpenseList.size(); i++) { final VariousExpenses variousExpenses = variousExpenseList.get(i); final ImageListWidgetItem item = new ImageListWidgetItem(); variousExpenses.setVariousExpensesFile(app.dbutil.selectVariousExpensesFile(calendar.getDate(), app.dbutil.getUser().getPersonalNumber(), variousExpenses.getVariousExpensesId())); DecimalFormat df = new DecimalFormat("###.00", new DecimalFormatSymbols(new Locale("en", "US"))); item.setDescription(app.enumUtil.variousExpensEnum.get(variousExpenses.getExpensesCode())); item.setImageBitmap(variousExpenses.getVariousExpensesFile().getSignPicBitmap()); if (!variousExpenses.getAmount().isEmpty()) { item.setType(df.format(Double.parseDouble(variousExpenses.getAmount()))); } items.add(item); variousExpenseListWidget.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, long id) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { VariousExpenses variousExpenses = variousExpenseList.get(position); return appman.getActiveApplication().leaveToForm(VariousExpensesImageNewEditForm.class, new VariousExpenseFileNewEditFormArguments(selectedDate, variousExpenses.getVariousExpensesFile().getSignPicBitmap(), variousExpenses)); } }, false); } }); } variousExpenseListWidget.addItems(items); } } @Override public void onFormReset() { super.onFormReset(); resetExpense(); } @Override protected void clearErrorMessages() { super.clearErrorMessages(); dailyExpensesEditText.clearError(); pikettExpensesEditText.clearError(); reasonForVariousExpensesValue.clearError(); freeTextEditText.clearError(); variousExpensesEditText.clearError(); deductionEditText.clearError(); deductionAmountEditText.clearError(); timeRadioButton.clearError(); expensesRadioButton.clearError(); vehicleFromEditText.clearError(); vehicleToEditText.clearError(); } private void fillExpenseCombo() { List miscExpenseValueList = new ArrayList(); Iterator itr = app.enumUtil.variousExpensEnum.iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); miscExpenseValueList.add(new CustomSpinnerItem((String) entry.getKey(), (String) entry.getValue())); } reasonForVariousExpensesValue.setContents(miscExpenseValueList); } private void setExpenseEnable(boolean enabled) { dailyExpensesEditText.setEnabled(enabled); pikettExpensesEditText.setEnabled(enabled); reasonForVariousExpensesValue.setEnabled(enabled); freeTextEditText.setEnabled(enabled); variousExpensesEditText.setEnabled(enabled); deductionEditText.setEnabled(enabled); deductionAmountEditText.setEnabled(enabled); // timeRadioButton.setEnabled(enabled); // expensesRadioButton.setEnabled(enabled); } public void saveExpense() { if(calendar.getStatus().isSENT()) { return; } if (!canSaveExpenseForDate(calendar.getDate(), DateTimeUtil.getToday().getTime())) { return; } Expenses expenses = calendar.getExpense(); expenses.setNoExpenses(noExpensesCheckBox.isChecked()); expenses.setDate(calendar.getDate()); expenses.setExpensesDate(calendar.getDate()); expenses.setDailyExpenses(getExpenseCurrencyValue(dailyExpensesEditText.getValue())); expenses.setPikettExpenses(getExpenseCurrencyValue(pikettExpensesEditText.getValue())); // Bug 1401 - hardcode ZKDMAEXPNS:SPNSKEY to value CHF expenses.setExpensesKey("CHF"); //$NON-NLS-1$ log.info(" VariousExpenses " + variousExpensesEditText.getValue()); expenses.setVariousExpenses(getExpenseCurrencyValue(variousExpensesEditText.getValue())); String spnstxt = ""; //$NON-NLS-1$ // Default string 00 "Bitte w�hlen.." must not be stored if (!reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ // Only entry 01 "Diverses.." allows to enter an additional // text, otherwise the Combobox string is stored if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase("01")) //$NON-NLS-1$ spnstxt = freeTextEditText.getText().toString(); else spnstxt = reasonForVariousExpensesValue.getSelectedName(); } expenses.setExpensesDescription(spnstxt); expenses.setDeductionDescription(deductionEditText.getText().toString()); expenses.setDeduction(getExpenseCurrencyValue(deductionAmountEditText.getValue())); expenses.setOperatingHoursOf(vehicleFromEditText.getText().toString()); expenses.setOperatingHoursUpTo(vehicleToEditText.getText().toString()); log.info("DailyExpenses " + expenses.getDailyExpenses() + " PikettExpenses " + expenses.getPikettExpenses() + " VariousExpenses " + expenses.getVariousExpenses() + " Deduction " + expenses.getDeduction() + " OperatingHoursOf " + expenses.getOperatingHoursOf() + " OperatingHoursUpTo " + expenses.getOperatingHoursUpTo()); expenses.setExpenseCompensation(); log.info("Compensation " + expenses.getCompensation()); boolean successfull = app.dbutil.saveCALENDAR(calendar); if (!successfull) { app.showMessageBox(TimeSheetMessages.getString("expenseSheetCouldNotBeSaved"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ //$NON-NLS-2$ } // Reload data from database reloadCalendar(); } static boolean canSaveExpenseForDate(Date selectedDate, Date today) { if (selectedDate == null || today == null) { return false; } return !DateTimeUtil.getDate(selectedDate).getTime().after(DateTimeUtil.getDate(today).getTime()); } static String getExpenseCurrencyValue(String value) { if (StringUtil.isEmpty(value)) { return ""; //$NON-NLS-1$ } char decimalSeparator = value.indexOf(',') >= 0 && value.indexOf('.') < 0 ? ',' : '.'; String result = removeInvalidCurrencyCharacters(value, decimalSeparator); return containsDigit(result) ? result : ""; //$NON-NLS-1$ } private static String removeInvalidCurrencyCharacters(String value, char decimalSeparator) { StringBuilder result = new StringBuilder(); boolean hasDecimalSeparator = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isDigit(c)) { result.append(c); } else if (c == decimalSeparator && !hasDecimalSeparator) { result.append(c); hasDecimalSeparator = true; } } return result.toString(); } private static boolean containsDigit(String value) { for (int i = 0; i < value.length(); i++) { if (Character.isDigit(value.charAt(i))) { return true; } } return false; } private boolean isEditedExpense() { boolean result = false; Expenses expenses = calendar.getExpense(); if (noExpensesCheckBox.isChecked() != expenses.isNoExpenses()) { result = true; } if (!vehicleFromEditText.getText().toString().equalsIgnoreCase(expenses.getOperatingHoursOf())) { result = true; } if (!vehicleToEditText.getText().toString().equalsIgnoreCase(expenses.getOperatingHoursUpTo())) { result = true; } if (!noExpensesCheckBox.isChecked()) { if (!dailyExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getDailyExpenses())) { result = true; } if (!pikettExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getPikettExpenses())) { result = true; } // 00: Bitte w�hlen.. if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ if (!variousExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getVariousExpenses())) { result = true; } } // 01: Diverses.. else if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase("01")) { //$NON-NLS-1$ if (!freeTextEditText.getText().toString().equals(expenses.getExpensesDescription())) { result = true; } } // others else { if (!reasonForVariousExpensesValue.getSelectedName().equalsIgnoreCase(expenses.getExpensesDescription())) { result = true; } } if (!variousExpensesEditText.getText().toString().equalsIgnoreCase(expenses.getVariousExpenses())) { result = true; } if (!deductionEditText.getText().toString().equalsIgnoreCase(expenses.getDeductionDescription())) { result = true; } if (!deductionAmountEditText.getText().toString().equalsIgnoreCase(expenses.getDeduction())) { result = true; } } return result; } private void contextMenuActionState(boolean state) { deleteAction.setVisible(state); deleteAction.setValidate(state); addAction.setVisible(state); addAction.setValidate(state); } public static class TimeSheetDetailFormArgument { private int tabSelected; private Date selectedDate; private boolean isServiceApp; public int getTabSelected() { return tabSelected; } protected TimeSheetDetailFormArgument() { } public TimeSheetDetailFormArgument(Date selectedDate, int tabSelect, boolean isServiceApp) { this.tabSelected = tabSelect; this.selectedDate = selectedDate; this.isServiceApp = isServiceApp; } public void setTabSelected(int tabSelected) { this.tabSelected = tabSelected; } public Date getDate() { return this.selectedDate; } public boolean isServiceApp() { return this.isServiceApp; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { timeRadioButton.clearError(); if ("TIME".equals(buttonView.getTag().toString()) && timeRadioButton.isChecked()) { //$NON-NLS-1$ expensesRadioButton.setChecked(false); } if ("EXPENSE".equals(buttonView.getTag().toString()) && expensesRadioButton.isChecked()) { //$NON-NLS-1$ timeRadioButton.setChecked(false); } } @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if ("MISC_EXPENSE".equals(parent.getTag())) { //$NON-NLS-1$ freeTextEditText.setEnabled(false); freeTextEditText.setText(""); variousExpensesEditText.setText(""); if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase(CommonConstants.PLEASE_SELECT)) { //$NON-NLS-1$ // Code 00 ("Please Select"): no selection was made so far -> disable text for "Diverse Spesen" and value field } else if (reasonForVariousExpensesValue.getSelectedId().equalsIgnoreCase("01")) { //$NON-NLS-1$ // Code 01 ("Diverse.."): -> enable text for "Diverse Spesen" and value field freeTextEditText.setEnabled(true); freeTextEditText.setText(calendar.getExpense().getExpensesDescription()); variousExpensesEditText.setText(calendar.getExpense().getVariousExpenses()); } else { // All other codes: -> disable text but enable value filed freeTextEditText.setText(""); //$NON-NLS-1$ variousExpensesEditText.setText(calendar.getExpense().getVariousExpenses()); } } else { validateExpense(); } } @Override public void onNothingSelected(AdapterView paramAdapterView) { // Auto-generated method stub } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/forms/TimeSheetForm.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.InternalWorkType; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.forms.CommonUtilForm; import ch.mfiles.kaba.kolibri.common.forms.adapters.CustomSpinnerItem; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDEditText; import ch.mfiles.kaba.kolibri.common.forms.widgets.MDSpinner; import ch.mfiles.kaba.kolibri.common.forms.widgets.TimeEditText; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.LayoutUtils; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.StringUtil; import ch.mfiles.kaba.kolibri.common.util.TimeUtil; import ch.mfiles.kaba.kolibri.timesheet.TimeSheetMessages; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.ui.Image; import ch.mfiles.kolibri.ui.LayoutInflater; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.DateUtils; import ch.mfiles.kolibri.util.ProgressMonitor; public class TimeSheetForm extends SuperForm implements OnItemSelectedListener { private static Log log = LogFactory.getLog(TimeSheetForm.class); private CalendarTimeSheet mCalendar; private TimeUtil timeUtil; private TimeSheet time; private RelativeLayout mainView; private MDSpinner internalWorkTypeValue; private TimeEditText fromText; private TimeEditText toText; private AppCompatCheckBox onCallCheckBox; private Button deleteButton; private boolean isEdit = false; public void onFormCall(Object argument) { if (argument instanceof TimeSheetFormArgument) { mCalendar = ((TimeSheetFormArgument) argument).getCALENDAR(); time = ((TimeSheetFormArgument) argument).getTime(); } else { log.error("Wrong form argument found: " + argument); //$NON-NLS-1$ throw new ApplicationException(TimeSheetMessages.getString("wrongFormArgument") + app.getCurrentForm()); //$NON-NLS-1$ } } @Override public View onFormLoad(final Context context, LayoutInflater inflater) { super.onFormLoad(context, inflater); timeUtil = new TimeUtil(app, app.dbutil, this); // customize Toolbar Toolbar toolbar = getToolbar(); // set navigation image and listener Image backImage = app.imagesUtil.getImage(ImagesUtil.Images.BACK_WHITE, CommonConstants.Images.IMAGE_DPI); toolbar.setNavigationIcon(getBitmanDrawable(backImage)); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { hideSoftInputFromWindow(); return onBackPressed(); } }, false); } }); mainView = new RelativeLayout(context); mainView.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_PARAMS()); LinearLayout contentLinearLayout = new LinearLayout(context); contentLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); contentLinearLayout.setOrientation(LinearLayout.VERTICAL); contentLinearLayout.setPadding(16, 16, 16, 16); LinearLayout dateLinearLayout = new LinearLayout(context); dateLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams leftIconLinearLayoutParams = new LinearLayout.LayoutParams(0, 0); leftIconLinearLayoutParams.gravity = Gravity.CENTER; leftIconLinearLayoutParams.width = LayoutParams.MATCH_PARENT; leftIconLinearLayoutParams.weight = 1; dateLinearLayout.setLayoutParams(leftIconLinearLayoutParams); fromText = TimeEditText.createDefaultEditText(dateLinearLayout, TimeSheetMessages.getString("from"), true); //$NON-NLS-1$ fromText.setTag("VON"); //$NON-NLS-1$ LinearLayout.LayoutParams fromInputLayoutParams = new LinearLayout.LayoutParams(0, 0); fromInputLayoutParams.gravity = Gravity.CENTER; fromInputLayoutParams.width = 0; fromInputLayoutParams.height = LayoutParams.MATCH_PARENT; fromInputLayoutParams.weight = 0.5f; fromText.getParentTextInputLayout().setLayoutParams(fromInputLayoutParams); toText = TimeEditText.createDefaultEditText(dateLinearLayout, TimeSheetMessages.getString("to"), true); //$NON-NLS-1$ toText.setTag("BIS"); //$NON-NLS-1$ LinearLayout.LayoutParams toInputLayoutParams = new LinearLayout.LayoutParams(0, 0); toInputLayoutParams.gravity = Gravity.CENTER; toInputLayoutParams.width = 0; toInputLayoutParams.height = LayoutParams.MATCH_PARENT; toInputLayoutParams.weight = 0.5f; toText.getParentTextInputLayout().setLayoutParams(toInputLayoutParams); contentLinearLayout.addView(dateLinearLayout); LinearLayout workTypeLinearLayout = new LinearLayout(context); workTypeLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); workTypeLinearLayout.setOrientation(LinearLayout.VERTICAL); // work type internalWorkTypeValue = MDSpinner.createDefaultSpinner(workTypeLinearLayout, TimeSheetMessages.getString("internalWorkType"), true); //$NON-NLS-1$ internalWorkTypeValue.setTag("ARBEITSART"); //$NON-NLS-1$ internalWorkTypeValue.setOnItemSelectedListener(this); contentLinearLayout.addView(workTypeLinearLayout); onCallCheckBox = CommonUtilForm.getCheckBox(context, TimeSheetMessages.getString("onCall")); //$NON-NLS-1$ contentLinearLayout.addView(onCallCheckBox); LinearLayout deleteLinearLayout = new LinearLayout(context); deleteLinearLayout.setLayoutParams(LayoutUtils.DEFAULT_MATCH_PARENT_AND_WRAP_CONTENT()); deleteLinearLayout.setOrientation(LinearLayout.HORIZONTAL); deleteLinearLayout.setGravity(Gravity.CENTER); deleteButton = new Button(context); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (time == null) { fromText.getText().clear(); toText.getText().clear(); fromText.clearError(); toText.clearError(); internalWorkTypeValue.clearError(); internalWorkTypeValue.setSelection(0); onCallCheckBox.setChecked(false); } else { deleteTime(); } } }); deleteLinearLayout.addView(deleteButton); contentLinearLayout.addView(deleteLinearLayout); relativeLayout.addView(contentLinearLayout); view.addView(relativeLayout); view.addView(mainView); return view; } /** * This event is received every time the form is shown. This happens if the * form is called by the framework, another form or if reactivated from the * application's form stack. <p/> * * The application developer has to set all member variables (reset the * state of the form) at this point because the framework reuses the forms * (every form is instantiated exactly once during the lifetime of an * application) *

* * @return Returns an {@link ApplicationEvent} that is used by the framework * to navigate to other forms or exit the application. *

*/ @Override public ApplicationEvent onFormShow() { super.onFormShow(); setFormTitle(DateTimeUtil.showDayOfWeek(mCalendar.getDate()) + ", " + DateTimeUtil.showDate(mCalendar.getDate())); //$NON-NLS-1$ if (mainView.getChildCount() > 0) { mainView.removeAllViewsInLayout(); mainView.invalidate(); } setFormTitle(DateTimeUtil.showDate(mCalendar.getDate())); loadData(); fromText.setEnabled(!mCalendar.getStatus().isSENT()); toText.setEnabled(!mCalendar.getStatus().isSENT()); internalWorkTypeValue.setEnabled(!mCalendar.getStatus().isSENT()); onCallCheckBox.setEnabled(!mCalendar.getStatus().isSENT()); deleteButton.setEnabled(!mCalendar.getStatus().isSENT()); mCalendar.getTimeSheets(); setSendButtonEnabled(true); if (time != null && time.getStopTime().equals(DateUtils.getInitialDateTime())) { // time capture started fromText.setRequired(false); fromText.setEnabled(false); toText.setEnabled(false); toText.setRequired(false); } return null; } public void loadData() { List internalWorkTypeValueList = new ArrayList(); List internalWorkTypeList = app.dbutil.selectInternalWorkTypeList(); for (InternalWorkType internalWorkType : internalWorkTypeList) { internalWorkTypeValueList.add(new CustomSpinnerItem((String) internalWorkType.getWorkTypeCode(), (String) internalWorkType.getText())); } fromText.clearError(); toText.clearError(); internalWorkTypeValue.setContents(internalWorkTypeValueList); if (time == null) { isEdit = false; fromText.setText(""); //$NON-NLS-1$ toText.setText(""); //$NON-NLS-1$ fromText.getText().clear(); toText.getText().clear(); internalWorkTypeValue.setSelection(0); deleteButton.setText(TimeSheetMessages.getString("clear")); //$NON-NLS-1$ onCallCheckBox.setChecked(false); } else { isEdit = true; if (!time.getStartTime().equals(DateUtils.getInitialDateTime())) { fromText.setText(DateTimeUtil.showTimeGMT(time.getStartTime())); fromText.clearFocus(); } if (!time.getStopTime().equals(DateUtils.getInitialDateTime())) { toText.setText(DateTimeUtil.showTimeGMT(time.getStopTime())); toText.clearFocus(); } if (!time.getWorkTypeCode().isEmpty()) { internalWorkTypeValue.setSelectionById(time.getWorkTypeCode()); } onCallCheckBox.setChecked(time.isCallFlag()); deleteButton.setText(TimeSheetMessages.getString("delete")); //$NON-NLS-1$ } } @Override public ApplicationEvent onBackPressed() { // not edited if (time == null && StringUtil.isEmpty(fromText.getText().toString()) && StringUtil.isEmpty(toText.getText().toString())) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } if (time != null && fromText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStartTime())) && toText.getText().toString().equalsIgnoreCase(DateTimeUtil.showTimeGMT(time.getStopTime())) && internalWorkTypeValue.getSelectedId().equalsIgnoreCase(time.getWorkTypeCode()) && onCallCheckBox.isChecked() == time.isCallFlag()) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } if(saveTime()) { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } }, false); } return null; } private boolean saveTime(){ boolean result = true; if (fromText.getText().length() == 0) { showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } Date startTime = DateTimeUtil.parseDateFromHHmm(fromText.getText().toString(), mCalendar.getDate()); Date stopTime = DateTimeUtil.parseDateFromHHmm(toText.getText().toString(), mCalendar.getDate()); if(time == null && fromText.getText().toString().equalsIgnoreCase(toText.getText().toString())) { // time not captured and same minutes. showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if(startTime == null) { showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; return result; } if (startTime.after(new Date())) { app.showWarningMessageBox(TimeSheetMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if (time != null && time.getStopTime().equals(DateUtils.getInitialDateTime())) { // time capture started stopTime = DateUtils.getInitialDateTime(); } else { if (toText.getText().length() == 0) { showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if(stopTime == null) { showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; return result; } if (startTime.after(stopTime)) { showError(fromText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } if (stopTime.after(new Date())) { app.showWarningMessageBox(TimeSheetMessages.getString("enteredValueIsInTheFuturePleaseEnterValidTime")); //$NON-NLS-1$ showError(toText, TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ result = false; } } if(!result) { return false; } else { TimeSheet timeSheet = null; if (isEdit) { timeSheet = time; timeSheet.setStartTime(startTime); timeSheet.setStopTime(stopTime); timeSheet.setWorkTypeCode(internalWorkTypeValue.getSelectedId()); timeSheet.setCallFlag(onCallCheckBox.isChecked()); } else { timeSheet = new TimeSheet(app.dbutil.getUser().getPersonalNumber()); timeSheet.setIdx(999); timeSheet.setDate(new Date()); timeSheet.setStartTime(startTime); timeSheet.setStopTime(stopTime); timeSheet.setWorkTypeCode(internalWorkTypeValue.getSelectedId()); timeSheet.setCallFlag(onCallCheckBox.isChecked()); mCalendar.getTimeSheets().add(timeSheet); } log.info("save WorkTypeCode " + timeSheet.getWorkTypeCode()); saveTimeSheet(timeSheet); } return result; } private void showError(final MDEditText textView, final String text) { new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); textView.setError(text); } }; } /** * Handles on click event for send. * * @return */ @Override public ApplicationEvent onSendPressed() { setSendButtonEnabled(false); if (saveTime() && mCalendar.isValid()) { new AsyncTask(this) { private CalendarTimeSheet sendCalendar; private MDEditText errorText = null; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { if(mCalendar.isValid()) { // Reload calendar object from database sendCalendar = app.sendTimeSheet(mCalendar); } return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); if (errorText != null) { errorText.setError(TimeSheetMessages.getString("pleaseEnterValidTime")); //$NON-NLS-1$ return; } setSendButtonEnabled(true); if (sendCalendar !=null && sendCalendar.getStatus().isSENT()) { app.showMessage(TimeSheetMessages.getString("timesheetSent")); //$NON-NLS-1$ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } }, false); } } }; } else { String errorMessage = TimeSheetMessages.getString("cannotTransmissonToServerThereIsUnsavedPersonalTimeData"); app.showWarningMessageBox(errorMessage, new RunOnUIThread() { @Override public void runOnUIThread() { setSendButtonEnabled(true); } }); } return null; } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { if (null == time) { // create new time } else { if ("ARBEITSART".equals(parent.getTag())) { //$NON-NLS-1$ if (position != 0) internalWorkTypeValue.clearError(); } } } @Override public void onNothingSelected(AdapterView parent) { // Auto-generated method stub } private void deleteTime() { if (time == null) { return; } new AsyncTask(this) { @Override protected ApplicationEvent runOnAMThread(ApplicationManager paramApplicationManager, DBSession paramDBSession, TransactionHandler paramTransactionHandler, Registry paramRegistry, ProgressMonitor paramProgressMonitor) { if (app.showMessageBox(TimeSheetMessages.getString("areYouSureThatYouWantToDeleteRecord"), TimeSheetMessages.getString("warning") //$NON-NLS-1$ //$NON-NLS-2$ , Application.MBOX_BUTTON_YES_NO, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_NO) { return null; } // number the timesheet entries consecutively in chronological // order TreeSet timeSheets = new TreeSet(mCalendar.getTimeSheets()); Iterator itr = timeSheets.iterator(); int idx = 0; while (itr.hasNext()) { TimeSheet temp = itr.next(); if (temp.getPersonalNumber() == time.getPersonalNumber() && temp.getStartTime().compareTo(time.getStartTime()) == 0) { itr.remove(); } else { temp.setIdx(idx); idx++; } } // Save the list of timesheet entries to the current calendar mCalendar.setTimeSheets(timeSheets); // Save hole CALENDAR Object to the database app.dbutil.saveCALENDAR(mCalendar); return null; } @Override protected void runOnUIThread() { appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(mCalendar.getDate(), 0, isServiceApp)); } }, false); } }; } /** * Saves all records in the table control to the ZKDMOBREP object and to the database. * ZKDMATIME.IDX attributes will be numbered consecutively according the VON attribute. * @param selectedRecord The currently selected record will be selected again (in the table control). * @return true if the time sheet was saved to the database without problem. false if the time sheet was not saved. */ private boolean saveTimeSheet(TimeSheet selectedRecord) { boolean success = true; TreeSet set = new TreeSet(); Iterator timeSetItr = mCalendar.getTimeSheets().iterator(); while (timeSetItr.hasNext()) { TimeSheet temp = (TimeSheet) timeSetItr.next(); if (!set.add(temp)) { String errorMessage = MessageFormat.format(TimeSheetMessages.getString("startTimeAlreadyExists"), new Object[] { //$NON-NLS-1$ DateTimeUtil.showDateTime(temp.getStartTime()) }); ch.mfiles.kaba.kolibri.common.forms.SuperForm.showWarningMessageBox(app, errorMessage); // reload CALENDAR from db mCalendar = app.dbutil.loadCalendar(mCalendar.getDate(), mCalendar.getPersonalNumber()); success = false; break; } } if (success) { // number the timesheet entries consecutively in chronological order Iterator itr = set.iterator(); int idx = 0; while (itr.hasNext()) { TimeSheet temp = (TimeSheet) itr.next(); temp.setIdx(idx); // Backup the new IDX of the currently edited record if (temp.getStartTime().compareTo(selectedRecord.getStartTime()) == 0) idx++; } // check if there are no overlapping entries int selOverlappingRowIdx = timeUtil.checkWorkTimesheetOverlapping(set); if (selOverlappingRowIdx > -1) { // reload CALENDAR from db mCalendar = app.dbutil.loadCalendar(mCalendar.getDate(), mCalendar.getPersonalNumber()); success = false; } else { // Save the list of timesheet entries to the current calendar mCalendar.setTimeSheets(set); // Save hole CALENDAR Object to the database app.dbutil.saveCALENDAR(mCalendar); success = true; } } return success; } public static class TimeSheetFormArgument { private CalendarTimeSheet calendar; private TimeSheet timeSheet; protected TimeSheetFormArgument() { } public TimeSheetFormArgument(CalendarTimeSheet calendar, TimeSheet timeSheet) { this.calendar = calendar; this.timeSheet = timeSheet; } public CalendarTimeSheet getCALENDAR() { return this.calendar; } public TimeSheet getTime() { return this.timeSheet; } } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/TimeSheetApplication.java:   package ch.mfiles.kaba.kolibri.timesheet; import java.io.File; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.mfiles.kaba.kolibri.common.Messages; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.types.CalendarStatus; import ch.mfiles.kaba.kolibri.common.net.CommSetupHelper; import ch.mfiles.kaba.kolibri.common.net.MasterDataDBHandler; import ch.mfiles.kaba.kolibri.common.net.RemoteTransactionHandler; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DatabaseUtil; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.EnumUtil; import ch.mfiles.kaba.kolibri.common.util.ImagesUtil; import ch.mfiles.kaba.kolibri.common.util.MessageUtil; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil; import ch.mfiles.kaba.kolibri.common.util.RunOnUIThread; import ch.mfiles.kaba.kolibri.common.util.RegistryUtil.RegistryProperties; import ch.mfiles.kaba.kolibri.timesheet.forms.CalendarOverviewForm; import ch.mfiles.kaba.kolibri.timesheet.forms.TimeSheetDetailForm; import ch.mfiles.kolibri.Application; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationException; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.Form; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.Runtime; import ch.mfiles.kolibri.db.ApplicationDescriptor; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.util.AsyncTask; import ch.mfiles.kolibri.util.ProgressMonitor; /** * Main application class. */ public class TimeSheetApplication extends Application { private Log log = LogFactory.getLog(TimeSheetApplication.class); public DatabaseUtil dbutil; public ImagesUtil imagesUtil; public EnumUtil enumUtil; public MessageUtil messageUtil; private static final int RETENTION_PERIOD_TIMESHEET = 3; // Month /** * Called by the framework each time the application is started. * * @param obj An (optional) object supplied by the application that started this application. * @return */ @Override public ApplicationEvent onApplicationStart(Object obj) { boolean isServiceApp = false; if (obj !=null && Boolean.valueOf(obj.toString())) { isServiceApp = true; } // attach master data db MasterDataDBHandler mdHandler = MasterDataDBHandler.getInstance(); mdHandler.attach(); // create a DbHelper dbutil = DatabaseUtil.getInstance(); imagesUtil = ImagesUtil.getInstance(this); enumUtil = EnumUtil.getInstance(this.dbutil); messageUtil = MessageUtil.getInstance(); Calendar retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.DAY_OF_MONTH, -30); List datesOlderThanOneMonth = dbutil.selectCalendarDatesOlderThan(retentionPeriodEnd.getTime()); Iterator datesOlderThanOneMonthIter = datesOlderThanOneMonth.iterator(); while (datesOlderThanOneMonthIter.hasNext()) { Date date = datesOlderThanOneMonthIter.next(); // Make sure that date is a date value and not a time value! if(!DateTimeUtil.isDate(date)) { showWarningMessageBox(Messages.getString("loadCALENDARObjectWithDatetime") + date + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } CalendarTimeSheet calendar = dbutil.loadCalendar(date, dbutil.getUser().getPersonalNumber()); if(!calendar.getStatus().isSENT()) { Object[] arguments = new Object[] { DateTimeUtil.showDate(date) }; String errorMessage = MessageFormat.format(TimeSheetMessages.getString("timeSheetNotSentOlderThanThirTyDays"), arguments); //$NON-NLS-1$ if (showMessageBox(errorMessage, TimeSheetMessages.getString("personalTimeAndExpensesNotSent"), Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) == Application.MBOX_RESULT_OK) { //$NON-NLS-1$ //go to timesheet return appman.getActiveApplication().leaveToForm(TimeSheetDetailForm.class, new TimeSheetDetailForm.TimeSheetDetailFormArgument(calendar.getDate(), 0, isServiceApp)); } } } retentionPeriodEnd = DateTimeUtil.getNow(); retentionPeriodEnd.add(Calendar.MONTH, -RETENTION_PERIOD_TIMESHEET); List dates = dbutil.selectCalendarDatesOlderThan(retentionPeriodEnd.getTime()); int cnt = dates.size(); Iterator itr = dates.iterator(); while (itr.hasNext()) { inform(TimeSheetMessages.getString("removingOldTimesheets") + cnt-- + "/" + dates.size()); //$NON-NLS-1$ //$NON-NLS-2$ Date date = itr.next(); CalendarTimeSheet calendar = dbutil.loadCalendar(date, dbutil.getUser().getPersonalNumber()); if (dbutil.deleteCalendarTimeSheet(calendar)) log.info("Calendar " + date + " is older than " + RETENTION_PERIOD_TIMESHEET + " months -> deleted"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else log.error("CALENDAR " + date + " can not be deleted"); //$NON-NLS-1$ //$NON-NLS-2$ } setDefaultScreenOrientation(Form.ScreenOrientation.PORTRAIT); // Load the CALENDAR to display. This could be the oldest (if older than 3 days) not yet transmitted or the current day. Date date = dbutil.selectOldestUnsavedCalendarDate(dbutil.getUser().getPersonalNumber()); CalendarTimeSheet calendar = dbutil.loadCalendar(date, dbutil.getUser().getPersonalNumber()); return leaveToForm(CalendarOverviewForm.class, new CalendarOverviewForm.CalendarOverviewFormArgument(calendar, isServiceApp)); } /** * Called by the framework if the application is about to be terminated. * * @return Return false if the application must not be * terminated. */ @Override public boolean onApplicationExit(boolean forced) { return true; } /** * Called by the framework before this application is removed from the * frameworks database. May be used to save important data. *

* This method might throw an ApplicationException to prevent * the removal in exceptional cases. */ @Override public void onApplicationRemoval() { deleteExtractedFiles(); // setup layout according to communication environment CommSetupHelper.setEnvironmentLayout(); } /** * Called by the framework for the new application to be deployed. May be * used to perform additional application specific upgrade preparations. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param droppedTables */ @Override public void onPreApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set droppedTables) { // do nothings } /** * Called by the framework after the application has been upgraded but * before the upgrade is commited to the database. Additional upgrade * postprocessing might be implemented here. *

* This method might throw an ApplicationException to prevent * the upgrade from happening this time. Use only in exceptional cases. * * @param oldApplicationDescriptor * @param newApplicationDescriptor * @param recreatedTables */ @Override public void onPostApplicationUpgrade(ApplicationDescriptor oldApplicationDescriptor, ApplicationDescriptor newApplicationDescriptor, Set recreatedTables) { ApplicationManager appman = (ApplicationManager) Runtime.getApplicationManager(); Registry reg = appman.getRegistry(CommonConstants.Application.SERVICE_APP); if (reg != null) { reg.setProperty(RegistryUtil.RegistryProperties.MASTER_DATA_REFRESH_DATE_PROPERTY_NAME, RegistryProperties.DEFAULT_MASTER_DATA_REFRESH_DATE); } } public void deleteExtractedFiles() { deleteExtractedDirAndFiles(new File(Runtime.getInstallationFolder() + File.separator + CommonConstants.Application.COMMON + File.separator)); } public boolean deleteExtractedDirAndFiles(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteExtractedDirAndFiles(files[i]); } else { files[i].delete(); } } } return (path.delete()); } public CalendarTimeSheet sendTimeSheet(CalendarTimeSheet calendar) { if (showMessageBox(TimeSheetMessages.getString("timesheetOrExpensesheetCannotBeEditedAfterTransmissonToServer"), TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_OK_CANCEL, Application.MBOX_ICON_WARNING) != Application.MBOX_RESULT_OK) { return calendar; } db.startTransaction(); try { if (!calendar.isValid()) { Object[] arguments = new Object[] { TimeSheetMessages.getString("timeSheet"), DateTimeUtil.tableDate(calendar.getDate()), TimeSheetMessages.getString("expenseSheet") }; //$NON-NLS-1$ //$NON-NLS-2$ String errorMessage = MessageFormat.format(TimeSheetMessages.getString("noPresentCannotBeSent"), arguments); //$NON-NLS-1$ showMessageBox(errorMessage, TimeSheetMessages.getString("warning"), Application.MBOX_BUTTON_OK, Application.MBOX_ICON_WARNING); //$NON-NLS-1$ return calendar; } else { log.info("sendTimeSheet -> Compensation " + calendar.getExpense().getCompensation()); calendar.setStatus(CalendarStatus.SENT); calendar.getExpense().setExpenseCompensation(); dbutil.saveCALENDAR(calendar); RemoteTransactionHandler transactionHandler = new RemoteTransactionHandler(); transactionHandler.runSaveTimeSheet(dbutil.getUser().getPersonalNumber(), calendar); if (db.isTransactionPending()) { db.rollback(); } // Reload calendar object from database and return. return dbutil.loadCalendar(calendar.getDate(), dbutil.getUser().getPersonalNumber()); } } // finally rollback if dbutil transaction is still pending finally { if (db.isTransactionPending()) { db.rollback(); } } } public void showWarningMessageBox(final String warningMessage){ appman.inject(new KolibriRunnable() { @Override public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { showMessageBox(warningMessage, TimeSheetMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } }, false); } public void showWarningMessageBox(final String warningMessage, final RunOnUIThread runOnUIThread){ new AsyncTask(getCurrentForm()) { private CalendarTimeSheet sendCalendar; @Override protected ApplicationEvent runOnAMThread(ApplicationManager appman, DBSession db, TransactionHandler tr, Registry reg, ProgressMonitor monitor) { showMessageBox(warningMessage, TimeSheetMessages.getString("warning"/*warning*/), Application.MBOX_BUTTON_OK, //$NON-NLS-1$ Application.MBOX_ICON_WARNING); return null; } @Override protected void runOnUIThread() { super.runOnUIThread(); if(runOnUIThread!=null) runOnUIThread.runOnUIThread(); } }; } public void showMessage(String message) { messageUtil.showMessage(message); } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarDateRange.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarDateRange { private static final int MONTH_EDGE_BUFFER_DAYS = 5; private static final int LOAD_MORE_DAYS = 31; public static Range initialMonth(Date focusDate) { Calendar start = firstDayOfMonth(focusDate); start.add(Calendar.DATE, -MONTH_EDGE_BUFFER_DAYS); Calendar end = firstDayOfMonth(focusDate); end.add(Calendar.MONTH, 1); end.add(Calendar.DATE, MONTH_EDGE_BUFFER_DAYS - 1); return new Range(start.getTime(), end.getTime()); } public static Range nextAfter(Date currentLastDate) { Calendar start = startOfDay(currentLastDate); start.add(Calendar.DATE, 1); Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, LOAD_MORE_DAYS - 1); return new Range(start.getTime(), end.getTime()); } public static Range previousBefore(Date currentFirstDate) { Calendar end = startOfDay(currentFirstDate); end.add(Calendar.DATE, -1); Calendar start = (Calendar) end.clone(); start.add(Calendar.DATE, -(LOAD_MORE_DAYS - 1)); return new Range(start.getTime(), end.getTime()); } private static Calendar firstDayOfMonth(Date date) { Calendar calendar = startOfDay(date); calendar.set(Calendar.DAY_OF_MONTH, 1); return calendar; } private static Calendar startOfDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } public static class Range { private final Date startDate; private final Date endDate; private Range(Date startDate, Date endDate) { this.startDate = new Date(startDate.getTime()); this.endDate = new Date(endDate.getTime()); } public Date getStartDate() { return new Date(startDate.getTime()); } public Date getEndDate() { return new Date(endDate.getTime()); } } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarDateSelection.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarDateSelection { public static boolean isSameCalendarDay(Date first, Date second) { if (first == null || second == null) { return false; } Calendar firstCalendar = Calendar.getInstance(); firstCalendar.setTime(first); Calendar secondCalendar = Calendar.getInstance(); secondCalendar.setTime(second); return firstCalendar.get(Calendar.YEAR) == secondCalendar.get(Calendar.YEAR) && firstCalendar.get(Calendar.DAY_OF_YEAR) == secondCalendar.get(Calendar.DAY_OF_YEAR); } public static Date getPickerDate(Date visibleDate, Date selectedDate) { if (visibleDate == null) { return selectedDate == null ? new Date() : new Date(selectedDate.getTime()); } if (selectedDate == null || !isSameCalendarMonth(visibleDate, selectedDate)) { return new Date(visibleDate.getTime()); } return new Date(selectedDate.getTime()); } public static Date getVisibleDate(Date calendarDate, Date selectedDate) { if (selectedDate != null) { return new Date(selectedDate.getTime()); } if (calendarDate != null) { return new Date(calendarDate.getTime()); } return new Date(); } private static boolean isSameCalendarMonth(Date first, Date second) { Calendar firstCalendar = Calendar.getInstance(); firstCalendar.setTime(first); Calendar secondCalendar = Calendar.getInstance(); secondCalendar.setTime(second); return firstCalendar.get(Calendar.YEAR) == secondCalendar.get(Calendar.YEAR) && firstCalendar.get(Calendar.MONTH) == secondCalendar.get(Calendar.MONTH); } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarListWindow.java:   package ch.mfiles.kaba.kolibri.timesheet.util; public class CalendarListWindow { public static int getTrimCount(int itemCount, int maxItems) { if (maxItems <= 0 || itemCount <= maxItems) { return 0; } return itemCount - maxItems; } public static int getPositionAfterStartTrim(int position, int removedFromStart) { int adjustedPosition = position - removedFromStart; if (adjustedPosition < 0) { return 0; } return adjustedPosition; } public static int getToolbarTitlePosition(int firstVisiblePosition, int itemCount) { if (itemCount <= 0) { return 0; } if (firstVisiblePosition < 0) { return 0; } if (firstVisiblePosition >= itemCount) { return itemCount - 1; } return firstVisiblePosition; } private CalendarListWindow() { } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarMonthHeaderPolicy.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarMonthHeaderPolicy { public static boolean shouldShowHeader(Date currentDate, Date previousDate, int position) { if (currentDate == null) { return false; } if (position <= 0 || previousDate == null) { return true; } Calendar current = Calendar.getInstance(); current.setTime(currentDate); Calendar previous = Calendar.getInstance(); previous.setTime(previousDate); return current.get(Calendar.MONTH) != previous.get(Calendar.MONTH) || current.get(Calendar.YEAR) != previous.get(Calendar.YEAR); } private CalendarMonthHeaderPolicy() { } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarMonthScroll.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarMonthScroll { public static Target nextMonth(Date focusDate) { Calendar target = firstDayOfMonth(focusDate); target.add(Calendar.MONTH, 1); return new Target(target.getTime(), target.getTime()); } public static Target previousMonth(Date focusDate) { Calendar target = firstDayOfMonth(focusDate); target.add(Calendar.MONTH, -1); return new Target(target.getTime(), target.getTime()); } private static Calendar firstDayOfMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } public static class Target { private final Date focusDate; private final Date selectedDate; private Target(Date focusDate, Date selectedDate) { this.focusDate = new Date(focusDate.getTime()); this.selectedDate = new Date(selectedDate.getTime()); } public Date getFocusDate() { return new Date(focusDate.getTime()); } public Date getSelectedDate() { return new Date(selectedDate.getTime()); } } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarMonthTitleState.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; public class CalendarMonthTitleState { private int visibleYear = -1; private int visibleMonth = -1; public boolean updateVisibleMonth(Date date) { if (date == null) { return false; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); if (year == visibleYear && month == visibleMonth) { return false; } visibleYear = year; visibleMonth = month; return true; } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarScrollTrigger.java:   package ch.mfiles.kaba.kolibri.timesheet.util; public class CalendarScrollTrigger { public static final int NONE = 0; public static final int PREVIOUS = 1; public static final int NEXT = 2; private static final int VISIBLE_THRESHOLD = 1; private static final int PREVIOUS_PREFETCH_THRESHOLD = 3; private static final int NEXT_PREFETCH_THRESHOLD = 10; private static final int UNKNOWN_POSITION = -1; private int lastFirstVisibleItem = UNKNOWN_POSITION; private boolean userScrolling = false; private boolean suppressUntilIdle = false; private int consumedTriggersUntilIdle = NONE; private int suppressedTriggersUntilIdle = NONE; public static int getTrigger(int firstVisibleItem, int visibleItemCount, int totalItemCount, boolean userScrolling, boolean loadRunning) { if (loadRunning || !userScrolling || visibleItemCount <= 0 || totalItemCount <= visibleItemCount) { return NONE; } if (firstVisibleItem <= VISIBLE_THRESHOLD) { return PREVIOUS; } if ((firstVisibleItem + visibleItemCount) >= totalItemCount) { return NEXT; } return NONE; } public void onScrollStateChanged(boolean userScrolling) { if (!userScrolling) { this.userScrolling = false; this.suppressUntilIdle = false; this.consumedTriggersUntilIdle = NONE; this.suppressedTriggersUntilIdle = NONE; this.lastFirstVisibleItem = UNKNOWN_POSITION; return; } if (!this.userScrolling) { this.consumedTriggersUntilIdle = NONE; this.suppressedTriggersUntilIdle = NONE; this.lastFirstVisibleItem = UNKNOWN_POSITION; } this.userScrolling = true; } public void suppressUntilIdle() { this.suppressUntilIdle = true; this.consumedTriggersUntilIdle = PREVIOUS | NEXT; } public void suppressTriggerUntilIdle(int trigger) { if (!isLoadTrigger(trigger)) { return; } this.suppressedTriggersUntilIdle |= trigger; this.consumedTriggersUntilIdle |= trigger; } public int getTrigger(int firstVisibleItem, int visibleItemCount, int totalItemCount, boolean loadRunning) { if (loadRunning || !userScrolling || suppressUntilIdle || visibleItemCount <= 0 || totalItemCount <= visibleItemCount) { rememberPosition(firstVisibleItem); return NONE; } if (lastFirstVisibleItem == UNKNOWN_POSITION) { rememberPosition(firstVisibleItem); return NONE; } int previousFirstVisibleItem = lastFirstVisibleItem; rememberPosition(firstVisibleItem); if (firstVisibleItem < previousFirstVisibleItem && firstVisibleItem <= PREVIOUS_PREFETCH_THRESHOLD) { return consumeTrigger(PREVIOUS); } if (firstVisibleItem > previousFirstVisibleItem && (firstVisibleItem + visibleItemCount) >= totalItemCount - NEXT_PREFETCH_THRESHOLD) { return consumeTrigger(NEXT); } return NONE; } public int getOverScrollTrigger(int firstVisibleItem, int lastVisibleItem, int totalItemCount, boolean loadRunning) { if (loadRunning || suppressUntilIdle || totalItemCount <= 0) { return NONE; } boolean topVisible = firstVisibleItem <= 0; boolean bottomVisible = lastVisibleItem >= totalItemCount - 1; if (topVisible && bottomVisible) { return NONE; } if (topVisible) { return consumeTrigger(PREVIOUS); } if (bottomVisible) { return consumeTrigger(NEXT); } return NONE; } private int consumeTrigger(int trigger) { if (isTriggerSuppressed(trigger)) { return NONE; } consumedTriggersUntilIdle |= trigger; return trigger; } private boolean isTriggerSuppressed(int trigger) { return (consumedTriggersUntilIdle & trigger) != 0 || (suppressedTriggersUntilIdle & trigger) != 0; } private boolean isLoadTrigger(int trigger) { return trigger == PREVIOUS || trigger == NEXT; } private void rememberPosition(int firstVisibleItem) { lastFirstVisibleItem = firstVisibleItem; } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarTimeSheetCache.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; public class CalendarTimeSheetCache { public interface Loader { CalendarTimeSheet loadCalendar(Date date, int personalNumber); } private final Loader loader; private final int personalNumber; private final Map calendarsByDate = new HashMap(); public CalendarTimeSheetCache(Loader loader, int personalNumber) { this.loader = loader; this.personalNumber = personalNumber; } public synchronized CalendarTimeSheet getCalendar(Date date) { Long key = getDateKey(date); CalendarTimeSheet calendar = calendarsByDate.get(key); if (calendar == null) { calendar = loader.loadCalendar(date, personalNumber); calendarsByDate.put(key, calendar); } return calendar; } public synchronized List getMonthItems(Date focusDate) { CalendarDateRange.Range range = CalendarDateRange.initialMonth(focusDate); return getRangeItems(range.getStartDate(), range.getEndDate()); } public synchronized List getRangeItems(Date startDate, Date endDate) { List result = new ArrayList(); Calendar date = startOfDay(startDate); Calendar end = startOfDay(endDate); while (!date.after(end)) { result.add(getCalendar(date.getTime())); date.add(Calendar.DATE, 1); } return result; } public synchronized void preloadAdjacentMonths(Date focusDate) { Calendar previous = Calendar.getInstance(); previous.setTime(focusDate); previous.add(Calendar.MONTH, -1); Calendar next = Calendar.getInstance(); next.setTime(focusDate); next.add(Calendar.MONTH, 1); getMonthItems(previous.getTime()); getMonthItems(focusDate); getMonthItems(next.getTime()); } public synchronized void invalidate(Date date) { calendarsByDate.remove(getDateKey(date)); } public synchronized void clear() { calendarsByDate.clear(); } private static Long getDateKey(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return Long.valueOf(calendar.getTimeInMillis()); } private static Calendar startOfDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/CalendarToolbarTitleText.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; public class CalendarToolbarTitleText { private CalendarMonthTitleState titleState = new CalendarMonthTitleState(); public String updateVisibleMonthTitle(Date date) { if (!titleState.updateVisibleMonth(date)) { return null; } return DateTimeUtil.showMonthNameYear(date); } }     timeSheet/src/ch/mfiles/kaba/kolibri/timesheet/util/TimesheetDateUtils.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** *

A suite of utilities surrounding the use of the * {@link java.util.Calendar} and {@link java.util.Date} object.

* *

TimesheetDateUtils contains a lot of common methods considering manipulations * of Dates or Calendars. Some methods require some extra explanation. * The truncate and round methods could be considered the Math.floor(), * Math.ceil() or Math.round versions for dates * This way date-fields will be ignored in bottom-up order. * As a complement to these methods we've introduced some fragment-methods. * With these methods the Date-fields will be ignored in top-down order. * Since a date without a year is not a valid date, you have to decide in what * kind of date-field you want your result, for instance milliseconds or days. *

* * * * @author Serge Knystautas * @author Stephen Colebourne * @author Janek Bogucki * @author Gary Gregory * @author Phil Steitz * @author Robert Scholte * @since 2.0 * @version $Id: TimesheetDateUtils.java,v 1.2 2011/05/07 08:16:58 bpauli Exp $ */ public class TimesheetDateUtils { /** * The UTC time zone (often referred to as GMT). */ // public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT"); /** * Number of milliseconds in a standard second. * @since 2.1 */ public static final long MILLIS_PER_SECOND = 1000; /** * Number of milliseconds in a standard minute. * @since 2.1 */ public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; /** * Number of milliseconds in a standard hour. * @since 2.1 */ public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; /** * Number of milliseconds in a standard day. * @since 2.1 */ public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; /** * This is half a month, so this represents whether a date is in the top * or bottom half of the month. */ public final static int SEMI_MONTH = 1001; private static final int[][] fields = { {Calendar.MILLISECOND}, {Calendar.SECOND}, {Calendar.MINUTE}, {Calendar.HOUR_OF_DAY, Calendar.HOUR}, {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */ }, {Calendar.MONTH, TimesheetDateUtils.SEMI_MONTH}, {Calendar.YEAR}, {Calendar.ERA}}; /** * A week range, starting on Sunday. */ public final static int RANGE_WEEK_SUNDAY = 1; /** * A week range, starting on Monday. */ public final static int RANGE_WEEK_MONDAY = 2; /** * A week range, starting on the day focused. */ public final static int RANGE_WEEK_RELATIVE = 3; /** * A week range, centered around the day focused. */ public final static int RANGE_WEEK_CENTER = 4; /** * A month range, the week starting on Sunday. */ public final static int RANGE_MONTH_SUNDAY = 5; /** * A month range, the week starting on Monday. */ public final static int RANGE_MONTH_MONDAY = 6; //----------------------------------------------------------------------- /** *

This constructs an Iterator over each day in a date * range defined by a focus date and range style.

* *

For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

* *

This method provides an iterator that returns Calendar objects. * The days are progressed using {@link Calendar#add(int, int)}.

* * @param focus the date to work with, not null * @param rangeStyle the style constant to use. Must be one of * {@link TimesheetDateUtils#RANGE_MONTH_SUNDAY}, * {@link TimesheetDateUtils#RANGE_MONTH_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_SUNDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_RELATIVE}, * {@link TimesheetDateUtils#RANGE_WEEK_CENTER} * @return the date iterator, which always returns Calendar instances * @throws IllegalArgumentException if the date is null * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(Date focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } Calendar gval = Calendar.getInstance(); gval.setTime(focus); return iterator(gval, rangeStyle); } /** *

This constructs an Iterator over each day in a date * range defined by a focus date and range style.

* *

For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

* *

This method provides an iterator that returns Calendar objects. * The days are progressed using {@link Calendar#add(int, int)}.

* * @param focus the date to work with * @param rangeStyle the style constant to use. Must be one of * {@link TimesheetDateUtils#RANGE_MONTH_SUNDAY}, * {@link TimesheetDateUtils#RANGE_MONTH_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_SUNDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_MONDAY}, * {@link TimesheetDateUtils#RANGE_WEEK_RELATIVE}, * {@link TimesheetDateUtils#RANGE_WEEK_CENTER} * @return the date iterator * @throws IllegalArgumentException if the date is null * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(Calendar focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } Calendar start = null; Calendar end = null; int startCutoff = Calendar.SUNDAY; int endCutoff = Calendar.SATURDAY; switch (rangeStyle) { case RANGE_MONTH_SUNDAY: case RANGE_MONTH_MONDAY: //Set start to the first of the month start = truncate(focus, Calendar.MONTH); //Set end to the last of the month end = (Calendar) start.clone(); end.add(Calendar.MONTH, 1); end.add(Calendar.DATE, -1); //Loop start back to the previous sunday or monday if (rangeStyle == RANGE_MONTH_MONDAY) { startCutoff = Calendar.MONDAY; endCutoff = Calendar.SUNDAY; } break; case RANGE_WEEK_SUNDAY: case RANGE_WEEK_MONDAY: case RANGE_WEEK_RELATIVE: case RANGE_WEEK_CENTER: //Set start and end to the current date start = truncate(focus, Calendar.DATE); end = truncate(focus, Calendar.DATE); switch (rangeStyle) { case RANGE_WEEK_SUNDAY: //already set by default break; case RANGE_WEEK_MONDAY: startCutoff = Calendar.MONDAY; endCutoff = Calendar.SUNDAY; break; case RANGE_WEEK_RELATIVE: startCutoff = focus.get(Calendar.DAY_OF_WEEK); endCutoff = startCutoff - 1; break; case RANGE_WEEK_CENTER: startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3; endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3; break; } break; default: throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid."); //$NON-NLS-1$ //$NON-NLS-2$ } if (startCutoff < Calendar.SUNDAY) { startCutoff += 7; } if (startCutoff > Calendar.SATURDAY) { startCutoff -= 7; } if (endCutoff < Calendar.SUNDAY) { endCutoff += 7; } if (endCutoff > Calendar.SATURDAY) { endCutoff -= 7; } while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) { start.add(Calendar.DATE, -1); } while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) { end.add(Calendar.DATE, 1); } return new DateIterator(start, end); } /** *

This constructs an Iterator over each day in a date * range defined by a focus date and range style.

* *

For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

* * @param focus the date to work with, either * Date or Calendar * @param rangeStyle the style constant to use. Must be one of the range * styles listed for the {@link #iterator(Calendar, int)} method. * @return the date iterator * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is * not a Date or Calendar */ public static Iterator iterator(Object focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } if (focus instanceof Date) { return iterator((Date) focus, rangeStyle); } else if (focus instanceof Calendar) { return iterator((Calendar) focus, rangeStyle); } else { throw new ClassCastException("Could not iterate based on " + focus); //$NON-NLS-1$ } } /** *

Truncate this date, leaving the field specified as the most * significant field.

* *

For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

* * @param date the date to work with, either Date * or Calendar * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is not a * Date or Calendar * @throws ArithmeticException if the year is over 280 million */ public static Date truncate(Object date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } if (date instanceof Date) { return truncate((Date) date, field); } else if (date instanceof Calendar) { return truncate((Calendar) date, field).getTime(); } else { throw new ClassCastException("Could not truncate " + date); //$NON-NLS-1$ } } /** *

Truncate this date, leaving the field specified as the most * significant field.

* *

For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

* * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million */ public static Calendar truncate(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); //$NON-NLS-1$ } Calendar truncated = (Calendar) date.clone(); modify(truncated, field, false); return truncated; } //----------------------------------------------------------------------- /** *

Internal calculation method.

* * @param val the calendar * @param field the field constant * @param round true to round, false to truncate * @throws ArithmeticException if the year is over 280 million */ private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); //$NON-NLS-1$ } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == TimesheetDateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case TimesheetDateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); //$NON-NLS-1$ //$NON-NLS-2$ } /** *

Date iterator.

*/ static class DateIterator implements Iterator { private final Calendar endFinal; private final Calendar spot; /** * Constructs a DateIterator that ranges from one date to another. * * @param startFinal start date (inclusive) * @param endFinal end date (not inclusive) */ DateIterator(Calendar startFinal, Calendar endFinal) { super(); this.endFinal = endFinal; spot = startFinal; spot.add(Calendar.DATE, -1); } /** * Has the iterator not reached the end date yet? * * @return true if the iterator has yet to reach the end date */ public boolean hasNext() { return spot.before(endFinal); } /** * Return the next calendar in the iteration * * @return Object calendar for the next date */ public Object next() { if (spot.equals(endFinal)) { throw new RuntimeException(); } spot.add(Calendar.DATE, 1); return spot.clone(); } /** * Always throws UnsupportedOperationException. * * @throws UnsupportedOperationException * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/forms/ExpenseCurrencyValueTest.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import junit.framework.TestCase; public class ExpenseCurrencyValueTest extends TestCase { public ExpenseCurrencyValueTest(String name) { super(name); } public void testRemovesSecondDecimalSeparatorBeforeSavingExpenseCurrency() { assertEquals("26.00", TimeSheetDetailForm.getExpenseCurrencyValue("26..00")); } public void testKeepsValidExpenseCurrencyValuesUnchanged() { assertEquals("56", TimeSheetDetailForm.getExpenseCurrencyValue("56")); assertEquals("12.50", TimeSheetDetailForm.getExpenseCurrencyValue("12.50")); } public void testClearsExpenseCurrencyWithoutNumbers() { assertEquals("", TimeSheetDetailForm.getExpenseCurrencyValue("..")); assertEquals("", TimeSheetDetailForm.getExpenseCurrencyValue("abc")); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/forms/ExpensesCompensationTest.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.Date; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import junit.framework.TestCase; public class ExpensesCompensationTest extends TestCase { public void testLegacyTimeSelectionIsSavedAsExpenseCompensation() { Expenses expenses = new Expenses(new Date(0), 99998); expenses.setCompensation(false); assertEquals("A", expenses.getCompensation()); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/forms/TestDateCorrectness.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.ArrayList; import java.util.Date; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Ignore; import ch.mfiles.kaba.kolibri.common.util.CommonConstants; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import ch.mfiles.kaba.kolibri.common.util.DbConstants; import ch.mfiles.kolibri.ApplicationEvent; import ch.mfiles.kolibri.ApplicationManager; import ch.mfiles.kolibri.ApplicationManagerBase; import ch.mfiles.kolibri.KolibriRunnable; import ch.mfiles.kolibri.Registry; import ch.mfiles.kolibri.db.DBManager; import ch.mfiles.kolibri.db.DBSession; import ch.mfiles.kolibri.db.RecordSet; import ch.mfiles.kolibri.impl.FrameworkController; import ch.mfiles.kolibri.net.ConnectionManager; import ch.mfiles.kolibri.net.TransactionHandler; import ch.mfiles.kolibri.net.impl.TransactionHandlerImpl; import ch.mfiles.kolibri.ui.ProgressDlg; @Ignore("Legacy database date checks are disabled.") public class TestDateCorrectness extends TestCase { private static Log log = LogFactory.getLog(TestDateCorrectness.class); public TestDateCorrectness(String name) { super(name); } /* public void testCorrectCALENDARDate() throws Exception { boolean testResult = true; ArrayList calendarDates = selectAllCalendarDates(); for (int i=0; i < calendarDates.size(); i++) { Date date = (Date)calendarDates.get(i); if (!DateTimeUtil.isDate(date)) { testResult = false; log.error("No Date value in CALENDAR (tested with Calendar Obj): " + date + " (" + date.getTime() + ")"); } } assertTrue(testResult); } public void testCorrectZKDMAEXPNSDate() throws Exception { boolean testResult = true; ArrayList calendarDates = selectAllZKDMAEXPNSDates(); for (int i=0; i < calendarDates.size(); i++) { Date date = (Date)calendarDates.get(i); if (!DateTimeUtil.isDate(date)) { testResult = false; log.error("No Date value in ZKDMAEXPNS (tested with Calendar Obj): " + date + " (" + date.getTime() + ")"); } } assertTrue(testResult); } public ArrayList selectAllCalendarDates() { ArrayList result = new ArrayList(); RecordSet rs = m_dbSession.getRecordSet(); String sql = "SELECT " + DbConstants.CALENDAR.C_DATUM + " FROM " + DbConstants.CALENDAR.T_CALENDAR + " ORDER BY " + DbConstants.CALENDAR.C_DATUM + " ASC" ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(rs.getDate(DbConstants.CALENDAR.C_DATUM)); } } finally { rs.dispose(); } return result; } public ArrayList selectAllZKDMAEXPNSDates() { ArrayList result = new ArrayList(); RecordSet rs = m_dbSession.getRecordSet(); String sql = "SELECT " + DbConstants.ZKDMAEXPNS.C_DATUM + " FROM " + DbConstants.ZKDMAEXPNS.T_ZKDMAEXPNS + " ORDER BY " + DbConstants.ZKDMAEXPNS.C_DATUM + " ASC" ; if (log.isDebugEnabled()) log.debug("sql /" + sql + "/"); rs.setQuery(sql); try { while (rs.moveNext()) { result.add(rs.getDate(DbConstants.CALENDAR.C_DATUM)); } } finally { rs.dispose(); } return result; } DBSession m_dbSession; TransactionHandlerImpl m_trHandler; ProgressDlg m_dlg; DBManager m_dbman = null; ConnectionManager m_connectionManager = null; ApplicationManager m_applicationManager = null; FrameworkController m_fc = FrameworkController.getInstance(new Class[] { FrameworkController.FCOMP_DB_MANAGER, FrameworkController.FCOMP_REGISTRY, FrameworkController.FCOMP_CONNECTION_MANAGER, FrameworkController.FCOMP_TRANSACTION_HANDLER, FrameworkController.FCOMP_LICENSE_ADAPTER, FrameworkController.FCOMP_DEPLOYMENT_MANAGER, FrameworkController.FCOMP_APPLICATION_MANAGER}); Thread m_thread; protected void setUp() throws Exception { m_thread = m_fc.runAsThread(); m_dbman = m_fc.getDBManager(); m_trHandler = (TransactionHandlerImpl) m_fc.getTransactionHandler(); m_dbSession = m_dbman.connect("database"); m_dlg = ProgressDlg.createProgressDlg(true, true, true); m_trHandler.startQueueProcessing(); try { m_applicationManager = m_fc.getApplicationManager(); } catch (Exception e) { e.getMessage(); } m_applicationManager.startApplication(CommonConstants.Application.TIMESHEET_APP, null); } protected void tearDown() throws Exception { m_applicationManager.inject(new KolibriRunnable() { public ApplicationEvent run(ApplicationManagerBase appman, DBSession db, TransactionHandler tr, Registry reg) { // Auto-generated method stub return appman.exitFramework(); } }, false); m_thread.join(); } */ }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/forms/TimeSheetDetailFormSavePolicyTest.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.Calendar; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import junit.framework.TestCase; public class TimeSheetDetailFormSavePolicyTest extends TestCase { public TimeSheetDetailFormSavePolicyTest(String name) { super(name); } public void testExpenseSaveIsNotAllowedForFutureDates() { Date today = DateTimeUtil.getToday().getTime(); Date futureDate = addDays(today, 1); assertFalse(TimeSheetDetailForm.canSaveExpenseForDate(futureDate, today)); } public void testExpenseSaveIsAllowedForTodayAndPastDates() { Date today = DateTimeUtil.getToday().getTime(); Date todayWithTime = addHours(today, 12); Date pastDate = addDays(today, -1); assertTrue(TimeSheetDetailForm.canSaveExpenseForDate(today, today)); assertTrue(TimeSheetDetailForm.canSaveExpenseForDate(todayWithTime, today)); assertTrue(TimeSheetDetailForm.canSaveExpenseForDate(pastDate, today)); } private Date addDays(Date date, int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, days); return calendar.getTime(); } private Date addHours(Date date, int hours) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.HOUR_OF_DAY, hours); return calendar.getTime(); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/forms/TimeSheetValidatorTest.java:   package ch.mfiles.kaba.kolibri.timesheet.forms; import java.util.Calendar; import java.util.Date; import org.junit.Test; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import ch.mfiles.kaba.kolibri.common.businessobjects.Expenses; import ch.mfiles.kaba.kolibri.common.businessobjects.TimeSheet; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import junit.framework.TestCase; public class TimeSheetValidatorTest extends TestCase { private int personalNumber = 99998; private Date today = DateTimeUtil.getToday().getTime(); public TimeSheetValidatorTest(String name) { super(name); } /** * @see "MIG-453 New validation for timesheet" */ @Test public void testValidateSaveTimeSheet() { CalendarTimeSheet calendarTimeSheet = getNewCalendarTimeSheetWithExpenseAndTimesheet(); calendarTimeSheet.getExpense().setNoExpenses(false); calendarTimeSheet.getExpense().setDailyExpenses("56"); calendarTimeSheet.getExpense().setOperatingHoursTotal("191"); calendarTimeSheet.getExpense().setOperatingHoursOf("90"); calendarTimeSheet.getExpense().setOperatingHoursUpTo("101"); assertTrue(calendarTimeSheet.getExpense().validate().isValid()); assertTrue(calendarTimeSheet.isValid()); } @Test public void testValidateTimeSheetWithNoExpenses() { CalendarTimeSheet calendarTimeSheet = getNewCalendarTimeSheetWithExpenseAndTimesheet(); calendarTimeSheet.getExpense().setNoExpenses(true); calendarTimeSheet.getExpense().setOperatingHoursOf("56"); calendarTimeSheet.getExpense().setOperatingHoursUpTo("66"); assertTrue(calendarTimeSheet.isValid()); } private CalendarTimeSheet getNewCalendarTimeSheet() { CalendarTimeSheet calendarTimeSheet = new CalendarTimeSheet(today, personalNumber); assertFalse(calendarTimeSheet.isValid()); return calendarTimeSheet; } private Expenses getNewExpenses(CalendarTimeSheet calendarTimeSheet) { Expenses expenses = new Expenses(calendarTimeSheet.getDate(), calendarTimeSheet.getPersonalNumber()); return expenses; } private TimeSheet getNewTimeSheet(CalendarTimeSheet calendarTimeSheet) { TimeSheet timeSheet = new TimeSheet(calendarTimeSheet.getPersonalNumber()); timeSheet.setDate(calendarTimeSheet.getDate()); timeSheet.setIdx(calendarTimeSheet.getTimeSheets().size() + 1); timeSheet.setWorkTypeCode("01"); return timeSheet; } private CalendarTimeSheet getNewCalendarTimeSheetWithExpenseAndTimesheet() { CalendarTimeSheet calendarTimeSheet = getNewCalendarTimeSheet(); Expenses expenses = getNewExpenses(calendarTimeSheet); assertFalse(calendarTimeSheet.isValid()); calendarTimeSheet.setExpense(expenses); assertFalse(calendarTimeSheet.isValid()); TimeSheet timeSheet = getNewTimeSheet(calendarTimeSheet); timeSheet.setStopTime(DateTimeUtil.getNow().getTime()); Calendar start = DateTimeUtil.getDate(timeSheet.getStopTime()); start.add(Calendar.HOUR, -3); timeSheet.setStartTime(start.getTime()); assertTrue(timeSheet.validate().isValid()); calendarTimeSheet.getTimeSheets().add(timeSheet); return calendarTimeSheet; } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarDateRangeTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarDateRangeTest extends TestCase { public CalendarDateRangeTest(String name) { super(name); } public void testInitialMonthRangeIncludesBufferAroundMonthEdges() { CalendarDateRange.Range range = CalendarDateRange.initialMonth(date(2026, Calendar.JUNE, 15)); assertDate(2026, Calendar.MAY, 27, range.getStartDate()); assertDate(2026, Calendar.JULY, 5, range.getEndDate()); } public void testNextRangeContinuesAfterCurrentLastDate() { CalendarDateRange.Range range = CalendarDateRange.nextAfter(date(2026, Calendar.JULY, 5)); assertDate(2026, Calendar.JULY, 6, range.getStartDate()); assertDate(2026, Calendar.AUGUST, 5, range.getEndDate()); } public void testPreviousRangeContinuesBeforeCurrentFirstDate() { CalendarDateRange.Range range = CalendarDateRange.previousBefore(date(2026, Calendar.MAY, 27)); assertDate(2026, Calendar.APRIL, 26, range.getStartDate()); assertDate(2026, Calendar.MAY, 26, range.getEndDate()); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarDateSelectionTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarDateSelectionTest extends TestCase { public CalendarDateSelectionTest(String name) { super(name); } public void testMatchesSameCalendarDayIgnoringTime() { assertTrue(CalendarDateSelection.isSameCalendarDay( date(2026, Calendar.JUNE, 1, 0), date(2026, Calendar.JUNE, 1, 20))); } public void testDoesNotMatchSameDayOfYearInDifferentYears() { assertFalse(CalendarDateSelection.isSameCalendarDay( date(2026, Calendar.JUNE, 1, 0), date(2027, Calendar.JUNE, 1, 0))); } public void testUsesSelectedDateForPickerWhenAvailable() { Date visibleDate = date(2026, Calendar.JULY, 1, 0); Date selectedDate = date(2026, Calendar.JULY, 12, 0); assertDate(2026, Calendar.JULY, 12, CalendarDateSelection.getPickerDate(visibleDate, selectedDate)); } public void testUsesVisibleDateForPickerWhenSelectedDateIsFromDifferentMonth() { Date visibleDate = date(2026, Calendar.JULY, 1, 0); Date selectedDate = date(2026, Calendar.JUNE, 20, 0); assertDate(2026, Calendar.JULY, 1, CalendarDateSelection.getPickerDate(visibleDate, selectedDate)); } public void testUsesVisibleDateForPickerWhenNothingSelected() { Date visibleDate = date(2026, Calendar.JULY, 1, 0); assertDate(2026, Calendar.JULY, 1, CalendarDateSelection.getPickerDate(visibleDate, null)); } public void testUsesCalendarDateWhenNoCalendarDayWasSelectedYet() { Date calendarDate = date(2026, Calendar.JULY, 1, 0); assertDate(2026, Calendar.JULY, 1, CalendarDateSelection.getVisibleDate(calendarDate, null)); } public void testKeepsSelectedCalendarDayWhenAvailable() { Date calendarDate = date(2026, Calendar.JULY, 1, 0); Date selectedDate = date(2026, Calendar.JULY, 15, 0); assertDate(2026, Calendar.JULY, 15, CalendarDateSelection.getVisibleDate(calendarDate, selectedDate)); } private static Date date(int year, int month, int day, int hour) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarListWindowTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import junit.framework.TestCase; public class CalendarListWindowTest extends TestCase { public CalendarListWindowTest(String name) { super(name); } public void testNoTrimWhenListIsWithinLimit() { assertEquals(0, CalendarListWindow.getTrimCount(90, 120)); } public void testTrimCountIsOverflowAboveLimit() { assertEquals(10, CalendarListWindow.getTrimCount(130, 120)); } public void testAnchorPositionMovesUpWhenRowsAreTrimmedFromStart() { assertEquals(50, CalendarListWindow.getPositionAfterStartTrim(70, 20)); } public void testAnchorPositionDoesNotBecomeNegativeAfterStartTrim() { assertEquals(0, CalendarListWindow.getPositionAfterStartTrim(10, 20)); } public void testToolbarTitlePositionUsesFirstVisibleRow() { assertEquals(30, CalendarListWindow.getToolbarTitlePosition(30, 62)); } public void testToolbarTitlePositionDoesNotBecomeNegative() { assertEquals(0, CalendarListWindow.getToolbarTitlePosition(-1, 62)); } public void testToolbarTitlePositionDoesNotExceedLastRow() { assertEquals(61, CalendarListWindow.getToolbarTitlePosition(70, 62)); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarMonthHeaderPolicyTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarMonthHeaderPolicyTest extends TestCase { public CalendarMonthHeaderPolicyTest(String name) { super(name); } public void testShowsHeaderForFirstVisibleCalendarItem() { assertTrue(CalendarMonthHeaderPolicy.shouldShowHeader(date(2026, Calendar.JUNE, 15), null, 0)); } public void testShowsHeaderWhenMonthChanges() { assertTrue(CalendarMonthHeaderPolicy.shouldShowHeader( date(2026, Calendar.JULY, 1), date(2026, Calendar.JUNE, 30), 1)); } public void testShowsHeaderWhenYearChanges() { assertTrue(CalendarMonthHeaderPolicy.shouldShowHeader( date(2027, Calendar.JANUARY, 1), date(2026, Calendar.DECEMBER, 31), 1)); } public void testDoesNotShowHeaderForSameMonth() { assertFalse(CalendarMonthHeaderPolicy.shouldShowHeader( date(2026, Calendar.JUNE, 15), date(2026, Calendar.JUNE, 14), 1)); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarMonthScrollTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarMonthScrollTest extends TestCase { public CalendarMonthScrollTest(String name) { super(name); } public void testForwardFromMonthEndTargetsBeginningOfNextMonth() { CalendarMonthScroll.Target target = CalendarMonthScroll.nextMonth(date(2026, Calendar.JANUARY, 31)); assertDate(2026, Calendar.FEBRUARY, 1, target.getFocusDate()); assertDate(2026, Calendar.FEBRUARY, 1, target.getSelectedDate()); } public void testBackwardFromNextMonthTargetsBeginningOfPreviousMonth() { CalendarMonthScroll.Target target = CalendarMonthScroll.previousMonth(date(2026, Calendar.JULY, 1)); assertDate(2026, Calendar.JUNE, 1, target.getFocusDate()); assertDate(2026, Calendar.JUNE, 1, target.getSelectedDate()); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarMonthTitleStateTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; public class CalendarMonthTitleStateTest extends TestCase { public CalendarMonthTitleStateTest(String name) { super(name); } public void testFirstMonthRequiresTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); assertTrue(state.updateVisibleMonth(date(2026, Calendar.JUNE, 1))); } public void testSameMonthDoesNotRequireTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); state.updateVisibleMonth(date(2026, Calendar.JUNE, 1)); assertFalse(state.updateVisibleMonth(date(2026, Calendar.JUNE, 15))); } public void testDifferentMonthRequiresTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); state.updateVisibleMonth(date(2026, Calendar.JUNE, 30)); assertTrue(state.updateVisibleMonth(date(2026, Calendar.JULY, 1))); } public void testDifferentYearRequiresTitleUpdate() { CalendarMonthTitleState state = new CalendarMonthTitleState(); state.updateVisibleMonth(date(2026, Calendar.JANUARY, 1)); assertTrue(state.updateVisibleMonth(date(2027, Calendar.JANUARY, 1))); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarScrollTriggerTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import junit.framework.TestCase; public class CalendarScrollTriggerTest extends TestCase { public CalendarScrollTriggerTest(String name) { super(name); } public void testStaticTriggerKeepsExistingBottomBehavior() { assertEquals(CalendarScrollTrigger.PREVIOUS, CalendarScrollTrigger.getTrigger(0, 10, 35, true, false)); } public void testStaticTriggerDoesNotTriggerWhileListIsPositionedProgrammatically() { assertEquals(CalendarScrollTrigger.NONE, CalendarScrollTrigger.getTrigger(0, 10, 35, false, false)); } public void testStaticTriggerKeepsExistingNextBehavior() { assertEquals(CalendarScrollTrigger.NEXT, CalendarScrollTrigger.getTrigger(25, 10, 35, true, false)); } public void testDoesNotTriggerNextMonthBeforeLastItemIsVisible() { assertEquals(CalendarScrollTrigger.NONE, CalendarScrollTrigger.getTrigger(24, 10, 35, true, false)); } public void testDoesNotTriggerWhileLoadIsRunning() { assertEquals(CalendarScrollTrigger.NONE, CalendarScrollTrigger.getTrigger(0, 10, 35, true, true)); } public void testStatefulTriggerWaitsUntilScrollDirectionIsKnown() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(25, 10, 35, false)); assertEquals(CalendarScrollTrigger.NEXT, trigger.getTrigger(26, 9, 35, false)); } public void testStatefulTriggerDoesNotTriggerPreviousWhenProgrammaticPositionLandsNearTop() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.suppressUntilIdle(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(0, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(1, 10, 35, false)); } public void testStatefulTriggerRearmsAfterIdleAndNewGesture() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.suppressUntilIdle(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(0, 10, 35, false)); trigger.onScrollStateChanged(false); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(2, 10, 35, false)); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getTrigger(1, 10, 35, false)); } public void testStatefulTriggerAllowsOnlyOneLoadPerGesture() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(14, 10, 35, false)); assertEquals(CalendarScrollTrigger.NEXT, trigger.getTrigger(15, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(26, 9, 35, false)); } public void testStatefulTriggerRequiresMatchingScrollDirection() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(0, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(1, 10, 35, false)); } public void testOverscrollAtBottomTriggersNextWithoutNeedingDirectionChange() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.NEXT, trigger.getOverScrollTrigger(25, 34, 35, false)); } public void testOverscrollAtTopTriggersPrevious() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getOverScrollTrigger(0, 9, 35, false)); } public void testOverscrollAllowsOnlyOneLoadPerGesture() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.NEXT, trigger.getOverScrollTrigger(25, 34, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getOverScrollTrigger(25, 34, 35, false)); } public void testOverscrollDoesNotTriggerWhenWholeListIsVisible() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.NONE, trigger.getOverScrollTrigger(0, 34, 35, false)); } public void testStatefulTriggerPrefetchesNextBeforeListEnd() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(14, 10, 35, false)); assertEquals(CalendarScrollTrigger.NEXT, trigger.getTrigger(15, 10, 35, false)); } public void testStatefulTriggerDoesNotPrefetchNextBeforeThreshold() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(13, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(14, 10, 35, false)); } public void testStatefulTriggerPrefetchesPreviousBeforeListStart() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(4, 10, 35, false)); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getTrigger(3, 10, 35, false)); } public void testStatefulTriggerDoesNotPrefetchPreviousBeforeThreshold() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); trigger.onScrollStateChanged(true); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(5, 10, 35, false)); assertEquals(CalendarScrollTrigger.NONE, trigger.getTrigger(4, 10, 35, false)); } public void testOppositeOverscrollDirectionCanTriggerBeforeIdle() { CalendarScrollTrigger trigger = new CalendarScrollTrigger(); assertEquals(CalendarScrollTrigger.PREVIOUS, trigger.getOverScrollTrigger(0, 9, 35, false)); trigger.suppressTriggerUntilIdle(CalendarScrollTrigger.PREVIOUS); assertEquals(CalendarScrollTrigger.NEXT, trigger.getOverScrollTrigger(25, 34, 35, false)); } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarTimeSheetCacheTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import java.util.List; import ch.mfiles.kaba.kolibri.common.businessobjects.CalendarTimeSheet; import junit.framework.TestCase; public class CalendarTimeSheetCacheTest extends TestCase { private static final int PERSONAL_NUMBER = 99998; public CalendarTimeSheetCacheTest(String name) { super(name); } public void testPreloadsAdjacentMonthSoNextMonthDoesNotLoadAgainAtScrollBoundary() { CountingLoader loader = new CountingLoader(); CalendarTimeSheetCache cache = new CalendarTimeSheetCache(loader, PERSONAL_NUMBER); cache.preloadAdjacentMonths(date(2026, Calendar.JUNE, 15)); int loadsAfterPreload = loader.getLoadCount(); List julyItems = cache.getMonthItems(date(2026, Calendar.JULY, 15)); assertFalse(julyItems.isEmpty()); assertEquals(loadsAfterPreload, loader.getLoadCount()); } public void testInvalidatingOneDayReloadsOnlyThatDay() { CountingLoader loader = new CountingLoader(); CalendarTimeSheetCache cache = new CalendarTimeSheetCache(loader, PERSONAL_NUMBER); Date date = date(2026, Calendar.JUNE, 15); CalendarTimeSheet firstLoad = cache.getCalendar(date); cache.invalidate(date); CalendarTimeSheet secondLoad = cache.getCalendar(date); assertNotSame(firstLoad, secondLoad); assertEquals(2, loader.getLoadCount()); } public void testMonthItemsIncludeBufferBeforeMonthStart() { CalendarTimeSheetCache cache = new CalendarTimeSheetCache(new CountingLoader(), PERSONAL_NUMBER); List juneItems = cache.getMonthItems(date(2026, Calendar.JUNE, 15)); assertDate(2026, Calendar.MAY, 27, juneItems.get(0).getDate()); } public void testMonthItemsIncludeBufferAfterMonthEnd() { CalendarTimeSheetCache cache = new CalendarTimeSheetCache(new CountingLoader(), PERSONAL_NUMBER); List mayItems = cache.getMonthItems(date(2026, Calendar.MAY, 15)); assertDate(2026, Calendar.JUNE, 5, mayItems.get(mayItems.size() - 1).getDate()); } public void testRangeItemsLoadInclusiveDateRange() { CalendarTimeSheetCache cache = new CalendarTimeSheetCache(new CountingLoader(), PERSONAL_NUMBER); List items = cache.getRangeItems( date(2026, Calendar.JUNE, 6), date(2026, Calendar.JUNE, 8)); assertEquals(3, items.size()); assertDate(2026, Calendar.JUNE, 6, items.get(0).getDate()); assertDate(2026, Calendar.JUNE, 8, items.get(2).getDate()); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } private static void assertDate(int year, int month, int day, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); } private static class CountingLoader implements CalendarTimeSheetCache.Loader { private int loadCount; public CalendarTimeSheet loadCalendar(Date date, int personalNumber) { loadCount++; return new CalendarTimeSheet(date, personalNumber); } public int getLoadCount() { return loadCount; } } }     timeSheet/test/ch/mfiles/kaba/kolibri/timesheet/util/CalendarToolbarTitleTextTest.java:   package ch.mfiles.kaba.kolibri.timesheet.util; import java.util.Calendar; import java.util.Date; import ch.mfiles.kaba.kolibri.common.util.DateTimeUtil; import junit.framework.TestCase; public class CalendarToolbarTitleTextTest extends TestCase { public CalendarToolbarTitleTextTest(String name) { super(name); } public void testReturnsMonthTitleForFirstVisibleMonth() { CalendarToolbarTitleText titleText = new CalendarToolbarTitleText(); Date date = date(2026, Calendar.JULY, 1); assertEquals(DateTimeUtil.showMonthNameYear(date), titleText.updateVisibleMonthTitle(date)); } public void testDoesNotReturnTitleForSameVisibleMonth() { CalendarToolbarTitleText titleText = new CalendarToolbarTitleText(); titleText.updateVisibleMonthTitle(date(2026, Calendar.JULY, 1)); assertNull(titleText.updateVisibleMonthTitle(date(2026, Calendar.JULY, 31))); } public void testReturnsMonthTitleWhenVisibleMonthChanges() { CalendarToolbarTitleText titleText = new CalendarToolbarTitleText(); titleText.updateVisibleMonthTitle(date(2026, Calendar.JULY, 31)); Date nextMonth = date(2026, Calendar.AUGUST, 1); assertEquals(DateTimeUtil.showMonthNameYear(nextMonth), titleText.updateVisibleMonthTitle(nextMonth)); } private static Date date(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } }