\");\r\n\t\tsb.append(\"\t\t\");\r\n\t\tappendStyleSheet(sb);\r\n\t\tsb.append(\"\t\");\r\n\t\tsb.append(\"\");\r\n\t}\r\n\t\r\n\tprivate static void appendStyleSheet(StringBuffer sb) {\r\n\t\t sb.append(\" \");\r\n\t}\r\n\r\n\tprivate static void appendHeader(StringBuffer sb, ResponseTO report,\r\n\t\t\tResults results, SaveReportType reportType) {\r\n\t\tsb.append(\"
\");\r\n\t\tsb.append(\"
\");\r\n\t\t\r\n\t\tsb.append(\"
\")\r\n\t .append(\" \\\"HealthIT.gov\\\"\")\r\n\t\")\r\n\t .append(\" \")\r\n\t .append(\"
\");\t\t\r\n\r\n\t\tsb.append(\"
\");\r\n\t\tappendHorizontalRuleWithBreaks(sb);\r\n\r\n\t\tsb.append(\"

\" + \"C-CDA \");\r\n\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\tsb.append(\"Scorecard For \"\r\n\t\t\t\t\t+ (report.getCcdaDocumentType() != null ? report\r\n\t\t\t\t\t\t\t.getCcdaDocumentType() : \"document\") + \"

\");\r\n\t\t\tsb.append(\"
\");\r\n\t\t\tsb.append(\"\" + \"Submitted By: \"\r\n\t\t\t+ (!ApplicationUtil.isEmpty(report.getFilename()) ? report.getFilename() : \"Unknown\")\r\n\t\t\t+ \"\");\r\n\t\t\tDateFormat dateFormat = new SimpleDateFormat(\"MM/dd/yyyy HH:mm:ss\");\r\n\t\t\tsb.append(\"\" + \"Submission Time: \" + dateFormat.format(new Date()) + \"\");\r\n\t\t\tsb.append(\"
\");\r\n\t\t\tsb.append(\"
\");\t\t\t\r\n\t\t\tappendBasicResults(sb, results);\t\t\t\r\n\t\t} else {\r\n\t\t\tsb.append(results.getCcdaVersion() + \" \" \r\n\t\t\t\t\t+ (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : \"document\") \r\n\t\t\t\t\t+ \" Scorecard For:\" + \"\");\t\t\r\n\t\t\tsb.append(\"

\" + report.getFilename() + \"

\");\r\n\t\t}\r\n\t\tsb.append(\"
\");\r\n\t\tsb.append(\"
\");\r\n\t}\r\n\t\r\n\tprivate static void appendPreTopLevelResultsContent(StringBuffer sb) {\r\n\t\t/*\r\n\t\tsb.append(\"

\")\r\n\t .append(\" The C-CDA Scorecard enables providers, implementers, and health\")\r\n\t .append(\" IT professionals with a tool that compares how artifacts (transition\")\r\n\t .append(\" of care documents, care plans etc) created by your organization\")\r\n\t .append(\" stack up against the HL7 C-CDA implementation guide and HL7 best\")\r\n\t .append(\" practices. The C-CDA Scorecard promotes best practices in C-CDA\")\r\n\t .append(\" implementation by assessing key aspects of the structured data found\")\r\n\t .append(\" in individual documents. The Scorecard tool provides a rough\")\r\n\t .append(\" quantitative assessment and highlights areas of improvement which\")\r\n\t .append(\" can be made today to move the needle forward in interoperability of\")\r\n\t .append(\" C-CDA documents. The \")\r\n\t .append(\" \"\r\n\t \t\t\t+ \"best practices and quantitative scoring criteria\"\r\n\t \t\t\t+ \"\")\r\n\t .append(\" have been developed by HL7 through the HL7-ONC Cooperative agreement\")\r\n\t .append(\" to improve the implementation of health care standards. We hope that\")\r\n\t .append(\" providers and health IT developers will use the tool to identify and\")\r\n\t .append(\" resolve issues around C-CDA document interoperability in their\")\r\n\t .append(\" health IT systems.\")\r\n\t .append(\"

\")\r\n\t */\r\n\t\t\r\n\t\tsb.append(\"

If you are not satisfied with your results:

\");\r\n\t\tsb.append(\"
    \");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\t\tsb.append(\"Please ask your vendor to submit the document to the SITE C-CDA Scorecard website \"\r\n\t\t\t\t\t\t+ \" at \" + \"\" + \"www.healthit.gov/scorecard\" + \"\"\r\n\t\t\t\t\t\t+ \" for more detailed information\");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\t\tsb.append(\"Using the results provided by the online tool, \"\r\n\t\t\t\t\t\t+ \"your vendor can update or provide insight on how to update your document to meet the latest HL7 best-practices\");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\t\tsb.append(\"Once updated, \"\r\n\t\t\t\t\t\t+ \"resubmitting your document to the ONC One Click Scorecard will produce a report with a higher score \"\r\n\t\t\t\t\t\t+ \"and/or less or no conformance errors or less or no certification feedback results\");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\tsb.append(\"
\");\r\n\t\t\r\n\t sb.append(\"

\")\r\n\t .append(\"This page contains a summary of the C-CDA Scorecard results highlighting the overall document grade \"\r\n\t \t\t+ \"which is derived from a quantitative score out of a maximum of 100. \")\r\n\t .append(\"

\");\r\n\t sb.append(\"

\")\r\n\t .append(\"The second and final page identifies areas for improvement organized by clinical domains.\")\r\n\t .append(\"

\");\r\n\t}\r\n\t\r\n\tprivate static void appendBasicResults(StringBuffer sb, Results results) {\r\n\t\tsb.append(\"
\");\r\n\t\tsb.append(\"

\");\r\n\t\tsb.append(\"Grade: \" + results.getFinalGrade() + \"\"); \r\n\t\tsb.append(\"Score: \" + results.getFinalNumericalGrade() + \"/100\" + \"\");\r\n\t\tsb.append(\"

\");\r\n\t\tsb.append(\"
\");\r\n\t}\r\n\t\r\n\tprivate static void appendTopLevelResults(StringBuffer sb, Results results,\r\n\t\t\tList categories, List referenceResults, SaveReportType reportType, String ccdaDocumentType) {\r\n\t\t\r\n\t\tboolean isReferenceResultsEmpty = ApplicationUtil.isEmpty(referenceResults);\r\n\t\tint conformanceErrorCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CONFORMANCE_ERROR_INDEX).getTotalErrorCount();\r\n\t\tint certificationFeedbackCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getTotalErrorCount();\r\n\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\t//brief summary of overall document results (without scorecard issues count listed)\r\n\t\t\tsb.append(\"

Summary

\");\r\n\t\t\tsb.append(\"

\"\r\n\t\t\t\t\t+ \"Your \" + ccdaDocumentType + \" document received a grade of \" + results.getFinalGrade() + \"\"\r\n\t\t\t\t\t+ \" compared to an industry average of \" + \"\" + results.getIndustryAverageGradeForCcdaDocumentType() + \"\" + \". \"\r\n\t\t\t\t\t+ \"The industry average, specific to the document type sent, was computed by scoring \" \r\n\t\t\t\t\t+ results.getNumberOfDocsScoredPerCcdaDocumentType() + \" \" + ccdaDocumentType + \r\n\t\t\t\t\t(results.getNumberOfDocsScoredPerCcdaDocumentType() > 1 ? \"s\" : \"\" ) + \". \" \r\n\t\t\t\t\t+ \"The document scored \" + \"\" + results.getFinalNumericalGrade() + \"/100\" + \"\"\r\n\t\t\t\t\t+ \" and is \"\r\n\t\t\t\t\t+ (conformanceErrorCount > 0 ? \"non-compliant\" : \"compliant\")\r\n\t\t\t\t\t+ \" with the HL7 C-CDA IG\"\r\n\t\t\t\t\t+ \" and is \"\r\n\t\t\t\t\t+ (certificationFeedbackCount > 0 ? \"non-compliant\" : \"compliant\")\r\n\t\t\t\t\t+ \" with 2015 Edition Certification requirements. \"\r\n\t\t\t\t\t+ \"The detailed results organized by clinical domains are provided in the table below:\"\r\n\t\t\t\t\t+ \"

\");\r\n\t\t\t//dynamic table\r\n\t\t\tappendHorizontalRuleWithBreaks(sb);\r\n\t\t\tsb.append(\"

\");\r\n\t\t\tsb.append(\"

Scorecard Results by Clinical Domain

\");\r\n\t\t\tappendDynamicTopLevelResultsTable(sb, results, categories, referenceResults);\r\n\t\t} else {\t\t\r\n\t\t\tsb.append(\"

Scorecard Grade: \" + results.getFinalGrade() + \"

\");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\tsb.append(\"

    Your document scored a \" + \"\"\r\n\t\t\t\t\t+ results.getFinalGrade() + \"\"\r\n\t\t\t\t\t+ \" compared to an industry average of \" + \"\"\r\n\t\t\t\t\t+ results.getIndustryAverageGrade() + \"\" + \".

    \");\r\n\t\t\tsb.append(\"
\");\r\n\t\r\n\t\t\tsb.append(\"

Scorecard Score: \" + results.getFinalNumericalGrade()\r\n\t\t\t\t\t+ \"

\");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\t\tsb.append(\"

    Your document scored \" + \"\"\r\n\t\t\t\t\t+ +results.getFinalNumericalGrade() + \"\" + \" out of \"\r\n\t\t\t\t\t+ \"\" + \" 100 \" + \"\" + \" total possible points.

    \");\r\n\t\t\tsb.append(\"
\");\r\n\t\r\n\t\t\tboolean isSingular = results.getNumberOfIssues() == 1;\r\n\t\t\tappendSummaryRow(sb, results.getNumberOfIssues(), \"Scorecard Issues\",\r\n\t\t\t\t\tnull, isSingular ? \"Scorecard Issue\" : \"Scorecard Issues\",\r\n\t\t\t\t\tisSingular);\r\n\t\t\tsb.append(\"\");\r\n\t\r\n\t\t\tString messageSuffix = null;\r\n\t\t\tif (isReferenceResultsEmpty) {\r\n\t\t\t\tfor (ReferenceInstanceType refType : ReferenceInstanceType.values()) {\r\n\t\t\t\t\tif (refType == ReferenceInstanceType.CERTIFICATION_2015) {\r\n\t\t\t\t\t\tmessageSuffix = \"results\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tappendSummaryRow(sb, 0, refType.getTypePrettyName(),\r\n\t\t\t\t\t\t\tmessageSuffix, refType.getTypePrettyName(), false, reportType);\r\n\t\t\t\t\tsb.append(\"\");\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tfor (ReferenceResult refResult : referenceResults) {\r\n\t\t\t\t\tint refErrorCount = refResult.getTotalErrorCount();\r\n\t\t\t\t\tisSingular = refErrorCount == 1;\r\n\t\t\t\t\tString refTypeName = refResult.getType().getTypePrettyName();\r\n\t\t\t\t\tString messageSubject = \"\";\r\n\t\t\t\t\tif (refResult.getType() == ReferenceInstanceType.IG_CONFORMANCE) {\r\n\t\t\t\t\t\tmessageSubject = isSingular ? refTypeName.substring(0,\r\n\t\t\t\t\t\t\t\trefTypeName.length() - 1) : refTypeName;\r\n\t\t\t\t\t} else if (refResult.getType() == ReferenceInstanceType.CERTIFICATION_2015) {\r\n\t\t\t\t\t\tmessageSuffix = isSingular ? \"result\" : \"results\";\r\n\t\t\t\t\t\tmessageSubject = refTypeName;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tappendSummaryRow(sb, refErrorCount, refTypeName, messageSuffix,\r\n\t\t\t\t\t\t\tmessageSubject, isSingular, reportType);\r\n\t\t\t\t\tsb.append(\"\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate static int getFailingSectionSpecificErrorCount(String categoryName,\r\n\t\t\tReferenceInstanceType refType, List referenceResults) {\r\n\t\tif (!ApplicationUtil.isEmpty(referenceResults)) {\r\n\t\t\tif (refType == ReferenceInstanceType.IG_CONFORMANCE) {\r\n\t\t\t\tList igErrors = \r\n\t\t\t\t\t\treferenceResults.get(CONFORMANCE_ERROR_INDEX).getReferenceErrors();\r\n\t\t\t\tif (!ApplicationUtil.isEmpty(igErrors)) {\r\n\t\t\t\t\treturn getFailingSectionSpecificErrorCountProcessor(categoryName, igErrors);\r\n\t\t\t\t}\r\n\t\t\t} else if (refType == ReferenceInstanceType.CERTIFICATION_2015) {\r\n\t\t\t\tList certErrors = \r\n\t\t\t\t\t\treferenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getReferenceErrors();\r\n\t\t\t\tif (!ApplicationUtil.isEmpty(certErrors)) {\r\n\t\t\t\t\treturn getFailingSectionSpecificErrorCountProcessor(categoryName, certErrors);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tprivate static int getFailingSectionSpecificErrorCountProcessor(\r\n\t\t\tString categoryName, List errors) {\r\n\t\tint count = 0;\r\n\t\tfor (int i = 0; i < errors.size(); i++) {\r\n\t\t\tString currentSectionInReferenceErrors = errors.get(i).getSectionName();\r\n\t\t\tif (!ApplicationUtil.isEmpty(currentSectionInReferenceErrors)) {\r\n\t\t\t\tif (currentSectionInReferenceErrors.equalsIgnoreCase(categoryName)) {\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn count;\r\n\t}\r\n\t\r\n\tprivate static void appendDynamicTopLevelResultsTable(StringBuffer sb, Results results,\r\n\t\t\tList categories, List referenceResults) { \r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\t\t\t\t\r\n\t\tfor(Category category : getSortedCategories(categories)) {\r\n//\t\t\tif(category.getNumberOfIssues() > 0 || referenceResults.get(ReferenceInstanceType.IG/CERT).getTotalErrorCount() > 0) {\r\n//\t\t\tif(category.getNumberOfIssues() > 0 || category.isFailingConformance() || category.isCertificationFeedback()) {\t\t\t\t\r\n\t\t\tsb.append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \");\r\n//\t\t\t}\r\n\t\t}\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\"
\");\r\n\t\tsb.append(\" The Scorecard grade is a quantitative assessment of the data quality of the submitted document. \"\r\n\t\t\t\t+ \"A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and \"\r\n\t\t\t\t+ \"has higher probability of being interoperable with other organizations.\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" A Scorecard Issue identifies data within the document which can be represented in a better way using \"\r\n\t\t\t\t+ \"HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. \"\r\n\t\t\t\t+ \"This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" A Certification Feedback result identifies areas where the generated documents are not compliant with \"\r\n\t\t\t\t+ \"the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.\");\r\n\t\tsb.append(\"
Clinical DomainScorecard GradeScorecard IssuesConformance ErrorsCertification Feedback
\" + (category.getCategoryName() != null ? category.getCategoryName() : \"Unknown\") + \"\" + (category.getCategoryGrade() != null ? category.getCategoryGrade() : \"N/A\") + \"\" + (category.isFailingConformance() || category.isCertificationFeedback() || category.isNullFlavorNI() \r\n\t\t \t\t ? \"N/A\" \r\n\t\t \t\t : category.getNumberOfIssues()) \r\n\t\t \t\t + \"\" \r\n\t\t + (!ApplicationUtil.isEmpty(category.getCategoryName()) \r\n\t\t \t\t ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults) \r\n\t\t \t\t : \"N/A\")\r\n\t\t + \"\" \r\n\t\t + (!ApplicationUtil.isEmpty(category.getCategoryName()) \r\n\t\t \t\t ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults) \r\n\t\t \t\t : \"N/A\") \r\n\t\t + \"
\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Order from best to worst:
\r\n\t * 1. Numerical score high to low 2. Empty/null 3. Certification Feedback 4. Conformance Error\r\n\t * @param categories - Category List to sort\r\n\t * @return sorted categories\r\n\t */\r\n\tprivate static List getSortedCategories(List categories) {\r\n\t\tList sortedCategories = new ArrayList(categories);\r\n\t\t//prepare for sort of non-scored items\r\n\t\tfor(Category category : sortedCategories) {\r\n\t\t\tif(category.isFailingConformance()) {\r\n\t\t\t\tcategory.setCategoryNumericalScore(-3);\r\n\t\t\t} else if(category.isCertificationFeedback()) {\r\n\t\t\t\tcategory.setCategoryNumericalScore(-2);\r\n\t\t\t} else if(category.isNullFlavorNI()) {\r\n\t\t\t\tcategory.setCategoryNumericalScore(-1);\r\n\t\t\t}\r\n\t\t}\r\n\t\t//sorts by numerical score via Comparable implementation in Category\r\n\t\tCollections.sort(sortedCategories, Collections.reverseOrder());\r\n\t\treturn sortedCategories;\r\n\t}\r\n\t\r\n\tprivate static void appendHeatmap(StringBuffer sb, Results results,\r\n\t\t\tList categories, List referenceResults) {\r\n\t\t\r\n\t\tsb.append(\"\" + \"\");\r\n\t\tfor (Category curCategory : getSortedCategories(categories)) {\r\n\t\t\tsb.append(\"

\" \r\n\t\t\t\t\t+ (curCategory.getNumberOfIssues() > 0 \r\n\t\t\t\t\t\t\t? \"\" : \"\")\r\n\t\t\t\t\t+ curCategory.getCategoryName()\r\n\t\t\t\t\t+ (curCategory.getNumberOfIssues() > 0\r\n\t\t\t\t\t\t\t? \"\" : \"\")\r\n\t\t\t\t\t+ \"

\");\r\n\r\n\t\t\tsb.append(\"
    \");\r\n\t\t\tif (curCategory.getCategoryGrade() != null) {\r\n\t\t\t\tsb.append(\"
  • \" + \"Section Grade: \" + \"\"\r\n\t\t\t\t\t\t+ curCategory.getCategoryGrade() + \"\" + \"
  • \"\r\n\t\t\t\t\t\t+ \"
  • \" + \"Number of Issues: \" + \"\"\r\n\t\t\t\t\t\t+ curCategory.getNumberOfIssues() + \"\" + \"
  • \");\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\"
  • \"\r\n\t\t\t\t\t\t+ \"This category was not scored as it \");\r\n\t\t\t\tif(curCategory.isNullFlavorNI()) {\r\n\t\t\t\t\tsb.append(\"is an empty section\");\r\n\t\t\t\t}\r\n\t\t\t \tboolean failingConformance = curCategory.isFailingConformance();\r\n\t\t\t \tboolean failingCertification = curCategory.isCertificationFeedback();\r\n\t\t\t \tif(failingConformance || failingCertification) {\r\n\t\t \t\t\tboolean isCategoryNameValid = !ApplicationUtil.isEmpty(curCategory.getCategoryName());\r\n\t\t\t \t\tif(failingConformance && failingCertification || failingConformance && !failingCertification) {\r\n\t\t\t\t \t\t//we default to IG if true for both since IG is considered a more serious issue (same with the heatmap label, so we match that)\r\n\t\t\t\t \t\t//there could be a duplicate for two reasons, right now, there's always at least one duplicate since we derive ig from cert in the backend\r\n\t\t\t\t \t\t//in the future this might not be the case, but, there could be multiple section fails in the same section, so we have a default for those too\r\n\t\t\t \t\t\tint igErrorCount = isCategoryNameValid \r\n\t\t\t \t\t\t\t\t? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults)\r\n\t\t\t \t\t\t\t\t: -1;\r\n\t\t\t\t\t\tsb.append(\"contains\" + (isCategoryNameValid ? \" \" + igErrorCount + \" \" : \"\")\r\n\t\t\t\t\t\t\t\t+ \"\" + \"Conformance Error\" + (igErrorCount != 1 ? \"s\" : \"\") + \"\");\r\n\t\t\t\t\t} else if(failingCertification && !failingConformance) {\r\n\t\t\t\t\t\tint certFeedbackCount = isCategoryNameValid\r\n\t\t\t\t\t\t\t\t? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults)\r\n\t\t\t\t\t\t\t\t: -1;\r\n\t\t\t\t\t\tsb.append(\"contains\" + (isCategoryNameValid ? \" \" + certFeedbackCount + \" \" : \"\")\r\n\t\t\t\t\t\t\t\t+ \"\" + \"Certification Feedback\" + \"\" + \" result\" + (certFeedbackCount != 1 ? \"s\" : \"\"));\r\n\t\t\t\t\t}\r\n\t\t\t \t}\r\n\t\t\t\tsb.append(\"
  • \");\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\tsb.append(\"
\");\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\tprivate static void appendSummaryRow(StringBuffer sb, int result,\r\n\t\t\tString header, String messageSuffix, String messageSubject,\r\n\t\t\tboolean isSingular) {\r\n\t\tappendSummaryRow(sb, result, header, messageSuffix, messageSubject, isSingular, null);\r\n\t}\r\n\t\r\n\tprivate static void appendSummaryRow(StringBuffer sb, int result,\r\n\t\t\tString header, String messageSuffix, String messageSubject,\r\n\t\t\tboolean isSingular, SaveReportType reportType) {\r\n\t\tif(reportType == null) {\r\n\t\t\treportType = SaveReportType.MATCH_UI;\r\n\t\t}\r\n\t\tsb.append(\"

\"\r\n\t\t\t\t+ header\r\n\t\t\t\t+ \": \"\r\n\t\t\t\t+ (\"Scorecard Issues\".equals(header) || result < 1 || reportType == SaveReportType.SUMMARY ? result\r\n\t\t\t\t\t\t: (\"\" + result + \"\"))\r\n\t\t\t\t+ \"

\");\r\n\t\tsb.append(\"
  • \");\r\n\t\tsb.append(\"

    There \" + (isSingular ? \"is\" : \"are\") + \" \" + \"\"\r\n\t\t\t\t+ result + \"\" + \" \" + messageSubject\r\n\t\t\t\t+ (messageSuffix != null ? \" \" + messageSuffix : \"\")\r\n\t\t\t\t+ \" in your document.

    \");\r\n\t}\r\n\r\n\tprivate static void appendDetailedResults(StringBuffer sb,\r\n\t\t\tList categories, List referenceResults) {\r\n\r\n\t\tsb.append(\"

    \" + \"Detailed Results\" + \"

    \");\r\n\r\n\t\tif (!ApplicationUtil.isEmpty(referenceResults)) {\r\n\t\t\tfor (ReferenceResult curRefInstance : referenceResults) {\r\n\r\n\t\t\t\tReferenceInstanceType refType = curRefInstance.getType();\r\n\t\t\t\tif (curRefInstance.getTotalErrorCount() > 0) {\r\n\t\t\t\t\tString refTypeName = refType.getTypePrettyName();\r\n\t\t\t\t\tsb.append(\"

    \"\r\n\t\t\t\t\t\t\t+ refTypeName + \"

    \");\r\n\t\r\n\t\t\t\t\tsb.append(\"
      \"); // START curRefInstance ul\r\n\t\t\t\t\tsb.append(\"
    • \"\r\n\t\t\t\t\t\t\t+ \"Number of \"\r\n\t\t\t\t\t\t\t+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? \"Results:\"\r\n\t\t\t\t\t\t\t\t\t: \"Errors:\") + \" \"\r\n\t\t\t\t\t\t\t+ curRefInstance.getTotalErrorCount() + \"
    • \");\r\n\t\r\n\t\t\t\t\tsb.append(\"
        \"); // START reference errors ol\r\n\t\r\n\t\t\t\t\tfor (ReferenceError curRefError : curRefInstance\r\n\t\t\t\t\t\t\t.getReferenceErrors()) {\r\n\t\r\n\t\t\t\t\t\tsb.append(\"
      1. \"\r\n\t\t\t\t\t\t\t\t+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? \"Feedback:\"\r\n\t\t\t\t\t\t\t\t\t\t: \"Error:\") + \" \"\r\n\t\t\t\t\t\t\t\t+ curRefError.getDescription() + \"
      2. \");\r\n\t\r\n\t\t\t\t\t\tsb.append(\"
          \"); // START ul within the curRefError\r\n\t\t\t\t\t\tif (!ApplicationUtil.isEmpty(curRefError\r\n\t\t\t\t\t\t\t\t.getSectionName())) {\r\n\t\t\t\t\t\t\tsb.append(\"
        • \" + \"Related Section: \"\r\n\t\t\t\t\t\t\t\t\t+ curRefError.getSectionName() + \"
        • \");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tsb.append(\"
        • \"\r\n\t\t\t\t\t\t\t\t+ \"Document Line Number (approximate): \"\r\n\t\t\t\t\t\t\t\t+ curRefError.getDocumentLineNumber() + \"
        • \");\r\n\t\t\t\t\t\tsb.append(\"
        • \"\r\n\t\t\t\t\t\t\t\t+ \"xPath: \"\r\n\t\t\t\t\t\t\t\t+ \"\&quot;\r\n\t\t\t\t\t\t\t\t+ curRefError.getxPath() + \&quot;\" + \"
        • \");\r\n\t\t\t\t\t\tsb.append(\"
        \"); // END ul within the curRefError\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tsb.append(\"
      \"); // END reference errors ol\r\n\t\t\t\tsb.append(\"
    \"); // END curRefInstance ul\r\n\t\t\t\tappendBackToTopWithBreaks(sb);\r\n\r\n\t\t\t} //END for (ReferenceResult curRefInstance : referenceResults)\r\n\t\t}\r\n\r\n\t\tfor (Category curCategory : getSortedCategories(categories)) {\r\n\t\t\tif (curCategory.getNumberOfIssues() > 0) {\r\n\t\t\tsb.append(\"

    \" + curCategory.getCategoryName() + \"

    \");\r\n\r\n\t\t\t\tsb.append(\"
      \"); // START curCategory ul\r\n\t\t\t\tsb.append(\"
    • \" + \"Section Grade: \"\r\n\t\t\t\t\t\t+ curCategory.getCategoryGrade() + \"
    • \" + \"
    • \"\r\n\t\t\t\t\t\t+ \"Number of Issues: \"\r\n\t\t\t\t\t\t+ curCategory.getNumberOfIssues() + \"
    • \");\r\n\r\n\t\t\t\t\tsb.append(\"
        \"); // START rules ol\r\n\t\t\t\t\tfor (CCDAScoreCardRubrics curRubric : curCategory\r\n\t\t\t\t\t\t\t.getCategoryRubrics()) {\r\n\t\t\t\t\t\tif (curRubric.getNumberOfIssues() > 0) {\r\n\t\t\t\t\t\t\tsb.append(\"
      1. \" + \"Rule: \" + curRubric.getRule()\r\n\t\t\t\t\t\t\t\t\t+ \"
      2. \");\r\n\t\t\t\t\t\t\tif (curRubric.getDescription() != null) {\r\n\t\t\t\t\t\t\t\tsb.append(\"
          \" + \"
        • \" + \"Description\"\r\n\t\t\t\t\t\t\t\t\t\t+ \"
        • \" + \"
            \" + \"
          • \"\r\n\t\t\t\t\t\t\t\t\t\t+ curRubric.getDescription() + \"
          • \"\r\n\t\t\t\t\t\t\t\t\t\t+ \"
          \" + \"
        \");\r\n\t\t\t\t\t\t\t\tsb.append(\"
        \");\r\n\r\n\t\t\t\t\t\t\t\tsb.append(\"
          \"); // START snippets ol\r\n\t\t\t\t\t\t\t\tfor (CCDAXmlSnippet curSnippet : curRubric\r\n\t\t\t\t\t\t\t\t\t\t.getIssuesList()) {\r\n\t\t\t\t\t\t\t\t\tsb.append(\"
        1. \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ \"XML at line number \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ curSnippet.getLineNumber()\r\n\t\t\t\t\t\t\t\t\t\t\t+ \"
        2. \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ \"
          \&quot;\r\n\t\t\t\t\t\t\t\t\t\t\t+ curSnippet.getXmlString()\r\n\t\t\t\t\t\t\t\t\t\t\t+ \&quot;

          \");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tsb.append(\"
        \"); // END snippets ol\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// don't display rules without occurrences\r\n\t\t\t\t\t\t\tsb.append(\"
      \");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsb.append(\"\"); // END rules ol\r\n\r\n\t\t\t\tsb.append(\"
    \"); // END curCategory ul\r\n\t\t\t\r\n\t\t\tappendBackToTopWithBreaks(sb);\r\n\t\t\t\r\n\t\t\t} //END if (curCategory.getNumberOfIssues() > 0)\r\n\t\t} //END for (Category curCategory : categories)\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate static void appendPictorialGuide(StringBuffer sb,\r\n\t\t\tList categories, List referenceResults) {\t\t\r\n\t\t//minimum breaks based on 11 categories\r\n\t\tsb.append(\"

















    \");\r\n\t\tsb.append(\"

    \" + \"Guide to Interpret the Scorecard Results Table\" + \"

    \");\t\t\r\n\t\t\r\n\t\tsb.append(\"

    \" + \"The following sample table identifies how to use the C-CDA Scorecard results \"\r\n\t\t\t\t\t\t+ \"to improve the C-CDA documents generated by your organization. \" \r\n\t\t+ \"Note: The table below is an example containing fictitious results \"\r\n\t\t+ \"and does not reflect C-CDAs generated by your organization.\" + \"

    \");\r\n\t\t\r\n\t\t//static table\r\n\t\tsb.append(\"\")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\"
    A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.
    The Scorecard grade is a quantitative assessment of the data quality of the submitted document. A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and has higher probability of being interoperable\")\r\n\t\t .append(\" with other organizations.A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.
    Clinical DomainScorecard GradeScorecard IssuesConformance ErrorsCertification FeedbackA Certification Feedback result identifies areas where the generated documents are not compliant with the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.
    The Problems row in this example has an A+ grade and all zeros across the board. This is the most desirable outcome for a Clinical Domain result set.ProblemsA+000
    Lab ResultsA-200
    Vital SignsA-100
    EncountersD1200
    MedicationsN/AN/A20This domain was not scored because the document did not have data pertaining to the clinical domain or there were conformance errors or certification results.
    AllergiesN/AN/A04
    ImmunizationsN/AN/A00
    \");\t\t\r\n\t}\r\n\t\r\n\tprivate static void appendPictorialGuideKey(StringBuffer sb) {\r\n\t\tsb.append(\"

    Additional Guidance to Interpret the Scorecard Results and Achieve Higher Grades

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Scorecard Grade: \")\r\n\t .append(\"The Scorecard grade is a quantitative assessment of the data quality of the submitted document. \"\r\n\t \t\t+ \"A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization \"\r\n\t \t\t+ \"and has higher probability of being interoperable with other organizations. \"\r\n\t \t\t+ \"The grades are derived from the scores as follows: \"\r\n\t \t\t+ \"A+ ( > 94), A- ( 90 to 94), B+ (85 to 89), B- (80 to 84), C (70 to 79) and D (< 70).\")\r\n\t .append(\"

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Scorecard Issues: \")\r\n\t .append(\"A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. \"\r\n\t \t\t+ \"This column should have numbers as close to zero as possible. \"\r\n\t \t\t+ \"The issues are counted for each occurrence of unimplemented best practice. \"\r\n\t \t\t+ \"For example, if a Vital Sign measurement is not using the appropriate UCUM units then each such occurrence would be flagged \"\r\n\t \t\t+ \"as an issue. A provider should work with their health IT vendor to better understand the source for why a best practice \"\r\n\t \t\t+ \"may not be implemented and then determine if it can be implemented in the future. Note: Scorecard Issues will be listed as \"\r\n\t \t\t+ \"'N/A' for a clinical domain, when there is no data for the domain or if there are conformance or certification feedback results.\")\r\n\t .append(\"

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Conformance Errors: \")\r\n\t .append(\"A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. \"\r\n\t \t\t+ \"This column should have zeros ideally. \"\r\n\t \t\t+ \"Providers should work with their health IT vendor to rectify the errors.\")\r\n\t .append(\"

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Certification Feedback: \")\r\n\t .append(\"A Certification Feedback result identifies areas where the generated documents are not compliant with \"\r\n\t \t\t+ \"the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.\"\r\n\t \t\t+ \"Most of these results fall into incorrect use of vocabularies and terminologies. \"\r\n\t \t\t+ \"Although not as severe as a Conformance Error, providers should work with their health IT vendor \"\r\n\t \t\t+ \"to address feedback provided to improve interoperable use of structured data between systems.\")\r\n\t .append(\"

    \");\t\t\r\n\t}\r\n\r\n\tprivate static void appendClosingHtml(StringBuffer sb) {\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\"\");\r\n\t}\r\n\r\n\tprivate static void appendHorizontalRuleWithBreaks(StringBuffer sb) {\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"
    \");\r\n\t}\r\n\r\n\tprivate static void appendBackToTopWithBreaks(StringBuffer sb) {\r\n\t\t// sb.append(\"
    \");\r\n\t\tsb.append(\"Back to Top\");\r\n\t\t// sb.append(\"
    \");\r\n\t\t// A PDF conversion bug is not processing this valid HTML so commenting\r\n\t\t// out until time to address\r\n\t\t// sb.append(\"Back to Section List\");\r\n\t\tsb.append(\"
    \");\r\n\t\t// sb.append(\"
    \");\r\n\t}\r\n\r\n\tprivate static void appendErrorMessage(StringBuffer sb, String errorMessage) {\r\n\t\tsb.append(\"

    \");\r\n\t\tsb.append(errorMessage);\r\n\t\tsb.append(\"

    \"); \r\n\t\tif(!errorMessage.contains(\"HL7 CDA Schema Errors\")) {\r\n\t\t\tsb.append(\"

    \" + ApplicationConstants.ErrorMessages.CONTACT + \"

    \");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static void appendGenericErrorMessage(StringBuffer sb) {\r\n\t\tsb.append(\"

    \"\r\n\t\t\t\t+ ApplicationConstants.ErrorMessages.JSON_TO_JAVA_JACKSON\r\n\t\t\t\t+ \"
    \" + ApplicationConstants.ErrorMessages.CONTACT\r\n\t\t\t\t+ \"

    \");\r\n\t}\r\n\r\n\tprivate static void appendErrorMessageFromReport(StringBuffer sb,\r\n\t\t\tResponseTO report) {\r\n\t\tappendErrorMessageFromReport(sb, report, null);\r\n\t}\r\n\r\n\tprivate static void appendErrorMessageFromReport(StringBuffer sb,\r\n\t\t\tResponseTO report, String extraMessage) {\r\n\t\tif (report.getErrorMessage() != null\r\n\t\t\t\t&& !report.getErrorMessage().isEmpty()) {\r\n\t\t\tboolean hasSchemaErrors = report.getSchemaErrorList() != null && !report.getSchemaErrorList().isEmpty();\r\n\t\t\tif(!hasSchemaErrors) {\r\n\t\t\t\tappendErrorMessage(sb, report.getErrorMessage());\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\"

    \" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART1 + \"

    \");\r\n\t\t\t\tsb.append(\"

    \" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART2 + \"

    \");\r\n\t\t\t\tfinal String noData = \"No data available\";\r\n\t\t\t\tsb.append(\"
      \");\r\n\t\t\t\tfor(ReferenceError schemaError : report.getSchemaErrorList()) {\r\n\t\t\t\t\tsb.append(\"
    1. \");\r\n\t\t\t\t\tsb.append(\"
        \");\r\n\t\t\t\t\tsb.append(\"
      • Message: \" + (schemaError.getDescription() != null ? schemaError.getDescription() : noData));\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      • Path: \" + (schemaError.getxPath() != null ? schemaError.getxPath() : noData));\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      • Line Number (approximate): \" + \r\n\t\t\t\t\t\t\t(schemaError.getDocumentLineNumber() != null ? schemaError.getDocumentLineNumber() : noData));\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      • xPath: \"\r\n\t\t\t\t\t\t\t+ \"\&quot;\r\n\t\t\t\t\t\t\t+ (schemaError.getxPath() != null ? schemaError.getxPath() : noData) + \&quot;\");\r\n\t\t\t\t\tsb.append(\"

        \");\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      \");\r\n\t\t\t\t\tsb.append(\"
    2. \");\r\n\t\t\t\t}\r\n\t\t\t\tsb.append(\"
    \");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tappendGenericErrorMessage(sb);\r\n\t\t}\r\n\t\tif (extraMessage != null && !extraMessage.isEmpty()) {\r\n\t\t\tsb.append(\"

    \" + extraMessage + \"

    \");\r\n\t\t}\r\n\t}\r\n\r\n\tprotected static String ensureLogicalParseTreeInHTML(String htmlReport) {\r\n\t\torg.jsoup.nodes.Document doc = Jsoup.parse(htmlReport);\r\n\t\tString cleanHtmlReport = doc.toString();\r\n\t\treturn cleanHtmlReport;\r\n\t}\r\n\t\r\n\tprivate static void convertHTMLToPDF(String cleanHtmlReport) {\r\n\t\tconvertHTMLToPDF(cleanHtmlReport, null);\r\n\t}\r\n\t\r\n\tprivate static void convertHTMLToPDF(String cleanHtmlReport, HttpServletResponse response) {\r\n\t\tOutputStream out = null;\r\n\t\ttry {\r\n\t\t\tDocumentBuilderFactory factory = DocumentBuilderFactory\r\n\t\t\t\t\t.newInstance();\r\n\t\t\tfactory.setNamespaceAware(false);\r\n\t\t\tfactory.setValidating(false);\r\n\r\n\t\t\tDocumentBuilder builder = factory.newDocumentBuilder();\r\n\t\t\tDocument refinedDoc = builder.parse(new ByteArrayInputStream(\r\n\t\t\t\t\tcleanHtmlReport.getBytes(\"UTF-8\")));\r\n\r\n\t\t\tITextRenderer renderer = new ITextRenderer();\r\n\t\t\trenderer.setDocument(refinedDoc, null);\r\n\t\t\trenderer.layout();\r\n\r\n\t\t\tif(response != null) {\r\n\t\t\t\t//Stream to Output\r\n\t\t\t\tresponse.setContentType(\"application/pdf\");\r\n\t\t\t\tresponse.setHeader(\"Content-disposition\", \"attachment; filename=\"\r\n\t\t\t\t\t\t+ \"scorecardReport.pdf\");\r\n\t\t\t\tresponse.setHeader(\"max-age=3600\", \"must-revalidate\");\r\n\t\t\t\tresponse.addCookie(new Cookie(\"fileDownload=true\", \"path=/\"));\r\n\t\t\t\tout = response.getOutputStream();\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\t//Save to local file system\r\n\t\t\t\tout = new FileOutputStream(new File(\"testSaveReportImplementation.pdf\"));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\trenderer.createPDF(out);\r\n\t\t} catch (ParserConfigurationException pcE) {\r\n\t\t\tpcE.printStackTrace();\r\n\t\t} catch (SAXException saxE) {\r\n\t\t\tsaxE.printStackTrace();\r\n\t\t} catch (DocumentException docE) {\r\n\t\t\tdocE.printStackTrace();\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (out != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tout.flush();\r\n\t\t\t\t\tout.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(LOG_HTML) {\r\n\t\t\t\tApplicationUtil.debugLog(\"cleanHtmlReport\", cleanHtmlReport);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprotected static void convertHTMLToPDFAndStreamToOutput(\r\n\t\t\tString cleanHtmlReport, HttpServletResponse response) {\r\n\t\tconvertHTMLToPDF(cleanHtmlReport, response);\r\n\t}\r\n\t\r\n\tprivate static void convertHTMLToPDFAndSaveToLocalFileSystem(String cleanHtmlReport) {\r\n\t\tconvertHTMLToPDF(cleanHtmlReport);\r\n\t}\r\n\r\n\t/**\r\n\t * Converts JSON to ResponseTO Java Object using The Jackson API\r\n\t * \r\n\t * @param jsonReportData\r\n\t * JSON which resembles ResponseTO\r\n\t * @return converted ResponseTO POJO\r\n\t */\r\n\tprotected static ResponseTO convertJsonToPojo(String jsonReportData) {\r\n\t\tObjectMapper mapper = new ObjectMapper();\r\n\t\tResponseTO pojo = null;\r\n\t\ttry {\r\n\t\t\tpojo = mapper.readValue(jsonReportData, ResponseTO.class);\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn pojo;\r\n\t}\r\n\t\r\n\tpublic enum SaveReportType {\r\n\t\tMATCH_UI, SUMMARY;\r\n\t}\r\n\t\r\n\tprivate static void buildReportUsingJSONFromLocalFile(String filenameWithoutExtension, \r\n\t\t\tSaveReportType reportType) throws URISyntaxException {\r\n\t\tURI jsonFileURI = new File(\r\n\t\t\t\t\"src/main/webapp/resources/\"\r\n\t\t\t\t\t\t+ filenameWithoutExtension + \".json\").toURI();\t\t\r\n\t\tSystem.out.println(\"jsonFileURI\");\r\n\t\tSystem.out.println(jsonFileURI);\r\n\t\tString jsonReportData = convertFileToString(jsonFileURI);\r\n\t\tSystem.out.println(\"jsonReportData\");\r\n\t\tSystem.out.println(jsonReportData);\r\n\t\tResponseTO pojoResponse = convertJsonToPojo(jsonReportData);\r\n\t\tSystem.out.println(\"response\");\r\n\t\tSystem.out.println(pojoResponse.getCcdaDocumentType());\r\n\t\t\r\n\t\tconvertHTMLToPDFAndSaveToLocalFileSystem(\r\n\t\t\t\tensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)));\t\t\r\n\t}\r\n\t\r\n\tprivate static String convertFileToString(URI fileURI) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tBufferedReader br = null;\r\n\t\ttry {\r\n\t\t\tbr = new BufferedReader(new FileReader(fileURI.getPath()));\r\n\t\t\tString sCurrentLine = \"\";\r\n\t\t\twhile ((sCurrentLine = br.readLine()) != null) {\r\n\t\t\t\tsb.append(sCurrentLine);\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} finally {\r\n\t\t\ttry {\r\n\t\t\t\tbr.close();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sb.toString();\r\n\t}\t\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\tString[] filenames = {\"highScoringSample\", \"lowScoringSample\", \"sampleWithErrors\", \r\n\t\t\t\t\"sampleWithSchemaErrors\", \"sampleWithoutAnyContent\"};\r\n\t\tfinal int HIGH_SCORING_SAMPLE = 0, LOW_SCORING_SAMPLE = 1, SAMPLE_WITH_ERRORS = 2, \r\n\t\t\t\tSAMPLE_WITH_SCHEMA_ERRORS = 3, SAMPLE_WITHOUT_ANY_CONTENT = 4;\r\n\t\ttry {\r\n\t\t\tbuildReportUsingJSONFromLocalFile(filenames[SAMPLE_WITH_ERRORS], SaveReportType.SUMMARY);\r\n\t\t} catch (URISyntaxException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\t\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"src/main/java/org/sitenv/service/ccda/smartscorecard/controller/SaveReportController.java"},"old_contents":{"kind":"string","value":"package org.sitenv.service.ccda.smartscorecard.controller;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.ByteArrayInputStream;\r\nimport java.io.File;\r\nimport java.io.FileOutputStream;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.io.OutputStream;\r\nimport java.net.URI;\r\nimport java.net.URISyntaxException;\r\nimport java.nio.charset.Charset;\r\nimport java.text.DateFormat;\r\nimport java.text.SimpleDateFormat;\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.Date;\r\nimport java.util.List;\r\n\r\nimport javax.servlet.http.Cookie;\r\nimport javax.servlet.http.HttpServletResponse;\r\nimport javax.xml.parsers.DocumentBuilder;\r\nimport javax.xml.parsers.DocumentBuilderFactory;\r\nimport javax.xml.parsers.ParserConfigurationException;\r\n\r\nimport org.apache.commons.io.IOUtils;\r\nimport org.jsoup.Jsoup;\r\nimport org.sitenv.ccdaparsing.model.CCDAXmlSnippet;\r\nimport org.sitenv.service.ccda.smartscorecard.cofiguration.ApplicationConfiguration;\r\nimport org.sitenv.service.ccda.smartscorecard.model.CCDAScoreCardRubrics;\r\nimport org.sitenv.service.ccda.smartscorecard.model.Category;\r\nimport org.sitenv.service.ccda.smartscorecard.model.ReferenceError;\r\nimport org.sitenv.service.ccda.smartscorecard.model.ReferenceResult;\r\nimport org.sitenv.service.ccda.smartscorecard.model.ReferenceTypes.ReferenceInstanceType;\r\nimport org.sitenv.service.ccda.smartscorecard.model.ResponseTO;\r\nimport org.sitenv.service.ccda.smartscorecard.model.Results;\r\nimport org.sitenv.service.ccda.smartscorecard.processor.ScorecardProcessor;\r\nimport org.sitenv.service.ccda.smartscorecard.util.ApplicationConstants;\r\nimport org.sitenv.service.ccda.smartscorecard.util.ApplicationUtil;\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.core.io.FileSystemResource;\r\nimport org.springframework.http.HttpEntity;\r\nimport org.springframework.http.HttpHeaders;\r\nimport org.springframework.http.MediaType;\r\nimport org.springframework.http.converter.FormHttpMessageConverter;\r\nimport org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;\r\nimport org.springframework.util.LinkedMultiValueMap;\r\nimport org.springframework.web.bind.annotation.RequestBody;\r\nimport org.springframework.web.bind.annotation.RequestMapping;\r\nimport org.springframework.web.bind.annotation.RequestMethod;\r\nimport org.springframework.web.bind.annotation.RequestParam;\r\nimport org.springframework.web.bind.annotation.RestController;\r\nimport org.springframework.web.client.RestTemplate;\r\nimport org.springframework.web.multipart.MultipartFile;\r\nimport org.w3c.dom.Document;\r\nimport org.xhtmlrenderer.pdf.ITextRenderer;\r\nimport org.xml.sax.SAXException;\r\n\r\nimport com.fasterxml.jackson.databind.ObjectMapper;\r\nimport com.lowagie.text.DocumentException;\r\n\r\n@RestController\r\npublic class SaveReportController {\r\n\t\r\n\t@Autowired\r\n\tprivate ScorecardProcessor scorecardProcessor;\t\r\n\r\n\tpublic static final String SAVE_REPORT_CHARSET_NAME = \"UTF8\";\r\n\tprivate static final int CONFORMANCE_ERROR_INDEX = 0;\r\n\tprivate static final int CERTIFICATION_FEEDBACK_INDEX = 1;\r\n\tprivate static final boolean LOG_HTML = true;\r\n\r\n\t/**\r\n\t * Converts received JSON to a ResponseTO POJO (via method signature\r\n\t * automagically), converts the ResponseTO to a cleaned (parsable) HTML\r\n\t * report including relevant data, converts the HTML to a PDF report, and,\r\n\t * finally, streams the data for consumption. \r\n\t * This is intended to be called from a frontend which has already collected the JSON results.\r\n\t * \r\n\t * @param jsonReportData\r\n\t * JSON which resembles ResponseTO\r\n\t * @param response\r\n\t * used to stream the PDF\r\n\t */\r\n\t@RequestMapping(value = \"/savescorecardservice\", method = RequestMethod.POST)\r\n\tpublic void savescorecardservice(@RequestBody ResponseTO jsonReportData,\r\n\t\t\tHttpServletResponse response) {\r\n\t\tconvertHTMLToPDFAndStreamToOutput(\r\n\t\t\t\tensureLogicalParseTreeInHTML(convertReportToHTML(jsonReportData, SaveReportType.MATCH_UI)),\r\n\t\t\t\tresponse);\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * A single service to handle a pure back-end implementation of the\r\n\t * scorecard which streams back a PDF report. \r\n\t * This does not require the completed JSON up-front, it creates it from the file sent.\r\n\t * \r\n\t * @param ccdaFile\r\n\t * The C-CDA XML file intended to be scored\r\n\t */\r\n\t@RequestMapping(value = \"/savescorecardservicebackend\", method = RequestMethod.POST)\r\n\tpublic void savescorecardservicebackend(\r\n\t\t\t@RequestParam(\"ccdaFile\") MultipartFile ccdaFile,\r\n\t\t\tHttpServletResponse response) {\r\n\t\thandlePureBackendCall(ccdaFile, response, SaveReportType.MATCH_UI, scorecardProcessor);\r\n\t}\r\n\t\r\n\t/**\r\n\t * A single service to handle a pure back-end implementation of the\r\n\t * scorecard which streams back a PDF report. \r\n\t * This does not require the completed JSON up-front, it creates it from the file sent.\r\n\t * This differs from the savescorecardservicebackend in that it has its own specific format of the results \r\n\t * (dynamic and static table with 'call outs', no filename, more overview type content, etc.) \r\n\t * and is intended to be used when a Direct Message is received with a C-CDA document.\r\n\t * \r\n\t * @param ccdaFile\r\n\t * The C-CDA XML file intended to be scored\r\n\t * @param sender\r\n\t * \t\t\t The email address of the sender to be logged in the report\r\n\t */\r\n\t@RequestMapping(value = \"/savescorecardservicebackendsummary\", method = RequestMethod.POST)\r\n\tpublic void savescorecardservicebackendsummary(\r\n\t\t\t@RequestParam(\"ccdaFile\") MultipartFile ccdaFile, @RequestParam(\"sender\") String sender,\r\n\t\t\tHttpServletResponse response) {\r\n\t\tif(ApplicationUtil.isEmpty(sender)) {\r\n\t\t\tsender = \"Unknown Sender\";\r\n\t\t}\r\n\t\thandlePureBackendCall(ccdaFile, response, SaveReportType.SUMMARY, scorecardProcessor, sender);\r\n\t}\r\n\t\r\n\tprivate static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType, \r\n\t\t\tScorecardProcessor scorecardProcessor) {\r\n\t\thandlePureBackendCall(ccdaFile, response, reportType, scorecardProcessor, \"savescorecardservicebackend\");\r\n\t}\r\n\t\r\n\tprivate static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType, \r\n\t\t\tScorecardProcessor scorecardProcessor, String sender) {\r\n\t\tResponseTO pojoResponse = callCcdascorecardserviceInternally(ccdaFile, scorecardProcessor, sender, reportType);\r\n\t\tif (pojoResponse == null) {\r\n\t\t\tpojoResponse = new ResponseTO();\r\n\t\t\tpojoResponse.setResults(null);\r\n\t\t\tpojoResponse.setSuccess(false);\r\n\t\t\tpojoResponse\r\n\t\t\t\t\t.setErrorMessage(ApplicationConstants.ErrorMessages.NULL_RESULT_ON_SAVESCORECARDSERVICEBACKEND_CALL);\r\n\t\t} else {\r\n\t\t\tif (!ApplicationUtil.isEmpty(ccdaFile.getOriginalFilename())\r\n\t\t\t\t\t&& ccdaFile.getOriginalFilename().contains(\".\")) {\r\n\t\t\t\tpojoResponse.setFilename(ccdaFile.getOriginalFilename());\r\n\t\t\t} else if (!ApplicationUtil.isEmpty(ccdaFile.getName())\r\n\t\t\t\t\t&& ccdaFile.getName().contains(\".\")) {\r\n\t\t\t\tpojoResponse.setFilename(ccdaFile.getName());\r\n\t\t\t}\r\n\t\t\tif(ApplicationUtil.isEmpty(pojoResponse.getFilename())) {\r\n\t\t\t\tpojoResponse.setFilename(\"Unknown\");\r\n\t\t\t}\r\n\t\t\t// otherwise it uses the name given by ccdascorecardservice\r\n\t\t}\r\n\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\tpojoResponse.setFilename(sender);\r\n\t\t}\r\n\t\tconvertHTMLToPDFAndStreamToOutput(\r\n\t\t\t\tensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)),\r\n\t\t\t\tresponse);\r\n\t};\r\n\t\r\n\tprotected static ResponseTO callCcdascorecardserviceInternally(MultipartFile ccdaFile, \r\n\t\t\tScorecardProcessor scorecardProcessor, String sender, SaveReportType reportType) {\r\n\t\treturn scorecardProcessor.processCCDAFile(ccdaFile, reportType == SaveReportType.SUMMARY, sender);\r\n\t}\r\n\r\n\tpublic static ResponseTO callCcdascorecardserviceExternally(MultipartFile ccdaFile) {\r\n\t\tString endpoint = ApplicationConfiguration.CCDASCORECARDSERVICE_URL;\r\n\t\treturn callServiceExternally(endpoint, ccdaFile, null);\r\n\t}\t\r\n\r\n\tpublic static ResponseTO callSavescorecardservicebackendExternally(MultipartFile ccdaFile) {\r\n\t\tString endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKEND_URL;\r\n\t\treturn callServiceExternally(endpoint, ccdaFile, null);\r\n\t}\r\n\t\r\n\tpublic static ResponseTO callSavescorecardservicebackendsummaryExternally(MultipartFile ccdaFile, String senderValue) {\r\n\t\tString endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKENDSUMMARY_URL;\r\n\t\treturn callServiceExternally(endpoint, ccdaFile, senderValue);\r\n\t}\r\n\t\r\n\tprivate static ResponseTO callServiceExternally(String endpoint, MultipartFile ccdaFile, String senderValue) {\r\n\t\tResponseTO pojoResponse = null;\r\n\r\n\t\tLinkedMultiValueMap requestMap = new LinkedMultiValueMap<>();\r\n\t\tFileOutputStream out = null;\r\n\t\tFile tempFile = null;\r\n\t\ttry {\r\n\t\t\tfinal String tempCcdaFileName = \"ccdaFile\";\r\n\t\t\ttempFile = File.createTempFile(tempCcdaFileName, \"xml\");\r\n\t\t\tout = new FileOutputStream(tempFile);\r\n\t\t\tIOUtils.copy(ccdaFile.getInputStream(), out);\r\n\t\t\trequestMap.add(tempCcdaFileName, new FileSystemResource(tempFile));\r\n\t\t\tif(senderValue != null) {\r\n\t\t\t\tString senderKey = \"sender\";\r\n\t\t\t\trequestMap.add(senderKey, senderValue);\r\n\t\t\t}\r\n\r\n\t\t\tHttpHeaders headers = new HttpHeaders();\r\n\t\t\theaders.setContentType(MediaType.MULTIPART_FORM_DATA);\r\n\t\t\tHttpEntity> requestEntity = new HttpEntity<>(\r\n\t\t\t\t\trequestMap, headers);\r\n\r\n\t\t\tFormHttpMessageConverter formConverter = new FormHttpMessageConverter();\r\n\t\t\tformConverter.setCharset(Charset.forName(SAVE_REPORT_CHARSET_NAME));\r\n\t\t\tRestTemplate restTemplate = new RestTemplate();\r\n\t\t\trestTemplate.getMessageConverters().add(formConverter);\r\n\t\t\trestTemplate.getMessageConverters().add(\r\n\t\t\t\t\tnew MappingJackson2HttpMessageConverter());\r\n\r\n\t\t\tpojoResponse = restTemplate.postForObject(endpoint, requestEntity, ResponseTO.class);\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (out != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tout.flush();\r\n\t\t\t\t\tout.close();\r\n\t\t\t\t} catch (IOException ioe) {\r\n\t\t\t\t\tioe.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (tempFile != null && tempFile.isFile()) {\r\n\t\t\t\ttempFile.delete();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn pojoResponse;\r\n\t}\t\r\n\r\n\t/**\r\n\t * Parses (POJO ResponseTO converted) JSON and builds the results into an\r\n\t * HTML report\r\n\t * \r\n\t * @param report\r\n\t * the ResponseTO report intended to be converted to HTML\r\n\t * @return the converted HTML report as a String\r\n\t */\r\n\tprotected static String convertReportToHTML(ResponseTO report, SaveReportType reportType) {\r\n\t\tStringBuffer sb = new StringBuffer();\r\n\t\tappendOpeningHtml(sb);\r\n\r\n\t\tif (report == null) {\r\n\t\t\treport = new ResponseTO();\r\n\t\t\treport.setResults(null);\r\n\t\t\treport.setSuccess(false);\r\n\t\t\treport.setErrorMessage(ApplicationConstants.ErrorMessages.GENERIC_WITH_CONTACT);\r\n\t\t\tappendErrorMessageFromReport(sb, report,\r\n\t\t\t\t\tApplicationConstants.ErrorMessages.RESULTS_ARE_NULL);\r\n\t\t} else {\r\n\t\t\t// report != null\r\n\t\t\tif (report.getResults() != null) {\r\n\t\t\t\tif (report.isSuccess()) {\r\n\t\t\t\t\tResults results = report.getResults();\r\n\t\t\t\t\tList categories = results.getCategoryList();\r\n\t\t\t\t\tList referenceResults = report\r\n\t\t\t\t\t\t\t.getReferenceResults();\r\n\r\n\t\t\t\t\tappendHeader(sb, report, results, reportType);\r\n\t\t\t\t\tappendHorizontalRuleWithBreaks(sb);\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\t\t\t\tappendPreTopLevelResultsContent(sb);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tappendTopLevelResults(sb, results, categories,\r\n\t\t\t\t\t\t\treferenceResults, reportType, report.getCcdaDocumentType());\r\n\t\t\t\t\tif(reportType == SaveReportType.MATCH_UI) {\r\n\t\t\t\t\t\tappendHorizontalRuleWithBreaks(sb);\r\n\t\t\t\t\t\tappendHeatmap(sb, results, categories,\r\n\t\t\t\t\t\t\t\treferenceResults);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsb.append(\"
    \");\r\n\t\t\t\t\tappendHorizontalRuleWithBreaks(sb);\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(reportType == SaveReportType.MATCH_UI) {\r\n\t\t\t\t\t\tif(!ApplicationUtil.isEmpty(report.getReferenceResults()) || results.getNumberOfIssues() > 0) {\r\n\t\t\t\t\t\t\tappendDetailedResults(sb, categories, referenceResults);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\t\t\t\t/*\r\n\t\t\t\t\t\tappendPictorialGuide(sb, categories, referenceResults);\r\n\t\t\t\t\t\tappendPictorialGuideKey(sb);\r\n\t\t\t\t\t\t*/\r\n\t\t\t\t\t} \t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\t// report.getResults() == null\r\n\t\t\t\tif (!report.isSuccess()) {\r\n\t\t\t\t\tappendErrorMessageFromReport(sb, report, null);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tappendErrorMessageFromReport(sb, report);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tappendClosingHtml(sb);\r\n\t\treturn sb.toString();\r\n\t}\r\n\r\n\tprivate static void appendOpeningHtml(StringBuffer sb) {\r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\"SITE C-CDA Scorecard Report\");\r\n\t\tappendStyleSheet(sb);\r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\"\");\r\n\t}\r\n\t\r\n\tprivate static void appendStyleSheet(StringBuffer sb) {\r\n\t\t sb.append(\" \");\r\n\t}\r\n\r\n\tprivate static void appendHeader(StringBuffer sb, ResponseTO report,\r\n\t\t\tResults results, SaveReportType reportType) {\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"
    \");\r\n\t\t\r\n\t\tsb.append(\"
    \")\r\n\t .append(\" \\\"HealthIT.gov\\\"\")\r\n\t\")\r\n\t .append(\" \")\r\n\t .append(\"
    \");\t\t\r\n\r\n\t\tsb.append(\"
    \");\r\n\t\tappendHorizontalRuleWithBreaks(sb);\r\n\r\n\t\tsb.append(\"

    \" + \"C-CDA \");\r\n\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\tsb.append(\"Scorecard For \"\r\n\t\t\t\t\t+ (report.getCcdaDocumentType() != null ? report\r\n\t\t\t\t\t\t\t.getCcdaDocumentType() : \"document\") + \"

    \");\r\n\t\t\tsb.append(\"
    \");\r\n\t\t\tsb.append(\"\" + \"Submitted By: \"\r\n\t\t\t+ (!ApplicationUtil.isEmpty(report.getFilename()) ? report.getFilename() : \"Unknown\")\r\n\t\t\t+ \"\");\r\n\t\t\tDateFormat dateFormat = new SimpleDateFormat(\"MM/dd/yyyy HH:mm:ss\");\r\n\t\t\tsb.append(\"\" + \"Submission Time: \" + dateFormat.format(new Date()) + \"\");\r\n\t\t\tsb.append(\"
    \");\r\n\t\t\tsb.append(\"
    \");\t\t\t\r\n\t\t\tappendBasicResults(sb, results);\t\t\t\r\n\t\t} else {\r\n\t\t\tsb.append(results.getCcdaVersion() + \" \" \r\n\t\t\t\t\t+ (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : \"document\") \r\n\t\t\t\t\t+ \" Scorecard For:\" + \"\");\t\t\r\n\t\t\tsb.append(\"

    \" + report.getFilename() + \"

    \");\r\n\t\t}\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"
    \");\r\n\t}\r\n\t\r\n\tprivate static void appendPreTopLevelResultsContent(StringBuffer sb) {\r\n\t\t/*\r\n\t\tsb.append(\"

    \")\r\n\t .append(\" The C-CDA Scorecard enables providers, implementers, and health\")\r\n\t .append(\" IT professionals with a tool that compares how artifacts (transition\")\r\n\t .append(\" of care documents, care plans etc) created by your organization\")\r\n\t .append(\" stack up against the HL7 C-CDA implementation guide and HL7 best\")\r\n\t .append(\" practices. The C-CDA Scorecard promotes best practices in C-CDA\")\r\n\t .append(\" implementation by assessing key aspects of the structured data found\")\r\n\t .append(\" in individual documents. The Scorecard tool provides a rough\")\r\n\t .append(\" quantitative assessment and highlights areas of improvement which\")\r\n\t .append(\" can be made today to move the needle forward in interoperability of\")\r\n\t .append(\" C-CDA documents. The \")\r\n\t .append(\" \"\r\n\t \t\t\t+ \"best practices and quantitative scoring criteria\"\r\n\t \t\t\t+ \"\")\r\n\t .append(\" have been developed by HL7 through the HL7-ONC Cooperative agreement\")\r\n\t .append(\" to improve the implementation of health care standards. We hope that\")\r\n\t .append(\" providers and health IT developers will use the tool to identify and\")\r\n\t .append(\" resolve issues around C-CDA document interoperability in their\")\r\n\t .append(\" health IT systems.\")\r\n\t .append(\"

    \")\r\n\t */\r\n\t\t\r\n\t\tsb.append(\"

    If you are not satisfied with your results:

    \");\r\n\t\tsb.append(\"
      \");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\t\tsb.append(\"Please ask your vendor to submit the document to the SITE C-CDA Scorecard website \"\r\n\t\t\t\t\t\t+ \" at \" + \"\" + \"www.healthit.gov/scorecard\" + \"\"\r\n\t\t\t\t\t\t+ \" for more detailed information\");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\t\tsb.append(\"Using the results provided by the online tool, \"\r\n\t\t\t\t\t\t+ \"your vendor can update or provide insight on how to update your document to meet the latest HL7 best-practices\");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\t\tsb.append(\"Once updated, \"\r\n\t\t\t\t\t\t+ \"resubmitting your document to the ONC One Click Scorecard will produce a report with a higher score \"\r\n\t\t\t\t\t\t+ \"and/or less or no conformance errors or less or no certification feedback results\");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\tsb.append(\"
    \");\r\n\t\t\r\n\t sb.append(\"

    \")\r\n\t .append(\"This page contains a summary of the C-CDA Scorecard results highlighting the overall document grade \"\r\n\t \t\t+ \"which is derived from a quantitative score out of a maximum of 100. \")\r\n\t .append(\"

    \");\r\n\t sb.append(\"

    \")\r\n\t .append(\"The second and final page identifies areas for improvement organized by clinical domains.\")\r\n\t .append(\"

    \");\r\n\t}\r\n\t\r\n\tprivate static void appendBasicResults(StringBuffer sb, Results results) {\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"

    \");\r\n\t\tsb.append(\"Grade: \" + results.getFinalGrade() + \"\"); \r\n\t\tsb.append(\"Score: \" + results.getFinalNumericalGrade() + \"/100\" + \"\");\r\n\t\tsb.append(\"

    \");\r\n\t\tsb.append(\"
    \");\r\n\t}\r\n\t\r\n\tprivate static void appendTopLevelResults(StringBuffer sb, Results results,\r\n\t\t\tList categories, List referenceResults, SaveReportType reportType, String ccdaDocumentType) {\r\n\t\t\r\n\t\tboolean isReferenceResultsEmpty = ApplicationUtil.isEmpty(referenceResults);\r\n\t\tint conformanceErrorCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CONFORMANCE_ERROR_INDEX).getTotalErrorCount();\r\n\t\tint certificationFeedbackCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getTotalErrorCount();\r\n\t\tif(reportType == SaveReportType.SUMMARY) {\r\n\t\t\t//brief summary of overall document results (without scorecard issues count listed)\r\n\t\t\tsb.append(\"

    Summary

    \");\r\n\t\t\tsb.append(\"

    \"\r\n\t\t\t\t\t+ \"Your \" + ccdaDocumentType + \" document received a grade of \" + results.getFinalGrade() + \"\"\r\n\t\t\t\t\t+ \" compared to an industry average of \" + \"\" + results.getIndustryAverageGradeForCcdaDocumentType() + \"\" + \". \"\r\n\t\t\t\t\t+ \"The industry average, specific to the document type sent, was computed by scoring \" \r\n\t\t\t\t\t+ results.getNumberOfDocsScoredPerCcdaDocumentType() + \" \" + ccdaDocumentType + \r\n\t\t\t\t\t(results.getNumberOfDocsScoredPerCcdaDocumentType() > 1 ? \"s\" : \"\" ) + \". \" \r\n\t\t\t\t\t+ \"The document scored \" + \"\" + results.getFinalNumericalGrade() + \"/100\" + \"\"\r\n\t\t\t\t\t+ \" and is \"\r\n\t\t\t\t\t+ (conformanceErrorCount > 0 ? \"non-compliant\" : \"compliant\")\r\n\t\t\t\t\t+ \" with the HL7 C-CDA IG\"\r\n\t\t\t\t\t+ \" and is \"\r\n\t\t\t\t\t+ (certificationFeedbackCount > 0 ? \"non-compliant\" : \"compliant\")\r\n\t\t\t\t\t+ \" with 2015 Edition Certification requirements. \"\r\n\t\t\t\t\t+ \"The detailed results organized by clinical domains are provided in the table below:\"\r\n\t\t\t\t\t+ \"

    \");\r\n\t\t\t//dynamic table\r\n\t\t\tappendHorizontalRuleWithBreaks(sb);\r\n\t\t\tsb.append(\"

    \");\r\n\t\t\tsb.append(\"

    Scorecard Results by Clinical Domain

    \");\r\n\t\t\tappendDynamicTopLevelResultsTable(sb, results, categories, referenceResults);\r\n\t\t} else {\t\t\r\n\t\t\tsb.append(\"

    Scorecard Grade: \" + results.getFinalGrade() + \"

    \");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\tsb.append(\"

      Your document scored a \" + \"\"\r\n\t\t\t\t\t+ results.getFinalGrade() + \"\"\r\n\t\t\t\t\t+ \" compared to an industry average of \" + \"\"\r\n\t\t\t\t\t+ results.getIndustryAverageGrade() + \"\" + \".

      \");\r\n\t\t\tsb.append(\"
  • \");\r\n\t\r\n\t\t\tsb.append(\"

    Scorecard Score: \" + results.getFinalNumericalGrade()\r\n\t\t\t\t\t+ \"

    \");\r\n\t\t\tsb.append(\"
    • \");\r\n\t\t\tsb.append(\"

      Your document scored \" + \"\"\r\n\t\t\t\t\t+ +results.getFinalNumericalGrade() + \"\" + \" out of \"\r\n\t\t\t\t\t+ \"\" + \" 100 \" + \"\" + \" total possible points.

      \");\r\n\t\t\tsb.append(\"
    \");\r\n\t\r\n\t\t\tboolean isSingular = results.getNumberOfIssues() == 1;\r\n\t\t\tappendSummaryRow(sb, results.getNumberOfIssues(), \"Scorecard Issues\",\r\n\t\t\t\t\tnull, isSingular ? \"Scorecard Issue\" : \"Scorecard Issues\",\r\n\t\t\t\t\tisSingular);\r\n\t\t\tsb.append(\"
\");\r\n\t\r\n\t\t\tString messageSuffix = null;\r\n\t\t\tif (isReferenceResultsEmpty) {\r\n\t\t\t\tfor (ReferenceInstanceType refType : ReferenceInstanceType.values()) {\r\n\t\t\t\t\tif (refType == ReferenceInstanceType.CERTIFICATION_2015) {\r\n\t\t\t\t\t\tmessageSuffix = \"results\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tappendSummaryRow(sb, 0, refType.getTypePrettyName(),\r\n\t\t\t\t\t\t\tmessageSuffix, refType.getTypePrettyName(), false, reportType);\r\n\t\t\t\t\tsb.append(\"\");\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tfor (ReferenceResult refResult : referenceResults) {\r\n\t\t\t\t\tint refErrorCount = refResult.getTotalErrorCount();\r\n\t\t\t\t\tisSingular = refErrorCount == 1;\r\n\t\t\t\t\tString refTypeName = refResult.getType().getTypePrettyName();\r\n\t\t\t\t\tString messageSubject = \"\";\r\n\t\t\t\t\tif (refResult.getType() == ReferenceInstanceType.IG_CONFORMANCE) {\r\n\t\t\t\t\t\tmessageSubject = isSingular ? refTypeName.substring(0,\r\n\t\t\t\t\t\t\t\trefTypeName.length() - 1) : refTypeName;\r\n\t\t\t\t\t} else if (refResult.getType() == ReferenceInstanceType.CERTIFICATION_2015) {\r\n\t\t\t\t\t\tmessageSuffix = isSingular ? \"result\" : \"results\";\r\n\t\t\t\t\t\tmessageSubject = refTypeName;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tappendSummaryRow(sb, refErrorCount, refTypeName, messageSuffix,\r\n\t\t\t\t\t\t\tmessageSubject, isSingular, reportType);\r\n\t\t\t\t\tsb.append(\"\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate static int getFailingSectionSpecificErrorCount(String categoryName,\r\n\t\t\tReferenceInstanceType refType, List referenceResults) {\r\n\t\tif (!ApplicationUtil.isEmpty(referenceResults)) {\r\n\t\t\tif (refType == ReferenceInstanceType.IG_CONFORMANCE) {\r\n\t\t\t\tList igErrors = \r\n\t\t\t\t\t\treferenceResults.get(CONFORMANCE_ERROR_INDEX).getReferenceErrors();\r\n\t\t\t\tif (!ApplicationUtil.isEmpty(igErrors)) {\r\n\t\t\t\t\treturn getFailingSectionSpecificErrorCountProcessor(categoryName, igErrors);\r\n\t\t\t\t}\r\n\t\t\t} else if (refType == ReferenceInstanceType.CERTIFICATION_2015) {\r\n\t\t\t\tList certErrors = \r\n\t\t\t\t\t\treferenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getReferenceErrors();\r\n\t\t\t\tif (!ApplicationUtil.isEmpty(certErrors)) {\r\n\t\t\t\t\treturn getFailingSectionSpecificErrorCountProcessor(categoryName, certErrors);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tprivate static int getFailingSectionSpecificErrorCountProcessor(\r\n\t\t\tString categoryName, List errors) {\r\n\t\tint count = 0;\r\n\t\tfor (int i = 0; i < errors.size(); i++) {\r\n\t\t\tString currentSectionInReferenceErrors = errors.get(i).getSectionName();\r\n\t\t\tif (!ApplicationUtil.isEmpty(currentSectionInReferenceErrors)) {\r\n\t\t\t\tif (currentSectionInReferenceErrors.equalsIgnoreCase(categoryName)) {\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn count;\r\n\t}\r\n\t\r\n\tprivate static void appendDynamicTopLevelResultsTable(StringBuffer sb, Results results,\r\n\t\t\tList categories, List referenceResults) { \r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" \");\t\t\t\t\r\n\t\tfor(Category category : getSortedCategories(categories)) {\r\n//\t\t\tif(category.getNumberOfIssues() > 0 || referenceResults.get(ReferenceInstanceType.IG/CERT).getTotalErrorCount() > 0) {\r\n//\t\t\tif(category.getNumberOfIssues() > 0 || category.isFailingConformance() || category.isCertificationFeedback()) {\t\t\t\t\r\n\t\t\tsb.append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \");\r\n//\t\t\t}\r\n\t\t}\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\"
\");\r\n\t\tsb.append(\" The Scorecard grade is a quantitative assessment of the data quality of the submitted document. \"\r\n\t\t\t\t+ \"A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and \"\r\n\t\t\t\t+ \"has higher probability of being interoperable with other organizations.\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" A Scorecard Issue identifies data within the document which can be represented in a better way using \"\r\n\t\t\t\t+ \"HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. \"\r\n\t\t\t\t+ \"This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.\");\r\n\t\tsb.append(\" \");\r\n\t\tsb.append(\" A Certification Feedback result identifies areas where the generated documents are not compliant with \"\r\n\t\t\t\t+ \"the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.\");\r\n\t\tsb.append(\"
Clinical DomainScorecard GradeScorecard IssuesConformance ErrorsCertification Feedback
\" + (category.getCategoryName() != null ? category.getCategoryName() : \"Unknown\") + \"\" + (category.getCategoryGrade() != null ? category.getCategoryGrade() : \"N/A\") + \"\" + (category.isFailingConformance() || category.isCertificationFeedback() || category.isNullFlavorNI() \r\n\t\t \t\t ? \"N/A\" \r\n\t\t \t\t : category.getNumberOfIssues()) \r\n\t\t \t\t + \"\" \r\n\t\t + (!ApplicationUtil.isEmpty(category.getCategoryName()) \r\n\t\t \t\t ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults) \r\n\t\t \t\t : \"N/A\")\r\n\t\t + \"\" \r\n\t\t + (!ApplicationUtil.isEmpty(category.getCategoryName()) \r\n\t\t \t\t ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults) \r\n\t\t \t\t : \"N/A\") \r\n\t\t + \"
\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Order from best to worst:
\r\n\t * 1. Numerical score high to low 2. Empty/null 3. Certification Feedback 4. Conformance Error\r\n\t * @param categories - Category List to sort\r\n\t * @return sorted categories\r\n\t */\r\n\tprivate static List getSortedCategories(List categories) {\r\n\t\tList sortedCategories = new ArrayList(categories);\r\n\t\t//prepare for sort of non-scored items\r\n\t\tfor(Category category : sortedCategories) {\r\n\t\t\tif(category.isFailingConformance()) {\r\n\t\t\t\tcategory.setCategoryNumericalScore(-3);\r\n\t\t\t} else if(category.isCertificationFeedback()) {\r\n\t\t\t\tcategory.setCategoryNumericalScore(-2);\r\n\t\t\t} else if(category.isNullFlavorNI()) {\r\n\t\t\t\tcategory.setCategoryNumericalScore(-1);\r\n\t\t\t}\r\n\t\t}\r\n\t\t//sorts by numerical score via Comparable implementation in Category\r\n\t\tCollections.sort(sortedCategories, Collections.reverseOrder());\r\n\t\treturn sortedCategories;\r\n\t}\r\n\t\r\n\tprivate static void appendHeatmap(StringBuffer sb, Results results,\r\n\t\t\tList categories, List referenceResults) {\r\n\t\t\r\n\t\tsb.append(\"\" + \"\");\r\n\t\tfor (Category curCategory : getSortedCategories(categories)) {\r\n\t\t\tsb.append(\"

\" \r\n\t\t\t\t\t+ (curCategory.getNumberOfIssues() > 0 \r\n\t\t\t\t\t\t\t? \"\" : \"\")\r\n\t\t\t\t\t+ curCategory.getCategoryName()\r\n\t\t\t\t\t+ (curCategory.getNumberOfIssues() > 0\r\n\t\t\t\t\t\t\t? \"\" : \"\")\r\n\t\t\t\t\t+ \"

\");\r\n\r\n\t\t\tsb.append(\"
    \");\r\n\t\t\tif (curCategory.getCategoryGrade() != null) {\r\n\t\t\t\tsb.append(\"
  • \" + \"Section Grade: \" + \"\"\r\n\t\t\t\t\t\t+ curCategory.getCategoryGrade() + \"\" + \"
  • \"\r\n\t\t\t\t\t\t+ \"
  • \" + \"Number of Issues: \" + \"\"\r\n\t\t\t\t\t\t+ curCategory.getNumberOfIssues() + \"\" + \"
  • \");\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\"
  • \"\r\n\t\t\t\t\t\t+ \"This category was not scored as it \");\r\n\t\t\t\tif(curCategory.isNullFlavorNI()) {\r\n\t\t\t\t\tsb.append(\"is an empty section\");\r\n\t\t\t\t}\r\n\t\t\t \tboolean failingConformance = curCategory.isFailingConformance();\r\n\t\t\t \tboolean failingCertification = curCategory.isCertificationFeedback();\r\n\t\t\t \tif(failingConformance || failingCertification) {\r\n\t\t \t\t\tboolean isCategoryNameValid = !ApplicationUtil.isEmpty(curCategory.getCategoryName());\r\n\t\t\t \t\tif(failingConformance && failingCertification || failingConformance && !failingCertification) {\r\n\t\t\t\t \t\t//we default to IG if true for both since IG is considered a more serious issue (same with the heatmap label, so we match that)\r\n\t\t\t\t \t\t//there could be a duplicate for two reasons, right now, there's always at least one duplicate since we derive ig from cert in the backend\r\n\t\t\t\t \t\t//in the future this might not be the case, but, there could be multiple section fails in the same section, so we have a default for those too\r\n\t\t\t \t\t\tint igErrorCount = isCategoryNameValid \r\n\t\t\t \t\t\t\t\t? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults)\r\n\t\t\t \t\t\t\t\t: -1;\r\n\t\t\t\t\t\tsb.append(\"contains\" + (isCategoryNameValid ? \" \" + igErrorCount + \" \" : \"\")\r\n\t\t\t\t\t\t\t\t+ \"\" + \"Conformance Error\" + (igErrorCount != 1 ? \"s\" : \"\") + \"\");\r\n\t\t\t\t\t} else if(failingCertification && !failingConformance) {\r\n\t\t\t\t\t\tint certFeedbackCount = isCategoryNameValid\r\n\t\t\t\t\t\t\t\t? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults)\r\n\t\t\t\t\t\t\t\t: -1;\r\n\t\t\t\t\t\tsb.append(\"contains\" + (isCategoryNameValid ? \" \" + certFeedbackCount + \" \" : \"\")\r\n\t\t\t\t\t\t\t\t+ \"\" + \"Certification Feedback\" + \"\" + \" result\" + (certFeedbackCount != 1 ? \"s\" : \"\"));\r\n\t\t\t\t\t}\r\n\t\t\t \t}\r\n\t\t\t\tsb.append(\"
  • \");\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\tsb.append(\"
\");\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\tprivate static void appendSummaryRow(StringBuffer sb, int result,\r\n\t\t\tString header, String messageSuffix, String messageSubject,\r\n\t\t\tboolean isSingular) {\r\n\t\tappendSummaryRow(sb, result, header, messageSuffix, messageSubject, isSingular, null);\r\n\t}\r\n\t\r\n\tprivate static void appendSummaryRow(StringBuffer sb, int result,\r\n\t\t\tString header, String messageSuffix, String messageSubject,\r\n\t\t\tboolean isSingular, SaveReportType reportType) {\r\n\t\tif(reportType == null) {\r\n\t\t\treportType = SaveReportType.MATCH_UI;\r\n\t\t}\r\n\t\tsb.append(\"

\"\r\n\t\t\t\t+ header\r\n\t\t\t\t+ \": \"\r\n\t\t\t\t+ (\"Scorecard Issues\".equals(header) || result < 1 || reportType == SaveReportType.SUMMARY ? result\r\n\t\t\t\t\t\t: (\"\" + result + \"\"))\r\n\t\t\t\t+ \"

\");\r\n\t\tsb.append(\"
  • \");\r\n\t\tsb.append(\"

    There \" + (isSingular ? \"is\" : \"are\") + \" \" + \"\"\r\n\t\t\t\t+ result + \"\" + \" \" + messageSubject\r\n\t\t\t\t+ (messageSuffix != null ? \" \" + messageSuffix : \"\")\r\n\t\t\t\t+ \" in your document.

    \");\r\n\t}\r\n\r\n\tprivate static void appendDetailedResults(StringBuffer sb,\r\n\t\t\tList categories, List referenceResults) {\r\n\r\n\t\tsb.append(\"

    \" + \"Detailed Results\" + \"

    \");\r\n\r\n\t\tif (!ApplicationUtil.isEmpty(referenceResults)) {\r\n\t\t\tfor (ReferenceResult curRefInstance : referenceResults) {\r\n\r\n\t\t\t\tReferenceInstanceType refType = curRefInstance.getType();\r\n\t\t\t\tif (curRefInstance.getTotalErrorCount() > 0) {\r\n\t\t\t\t\tString refTypeName = refType.getTypePrettyName();\r\n\t\t\t\t\tsb.append(\"

    \"\r\n\t\t\t\t\t\t\t+ refTypeName + \"

    \");\r\n\t\r\n\t\t\t\t\tsb.append(\"
      \"); // START curRefInstance ul\r\n\t\t\t\t\tsb.append(\"
    • \"\r\n\t\t\t\t\t\t\t+ \"Number of \"\r\n\t\t\t\t\t\t\t+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? \"Results:\"\r\n\t\t\t\t\t\t\t\t\t: \"Errors:\") + \" \"\r\n\t\t\t\t\t\t\t+ curRefInstance.getTotalErrorCount() + \"
    • \");\r\n\t\r\n\t\t\t\t\tsb.append(\"
        \"); // START reference errors ol\r\n\t\r\n\t\t\t\t\tfor (ReferenceError curRefError : curRefInstance\r\n\t\t\t\t\t\t\t.getReferenceErrors()) {\r\n\t\r\n\t\t\t\t\t\tsb.append(\"
      1. \"\r\n\t\t\t\t\t\t\t\t+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? \"Feedback:\"\r\n\t\t\t\t\t\t\t\t\t\t: \"Error:\") + \" \"\r\n\t\t\t\t\t\t\t\t+ curRefError.getDescription() + \"
      2. \");\r\n\t\r\n\t\t\t\t\t\tsb.append(\"
          \"); // START ul within the curRefError\r\n\t\t\t\t\t\tif (!ApplicationUtil.isEmpty(curRefError\r\n\t\t\t\t\t\t\t\t.getSectionName())) {\r\n\t\t\t\t\t\t\tsb.append(\"
        • \" + \"Related Section: \"\r\n\t\t\t\t\t\t\t\t\t+ curRefError.getSectionName() + \"
        • \");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tsb.append(\"
        • \"\r\n\t\t\t\t\t\t\t\t+ \"Document Line Number (approximate): \"\r\n\t\t\t\t\t\t\t\t+ curRefError.getDocumentLineNumber() + \"
        • \");\r\n\t\t\t\t\t\tsb.append(\"
        • \"\r\n\t\t\t\t\t\t\t\t+ \"xPath: \"\r\n\t\t\t\t\t\t\t\t+ \"\&quot;\r\n\t\t\t\t\t\t\t\t+ curRefError.getxPath() + \&quot;\" + \"
        • \");\r\n\t\t\t\t\t\tsb.append(\"
        \"); // END ul within the curRefError\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tsb.append(\"
      \"); // END reference errors ol\r\n\t\t\t\tsb.append(\"
    \"); // END curRefInstance ul\r\n\t\t\t\tappendBackToTopWithBreaks(sb);\r\n\r\n\t\t\t} //END for (ReferenceResult curRefInstance : referenceResults)\r\n\t\t}\r\n\r\n\t\tfor (Category curCategory : getSortedCategories(categories)) {\r\n\t\t\tif (curCategory.getNumberOfIssues() > 0) {\r\n\t\t\tsb.append(\"

    \" + curCategory.getCategoryName() + \"

    \");\r\n\r\n\t\t\t\tsb.append(\"
      \"); // START curCategory ul\r\n\t\t\t\tsb.append(\"
    • \" + \"Section Grade: \"\r\n\t\t\t\t\t\t+ curCategory.getCategoryGrade() + \"
    • \" + \"
    • \"\r\n\t\t\t\t\t\t+ \"Number of Issues: \"\r\n\t\t\t\t\t\t+ curCategory.getNumberOfIssues() + \"
    • \");\r\n\r\n\t\t\t\t\tsb.append(\"
        \"); // START rules ol\r\n\t\t\t\t\tfor (CCDAScoreCardRubrics curRubric : curCategory\r\n\t\t\t\t\t\t\t.getCategoryRubrics()) {\r\n\t\t\t\t\t\tif (curRubric.getNumberOfIssues() > 0) {\r\n\t\t\t\t\t\t\tsb.append(\"
      1. \" + \"Rule: \" + curRubric.getRule()\r\n\t\t\t\t\t\t\t\t\t+ \"
      2. \");\r\n\t\t\t\t\t\t\tif (curRubric.getDescription() != null) {\r\n\t\t\t\t\t\t\t\tsb.append(\"
          \" + \"
        • \" + \"Description\"\r\n\t\t\t\t\t\t\t\t\t\t+ \"
        • \" + \"
            \" + \"
          • \"\r\n\t\t\t\t\t\t\t\t\t\t+ curRubric.getDescription() + \"
          • \"\r\n\t\t\t\t\t\t\t\t\t\t+ \"
          \" + \"
        \");\r\n\t\t\t\t\t\t\t\tsb.append(\"
        \");\r\n\r\n\t\t\t\t\t\t\t\tsb.append(\"
          \"); // START snippets ol\r\n\t\t\t\t\t\t\t\tfor (CCDAXmlSnippet curSnippet : curRubric\r\n\t\t\t\t\t\t\t\t\t\t.getIssuesList()) {\r\n\t\t\t\t\t\t\t\t\tsb.append(\"
        1. \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ \"XML at line number \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ curSnippet.getLineNumber()\r\n\t\t\t\t\t\t\t\t\t\t\t+ \"
        2. \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ \"
          \&quot;\r\n\t\t\t\t\t\t\t\t\t\t\t+ curSnippet.getXmlString()\r\n\t\t\t\t\t\t\t\t\t\t\t+ \&quot;

          \");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tsb.append(\"
        \"); // END snippets ol\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// don't display rules without occurrences\r\n\t\t\t\t\t\t\tsb.append(\"
      \");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsb.append(\"\"); // END rules ol\r\n\r\n\t\t\t\tsb.append(\"
    \"); // END curCategory ul\r\n\t\t\t\r\n\t\t\tappendBackToTopWithBreaks(sb);\r\n\t\t\t\r\n\t\t\t} //END if (curCategory.getNumberOfIssues() > 0)\r\n\t\t} //END for (Category curCategory : categories)\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate static void appendPictorialGuide(StringBuffer sb,\r\n\t\t\tList categories, List referenceResults) {\t\t\r\n\t\t//minimum breaks based on 11 categories\r\n\t\tsb.append(\"

















    \");\r\n\t\tsb.append(\"

    \" + \"Guide to Interpret the Scorecard Results Table\" + \"

    \");\t\t\r\n\t\t\r\n\t\tsb.append(\"

    \" + \"The following sample table identifies how to use the C-CDA Scorecard results \"\r\n\t\t\t\t\t\t+ \"to improve the C-CDA documents generated by your organization. \" \r\n\t\t+ \"Note: The table below is an example containing fictitious results \"\r\n\t\t+ \"and does not reflect C-CDAs generated by your organization.\" + \"

    \");\r\n\t\t\r\n\t\t//static table\r\n\t\tsb.append(\"\")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\" \")\r\n\t\t .append(\"
    A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.
    The Scorecard grade is a quantitative assessment of the data quality of the submitted document. A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and has higher probability of being interoperable\")\r\n\t\t .append(\" with other organizations.A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.
    Clinical DomainScorecard GradeScorecard IssuesConformance ErrorsCertification FeedbackA Certification Feedback result identifies areas where the generated documents are not compliant with the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.
    The Problems row in this example has an A+ grade and all zeros across the board. This is the most desirable outcome for a Clinical Domain result set.ProblemsA+000
    Lab ResultsA-200
    Vital SignsA-100
    EncountersD1200
    MedicationsN/AN/A20This domain was not scored because the document did not have data pertaining to the clinical domain or there were conformance errors or certification results.
    AllergiesN/AN/A04
    ImmunizationsN/AN/A00
    \");\t\t\r\n\t}\r\n\t\r\n\tprivate static void appendPictorialGuideKey(StringBuffer sb) {\r\n\t\tsb.append(\"

    Additional Guidance to Interpret the Scorecard Results and Achieve Higher Grades

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Scorecard Grade: \")\r\n\t .append(\"The Scorecard grade is a quantitative assessment of the data quality of the submitted document. \"\r\n\t \t\t+ \"A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization \"\r\n\t \t\t+ \"and has higher probability of being interoperable with other organizations. \"\r\n\t \t\t+ \"The grades are derived from the scores as follows: \"\r\n\t \t\t+ \"A+ ( > 94), A- ( 90 to 94), B+ (85 to 89), B- (80 to 84), C (70 to 79) and D (< 70).\")\r\n\t .append(\"

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Scorecard Issues: \")\r\n\t .append(\"A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. \"\r\n\t \t\t+ \"This column should have numbers as close to zero as possible. \"\r\n\t \t\t+ \"The issues are counted for each occurrence of unimplemented best practice. \"\r\n\t \t\t+ \"For example, if a Vital Sign measurement is not using the appropriate UCUM units then each such occurrence would be flagged \"\r\n\t \t\t+ \"as an issue. A provider should work with their health IT vendor to better understand the source for why a best practice \"\r\n\t \t\t+ \"may not be implemented and then determine if it can be implemented in the future. Note: Scorecard Issues will be listed as \"\r\n\t \t\t+ \"'N/A' for a clinical domain, when there is no data for the domain or if there are conformance or certification feedback results.\")\r\n\t .append(\"

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Conformance Errors: \")\r\n\t .append(\"A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. \"\r\n\t \t\t+ \"This column should have zeros ideally. \"\r\n\t \t\t+ \"Providers should work with their health IT vendor to rectify the errors.\")\r\n\t .append(\"

    \")\r\n\t .append(\"

    \")\r\n\t .append(\" Certification Feedback: \")\r\n\t .append(\"A Certification Feedback result identifies areas where the generated documents are not compliant with \"\r\n\t \t\t+ \"the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.\"\r\n\t \t\t+ \"Most of these results fall into incorrect use of vocabularies and terminologies. \"\r\n\t \t\t+ \"Although not as severe as a Conformance Error, providers should work with their health IT vendor \"\r\n\t \t\t+ \"to address feedback provided to improve interoperable use of structured data between systems.\")\r\n\t .append(\"

    \");\t\t\r\n\t}\r\n\r\n\tprivate static void appendClosingHtml(StringBuffer sb) {\r\n\t\tsb.append(\"\");\r\n\t\tsb.append(\"\");\r\n\t}\r\n\r\n\tprivate static void appendHorizontalRuleWithBreaks(StringBuffer sb) {\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"
    \");\r\n\t\tsb.append(\"
    \");\r\n\t}\r\n\r\n\tprivate static void appendBackToTopWithBreaks(StringBuffer sb) {\r\n\t\t// sb.append(\"
    \");\r\n\t\tsb.append(\"Back to Top\");\r\n\t\t// sb.append(\"
    \");\r\n\t\t// A PDF conversion bug is not processing this valid HTML so commenting\r\n\t\t// out until time to address\r\n\t\t// sb.append(\"Back to Section List\");\r\n\t\tsb.append(\"
    \");\r\n\t\t// sb.append(\"
    \");\r\n\t}\r\n\r\n\tprivate static void appendErrorMessage(StringBuffer sb, String errorMessage) {\r\n\t\tsb.append(\"

    \");\r\n\t\tsb.append(errorMessage);\r\n\t\tsb.append(\"

    \"); \r\n\t\tif(!errorMessage.contains(\"HL7 CDA Schema Errors\")) {\r\n\t\t\tsb.append(\"

    \" + ApplicationConstants.ErrorMessages.CONTACT + \"

    \");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static void appendGenericErrorMessage(StringBuffer sb) {\r\n\t\tsb.append(\"

    \"\r\n\t\t\t\t+ ApplicationConstants.ErrorMessages.JSON_TO_JAVA_JACKSON\r\n\t\t\t\t+ \"
    \" + ApplicationConstants.ErrorMessages.CONTACT\r\n\t\t\t\t+ \"

    \");\r\n\t}\r\n\r\n\tprivate static void appendErrorMessageFromReport(StringBuffer sb,\r\n\t\t\tResponseTO report) {\r\n\t\tappendErrorMessageFromReport(sb, report, null);\r\n\t}\r\n\r\n\tprivate static void appendErrorMessageFromReport(StringBuffer sb,\r\n\t\t\tResponseTO report, String extraMessage) {\r\n\t\tif (report.getErrorMessage() != null\r\n\t\t\t\t&& !report.getErrorMessage().isEmpty()) {\r\n\t\t\tboolean hasSchemaErrors = report.getSchemaErrorList() != null && !report.getSchemaErrorList().isEmpty();\r\n\t\t\tif(!hasSchemaErrors) {\r\n\t\t\t\tappendErrorMessage(sb, report.getErrorMessage());\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\"

    \" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART1 + \"

    \");\r\n\t\t\t\tsb.append(\"

    \" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART2 + \"

    \");\r\n\t\t\t\tfinal String noData = \"No data available\";\r\n\t\t\t\tsb.append(\"
      \");\r\n\t\t\t\tfor(ReferenceError schemaError : report.getSchemaErrorList()) {\r\n\t\t\t\t\tsb.append(\"
    1. \");\r\n\t\t\t\t\tsb.append(\"
        \");\r\n\t\t\t\t\tsb.append(\"
      • Message: \" + (schemaError.getDescription() != null ? schemaError.getDescription() : noData));\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      • Path: \" + (schemaError.getxPath() != null ? schemaError.getxPath() : noData));\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      • Line Number (approximate): \" + \r\n\t\t\t\t\t\t\t(schemaError.getDocumentLineNumber() != null ? schemaError.getDocumentLineNumber() : noData));\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      • xPath: \"\r\n\t\t\t\t\t\t\t+ \"\&quot;\r\n\t\t\t\t\t\t\t+ (schemaError.getxPath() != null ? schemaError.getxPath() : noData) + \&quot;\");\r\n\t\t\t\t\tsb.append(\"

        \");\r\n\t\t\t\t\tsb.append(\"
      • \");\r\n\t\t\t\t\tsb.append(\"
      \");\r\n\t\t\t\t\tsb.append(\"
    2. \");\r\n\t\t\t\t}\r\n\t\t\t\tsb.append(\"
    \");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tappendGenericErrorMessage(sb);\r\n\t\t}\r\n\t\tif (extraMessage != null && !extraMessage.isEmpty()) {\r\n\t\t\tsb.append(\"

    \" + extraMessage + \"

    \");\r\n\t\t}\r\n\t}\r\n\r\n\tprotected static String ensureLogicalParseTreeInHTML(String htmlReport) {\r\n\t\torg.jsoup.nodes.Document doc = Jsoup.parse(htmlReport);\r\n\t\tString cleanHtmlReport = doc.toString();\r\n\t\treturn cleanHtmlReport;\r\n\t}\r\n\t\r\n\tprivate static void convertHTMLToPDF(String cleanHtmlReport) {\r\n\t\tconvertHTMLToPDF(cleanHtmlReport, null);\r\n\t}\r\n\t\r\n\tprivate static void convertHTMLToPDF(String cleanHtmlReport, HttpServletResponse response) {\r\n\t\tOutputStream out = null;\r\n\t\ttry {\r\n\t\t\tDocumentBuilderFactory factory = DocumentBuilderFactory\r\n\t\t\t\t\t.newInstance();\r\n\t\t\tfactory.setNamespaceAware(false);\r\n\t\t\tfactory.setValidating(false);\r\n\r\n\t\t\tDocumentBuilder builder = factory.newDocumentBuilder();\r\n\t\t\tDocument refineddoc = builder.parse(new ByteArrayInputStream(\r\n\t\t\t\t\tcleanHtmlReport.getBytes(\"UTF-8\")));\r\n\r\n\t\t\tITextRenderer renderer = new ITextRenderer();\r\n\t\t\trenderer.setDocument(refineddoc, null);\r\n\t\t\trenderer.layout();\r\n\r\n\t\t\tif(response != null) {\r\n\t\t\t\t//Stream to Output\r\n\t\t\t\tresponse.setContentType(\"application/pdf\");\r\n\t\t\t\tresponse.setHeader(\"Content-disposition\", \"attachment; filename=\"\r\n\t\t\t\t\t\t+ \"scorecardReport.pdf\");\r\n\t\t\t\tresponse.setHeader(\"max-age=3600\", \"must-revalidate\");\r\n\t\t\t\tresponse.addCookie(new Cookie(\"fileDownload=true\", \"path=/\"));\r\n\t\t\t\tout = response.getOutputStream();\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\t//Save to local file system\r\n\t\t\t\tout = new FileOutputStream(new File(\"testSaveReportImplementation.pdf\"));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\trenderer.createPDF(out);\r\n\t\t} catch (ParserConfigurationException pcE) {\r\n\t\t\tpcE.printStackTrace();\r\n\t\t} catch (SAXException saxE) {\r\n\t\t\tsaxE.printStackTrace();\r\n\t\t} catch (DocumentException docE) {\r\n\t\t\tdocE.printStackTrace();\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (out != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tout.flush();\r\n\t\t\t\t\tout.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(LOG_HTML) {\r\n\t\t\t\tApplicationUtil.debugLog(\"cleanHtmlReport\", cleanHtmlReport);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprotected static void convertHTMLToPDFAndStreamToOutput(\r\n\t\t\tString cleanHtmlReport, HttpServletResponse response) {\r\n\t\tconvertHTMLToPDF(cleanHtmlReport, response);\r\n\t}\r\n\t\r\n\tprivate static void convertHTMLToPDFAndSaveToLocalFileSystem(String cleanHtmlReport) {\r\n\t\tconvertHTMLToPDF(cleanHtmlReport);\r\n\t}\r\n\r\n\t/**\r\n\t * Converts JSON to ResponseTO Java Object using The Jackson API\r\n\t * \r\n\t * @param jsonReportData\r\n\t * JSON which resembles ResponseTO\r\n\t * @return converted ResponseTO POJO\r\n\t */\r\n\tprotected static ResponseTO convertJsonToPojo(String jsonReportData) {\r\n\t\tObjectMapper mapper = new ObjectMapper();\r\n\t\tResponseTO pojo = null;\r\n\t\ttry {\r\n\t\t\tpojo = mapper.readValue(jsonReportData, ResponseTO.class);\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn pojo;\r\n\t}\r\n\t\r\n\tpublic enum SaveReportType {\r\n\t\tMATCH_UI, SUMMARY;\r\n\t}\r\n\t\r\n\tprivate static void buildReportUsingJSONFromLocalFile(String filenameWithoutExtension, \r\n\t\t\tSaveReportType reportType) throws URISyntaxException {\r\n\t\tURI jsonFileURI = new File(\r\n\t\t\t\t\"src/main/webapp/resources/\"\r\n\t\t\t\t\t\t+ filenameWithoutExtension + \".json\").toURI();\t\t\r\n\t\tSystem.out.println(\"jsonFileURI\");\r\n\t\tSystem.out.println(jsonFileURI);\r\n\t\tString jsonReportData = convertFileToString(jsonFileURI);\r\n\t\tSystem.out.println(\"jsonReportData\");\r\n\t\tSystem.out.println(jsonReportData);\r\n\t\tResponseTO pojoResponse = convertJsonToPojo(jsonReportData);\r\n\t\tSystem.out.println(\"response\");\r\n\t\tSystem.out.println(pojoResponse.getCcdaDocumentType());\r\n\t\t\r\n\t\tconvertHTMLToPDFAndSaveToLocalFileSystem(\r\n\t\t\t\tensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)));\t\t\r\n\t}\r\n\t\r\n\tprivate static String convertFileToString(URI fileURI) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tBufferedReader br = null;\r\n\t\ttry {\r\n\t\t\tbr = new BufferedReader(new FileReader(fileURI.getPath()));\r\n\t\t\tString sCurrentLine = \"\";\r\n\t\t\twhile ((sCurrentLine = br.readLine()) != null) {\r\n\t\t\t\tsb.append(sCurrentLine);\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} finally {\r\n\t\t\ttry {\r\n\t\t\t\tbr.close();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sb.toString();\r\n\t}\t\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\tString[] filenames = {\"highScoringSample\", \"lowScoringSample\", \"sampleWithErrors\", \r\n\t\t\t\t\"sampleWithSchemaErrors\", \"sampleWithoutAnyContent\"};\r\n\t\tfinal int HIGH_SCORING_SAMPLE = 0, LOW_SCORING_SAMPLE = 1, SAMPLE_WITH_ERRORS = 2, \r\n\t\t\t\tSAMPLE_WITH_SCHEMA_ERRORS = 3, SAMPLE_WITHOUT_ANY_CONTENT = 4;\r\n\t\ttry {\r\n\t\t\tbuildReportUsingJSONFromLocalFile(filenames[SAMPLE_WITH_ERRORS], SaveReportType.SUMMARY);\r\n\t\t} catch (URISyntaxException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\t\r\n\r\n}\r\n"},"message":{"kind":"string","value":"Add author, subject, keywords, and language metadata for 508"},"old_file":{"kind":"string","value":"src/main/java/org/sitenv/service/ccda/smartscorecard/controller/SaveReportController.java"},"subject":{"kind":"string","value":"Add author, subject, keywords, and language metadata for 508"}}},{"rowIdx":706,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"dd84c3fa851d76c837b9df396501884f5095fc3a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon"},"new_contents":{"kind":"string","value":"/*\n * $Id: TestOnixBooksSourceArchivalUnit.java,v 1.3 2014-01-13 19:33:31 alexandraohlson Exp $\n */\n\n/*\n\nCopyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University,\nall rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nSTANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nExcept as contained in this notice, the name of Stanford University shall not\nbe used in advertising or otherwise to promote the sale, use or other dealings\nin this Software without prior written authorization from Stanford University.\n\n*/\n\npackage org.lockss.plugin.clockss.onixbooks;\n\nimport java.net.URL;\nimport java.util.Properties;\n\nimport org.lockss.config.Configuration;\nimport org.lockss.daemon.*;\nimport org.lockss.plugin.*;\nimport org.lockss.plugin.base.*;\nimport org.lockss.plugin.definable.*;\nimport org.lockss.test.*;\nimport org.lockss.util.*;\n\n//\n// This plugin test framework is set up to run the same tests in two variants - CLOCKSS and GLN\n// without having to actually duplicate any of the written tests\n//\npublic class TestOnixBooksSourceArchivalUnit extends LockssTestCase {\n private MockLockssDaemon theDaemon;\n static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();\n static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey();\n static final String ROOT_URL = \"http://www.sourcecontent.com/\"; //this is not a real url\n \n static Logger log = Logger.getLogger(\"TestOnixBooksSourceArchivalUnit\");\n \n static final String PLUGIN_ID = \"org.lockss.plugin.clockss.onixbooks.ClockssOnix3BooksSourcePlugin\";\n static final String PluginName = \"ONIX 3 Books Source Plugin (CLOCKSS)\";\n \n public void setUp() throws Exception {\n super.setUp();\n setUpDiskSpace();\n theDaemon = getMockLockssDaemon();\n theDaemon.getHashService();\n }\n\n public void tearDown() throws Exception {\n super.tearDown();\n }\n\n private DefinableArchivalUnit makeAu(URL url, String year)\n throws Exception {\n\n Properties props = new Properties();\n props.setProperty(YEAR_KEY, year);\n if (url != null) {\n props.setProperty(BASE_URL_KEY, url.toString());\n }\n Configuration config = ConfigurationUtil.fromProps(props);\n \n DefinablePlugin ap = new DefinablePlugin();\n ap.initPlugin(getMockLockssDaemon(),\n PLUGIN_ID);\n DefinableArchivalUnit au = (DefinableArchivalUnit)ap.createAu(config);\n return au;\n }\n\n public void testConstructNullUrl() throws Exception {\n try {\n makeAu(null, \"2012\");\n fail(\"Should have thrown ArchivalUnit.ConfigurationException\");\n } catch (ArchivalUnit.ConfigurationException e) {\n }\n }\n \n //\n // Test the crawl rules\n //\n public void testShouldCacheProperPages() throws Exception {\n URL base = new URL(ROOT_URL);\n ArchivalUnit sourceAU = makeAu(base, \"2012\");\n theDaemon.getLockssRepository(sourceAU);\n theDaemon.getNodeManager(sourceAU);\n BaseCachedUrlSet cus = new BaseCachedUrlSet(sourceAU,\n new RangeCachedUrlSetSpec(base.toString()));\n\n // Test for pages that should get crawled\n\n //with a subdirectory under the year\n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.xml\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.pdf\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.epub\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.jpg\", true, sourceAU, cus);\n //without a subdirectory under the year\n shouldCacheTest(ROOT_URL+\"2012/\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.xml\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.pdf\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.epub\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.jpg\", true, sourceAU, cus);\n \n // Now a couple that shouldn't get crawled\n // md5sum file\n shouldCacheTest(ROOT_URL+\"2012/xxxx/blah.pdf.md5sum\", false, sourceAU, cus);\n //wrong year\n shouldCacheTest(ROOT_URL+\"2013/xxxx/blah.pdf\", false, sourceAU, cus);\n // too deep\n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/randomdirectory/blah.jpg\", true, sourceAU, cus);\n }\n \n private void shouldCacheTest(String url, boolean shouldCache,\n ArchivalUnit au, CachedUrlSet cus) {\n UrlCacher uc = au.makeUrlCacher(url);\n assertEquals(shouldCache, uc.shouldBeCached());\n }\n \n \n public void testgetName() throws Exception {\n DefinableArchivalUnit au =\n makeAu(new URL(\"http://www.source.com/\"), \"2011\");\n assertEquals(PluginName + \", Base URL http://www.source.com/, Year 2011\", au.getName());\n DefinableArchivalUnit au1 =\n makeAu(new URL(\"http://www.source.com/\"), \"2009\");\n assertEquals(PluginName + \", Base URL http://www.source.com/, Year 2009\", au1.getName());\n }\n\n}\n\n"},"new_file":{"kind":"string","value":"plugins/test/src/org/lockss/plugin/clockss/onixbooks/TestOnixBooksSourceArchivalUnit.java"},"old_contents":{"kind":"string","value":"/*\n * $Id: TestOnixBooksSourceArchivalUnit.java,v 1.2 2013-11-13 18:47:37 alexandraohlson Exp $\n */\n\n/*\n\nCopyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University,\nall rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nSTANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nExcept as contained in this notice, the name of Stanford University shall not\nbe used in advertising or otherwise to promote the sale, use or other dealings\nin this Software without prior written authorization from Stanford University.\n\n*/\n\npackage org.lockss.plugin.clockss.onixbooks;\n\nimport java.net.URL;\nimport java.util.Properties;\n\nimport org.lockss.config.Configuration;\nimport org.lockss.daemon.*;\nimport org.lockss.plugin.*;\nimport org.lockss.plugin.base.*;\nimport org.lockss.plugin.definable.*;\nimport org.lockss.test.*;\nimport org.lockss.util.*;\n\n//\n// This plugin test framework is set up to run the same tests in two variants - CLOCKSS and GLN\n// without having to actually duplicate any of the written tests\n//\npublic class TestOnixBooksSourceArchivalUnit extends LockssTestCase {\n private MockLockssDaemon theDaemon;\n static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();\n static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey();\n static final String ROOT_URL = \"http://www.sourcecontent.com/\"; //this is not a real url\n \n static Logger log = Logger.getLogger(\"TestOnixBooksSourceArchivalUnit\");\n \n static final String PLUGIN_ID = \"org.lockss.plugin.clockss.onixbooks.ClockssOnix3BooksSourcePlugin\";\n static final String PluginName = \"Onix3 Books Source Plugin (CLOCKSS)\";\n \n public void setUp() throws Exception {\n super.setUp();\n setUpDiskSpace();\n theDaemon = getMockLockssDaemon();\n theDaemon.getHashService();\n }\n\n public void tearDown() throws Exception {\n super.tearDown();\n }\n\n private DefinableArchivalUnit makeAu(URL url, String year)\n throws Exception {\n\n Properties props = new Properties();\n props.setProperty(YEAR_KEY, year);\n if (url != null) {\n props.setProperty(BASE_URL_KEY, url.toString());\n }\n Configuration config = ConfigurationUtil.fromProps(props);\n \n DefinablePlugin ap = new DefinablePlugin();\n ap.initPlugin(getMockLockssDaemon(),\n PLUGIN_ID);\n DefinableArchivalUnit au = (DefinableArchivalUnit)ap.createAu(config);\n return au;\n }\n\n public void testConstructNullUrl() throws Exception {\n try {\n makeAu(null, \"2012\");\n fail(\"Should have thrown ArchivalUnit.ConfigurationException\");\n } catch (ArchivalUnit.ConfigurationException e) {\n }\n }\n \n //\n // Test the crawl rules\n //\n public void testShouldCacheProperPages() throws Exception {\n URL base = new URL(ROOT_URL);\n ArchivalUnit sourceAU = makeAu(base, \"2012\");\n theDaemon.getLockssRepository(sourceAU);\n theDaemon.getNodeManager(sourceAU);\n BaseCachedUrlSet cus = new BaseCachedUrlSet(sourceAU,\n new RangeCachedUrlSetSpec(base.toString()));\n\n // Test for pages that should get crawled\n\n //with a subdirectory under the year\n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.xml\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.pdf\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.epub\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/blah.jpg\", true, sourceAU, cus);\n //without a subdirectory under the year\n shouldCacheTest(ROOT_URL+\"2012/\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.xml\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.pdf\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.epub\", true, sourceAU, cus); \n shouldCacheTest(ROOT_URL+\"2012/blah.jpg\", true, sourceAU, cus);\n \n // Now a couple that shouldn't get crawled\n // md5sum file\n shouldCacheTest(ROOT_URL+\"2012/xxxx/blah.pdf.md5sum\", false, sourceAU, cus);\n //wrong year\n shouldCacheTest(ROOT_URL+\"2013/xxxx/blah.pdf\", false, sourceAU, cus);\n // too deep\n shouldCacheTest(ROOT_URL+\"2012/Berghahn_Press/randomdirectory/blah.jpg\", true, sourceAU, cus);\n }\n \n private void shouldCacheTest(String url, boolean shouldCache,\n ArchivalUnit au, CachedUrlSet cus) {\n UrlCacher uc = au.makeUrlCacher(url);\n assertEquals(shouldCache, uc.shouldBeCached());\n }\n \n \n public void testgetName() throws Exception {\n DefinableArchivalUnit au =\n makeAu(new URL(\"http://www.source.com/\"), \"2011\");\n assertEquals(PluginName + \", Base URL http://www.source.com/, Year 2011\", au.getName());\n DefinableArchivalUnit au1 =\n makeAu(new URL(\"http://www.source.com/\"), \"2009\");\n assertEquals(PluginName + \", Base URL http://www.source.com/, Year 2009\", au1.getName());\n }\n\n}\n\n"},"message":{"kind":"string","value":"update test to handle updated plugin name\n\n\ngit-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@32023 4f837ed2-42f5-46e7-a7a5-fa17313484d4\n"},"old_file":{"kind":"string","value":"plugins/test/src/org/lockss/plugin/clockss/onixbooks/TestOnixBooksSourceArchivalUnit.java"},"subject":{"kind":"string","value":"update test to handle updated plugin name"}}},{"rowIdx":707,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"287c53379524f2c0038e33be75a0573e26d3cc7e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro"},"new_contents":{"kind":"string","value":"/* $This file is distributed under the terms of the license in /doc/license.txt$ */\n\npackage edu.cornell.mannlib.vitro.webapp.dao.jena;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.hp.hpl.jena.ontology.OntModel;\nimport com.hp.hpl.jena.rdf.listeners.StatementListener;\nimport com.hp.hpl.jena.rdf.model.Literal;\nimport com.hp.hpl.jena.rdf.model.NodeIterator;\nimport com.hp.hpl.jena.rdf.model.Property;\nimport com.hp.hpl.jena.rdf.model.RDFNode;\nimport com.hp.hpl.jena.rdf.model.ResourceFactory;\nimport com.hp.hpl.jena.rdf.model.Statement;\n\nimport edu.cornell.mannlib.vitro.webapp.beans.Portal;\nimport edu.cornell.mannlib.vitro.webapp.dao.ApplicationDao;\nimport edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;\n\npublic class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao {\n\n private static final Property LINKED_NAMESPACE_PROP = \n ResourceFactory.createProperty(\n VitroVocabulary.DISPLAY + \"linkedNamespace\");\n \n\tInteger portalCount = null;\n\tList externallyLinkedNamespaces = null;\n\t\n public ApplicationDaoJena(WebappDaoFactoryJena wadf) {\n super(wadf);\n getOntModelSelector().getDisplayModel().register(\n new ExternalNamespacesChangeListener());\n }\n\t \n\t\n\tpublic boolean isFlag1Active() {\n\t\tboolean somePortalIsFiltering=false;\t\t\n\t\tif (portalCount == null) {\n\t\t\tboolean active = false;\n\t\t\tfor (Portal p : getWebappDaoFactory().getPortalDao().getAllPortals()) {\n\t\t\t\tif (p.isFlag1Filtering()) {\n\t\t\t\t\tsomePortalIsFiltering = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\n\t\treturn somePortalIsFiltering && getWebappDaoFactory().getPortalDao().getAllPortals().size() > 1;\t\t\n\t}\n\n\t\n\tpublic boolean isFlag2Active() {\n\t\treturn (getFlag2ValueMap().isEmpty()) ? false : true;\n\t}\n\n\tprivate static final boolean CLEAR_CACHE = true;\n\t\n\tpublic synchronized List getExternallyLinkedNamespaces() {\n\t return getExternallyLinkedNamespaces(!CLEAR_CACHE);\n\t}\n\n public synchronized List getExternallyLinkedNamespaces(boolean clearCache) {\n if (clearCache || externallyLinkedNamespaces == null) { \n externallyLinkedNamespaces = new ArrayList();\n OntModel ontModel = getOntModelSelector().getDisplayModel();\n NodeIterator nodes = ontModel.listObjectsOfProperty(LINKED_NAMESPACE_PROP);\n while (nodes.hasNext()) {\n RDFNode node = nodes.next();\n if (node.isLiteral()) {\n String namespace = ((Literal)node).getLexicalForm();\n // org.openrdf.model.impl.URIImpl.URIImpl.getNamespace() returns a \n // namespace with a final slash, so this makes matching easier.\n // It also accords with the way the default namespace is defined.\n if (!namespace.endsWith(\"/\")) {\n namespace = namespace + \"/\";\n }\n externallyLinkedNamespaces.add(namespace);\n }\n }\n }\n return externallyLinkedNamespaces;\n }\n \n private class ExternalNamespacesChangeListener extends StatementListener {\n \n @Override\n public void addedStatement(Statement stmt) {\n process(stmt);\n }\n \n @Override\n public void removedStatement(Statement stmt) {\n process(stmt);\n }\n \n //We could also listen for end-of-edit events,\n //but there should be so few of these statments that\n //it won't be very expensive to run this method multiple\n //times when the model is updated.\n \n private void process(Statement stmt) {\n if (stmt.getPredicate().equals(LINKED_NAMESPACE_PROP)) {\n getExternallyLinkedNamespaces(CLEAR_CACHE);\n }\n }\n \n }\n \n}\n"},"new_file":{"kind":"string","value":"webapp/src/edu/cornell/mannlib/vitro/webapp/dao/jena/ApplicationDaoJena.java"},"old_contents":{"kind":"string","value":"/* $This file is distributed under the terms of the license in /doc/license.txt$ */\n\npackage edu.cornell.mannlib.vitro.webapp.dao.jena;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.hp.hpl.jena.ontology.OntModel;\nimport com.hp.hpl.jena.rdf.listeners.StatementListener;\nimport com.hp.hpl.jena.rdf.model.Literal;\nimport com.hp.hpl.jena.rdf.model.NodeIterator;\nimport com.hp.hpl.jena.rdf.model.Property;\nimport com.hp.hpl.jena.rdf.model.RDFNode;\nimport com.hp.hpl.jena.rdf.model.ResourceFactory;\nimport com.hp.hpl.jena.rdf.model.Statement;\n\nimport edu.cornell.mannlib.vitro.webapp.beans.Portal;\nimport edu.cornell.mannlib.vitro.webapp.dao.ApplicationDao;\nimport edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;\n\npublic class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao {\n\n Property LINKED_NAMESPACE_PROP = ResourceFactory.createProperty(\n VitroVocabulary.DISPLAY + \"linkedNamespace\");\n \n\tInteger portalCount = null;\n\tList externallyLinkedNamespaces = null;\n\t\n public ApplicationDaoJena(WebappDaoFactoryJena wadf) {\n super(wadf);\n getOntModelSelector().getDisplayModel().register(\n new ExternalNamespacesChangeListener());\n }\n\t \n\t\n\tpublic boolean isFlag1Active() {\n\t\tboolean somePortalIsFiltering=false;\t\t\n\t\tif (portalCount == null) {\n\t\t\tboolean active = false;\n\t\t\tfor (Portal p : getWebappDaoFactory().getPortalDao().getAllPortals()) {\n\t\t\t\tif (p.isFlag1Filtering()) {\n\t\t\t\t\tsomePortalIsFiltering = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\n\t\treturn somePortalIsFiltering && getWebappDaoFactory().getPortalDao().getAllPortals().size() > 1;\t\t\n\t}\n\n\t\n\tpublic boolean isFlag2Active() {\n\t\treturn (getFlag2ValueMap().isEmpty()) ? false : true;\n\t}\n\n\tprivate static final boolean CLEAR_CACHE = true;\n\t\n\tpublic synchronized List getExternallyLinkedNamespaces() {\n\t return getExternallyLinkedNamespaces(!CLEAR_CACHE);\n\t}\n\n public synchronized List getExternallyLinkedNamespaces(boolean clearCache) {\n if (clearCache || externallyLinkedNamespaces == null) { \n externallyLinkedNamespaces = new ArrayList();\n OntModel ontModel = getOntModelSelector().getDisplayModel();\n NodeIterator nodes = ontModel.listObjectsOfProperty(LINKED_NAMESPACE_PROP);\n while (nodes.hasNext()) {\n RDFNode node = nodes.next();\n if (node.isLiteral()) {\n String namespace = ((Literal)node).getLexicalForm();\n // org.openrdf.model.impl.URIImpl.URIImpl.getNamespace() returns a \n // namespace with a final slash, so this makes matching easier.\n // It also accords with the way the default namespace is defined.\n if (!namespace.endsWith(\"/\")) {\n namespace = namespace + \"/\";\n }\n externallyLinkedNamespaces.add(namespace);\n }\n }\n }\n return externallyLinkedNamespaces;\n }\n \n private class ExternalNamespacesChangeListener extends StatementListener {\n \n @Override\n public void addedStatement(Statement stmt) {\n process(stmt);\n }\n \n @Override\n public void removedStatement(Statement stmt) {\n process(stmt);\n }\n \n //We could also listen for end-of-edit events,\n //but there should be so few of these statments that\n //it won't be very expensive to run this method multiple\n //times when the model is updated.\n \n private void process(Statement stmt) {\n if (stmt.getPredicate().equals(LINKED_NAMESPACE_PROP)) {\n getExternallyLinkedNamespaces(CLEAR_CACHE);\n }\n }\n \n }\n \n}\n"},"message":{"kind":"string","value":"NIHVIVO-1193 listener to update externally-linked namespaces\n"},"old_file":{"kind":"string","value":"webapp/src/edu/cornell/mannlib/vitro/webapp/dao/jena/ApplicationDaoJena.java"},"subject":{"kind":"string","value":"NIHVIVO-1193 listener to update externally-linked namespaces"}}},{"rowIdx":708,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"c7c1a22bae08b75c7c3183a31e149b48943fc4ba"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"darklordwonton/ElementsOfPower"},"new_contents":{"kind":"string","value":"package gigaherz.elementsofpower.client.renderers;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport net.minecraft.client.Minecraft;\nimport net.minecraft.client.renderer.Tessellator;\nimport net.minecraft.client.renderer.VertexBuffer;\nimport net.minecraft.client.renderer.block.model.BakedQuad;\nimport net.minecraft.client.renderer.block.model.IBakedModel;\nimport net.minecraft.client.renderer.vertex.DefaultVertexFormats;\nimport net.minecraft.client.renderer.vertex.VertexFormat;\nimport net.minecraft.client.resources.IReloadableResourceManager;\nimport net.minecraft.client.resources.IResourceManager;\nimport net.minecraft.client.resources.IResourceManagerReloadListener;\nimport net.minecraft.crash.CrashReport;\nimport net.minecraft.util.ReportedException;\nimport net.minecraft.util.ResourceLocation;\nimport net.minecraftforge.client.model.*;\nimport net.minecraftforge.client.model.pipeline.LightUtil;\nimport org.lwjgl.opengl.GL11;\n\nimport javax.annotation.Nonnull;\nimport java.util.Map;\n\npublic class ModelHandle\n{\n static Map loadedModels = Maps.newHashMap();\n\n private String model;\n private String key;\n private final Map textureReplacements = Maps.newHashMap();\n private VertexFormat vertexFormat = Attributes.DEFAULT_BAKED_FORMAT;\n\n private ModelHandle(String model)\n {\n this.model = model;\n this.key = model;\n }\n\n public ModelHandle replace(String texChannel, String resloc)\n {\n key += \"//\" + texChannel + \"/\" + resloc;\n textureReplacements.put(texChannel, resloc);\n return this;\n }\n\n public ModelHandle vertexFormat(VertexFormat fmt)\n {\n key += \"//VF:\" + fmt.hashCode();\n vertexFormat = fmt;\n return this;\n }\n\n public String getModel()\n {\n return model;\n }\n\n public String getKey()\n {\n return key;\n }\n\n public Map getTextureReplacements()\n {\n return textureReplacements;\n }\n\n public VertexFormat getVertexFormat()\n {\n return vertexFormat;\n }\n\n public IBakedModel get()\n {\n return loadModel(this);\n }\n\n // ========================================================= STATIC METHODS\n\n public static void init()\n {\n IResourceManager rm = Minecraft.getMinecraft().getResourceManager();\n if (rm instanceof IReloadableResourceManager)\n {\n ((IReloadableResourceManager) rm).registerReloadListener(new IResourceManagerReloadListener()\n {\n @Override\n public void onResourceManagerReload(IResourceManager __)\n {\n loadedModels.clear();\n }\n });\n }\n }\n\n @Nonnull\n public static ModelHandle of(String model)\n {\n return new ModelHandle(model);\n }\n\n public static void renderModel(IBakedModel model)\n {\n renderModel(model, DefaultVertexFormats.ITEM);\n }\n\n public static void renderModel(IBakedModel model, VertexFormat fmt)\n {\n Tessellator tessellator = Tessellator.getInstance();\n VertexBuffer worldrenderer = tessellator.getBuffer();\n worldrenderer.begin(GL11.GL_QUADS, fmt);\n for (BakedQuad bakedquad : model.getQuads(null, null, 0))\n {\n worldrenderer.addVertexData(bakedquad.getVertexData());\n }\n tessellator.draw();\n }\n\n public static void renderModel(IBakedModel model, int color)\n {\n Tessellator tessellator = Tessellator.getInstance();\n VertexBuffer worldrenderer = tessellator.getBuffer();\n worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM);\n for (BakedQuad bakedquad : model.getQuads(null, null, 0))\n {\n LightUtil.renderQuadColor(worldrenderer, bakedquad, color);\n }\n tessellator.draw();\n }\n\n private static IBakedModel loadModel(ModelHandle handle)\n {\n IBakedModel model = loadedModels.get(handle.getKey());\n if (model != null)\n return model;\n\n try\n {\n IModel mod = ModelLoaderRegistry.getModel(new ResourceLocation(handle.getModel()));\n if (mod instanceof IRetexturableModel && handle.getTextureReplacements().size() > 0)\n {\n IRetexturableModel rtm = (IRetexturableModel) mod;\n mod = rtm.retexture(ImmutableMap.copyOf(handle.getTextureReplacements()));\n }\n model = mod.bake(mod.getDefaultState(), handle.getVertexFormat(),\n ModelLoader.defaultTextureGetter());\n loadedModels.put(handle.getKey(), model);\n return model;\n }\n catch (Exception e)\n {\n throw new ReportedException(new CrashReport(\"Error loading custom model \" + handle.getModel(), e));\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/gigaherz/elementsofpower/client/renderers/ModelHandle.java"},"old_contents":{"kind":"string","value":"package gigaherz.elementsofpower.client.renderers;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport net.minecraft.client.Minecraft;\nimport net.minecraft.client.renderer.Tessellator;\nimport net.minecraft.client.renderer.VertexBuffer;\nimport net.minecraft.client.renderer.block.model.BakedQuad;\nimport net.minecraft.client.renderer.block.model.IBakedModel;\nimport net.minecraft.client.renderer.vertex.DefaultVertexFormats;\nimport net.minecraft.client.renderer.vertex.VertexFormat;\nimport net.minecraft.client.resources.IReloadableResourceManager;\nimport net.minecraft.client.resources.IResourceManager;\nimport net.minecraft.client.resources.IResourceManagerReloadListener;\nimport net.minecraft.crash.CrashReport;\nimport net.minecraft.util.ReportedException;\nimport net.minecraft.util.ResourceLocation;\nimport net.minecraftforge.client.model.*;\nimport net.minecraftforge.client.model.pipeline.LightUtil;\nimport org.lwjgl.opengl.GL11;\n\nimport javax.annotation.Nonnull;\nimport java.util.Map;\n\npublic class ModelHandle\n{\n static Map loadedModels = Maps.newHashMap();\n\n private String model;\n private String key;\n private final Map textureReplacements = Maps.newHashMap();\n private VertexFormat vertexFormat = Attributes.DEFAULT_BAKED_FORMAT;\n\n private ModelHandle(String model)\n {\n this.model = model;\n this.key = model;\n }\n\n public ModelHandle replace(String texChannel, String resloc)\n {\n key += \"//\" + texChannel + \"/\" + resloc;\n textureReplacements.put(texChannel, resloc);\n return this;\n }\n\n public ModelHandle vertexFormat(VertexFormat fmt)\n {\n key += \"//VF:\" + fmt.hashCode();\n vertexFormat = fmt;\n return this;\n }\n\n public String getModel()\n {\n return model;\n }\n\n public String getKey()\n {\n return key;\n }\n\n public Map getTextureReplacements()\n {\n return textureReplacements;\n }\n\n public VertexFormat getVertexFormat()\n {\n return vertexFormat;\n }\n\n public void setVertexFormat(VertexFormat vertexFormat)\n {\n this.vertexFormat = vertexFormat;\n }\n\n public IBakedModel get()\n {\n return loadModel(this);\n }\n\n // ========================================================= STATIC METHODS\n\n public static void init()\n {\n IResourceManager rm = Minecraft.getMinecraft().getResourceManager();\n if (rm instanceof IReloadableResourceManager)\n {\n ((IReloadableResourceManager) rm).registerReloadListener(new IResourceManagerReloadListener()\n {\n @Override\n public void onResourceManagerReload(IResourceManager __)\n {\n loadedModels.clear();\n }\n });\n }\n }\n\n @Nonnull\n public static ModelHandle of(String model)\n {\n return new ModelHandle(model);\n }\n\n public static void renderModel(IBakedModel model)\n {\n renderModel(model, DefaultVertexFormats.ITEM);\n }\n\n public static void renderModel(IBakedModel model, VertexFormat fmt)\n {\n Tessellator tessellator = Tessellator.getInstance();\n VertexBuffer worldrenderer = tessellator.getBuffer();\n worldrenderer.begin(GL11.GL_QUADS, fmt);\n for (BakedQuad bakedquad : model.getQuads(null, null, 0))\n {\n worldrenderer.addVertexData(bakedquad.getVertexData());\n }\n tessellator.draw();\n }\n\n public static void renderModel(IBakedModel model, int color)\n {\n Tessellator tessellator = Tessellator.getInstance();\n VertexBuffer worldrenderer = tessellator.getBuffer();\n worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM);\n for (BakedQuad bakedquad : model.getQuads(null, null, 0))\n {\n LightUtil.renderQuadColor(worldrenderer, bakedquad, color);\n }\n tessellator.draw();\n }\n\n private static IBakedModel loadModel(ModelHandle handle)\n {\n IBakedModel model = loadedModels.get(handle.getKey());\n if (model != null)\n return model;\n\n try\n {\n IModel mod = ModelLoaderRegistry.getModel(new ResourceLocation(handle.getModel()));\n if (mod instanceof IRetexturableModel && handle.getTextureReplacements().size() > 0)\n {\n IRetexturableModel rtm = (IRetexturableModel) mod;\n mod = rtm.retexture(ImmutableMap.copyOf(handle.getTextureReplacements()));\n }\n model = mod.bake(mod.getDefaultState(), handle.getVertexFormat(),\n ModelLoader.defaultTextureGetter());\n loadedModels.put(handle.getKey(), model);\n return model;\n }\n catch (Exception e)\n {\n throw new ReportedException(new CrashReport(\"Error loading custom model \" + handle.getModel(), e));\n }\n }\n}\n"},"message":{"kind":"string","value":"Remove derp from using the IDE to autogenerate accessors.\n"},"old_file":{"kind":"string","value":"src/main/java/gigaherz/elementsofpower/client/renderers/ModelHandle.java"},"subject":{"kind":"string","value":"Remove derp from using the IDE to autogenerate accessors."}}},{"rowIdx":709,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"cee6b683119db56130352b5e034c02ab51d83b76"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"EduardoHFreitas/ExemplosJavaSE"},"new_contents":{"kind":"string","value":"package br.univel;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.EventQueue;\r\n\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JOptionPane;\r\nimport javax.swing.JPanel;\r\nimport javax.swing.border.EmptyBorder;\r\n\r\nimport java.awt.GridBagLayout;\r\n\r\nimport javax.swing.JScrollPane;\r\n\r\nimport java.awt.GridBagConstraints;\r\n\r\nimport javax.swing.JTable;\r\nimport javax.swing.JButton;\r\n\r\nimport java.awt.Insets;\r\nimport java.awt.Point;\r\nimport java.awt.event.ActionListener;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.MouseAdapter;\r\nimport java.awt.event.MouseEvent;\r\nimport java.math.BigDecimal;\r\nimport java.text.NumberFormat;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\n\r\npublic class TelaTabela extends JFrame {\r\n\r\n\tprivate JPanel contentPane;\r\n\tprivate JTable table;\r\n\r\n\t/**\r\n\t * Launch the application.\r\n\t */\r\n\tpublic static void main(String[] args) {\r\n\t\tEventQueue.invokeLater(new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTelaTabela frame = new TelaTabela();\r\n\t\t\t\t\tframe.setVisible(true);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Create the frame.\r\n\t */\r\n\tpublic TelaTabela() {\r\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n\t\tsetBounds(100, 100, 450, 300);\r\n\t\tcontentPane = new JPanel();\r\n\t\tcontentPane.setBorder(new EmptyBorder(5, 5, 5, 5));\r\n\t\tsetContentPane(contentPane);\r\n\t\tGridBagLayout gbl_contentPane = new GridBagLayout();\r\n\t\tgbl_contentPane.columnWidths = new int[] { 0, 0 };\r\n\t\tgbl_contentPane.rowHeights = new int[] { 0, 0, 0, 0, 0 };\r\n\t\tgbl_contentPane.columnWeights = new double[] { 1.0, Double.MIN_VALUE };\r\n\t\tgbl_contentPane.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0,\r\n\t\t\t\tDouble.MIN_VALUE };\r\n\t\tcontentPane.setLayout(gbl_contentPane);\r\n\r\n\t\tJButton btnNewButton = new JButton(\"Preenche\");\r\n\t\tbtnNewButton.addActionListener(new ActionListener() {\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tpreencheTabela();\r\n\t\t\t}\r\n\t\t});\r\n\t\tGridBagConstraints gbc_btnNewButton = new GridBagConstraints();\r\n\t\tgbc_btnNewButton.insets = new Insets(0, 0, 5, 0);\r\n\t\tgbc_btnNewButton.gridx = 0;\r\n\t\tgbc_btnNewButton.gridy = 0;\r\n\t\tcontentPane.add(btnNewButton, gbc_btnNewButton);\r\n\r\n\t\tJButton btnRemove = new JButton(\"Remove\");\r\n\t\tbtnRemove.addActionListener(new ActionListener() {\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tremoverSelecionado();\r\n\t\t\t}\r\n\t\t});\r\n\t\tGridBagConstraints gbc_btnRemove = new GridBagConstraints();\r\n\t\tgbc_btnRemove.insets = new Insets(0, 0, 5, 0);\r\n\t\tgbc_btnRemove.gridx = 0;\r\n\t\tgbc_btnRemove.gridy = 1;\r\n\t\tcontentPane.add(btnRemove, gbc_btnRemove);\r\n\r\n\t\tJButton btnAdiciona = new JButton(\"Adiciona\");\r\n\t\tbtnAdiciona.addActionListener(new ActionListener() {\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tadicionarDoAlem();\r\n\t\t\t}\r\n\t\t});\r\n\t\tGridBagConstraints gbc_btnAdiciona = new GridBagConstraints();\r\n\t\tgbc_btnAdiciona.insets = new Insets(0, 0, 5, 0);\r\n\t\tgbc_btnAdiciona.gridx = 0;\r\n\t\tgbc_btnAdiciona.gridy = 2;\r\n\t\tcontentPane.add(btnAdiciona, gbc_btnAdiciona);\r\n\r\n\t\tJScrollPane scrollPane = new JScrollPane();\r\n\t\tGridBagConstraints gbc_scrollPane = new GridBagConstraints();\r\n\t\tgbc_scrollPane.fill = GridBagConstraints.BOTH;\r\n\t\tgbc_scrollPane.gridx = 0;\r\n\t\tgbc_scrollPane.gridy = 3;\r\n\t\tcontentPane.add(scrollPane, gbc_scrollPane);\r\n\r\n\t\ttable = new JTable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic String getToolTipText(MouseEvent e) {\r\n\r\n\t\t\t\tString tip = null;\r\n\r\n\t\t\t\tPoint p = e.getPoint();\r\n\r\n int rowIndex = rowAtPoint(p);\r\n int colIndex = columnAtPoint(p);\r\n\r\n if (rowIndex == -1 || colIndex == -1) {\r\n \treturn null;\r\n }\r\n\r\n try {\r\n tip = getValueAt(rowIndex, colIndex).toString();\r\n } catch (RuntimeException e1) {\r\n\r\n }\r\n\r\n return tip;\r\n\r\n\t\t\t}\r\n\r\n\t\t};\r\n\r\n\t\tscrollPane.setViewportView(table);\r\n\r\n\t\t// final\r\n\t\tconfiguraTabela();\r\n\t}\r\n\r\n\tprotected void adicionarDoAlem() {\r\n\r\n\t\tProduto c = new Produto(123, \"Treta\", new BigDecimal(15));\r\n\r\n\r\n\t\t((ProdutoModel)table.getModel()).adicionarProduto(c);\r\n\r\n\t}\r\n\r\n\tprotected void removerSelecionado() {\r\n\t\tProduto c = getProdutoSelecionadoNaTabela();\r\n\t\tif (c != null) {\r\n\t\t\t((ProdutoModel)table.getModel()).removerProduto(c);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate void configuraTabela() {\r\n\t\ttable.addMouseListener(new MouseAdapter() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void mouseClicked(MouseEvent e) {\r\n\r\n\t\t\t\tif (e.getClickCount() == 2) {\r\n\t\t\t\t\tProduto c = getProdutoSelecionadoNaTabela();\r\n\t\t\t\t\tif (c != null) {\r\n\t\t\t\t\t\tJOptionPane.showMessageDialog(null,\r\n\t\t\t\t\t\t\t\t\"Produto: \" + c.toString());\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t});\r\n\r\n\t}\r\n\r\n\tprotected void preencheTabela() {\r\n\r\n/*\t\tList lista = new ArrayList<>();\r\n\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\tlista.add(new Produto(i, \"Produto \", new BigDecimal(0)));\r\n\t\t}\r\n*/\r\n\r\n\t\tReaderURL reader = new ReaderURL();\r\n\t\tList lista = reader.lerUrl();\r\n\r\n//\t\tReaderArquivo reader = new ReaderArquivo();\r\n//\t\tList lista = reader.lerArquivo();\r\n\r\n\t\tProdutoParser parser = new ProdutoParser();\r\n\t\tList listaPrd = parser.getProduto(lista);\r\n\r\n\t\tNumberFormat formatUS = NumberFormat.getCurrencyInstance(new Locale(\"en\", \"US\"));\r\n\t\tNumberFormat formatBR = NumberFormat.getCurrencyInstance(new Locale(\"pt\", \"BR\"));\r\n\r\n\t\tBigDecimal cotacao = new BigDecimal(3.37); /* formato para valores MONETARIOS*/\r\n\r\n\r\n\t\tProdutoModel model = new ProdutoModel(listaPrd);\r\n\t\ttable.setModel(model);\r\n\r\n\t}\r\n\r\n\tprivate Produto getProdutoSelecionadoNaTabela() {\r\n\t\tProduto c = null;\r\n\t\tint index = table.getSelectedRow();\r\n\t\tif (index == -1) {\r\n\t\t\tJOptionPane.showMessageDialog(null, \"Nenhuma linha selecionada!\");\r\n\t\t} else {\r\n\t\t\tc = ((ProdutoModel) table.getModel()).getProdutoNaLinha(index);\r\n\t\t}\r\n\t\treturn c;\r\n\t}\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"CadastroImport/src/br/univel/TelaTabela.java"},"old_contents":{"kind":"string","value":"package br.univel;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.EventQueue;\r\n\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JOptionPane;\r\nimport javax.swing.JPanel;\r\nimport javax.swing.border.EmptyBorder;\r\n\r\nimport java.awt.GridBagLayout;\r\n\r\nimport javax.swing.JScrollPane;\r\n\r\nimport java.awt.GridBagConstraints;\r\n\r\nimport javax.swing.JTable;\r\nimport javax.swing.JButton;\r\n\r\nimport java.awt.Insets;\r\nimport java.awt.Point;\r\nimport java.awt.event.ActionListener;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.MouseAdapter;\r\nimport java.awt.event.MouseEvent;\r\nimport java.math.BigDecimal;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\npublic class TelaTabela extends JFrame {\r\n\r\n\tprivate JPanel contentPane;\r\n\tprivate JTable table;\r\n\r\n\t/**\r\n\t * Launch the application.\r\n\t */\r\n\tpublic static void main(String[] args) {\r\n\t\tEventQueue.invokeLater(new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTelaTabela frame = new TelaTabela();\r\n\t\t\t\t\tframe.setVisible(true);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Create the frame.\r\n\t */\r\n\tpublic TelaTabela() {\r\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n\t\tsetBounds(100, 100, 450, 300);\r\n\t\tcontentPane = new JPanel();\r\n\t\tcontentPane.setBorder(new EmptyBorder(5, 5, 5, 5));\r\n\t\tsetContentPane(contentPane);\r\n\t\tGridBagLayout gbl_contentPane = new GridBagLayout();\r\n\t\tgbl_contentPane.columnWidths = new int[] { 0, 0 };\r\n\t\tgbl_contentPane.rowHeights = new int[] { 0, 0, 0, 0, 0 };\r\n\t\tgbl_contentPane.columnWeights = new double[] { 1.0, Double.MIN_VALUE };\r\n\t\tgbl_contentPane.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0,\r\n\t\t\t\tDouble.MIN_VALUE };\r\n\t\tcontentPane.setLayout(gbl_contentPane);\r\n\r\n\t\tJButton btnNewButton = new JButton(\"Preenche\");\r\n\t\tbtnNewButton.addActionListener(new ActionListener() {\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tpreencheTabela();\r\n\t\t\t}\r\n\t\t});\r\n\t\tGridBagConstraints gbc_btnNewButton = new GridBagConstraints();\r\n\t\tgbc_btnNewButton.insets = new Insets(0, 0, 5, 0);\r\n\t\tgbc_btnNewButton.gridx = 0;\r\n\t\tgbc_btnNewButton.gridy = 0;\r\n\t\tcontentPane.add(btnNewButton, gbc_btnNewButton);\r\n\r\n\t\tJButton btnRemove = new JButton(\"Remove\");\r\n\t\tbtnRemove.addActionListener(new ActionListener() {\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tremoverSelecionado();\r\n\t\t\t}\r\n\t\t});\r\n\t\tGridBagConstraints gbc_btnRemove = new GridBagConstraints();\r\n\t\tgbc_btnRemove.insets = new Insets(0, 0, 5, 0);\r\n\t\tgbc_btnRemove.gridx = 0;\r\n\t\tgbc_btnRemove.gridy = 1;\r\n\t\tcontentPane.add(btnRemove, gbc_btnRemove);\r\n\r\n\t\tJButton btnAdiciona = new JButton(\"Adiciona\");\r\n\t\tbtnAdiciona.addActionListener(new ActionListener() {\r\n\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\tadicionarDoAlem();\r\n\t\t\t}\r\n\t\t});\r\n\t\tGridBagConstraints gbc_btnAdiciona = new GridBagConstraints();\r\n\t\tgbc_btnAdiciona.insets = new Insets(0, 0, 5, 0);\r\n\t\tgbc_btnAdiciona.gridx = 0;\r\n\t\tgbc_btnAdiciona.gridy = 2;\r\n\t\tcontentPane.add(btnAdiciona, gbc_btnAdiciona);\r\n\r\n\t\tJScrollPane scrollPane = new JScrollPane();\r\n\t\tGridBagConstraints gbc_scrollPane = new GridBagConstraints();\r\n\t\tgbc_scrollPane.fill = GridBagConstraints.BOTH;\r\n\t\tgbc_scrollPane.gridx = 0;\r\n\t\tgbc_scrollPane.gridy = 3;\r\n\t\tcontentPane.add(scrollPane, gbc_scrollPane);\r\n\r\n\t\ttable = new JTable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic String getToolTipText(MouseEvent e) {\r\n\r\n\t\t\t\tString tip = null;\r\n\r\n\t\t\t\tPoint p = e.getPoint();\r\n\r\n int rowIndex = rowAtPoint(p);\r\n int colIndex = columnAtPoint(p);\r\n\r\n if (rowIndex == -1 || colIndex == -1) {\r\n \treturn null;\r\n }\r\n\r\n try {\r\n tip = getValueAt(rowIndex, colIndex).toString();\r\n } catch (RuntimeException e1) {\r\n\r\n }\r\n\r\n return tip;\r\n\r\n\t\t\t}\r\n\r\n\t\t};\r\n\r\n\t\tscrollPane.setViewportView(table);\r\n\r\n\t\t// final\r\n\t\tconfiguraTabela();\r\n\t}\r\n\r\n\tprotected void adicionarDoAlem() {\r\n\r\n\t\tProduto c = new Produto(123, \"Treta\", new BigDecimal(15));\r\n\r\n\r\n\t\t((ProdutoModel)table.getModel()).adicionarProduto(c);\r\n\r\n\t}\r\n\r\n\tprotected void removerSelecionado() {\r\n\t\tProduto c = getProdutoSelecionadoNaTabela();\r\n\t\tif (c != null) {\r\n\t\t\t((ProdutoModel)table.getModel()).removerProduto(c);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate void configuraTabela() {\r\n\t\ttable.addMouseListener(new MouseAdapter() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void mouseClicked(MouseEvent e) {\r\n\r\n\t\t\t\tif (e.getClickCount() == 2) {\r\n\t\t\t\t\tProduto c = getProdutoSelecionadoNaTabela();\r\n\t\t\t\t\tif (c != null) {\r\n\t\t\t\t\t\tJOptionPane.showMessageDialog(null,\r\n\t\t\t\t\t\t\t\t\"Produto: \" + c.toString());\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t});\r\n\r\n\t}\r\n\r\n\tprotected void preencheTabela() {\r\n\r\n\t\tList lista = new ArrayList<>();\r\n\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\tlista.add(new Produto(i, \"Produto \", new BigDecimal(0)));\r\n\t\t}\r\n\r\n\t\tProdutoModel model = new ProdutoModel(lista);\r\n\t\ttable.setModel(model);\r\n\r\n\t}\r\n\r\n\tprivate Produto getProdutoSelecionadoNaTabela() {\r\n\t\tProduto c = null;\r\n\t\tint index = table.getSelectedRow();\r\n\t\tif (index == -1) {\r\n\t\t\tJOptionPane.showMessageDialog(null, \"Nenhuma linha selecionada!\");\r\n\t\t} else {\r\n\t\t\tc = ((ProdutoModel) table.getModel()).getProdutoNaLinha(index);\r\n\t\t}\r\n\t\treturn c;\r\n\t}\r\n\r\n}\r\n"},"message":{"kind":"string","value":"deu bom"},"old_file":{"kind":"string","value":"CadastroImport/src/br/univel/TelaTabela.java"},"subject":{"kind":"string","value":"deu bom"}}},{"rowIdx":710,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"760da43742c28f6c4998205d6af407c4aa998076"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"stachon/XChange,andre77/XChange,nopy/XChange,timmolter/XChange,LeonidShamis/XChange,npomfret/XChange,gaborkolozsy/XChange,evdubs/XChange,ww3456/XChange,Panchen/XChange,chrisrico/XChange,douggie/XChange,TSavo/XChange"},"new_contents":{"kind":"string","value":"package org.knowm.xchange.examples.bittrex.v1.trade;\n\nimport java.io.IOException;\nimport java.math.BigDecimal;\n\nimport org.knowm.xchange.Exchange;\nimport org.knowm.xchange.bittrex.v1.service.BittrexTradeServiceRaw;\nimport org.knowm.xchange.currency.CurrencyPair;\nimport org.knowm.xchange.dto.Order.OrderType;\nimport org.knowm.xchange.dto.trade.LimitOrder;\nimport org.knowm.xchange.examples.bittrex.v1.BittrexExamplesUtils;\nimport org.knowm.xchange.service.trade.TradeService;\n\npublic class BittrexTradeDemo {\n\n public static void main(String[] args) throws IOException {\n\n Exchange exchange = BittrexExamplesUtils.getExchange();\n\n TradeService tradeService = exchange.getTradeService();\n\n generic(tradeService);\n raw((BittrexTradeServiceRaw) tradeService);\n\n }\n\n private static void generic(TradeService tradeService) throws IOException {\n\n CurrencyPair pair = new CurrencyPair(\"ZET\", \"BTC\");\n LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal(\"0.00001000\")).tradableAmount(new BigDecimal(\"100\"))\n .build();\n\n try {\n String uuid = tradeService.placeLimitOrder(limitOrder);\n System.out.println(\"Order successfully placed. ID=\" + uuid);\n\n Thread.sleep(7000); // wait for order to propagate\n\n System.out.println();\n System.out.println(tradeService.getOpenOrders());\n\n System.out.println(\"Attempting to cancel order \" + uuid);\n boolean cancelled = tradeService.cancelOrder(uuid);\n\n if (cancelled) {\n System.out.println(\"Order successfully canceled.\");\n } else {\n System.out.println(\"Order not successfully canceled.\");\n }\n\n Thread.sleep(7000); // wait for cancellation to propagate\n\n System.out.println();\n System.out.println(tradeService.getOpenOrders());\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private static void raw(BittrexTradeServiceRaw tradeService) throws IOException {\n\n CurrencyPair pair = new CurrencyPair(\"ZET\", \"BTC\");\n LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal(\"0.00001000\")).tradableAmount(new BigDecimal(\"100\"))\n .build();\n\n try {\n String uuid = tradeService.placeBittrexLimitOrder(limitOrder);\n System.out.println(\"Order successfully placed. ID=\" + uuid);\n\n Thread.sleep(7000); // wait for order to propagate\n\n System.out.println();\n System.out.println(tradeService.getBittrexOpenOrders(null));\n\n System.out.println(\"Attempting to cancel order \" + uuid);\n boolean cancelled = tradeService.cancelBittrexLimitOrder(uuid);\n\n if (cancelled) {\n System.out.println(\"Order successfully canceled.\");\n } else {\n System.out.println(\"Order not successfully canceled.\");\n }\n\n Thread.sleep(7000); // wait for cancellation to propagate\n\n System.out.println();\n System.out.println(tradeService.getBittrexOpenOrders(null));\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"xchange-examples/src/main/java/org/knowm/xchange/examples/bittrex/v1/trade/BittrexTradeDemo.java"},"old_contents":{"kind":"string","value":"package org.knowm.xchange.examples.bittrex.v1.trade;\n\nimport java.io.IOException;\nimport java.math.BigDecimal;\n\nimport org.knowm.xchange.Exchange;\nimport org.knowm.xchange.bittrex.v1.service.BittrexTradeServiceRaw;\nimport org.knowm.xchange.currency.CurrencyPair;\nimport org.knowm.xchange.dto.Order.OrderType;\nimport org.knowm.xchange.dto.trade.LimitOrder;\nimport org.knowm.xchange.examples.bittrex.v1.BittrexExamplesUtils;\nimport org.knowm.xchange.service.trade.TradeService;\n\npublic class BittrexTradeDemo {\n\n public static void main(String[] args) throws IOException {\n\n Exchange exchange = BittrexExamplesUtils.getExchange();\n\n TradeService tradeService = exchange.getTradeService();\n\n generic(tradeService);\n raw((BittrexTradeServiceRaw) tradeService);\n\n }\n\n private static void generic(TradeService tradeService) throws IOException {\n\n CurrencyPair pair = new CurrencyPair(\"ZET\", \"BTC\");\n LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal(\"0.00001000\")).tradableAmount(new BigDecimal(\"100\"))\n .build();\n\n try {\n String uuid = tradeService.placeLimitOrder(limitOrder);\n System.out.println(\"Order successfully placed. ID=\" + uuid);\n\n Thread.sleep(7000); // wait for order to propagate\n\n System.out.println();\n System.out.println(tradeService.getOpenOrders());\n\n System.out.println(\"Attempting to cancel order \" + uuid);\n boolean cancelled = tradeService.cancelOrder(uuid);\n\n if (cancelled) {\n System.out.println(\"Order successfully canceled.\");\n } else {\n System.out.println(\"Order not successfully canceled.\");\n }\n\n Thread.sleep(7000); // wait for cancellation to propagate\n\n System.out.println();\n System.out.println(tradeService.getOpenOrders());\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private static void raw(BittrexTradeServiceRaw tradeService) throws IOException {\n\n CurrencyPair pair = new CurrencyPair(\"ZET\", \"BTC\");\n LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal(\"0.00001000\")).tradableAmount(new BigDecimal(\"100\"))\n .build();\n\n try {\n String uuid = tradeService.placeBittrexLimitOrder(limitOrder);\n System.out.println(\"Order successfully placed. ID=\" + uuid);\n\n Thread.sleep(7000); // wait for order to propagate\n\n System.out.println();\n System.out.println(tradeService.getBittrexOpenOrders());\n\n System.out.println(\"Attempting to cancel order \" + uuid);\n boolean cancelled = tradeService.cancelBittrexLimitOrder(uuid);\n\n if (cancelled) {\n System.out.println(\"Order successfully canceled.\");\n } else {\n System.out.println(\"Order not successfully canceled.\");\n }\n\n Thread.sleep(7000); // wait for cancellation to propagate\n\n System.out.println();\n System.out.println(tradeService.getBittrexOpenOrders());\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n"},"message":{"kind":"string","value":"another build fix\n"},"old_file":{"kind":"string","value":"xchange-examples/src/main/java/org/knowm/xchange/examples/bittrex/v1/trade/BittrexTradeDemo.java"},"subject":{"kind":"string","value":"another build fix"}}},{"rowIdx":711,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"793ecb4569633d297f7f407ad4bc76802ffbabd4"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Vlatombe/git-plugin,kzantow/git-plugin,mlgiroux/git-plugin,martinda/git-plugin,ivan-fedorov/git-plugin,mlgiroux/git-plugin,bjacklyn/git-plugin,avdv/git-plugin,KostyaSha/git-plugin,KostyaSha/git-plugin,jenkinsci/git-plugin,Vlatombe/git-plugin,Deveo/git-plugin,martinda/git-plugin,ydubreuil/git-plugin,ndeloof/git-plugin,Talend/git-plugin,martinda/git-plugin,Deveo/git-plugin,jacob-keller/git-plugin,v1v/git-plugin,MarkEWaite/git-plugin,kzantow/git-plugin,loomchild/git-plugin,abaditsegay/git-plugin,kzantow/git-plugin,ldtkms/git-plugin,ldtkms/git-plugin,abaditsegay/git-plugin,recena/git-plugin,jenkinsci/git-plugin,ydubreuil/git-plugin,pauxus/git-plugin,Jellyvision/git-plugin,loomchild/git-plugin,mklein0/git-plugin,jenkinsci/git-plugin,recena/git-plugin,nordstrand/git-plugin,MarkEWaite/git-plugin,ialbors/git-plugin,nKey/git-plugin,nKey/git-plugin,Talend/git-plugin,bjacklyn/git-plugin,pauxus/git-plugin,ialbors/git-plugin,jacob-keller/git-plugin,nordstrand/git-plugin,PinguinAG/git-plugin,nordstrand/git-plugin,PinguinAG/git-plugin,avdv/git-plugin,Deveo/git-plugin,sgargan/git-plugin,mklein0/git-plugin,sgargan/git-plugin,ndeloof/git-plugin,Nonymus/git-plugin,Vlatombe/git-plugin,jenkinsci/git-plugin,MarkEWaite/git-plugin,mlgiroux/git-plugin,Talend/git-plugin,Nonymus/git-plugin,Jellyvision/git-plugin,jacob-keller/git-plugin,recena/git-plugin,abaditsegay/git-plugin,sgargan/git-plugin,ydubreuil/git-plugin,Nonymus/git-plugin,ivan-fedorov/git-plugin,v1v/git-plugin,nKey/git-plugin,mklein0/git-plugin,loomchild/git-plugin,ivan-fedorov/git-plugin,v1v/git-plugin,MarkEWaite/git-plugin,ldtkms/git-plugin,avdv/git-plugin,pauxus/git-plugin,Jellyvision/git-plugin,bjacklyn/git-plugin,ndeloof/git-plugin"},"new_contents":{"kind":"string","value":"package hudson.plugins.git.util;\n\nimport hudson.Extension;\nimport hudson.model.TaskListener;\nimport hudson.plugins.git.Branch;\nimport hudson.plugins.git.BranchSpec;\nimport hudson.plugins.git.GitException;\nimport hudson.plugins.git.GitSCM;\nimport hudson.plugins.git.IGitAPI;\nimport hudson.plugins.git.Revision;\nimport org.kohsuke.stapler.DataBoundConstructor;\nimport org.eclipse.jgit.lib.ObjectId;\n\nimport java.io.IOException;\nimport java.text.MessageFormat;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport static java.util.Collections.emptyList;\n\npublic class DefaultBuildChooser extends BuildChooser {\n @DataBoundConstructor\n public DefaultBuildChooser() {\n }\n\n /**\n * Determines which Revisions to build.\n *\n * If only one branch is chosen and only one repository is listed, then\n * just attempt to find the latest revision number for the chosen branch.\n *\n * If multiple branches are selected or the branches include wildcards, then\n * use the advanced usecase as defined in the getAdvancedCandidateRevisons\n * method.\n *\n * @throws IOException\n * @throws GitException\n */\n public Collection getCandidateRevisions(boolean isPollCall, String singleBranch,\n IGitAPI git, TaskListener listener, BuildData data)\n throws GitException, IOException {\n\n verbose(listener,\"getCandidateRevisions({0},{1},,,{2}) considering branches to build\",isPollCall,singleBranch,data);\n\n // if the branch name contains more wildcards then the simple usecase\n // does not apply and we need to skip to the advanced usecase\n if (singleBranch == null || singleBranch.contains(\"*\"))\n return getAdvancedCandidateRevisions(isPollCall,listener,new GitUtils(listener,git),data);\n\n // check if we're trying to build a specific commit\n // this only makes sense for a build, there is no\n // reason to poll for a commit\n if (!isPollCall && singleBranch.matches(\"[0-9a-f]{6,40}\")) {\n try {\n ObjectId sha1 = git.revParse(singleBranch);\n Revision revision = new Revision(sha1);\n revision.getBranches().add(new Branch(\"detached\", sha1));\n verbose(listener,\"Will build the detached SHA1 {0}\",sha1);\n return Collections.singletonList(revision);\n } catch (GitException e) {\n // revision does not exist, may still be a branch\n // for example a branch called \"badface\" would show up here\n verbose(listener, \"Not a valid SHA1 {0}\", singleBranch);\n }\n }\n\n // if it doesn't contain '/' then it could be either a tag or an unqualified branch\n if (!singleBranch.contains(\"/\")) {\n // the 'branch' could actually be a tag:\n Set tags = git.getTagNames(singleBranch);\n if(tags.size() == 0) {\n // its not a tag, so lets fully qualify the branch\n String repository = gitSCM.getRepositories().get(0).getName();\n singleBranch = repository + \"/\" + singleBranch;\n verbose(listener, \"{0} is not a tag. Qualifying with the repository {1} a a branch\", singleBranch, repository);\n }\n }\n\n try {\n ObjectId sha1 = git.revParse(singleBranch);\n verbose(listener, \"rev-parse {0} -> {1}\", singleBranch, sha1);\n\n // if polling for changes don't select something that has\n // already been built as a build candidate\n if (isPollCall && data.hasBeenBuilt(sha1)) {\n verbose(listener, \"{0} has already been built\", sha1);\n return emptyList();\n }\n\n verbose(listener, \"Found a new commit {0} to be built on {1}\", sha1, singleBranch);\n\n Revision revision = new Revision(sha1);\n revision.getBranches().add(new Branch(singleBranch, sha1));\n return Collections.singletonList(revision);\n } catch (GitException e) {\n // branch does not exist, there is nothing to build\n verbose(listener, \"Failed to rev-parse: {0}\", singleBranch);\n return emptyList();\n }\n }\n\n /**\n * In order to determine which Revisions to build.\n *\n * Does the following :\n * 1. Find all the branch revisions\n * 2. Filter out branches that we don't care about from the revisions.\n * Any Revisions with no interesting branches are dropped.\n * 3. Get rid of any revisions that are wholly subsumed by another\n * revision we're considering.\n * 4. Get rid of any revisions that we've already built.\n *\n * NB: Alternate BuildChooser implementations are possible - this\n * may be beneficial if \"only 1\" branch is to be built, as much of\n * this work is irrelevant in that usecase.\n * @throws IOException\n * @throws GitException\n */\n private Collection getAdvancedCandidateRevisions(boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data) throws GitException, IOException {\n // 1. Get all the (branch) revisions that exist\n Collection revs = utils.getAllBranchRevisions();\n verbose(listener, \"Starting with all the branches: {0}\", revs);\n\n // 2. Filter out any revisions that don't contain any branches that we\n // actually care about (spec)\n for (Iterator i = revs.iterator(); i.hasNext();) {\n Revision r = i.next();\n\n // filter out uninteresting branches\n for (Iterator j = r.getBranches().iterator(); j.hasNext();) {\n Branch b = j.next();\n boolean keep = false;\n for (BranchSpec bspec : gitSCM.getBranches()) {\n if (bspec.matches(b.getName())) {\n keep = true;\n break;\n }\n }\n\n if (!keep) {\n verbose(listener, \"Ignoring {0} because it doesn''t match branch specifier\", b);\n j.remove();\n }\n }\n\n if (r.getBranches().size() == 0) {\n verbose(listener, \"Ignoring {0} because we don''t care about any of the branches that point to it\", r);\n i.remove();\n }\n }\n\n verbose(listener, \"After branch filtering: {0}\", revs);\n\n // 3. We only want 'tip' revisions\n revs = utils.filterTipBranches(revs);\n verbose(listener, \"After non-tip filtering: {0}\", revs);\n\n // 4. Finally, remove any revisions that have already been built.\n verbose(listener, \"Removing what''s already been built: {0}\", data.getBuildsByBranchName());\n for (Iterator i = revs.iterator(); i.hasNext();) {\n Revision r = i.next();\n\n if (data.hasBeenBuilt(r.getSha1())) {\n i.remove();\n }\n }\n verbose(listener, \"After filtering out what''s already been built: {0}\", revs);\n\n // if we're trying to run a build (not an SCM poll) and nothing new\n // was found then just run the last build again\n if (!isPollCall && revs.isEmpty() && data.getLastBuiltRevision() != null) {\n verbose(listener, \"Nothing seems worth building, so falling back to the previously built revision: {0}\", data.getLastBuiltRevision());\n return Collections.singletonList(data.getLastBuiltRevision());\n }\n\n return revs;\n }\n\n /**\n * Write the message to the listener only when the verbose mode is on.\n */\n private void verbose(TaskListener listener, String format, Object... args) {\n if (GitSCM.VERBOSE)\n listener.getLogger().println(MessageFormat.format(format,args));\n }\n\n @Extension\n public static final class DescriptorImpl extends BuildChooserDescriptor {\n @Override\n public String getDisplayName() {\n return \"Default\";\n }\n\n @Override\n public String getLegacyId() {\n return \"Default\";\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java"},"old_contents":{"kind":"string","value":"package hudson.plugins.git.util;\n\nimport hudson.Extension;\nimport hudson.model.TaskListener;\nimport hudson.plugins.git.Branch;\nimport hudson.plugins.git.BranchSpec;\nimport hudson.plugins.git.GitException;\nimport hudson.plugins.git.GitSCM;\nimport hudson.plugins.git.IGitAPI;\nimport hudson.plugins.git.Revision;\nimport org.kohsuke.stapler.DataBoundConstructor;\nimport org.eclipse.jgit.lib.ObjectId;\n\nimport java.io.IOException;\nimport java.text.MessageFormat;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport static java.util.Collections.emptyList;\n\npublic class DefaultBuildChooser extends BuildChooser {\n @DataBoundConstructor\n public DefaultBuildChooser() {\n }\n\n /**\n * Determines which Revisions to build.\n *\n * If only one branch is chosen and only one repository is listed, then\n * just attempt to find the latest revision number for the chosen branch.\n *\n * If multiple branches are selected or the branches include wildcards, then\n * use the advanced usecase as defined in the getAdvancedCandidateRevisons\n * method.\n *\n * @throws IOException\n * @throws GitException\n */\n public Collection getCandidateRevisions(boolean isPollCall, String singleBranch,\n IGitAPI git, TaskListener listener, BuildData data)\n throws GitException, IOException {\n\n verbose(listener,\"getCandidateRevisions({0},{1},,,{2}) considering branches to build\",isPollCall,singleBranch,data);\n\n // if the branch name contains more wildcards then the simple usecase\n // does not apply and we need to skip to the advanced usecase\n if (singleBranch == null || singleBranch.contains(\"*\"))\n return getAdvancedCandidateRevisions(isPollCall,listener,new GitUtils(listener,git),data);\n\n // check if we're trying to build a specific commit\n // this only makes sense for a build, there is no\n // reason to poll for a commit\n if (!isPollCall && singleBranch.matches(\"[0-9a-f]{6,40}\")) {\n try {\n ObjectId sha1 = git.revParse(singleBranch);\n Revision revision = new Revision(sha1);\n revision.getBranches().add(new Branch(\"detached\", sha1));\n verbose(listener,\"Will build the detached SHA1 {0}\",sha1);\n return Collections.singletonList(revision);\n } catch (GitException e) {\n // revision does not exist, may still be a branch\n // for example a branch called \"badface\" would show up here\n verbose(listener, \"Not a valid SHA1 {0}\", singleBranch);\n }\n }\n\n // if it doesn't contain '/' then it could be either a tag or an unqualified branch\n if (!singleBranch.contains(\"/\")) {\n // the 'branch' could actually be a tag:\n Set tags = git.getTagNames(singleBranch);\n if(tags.size() == 0) {\n // its not a tag, so lets fully qualify the branch\n String repository = gitSCM.getRepositories().get(0).getName();\n singleBranch = repository + \"/\" + singleBranch;\n verbose(listener, \"{0} is not a tag. Qualifying with the repository {1} a a branch\", singleBranch, repository);\n }\n }\n\n try {\n ObjectId sha1 = git.revParse(singleBranch);\n verbose(listener, \"rev-parse {0} -> {1}\", singleBranch, sha1);\n\n // if polling for changes don't select something that has\n // already been built as a build candidate\n if (isPollCall && data.hasBeenBuilt(sha1)) {\n verbose(listener, \"{0} has already been built\", sha1);\n return emptyList();\n }\n\n verbose(listener, \"Found a new commit {0} to be built on {1}\", sha1, singleBranch);\n\n Revision revision = new Revision(sha1);\n revision.getBranches().add(new Branch(singleBranch, sha1));\n return Collections.singletonList(revision);\n } catch (GitException e) {\n // branch does not exist, there is nothing to build\n verbose(listener, \"Failed to rev-parse: {0}\", singleBranch);\n return emptyList();\n }\n }\n\n /**\n * In order to determine which Revisions to build.\n *\n * Does the following :\n * 1. Find all the branch revisions\n * 2. Filter out branches that we don't care about from the revisions.\n * Any Revisions with no interesting branches are dropped.\n * 3. Get rid of any revisions that are wholly subsumed by another\n * revision we're considering.\n * 4. Get rid of any revisions that we've already built.\n *\n * NB: Alternate BuildChooser implementations are possible - this\n * may be beneficial if \"only 1\" branch is to be built, as much of\n * this work is irrelevant in that usecase.\n * @throws IOException\n * @throws GitException\n */\n private Collection getAdvancedCandidateRevisions(boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data) throws GitException, IOException {\n // 1. Get all the (branch) revisions that exist\n Collection revs = utils.getAllBranchRevisions();\n verbose(listener, \"Starting with all the branches: {0}\", revs);\n\n // 2. Filter out any revisions that don't contain any branches that we\n // actually care about (spec)\n for (Iterator i = revs.iterator(); i.hasNext();) {\n Revision r = i.next();\n\n // filter out uninteresting branches\n for (Iterator j = r.getBranches().iterator(); j.hasNext();) {\n Branch b = j.next();\n boolean keep = false;\n for (BranchSpec bspec : gitSCM.getBranches()) {\n if (bspec.matches(b.getName())) {\n keep = true;\n break;\n }\n }\n\n if (!keep) {\n verbose(listener, \"Ignoring {0} because it doesn't match branch specifier\", b);\n j.remove();\n }\n }\n\n if (r.getBranches().size() == 0) {\n verbose(listener, \"Ignoring {0} because we don't care about any of the branches that point to it\", r);\n i.remove();\n }\n }\n\n verbose(listener, \"After branch filtering: {0}\", revs);\n\n // 3. We only want 'tip' revisions\n revs = utils.filterTipBranches(revs);\n verbose(listener, \"After non-tip filtering: {0}\", revs);\n\n // 4. Finally, remove any revisions that have already been built.\n verbose(listener, \"Removing what''s already been built: {0}\", data.getBuildsByBranchName());\n for (Iterator i = revs.iterator(); i.hasNext();) {\n Revision r = i.next();\n\n if (data.hasBeenBuilt(r.getSha1())) {\n i.remove();\n }\n }\n verbose(listener, \"After filtering out what''s already been built: {0}\", revs);\n\n // if we're trying to run a build (not an SCM poll) and nothing new\n // was found then just run the last build again\n if (!isPollCall && revs.isEmpty() && data.getLastBuiltRevision() != null) {\n verbose(listener, \"Nothing seems worth building, so falling back to the previously built revision: {0}\", data.getLastBuiltRevision());\n return Collections.singletonList(data.getLastBuiltRevision());\n }\n\n return revs;\n }\n\n /**\n * Write the message to the listener only when the verbose mode is on.\n */\n private void verbose(TaskListener listener, String format, Object... args) {\n if (GitSCM.VERBOSE)\n listener.getLogger().println(MessageFormat.format(format,args));\n }\n\n @Extension\n public static final class DescriptorImpl extends BuildChooserDescriptor {\n @Override\n public String getDisplayName() {\n return \"Default\";\n }\n\n @Override\n public String getLegacyId() {\n return \"Default\";\n }\n }\n}\n"},"message":{"kind":"string","value":"Add missing single-quote in calls to MessageFormat\n\nCloses pull request #29"},"old_file":{"kind":"string","value":"src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java"},"subject":{"kind":"string","value":"Add missing single-quote in calls to MessageFormat"}}},{"rowIdx":712,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"553418c0958317310181d7d4998b22b405cf719c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"McJty/LostCities"},"new_contents":{"kind":"string","value":"package mcjty.lostcities.dimensions.world;\n\nimport mcjty.lib.compat.CompatChunkGenerator;\nimport mcjty.lib.compat.CompatMapGenStructure;\nimport mcjty.lib.tools.EntityTools;\nimport mcjty.lostcities.api.IChunkPrimerFactory;\nimport mcjty.lostcities.api.ILostChunkGenerator;\nimport mcjty.lostcities.api.ILostChunkInfo;\nimport mcjty.lostcities.config.LostCityProfile;\nimport mcjty.lostcities.dimensions.world.lost.BiomeInfo;\nimport mcjty.lostcities.dimensions.world.lost.BuildingInfo;\nimport mcjty.lostcities.dimensions.world.lost.cityassets.AssetRegistries;\nimport mcjty.lostcities.dimensions.world.lost.cityassets.WorldStyle;\nimport mcjty.lostcities.varia.ChunkCoord;\nimport net.minecraft.block.BlockChest;\nimport net.minecraft.block.BlockFalling;\nimport net.minecraft.block.BlockSapling;\nimport net.minecraft.block.BlockVine;\nimport net.minecraft.block.properties.PropertyBool;\nimport net.minecraft.block.state.IBlockState;\nimport net.minecraft.entity.EnumCreatureType;\nimport net.minecraft.init.Biomes;\nimport net.minecraft.init.Blocks;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.tileentity.TileEntityChest;\nimport net.minecraft.tileentity.TileEntityMobSpawner;\nimport net.minecraft.util.EnumFacing;\nimport net.minecraft.util.ResourceLocation;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.util.math.ChunkPos;\nimport net.minecraft.world.World;\nimport net.minecraft.world.WorldEntitySpawner;\nimport net.minecraft.world.WorldType;\nimport net.minecraft.world.biome.Biome;\nimport net.minecraft.world.chunk.Chunk;\nimport net.minecraft.world.chunk.ChunkPrimer;\nimport net.minecraft.world.gen.ChunkProviderSettings;\nimport net.minecraft.world.gen.MapGenBase;\nimport net.minecraft.world.gen.MapGenCaves;\nimport net.minecraft.world.gen.MapGenRavine;\nimport net.minecraft.world.gen.feature.WorldGenDungeons;\nimport net.minecraft.world.gen.feature.WorldGenLakes;\nimport net.minecraft.world.gen.structure.*;\nimport net.minecraft.world.storage.loot.LootTableList;\nimport net.minecraftforge.common.MinecraftForge;\nimport net.minecraftforge.event.terraingen.PopulateChunkEvent;\nimport net.minecraftforge.event.terraingen.TerrainGen;\nimport org.apache.commons.lang3.tuple.Pair;\n\nimport java.util.*;\n\nimport static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.*;\n\npublic class LostCityChunkGenerator implements CompatChunkGenerator, ILostChunkGenerator {\n\n public LostCityProfile profile; // Current profile\n public WorldStyle worldStyle;\n\n public Random rand;\n public long seed;\n public int dimensionId;\n\n public World worldObj;\n public WorldType worldType;\n public final LostCitiesTerrainGenerator terrainGenerator;\n\n private ChunkProviderSettings settings = null;\n\n private Biome[] biomesForGeneration;\n\n private MapGenBase caveGenerator;\n\n // Sometimes we have to precalculate primers for a chunk before the\n // chunk is generated. In that case we cache them here so that when the\n // chunk is really generated it will find it and use that instead of\n // making that primer again\n // @todo, make this cache timed so that primers expire if they are not used quickly enough?\n private Map cachedPrimers = new HashMap<>();\n private Map cachedHeightmaps = new HashMap<>();\n\n private MapGenStronghold strongholdGenerator = new MapGenStronghold();\n private StructureOceanMonument oceanMonumentGenerator = new StructureOceanMonument();\n private MapGenVillage villageGenerator = new MapGenVillage();\n private MapGenMineshaft mineshaftGenerator = new MapGenMineshaft();\n private MapGenScatteredFeature scatteredFeatureGenerator = new MapGenScatteredFeature();\n\n public ChunkProviderSettings getSettings() {\n if (settings == null) {\n ChunkProviderSettings.Factory factory = new ChunkProviderSettings.Factory();\n settings = factory.build();\n }\n return settings;\n }\n\n // Holds ravine generator\n private MapGenBase ravineGenerator = new MapGenRavine();\n\n public IChunkPrimerFactory otherGenerator = null;\n\n public LostCityChunkGenerator(World world, IChunkPrimerFactory otherGenerator) {\n this(world, world.getSeed());\n this.otherGenerator = otherGenerator;\n }\n\n public LostCityChunkGenerator(World world, long seed) {\n\n {\n caveGenerator = new LostGenCaves(this);\n caveGenerator = TerrainGen.getModdedMapGen(caveGenerator, CAVE);\n strongholdGenerator = (MapGenStronghold) TerrainGen.getModdedMapGen(strongholdGenerator, STRONGHOLD);\n\n villageGenerator = (MapGenVillage) TerrainGen.getModdedMapGen(villageGenerator, VILLAGE);\n mineshaftGenerator = (MapGenMineshaft) TerrainGen.getModdedMapGen(mineshaftGenerator, MINESHAFT);\n scatteredFeatureGenerator = (MapGenScatteredFeature) TerrainGen.getModdedMapGen(scatteredFeatureGenerator, SCATTERED_FEATURE);\n ravineGenerator = TerrainGen.getModdedMapGen(ravineGenerator, RAVINE);\n oceanMonumentGenerator = (StructureOceanMonument) TerrainGen.getModdedMapGen(oceanMonumentGenerator, OCEAN_MONUMENT);\n }\n\n dimensionId = world.provider.getDimension();\n profile = LostWorldType.getProfile(world);\n\n System.out.println(\"LostCityChunkGenerator.LostCityChunkGenerator: profile=\" + profile.getName());\n worldStyle = AssetRegistries.WORLDSTYLES.get(profile.getWorldStyle());\n if (worldStyle == null) {\n throw new RuntimeException(\"Unknown worldstyle '\" + profile.getWorldStyle() + \"'!\");\n }\n\n String generatorOptions = profile.GENERATOR_OPTIONS;\n if (generatorOptions != null && !generatorOptions.isEmpty()) {\n this.settings = ChunkProviderSettings.Factory.jsonToFactory(generatorOptions).build();\n }\n\n this.worldObj = world;\n\n this.worldType = world.getWorldInfo().getTerrainType();\n\n this.seed = seed;\n this.rand = new Random((seed + 516) * 314);\n\n int waterLevel = (byte) (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET);\n world.setSeaLevel(waterLevel);\n\n terrainGenerator = new LostCitiesTerrainGenerator(this);\n terrainGenerator.setup(world);\n }\n\n public ChunkPrimer generatePrimer(int chunkX, int chunkZ) {\n this.rand.setSeed(chunkX * 341873128712L + chunkZ * 132897987541L);\n ChunkPrimer chunkprimer = new ChunkPrimer();\n\n if (otherGenerator != null) {\n // For ATG, experimental\n otherGenerator.fillChunk(chunkX, chunkZ, chunkprimer);\n } else {\n terrainGenerator.doCoreChunk(chunkX, chunkZ, chunkprimer);\n }\n return chunkprimer;\n }\n\n // Get a heightmap for a chunk. If needed calculate (and cache) a primer\n public ChunkHeightmap getHeightmap(int chunkX, int chunkZ) {\n ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ);\n if (cachedHeightmaps.containsKey(key)) {\n return cachedHeightmaps.get(key);\n } else if (cachedPrimers.containsKey(key)) {\n ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key));\n cachedHeightmaps.put(key, heightmap);\n return heightmap;\n } else {\n ChunkPrimer primer = generatePrimer(chunkX, chunkZ);\n cachedPrimers.put(key, primer);\n ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key));\n cachedHeightmaps.put(key, heightmap);\n return heightmap;\n }\n }\n\n\n\n @Override\n public Chunk provideChunk(int chunkX, int chunkZ) {\n LostCitiesTerrainGenerator.setupChars();\n boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this);\n\n ChunkPrimer chunkprimer;\n if (isCity) {\n chunkprimer = new ChunkPrimer();\n } else {\n ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ);\n if (cachedPrimers.containsKey(key)) {\n // We calculated a primer earlier. Reuse it\n chunkprimer = cachedPrimers.get(key);\n cachedPrimers.remove(key);\n } else {\n chunkprimer = generatePrimer(chunkX, chunkZ);\n }\n // Calculate the chunk heightmap in case we need it later\n if (!cachedHeightmaps.containsKey(key)) {\n // We might need this later\n cachedHeightmaps.put(key, new ChunkHeightmap(chunkprimer));\n }\n }\n\n terrainGenerator.generate(chunkX, chunkZ, chunkprimer);\n\n this.biomesForGeneration = this.worldObj.getBiomeProvider().getBiomes(this.biomesForGeneration, chunkX * 16, chunkZ * 16, 16, 16);\n terrainGenerator.replaceBlocksForBiome(chunkX, chunkZ, chunkprimer, this.biomesForGeneration);\n\n if (profile.GENERATE_CAVES) {\n this.caveGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n if (profile.GENERATE_RAVINES) {\n if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) {\n this.ravineGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n }\n\n if (profile.GENERATE_MINESHAFTS) {\n this.mineshaftGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n if (profile.GENERATE_VILLAGES) {\n if (profile.PREVENT_VILLAGES_IN_CITIES) {\n if (!isCity) {\n this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n } else {\n this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n }\n\n if (profile.GENERATE_STRONGHOLDS) {\n this.strongholdGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n if (profile.GENERATE_SCATTERED) {\n this.scatteredFeatureGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n if (profile.GENERATE_OCEANMONUMENTS) {\n this.oceanMonumentGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n Chunk chunk = new Chunk(this.worldObj, chunkprimer, chunkX, chunkZ);\n byte[] abyte = chunk.getBiomeArray();\n\n for (int i = 0; i < abyte.length; ++i) {\n abyte[i] = (byte) Biome.getIdForBiome(this.biomesForGeneration[i]);\n }\n\n chunk.generateSkylightMap();\n\n return chunk;\n }\n\n private void generateTrees(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) {\n BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider);\n for (BlockPos pos : info.getSaplingTodo()) {\n IBlockState state = world.getBlockState(pos);\n if (state.getBlock() == Blocks.SAPLING) {\n ((BlockSapling)Blocks.SAPLING).generateTree(world, pos, state, random);\n }\n }\n info.clearSaplingTodo();\n }\n\n private void generateVines(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) {\n int cx = chunkX * 16;\n int cz = chunkZ * 16;\n BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider);\n\n if (info.hasBuilding) {\n BuildingInfo adjacent = info.getXmax();\n int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3));\n for (int z = 0; z < 15; z++) {\n for (int y = bottom; y < (info.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.WEST, new BlockPos(cx + 16, y, cz + z), new BlockPos(cx + 15, y, cz + z));\n }\n }\n }\n }\n if (info.getXmax().hasBuilding) {\n BuildingInfo adjacent = info.getXmax();\n int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3));\n for (int z = 0; z < 15; z++) {\n for (int y = bottom; y < (adjacent.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.EAST, new BlockPos(cx + 15, y, cz + z), new BlockPos(cx + 16, y, cz + z));\n }\n }\n }\n }\n\n if (info.hasBuilding) {\n BuildingInfo adjacent = info.getZmax();\n int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3));\n for (int x = 0; x < 15; x++) {\n for (int y = bottom; y < (info.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.NORTH, new BlockPos(cx + x, y, cz + 16), new BlockPos(cx + x, y, cz + 15));\n }\n }\n }\n }\n if (info.getZmax().hasBuilding) {\n BuildingInfo adjacent = info.getZmax();\n int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3));\n for (int x = 0; x < 15; x++) {\n for (int y = bottom; y < (adjacent.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.SOUTH, new BlockPos(cx + x, y, cz + 15), new BlockPos(cx + x, y, cz + 16));\n }\n }\n }\n }\n }\n\n private void createVineStrip(Random random, World world, int bottom, PropertyBool direction, BlockPos pos, BlockPos vineHolderPos) {\n if (world.isAirBlock(vineHolderPos)) {\n return;\n }\n if (!world.isAirBlock(pos)) {\n return;\n }\n world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true));\n pos = pos.down();\n while (pos.getY() >= bottom && random.nextFloat() < .8f) {\n if (!world.isAirBlock(pos)) {\n return;\n }\n world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true));\n pos = pos.down();\n }\n }\n\n private void generateLootSpawners(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator chunkGenerator) {\n BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, chunkGenerator);\n\n for (Pair pair : info.getMobSpawnerTodo()) {\n BlockPos pos = pair.getKey();\n // Double check that it is still a spawner (could be destroyed by explosion)\n if (world.getBlockState(pos).getBlock() == Blocks.MOB_SPAWNER) {\n TileEntity tileentity = world.getTileEntity(pos);\n if (tileentity instanceof TileEntityMobSpawner) {\n TileEntityMobSpawner spawner = (TileEntityMobSpawner) tileentity;\n String id = pair.getValue();\n String fixedId = EntityTools.fixEntityId(id);\n EntityTools.setSpawnerEntity(world, spawner, new ResourceLocation(fixedId), fixedId);\n }\n }\n }\n info.clearMobSpawnerTodo();\n\n\n for (Pair pair : info.getChestTodo()) {\n BlockPos pos = pair.getKey();\n // Double check that it is still a chest (could be destroyed by explosion)\n IBlockState state = world.getBlockState(pos);\n if (state.getBlock() == Blocks.CHEST) {\n if (chunkGenerator.profile.GENERATE_LOOT) {\n createLootChest(random, world, pos, pair.getRight());\n }\n }\n }\n info.clearChestTodo();\n\n\n for (BlockPos pos : info.getGenericTodo()) {\n IBlockState state = world.getBlockState(pos);\n if (state.getBlock() == Blocks.GLOWSTONE) {\n world.setBlockState(pos, state, 3);\n }\n }\n info.clearGenericTodo();\n }\n\n\n private void createLootChest(Random random, World world, BlockPos pos, String lootTable) {\n world.setBlockState(pos, Blocks.CHEST.getDefaultState().withProperty(BlockChest.FACING, EnumFacing.SOUTH));\n TileEntity tileentity = world.getTileEntity(pos);\n if (tileentity instanceof TileEntityChest) {\n if (lootTable != null) {\n ((TileEntityChest) tileentity).setLootTable(new ResourceLocation(lootTable), random.nextLong());\n } else {\n switch (random.nextInt(30)) {\n case 0:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_DESERT_PYRAMID, random.nextLong());\n break;\n case 1:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_JUNGLE_TEMPLE, random.nextLong());\n break;\n case 2:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_VILLAGE_BLACKSMITH, random.nextLong());\n break;\n case 3:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_ABANDONED_MINESHAFT, random.nextLong());\n break;\n case 4:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_NETHER_BRIDGE, random.nextLong());\n break;\n default:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_SIMPLE_DUNGEON, random.nextLong());\n break;\n }\n }\n }\n }\n\n\n @Override\n public void populate(int chunkX, int chunkZ) {\n BlockFalling.fallInstantly = true;\n int x = chunkX * 16;\n int z = chunkZ * 16;\n World w = this.worldObj;\n Biome Biome = w.getBiomeForCoordsBody(new BlockPos(x + 16, 0, z + 16));\n this.rand.setSeed(w.getSeed());\n long i1 = this.rand.nextLong() / 2L * 2L + 1L;\n long j1 = this.rand.nextLong() / 2L * 2L + 1L;\n this.rand.setSeed(chunkX * i1 + chunkZ * j1 ^ w.getSeed());\n boolean flag = false;\n\n MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Pre(this, w, rand, chunkX, chunkZ, flag));\n\n ChunkPos cp = new ChunkPos(chunkX, chunkZ);\n\n if (profile.GENERATE_MINESHAFTS) {\n this.mineshaftGenerator.generateStructure(w, this.rand, cp);\n }\n if (profile.GENERATE_VILLAGES) {\n if (profile.PREVENT_VILLAGES_IN_CITIES) {\n if (!BuildingInfo.isCity(chunkX, chunkZ, this)) {\n flag = this.villageGenerator.generateStructure(w, this.rand, cp);\n }\n } else {\n flag = this.villageGenerator.generateStructure(w, this.rand, cp);\n }\n }\n if (profile.GENERATE_STRONGHOLDS) {\n this.strongholdGenerator.generateStructure(w, this.rand, cp);\n }\n if (profile.GENERATE_SCATTERED) {\n this.scatteredFeatureGenerator.generateStructure(w, this.rand, cp);\n }\n if (profile.GENERATE_OCEANMONUMENTS) {\n this.oceanMonumentGenerator.generateStructure(w, this.rand, cp);\n }\n\n int k1;\n int l1;\n int i2;\n\n if (profile.GENERATE_LAKES) {\n boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this);\n if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) {\n if (Biome != Biomes.DESERT && Biome != Biomes.DESERT_HILLS && !flag && this.rand.nextInt(4) == 0\n && TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAKE)) {\n k1 = x + this.rand.nextInt(16) + 8;\n l1 = this.rand.nextInt(256);\n i2 = z + this.rand.nextInt(16) + 8;\n (new WorldGenLakes(Blocks.WATER)).generate(w, this.rand, new BlockPos(k1, l1, i2));\n }\n\n if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAVA) && !flag && this.rand.nextInt(8) == 0) {\n k1 = x + this.rand.nextInt(16) + 8;\n l1 = this.rand.nextInt(this.rand.nextInt(248) + 8);\n i2 = z + this.rand.nextInt(16) + 8;\n\n if (l1 < (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET) || this.rand.nextInt(10) == 0) {\n (new WorldGenLakes(Blocks.LAVA)).generate(w, this.rand, new BlockPos(k1, l1, i2));\n }\n }\n }\n }\n\n boolean doGen = false;\n if (profile.GENERATE_DUNGEONS) {\n doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.DUNGEON);\n for (k1 = 0; doGen && k1 < 8; ++k1) {\n l1 = x + this.rand.nextInt(16) + 8;\n i2 = this.rand.nextInt(256);\n int j2 = z + this.rand.nextInt(16) + 8;\n (new WorldGenDungeons()).generate(w, this.rand, new BlockPos(l1, i2, j2));\n }\n }\n\n BlockPos pos = new BlockPos(x, 0, z);\n Biome.decorate(w, this.rand, pos);\n\n if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ANIMALS)) {\n WorldEntitySpawner.performWorldGenSpawning(w, Biome, x + 8, z + 8, 16, 16, this.rand);\n }\n x += 8;\n z += 8;\n\n doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ICE);\n for (k1 = 0; doGen && k1 < 16; ++k1) {\n for (l1 = 0; l1 < 16; ++l1) {\n i2 = w.getPrecipitationHeight(new BlockPos(x + k1, 0, z + l1)).getY();\n\n if (w.canBlockFreeze(new BlockPos(k1 + x, i2 - 1, l1 + z), false)) {\n w.setBlockState(new BlockPos(k1 + x, i2 - 1, l1 + z), Blocks.ICE.getDefaultState(), 2);\n }\n\n if (w.canSnowAt(new BlockPos(k1 + x, i2, l1 + z), true)) {\n w.setBlockState(new BlockPos(k1 + x, i2, l1 + z), Blocks.SNOW_LAYER.getDefaultState(), 2);\n }\n }\n }\n\n generateTrees(rand, chunkX, chunkZ, w, this);\n generateVines(rand, chunkX, chunkZ, w, this);\n generateLootSpawners(rand, chunkX, chunkZ, w, this);\n\n MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Post(this, w, rand, chunkX, chunkZ, flag));\n\n BlockFalling.fallInstantly = false;\n }\n\n @Override\n public boolean generateStructures(Chunk chunkIn, int x, int z) {\n boolean flag = false;\n\n if (profile.GENERATE_OCEANMONUMENTS) {\n if (chunkIn.getInhabitedTime() < 3600L) {\n flag |= this.oceanMonumentGenerator.generateStructure(this.worldObj, this.rand, new ChunkPos(x, z));\n }\n }\n\n return flag;\n }\n\n @Override\n public List getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) {\n return getDefaultCreatures(creatureType, pos);\n }\n\n private List getDefaultCreatures(EnumCreatureType creatureType, BlockPos pos) {\n Biome Biome = this.worldObj.getBiomeForCoordsBody(pos);\n if (creatureType == EnumCreatureType.MONSTER) {\n if (profile.GENERATE_SCATTERED) {\n if (this.scatteredFeatureGenerator.isInsideStructure(pos)) {\n return this.scatteredFeatureGenerator.getScatteredFeatureSpawnList();\n }\n }\n if (profile.GENERATE_OCEANMONUMENTS) {\n if (this.oceanMonumentGenerator.isPositionInStructure(this.worldObj, pos)) {\n return this.oceanMonumentGenerator.getScatteredFeatureSpawnList();\n }\n }\n }\n\n return Biome.getSpawnableList(creatureType);\n }\n\n @Override\n public BlockPos clGetStrongholdGen(World worldIn, String structureName, BlockPos position) {\n return \"Stronghold\".equals(structureName) && this.strongholdGenerator != null\n ? CompatMapGenStructure.getClosestStrongholdPos(this.strongholdGenerator, worldIn, position)\n : null;\n }\n\n @Override\n public void recreateStructures(Chunk chunkIn, int x, int z) {\n if (profile.GENERATE_MINESHAFTS) {\n this.mineshaftGenerator.generate(this.worldObj, x, z, null);\n }\n\n if (profile.GENERATE_VILLAGES) {\n if (profile.PREVENT_VILLAGES_IN_CITIES) {\n if (!BuildingInfo.isCity(x, z, this)) {\n this.villageGenerator.generate(this.worldObj, x, z, null);\n }\n } else {\n this.villageGenerator.generate(this.worldObj, x, z, null);\n }\n }\n\n if (profile.GENERATE_STRONGHOLDS) {\n this.strongholdGenerator.generate(this.worldObj, x, z, null);\n }\n\n if (profile.GENERATE_SCATTERED) {\n this.scatteredFeatureGenerator.generate(this.worldObj, x, z, null);\n }\n\n if (profile.GENERATE_OCEANMONUMENTS) {\n this.oceanMonumentGenerator.generate(this.worldObj, x, z, null);\n }\n }\n\n @Override\n public ILostChunkInfo getChunkInfo(int chunkX, int chunkZ) {\n return BuildingInfo.getBuildingInfo(chunkX, chunkZ, this);\n }\n\n @Override\n public int getRealHeight(int level) {\n return profile.GROUNDLEVEL + level * 6;\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/mcjty/lostcities/dimensions/world/LostCityChunkGenerator.java"},"old_contents":{"kind":"string","value":"package mcjty.lostcities.dimensions.world;\n\nimport mcjty.lib.compat.CompatChunkGenerator;\nimport mcjty.lib.compat.CompatMapGenStructure;\nimport mcjty.lib.tools.EntityTools;\nimport mcjty.lostcities.api.IChunkPrimerFactory;\nimport mcjty.lostcities.api.ILostChunkGenerator;\nimport mcjty.lostcities.api.ILostChunkInfo;\nimport mcjty.lostcities.config.LostCityProfile;\nimport mcjty.lostcities.dimensions.world.lost.BiomeInfo;\nimport mcjty.lostcities.dimensions.world.lost.BuildingInfo;\nimport mcjty.lostcities.dimensions.world.lost.cityassets.AssetRegistries;\nimport mcjty.lostcities.dimensions.world.lost.cityassets.WorldStyle;\nimport mcjty.lostcities.varia.ChunkCoord;\nimport net.minecraft.block.BlockChest;\nimport net.minecraft.block.BlockFalling;\nimport net.minecraft.block.BlockSapling;\nimport net.minecraft.block.BlockVine;\nimport net.minecraft.block.properties.PropertyBool;\nimport net.minecraft.block.state.IBlockState;\nimport net.minecraft.entity.EnumCreatureType;\nimport net.minecraft.init.Biomes;\nimport net.minecraft.init.Blocks;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.tileentity.TileEntityChest;\nimport net.minecraft.tileentity.TileEntityMobSpawner;\nimport net.minecraft.util.EnumFacing;\nimport net.minecraft.util.ResourceLocation;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.util.math.ChunkPos;\nimport net.minecraft.world.World;\nimport net.minecraft.world.WorldEntitySpawner;\nimport net.minecraft.world.WorldType;\nimport net.minecraft.world.biome.Biome;\nimport net.minecraft.world.chunk.Chunk;\nimport net.minecraft.world.chunk.ChunkPrimer;\nimport net.minecraft.world.gen.ChunkProviderSettings;\nimport net.minecraft.world.gen.MapGenBase;\nimport net.minecraft.world.gen.MapGenCaves;\nimport net.minecraft.world.gen.MapGenRavine;\nimport net.minecraft.world.gen.feature.WorldGenDungeons;\nimport net.minecraft.world.gen.feature.WorldGenLakes;\nimport net.minecraft.world.gen.structure.*;\nimport net.minecraft.world.storage.loot.LootTableList;\nimport net.minecraftforge.common.MinecraftForge;\nimport net.minecraftforge.event.terraingen.PopulateChunkEvent;\nimport net.minecraftforge.event.terraingen.TerrainGen;\nimport org.apache.commons.lang3.tuple.Pair;\n\nimport java.util.*;\n\nimport static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.*;\n\npublic class LostCityChunkGenerator implements CompatChunkGenerator, ILostChunkGenerator {\n\n public LostCityProfile profile; // Current profile\n public WorldStyle worldStyle;\n\n public Random rand;\n public long seed;\n public int dimensionId;\n\n public World worldObj;\n public WorldType worldType;\n public final LostCitiesTerrainGenerator terrainGenerator;\n\n private ChunkProviderSettings settings = null;\n\n private Biome[] biomesForGeneration;\n\n private MapGenBase caveGenerator;\n\n // Sometimes we have to precalculate primers for a chunk before the\n // chunk is generated. In that case we cache them here so that when the\n // chunk is really generated it will find it and use that instead of\n // making that primer again\n // @todo, make this cache timed so that primers expire if they are not used quickly enough?\n private Map cachedPrimers = new HashMap<>();\n private Map cachedHeightmaps = new HashMap<>();\n\n private MapGenStronghold strongholdGenerator = new MapGenStronghold();\n private StructureOceanMonument oceanMonumentGenerator = new StructureOceanMonument();\n private MapGenVillage villageGenerator = new MapGenVillage();\n private MapGenMineshaft mineshaftGenerator = new MapGenMineshaft();\n private MapGenScatteredFeature scatteredFeatureGenerator = new MapGenScatteredFeature();\n\n public ChunkProviderSettings getSettings() {\n if (settings == null) {\n ChunkProviderSettings.Factory factory = new ChunkProviderSettings.Factory();\n settings = factory.build();\n }\n return settings;\n }\n\n // Holds ravine generator\n private MapGenBase ravineGenerator = new MapGenRavine();\n\n public IChunkPrimerFactory otherGenerator = null;\n\n public LostCityChunkGenerator(World world, IChunkPrimerFactory otherGenerator) {\n this(world, world.getSeed());\n this.otherGenerator = otherGenerator;\n }\n\n public LostCityChunkGenerator(World world, long seed) {\n\n {\n caveGenerator = new LostGenCaves(this);\n caveGenerator = TerrainGen.getModdedMapGen(caveGenerator, CAVE);\n strongholdGenerator = (MapGenStronghold) TerrainGen.getModdedMapGen(strongholdGenerator, STRONGHOLD);\n\n villageGenerator = (MapGenVillage) TerrainGen.getModdedMapGen(villageGenerator, VILLAGE);\n mineshaftGenerator = (MapGenMineshaft) TerrainGen.getModdedMapGen(mineshaftGenerator, MINESHAFT);\n scatteredFeatureGenerator = (MapGenScatteredFeature) TerrainGen.getModdedMapGen(scatteredFeatureGenerator, SCATTERED_FEATURE);\n ravineGenerator = TerrainGen.getModdedMapGen(ravineGenerator, RAVINE);\n oceanMonumentGenerator = (StructureOceanMonument) TerrainGen.getModdedMapGen(oceanMonumentGenerator, OCEAN_MONUMENT);\n }\n\n dimensionId = world.provider.getDimension();\n profile = LostWorldType.getProfile(world);\n\n System.out.println(\"LostCityChunkGenerator.LostCityChunkGenerator: profile=\" + profile.getName());\n worldStyle = AssetRegistries.WORLDSTYLES.get(profile.getWorldStyle());\n if (worldStyle == null) {\n throw new RuntimeException(\"Unknown worldstyle '\" + profile.getWorldStyle() + \"'!\");\n }\n\n String generatorOptions = profile.GENERATOR_OPTIONS;\n if (generatorOptions != null && !generatorOptions.isEmpty()) {\n this.settings = ChunkProviderSettings.Factory.jsonToFactory(generatorOptions).build();\n }\n\n this.worldObj = world;\n\n this.worldType = world.getWorldInfo().getTerrainType();\n\n this.seed = seed;\n this.rand = new Random((seed + 516) * 314);\n\n int waterLevel = (byte) (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET);\n world.setSeaLevel(waterLevel);\n\n terrainGenerator = new LostCitiesTerrainGenerator(this);\n terrainGenerator.setup(world);\n }\n\n public ChunkPrimer generatePrimer(int chunkX, int chunkZ) {\n this.rand.setSeed(chunkX * 341873128712L + chunkZ * 132897987541L);\n ChunkPrimer chunkprimer = new ChunkPrimer();\n\n if (otherGenerator != null) {\n // For ATG, experimental\n otherGenerator.fillChunk(chunkX, chunkZ, chunkprimer);\n } else {\n terrainGenerator.doCoreChunk(chunkX, chunkZ, chunkprimer);\n }\n return chunkprimer;\n }\n\n // Get a heightmap for a chunk. If needed calculate (and cache) a primer\n public ChunkHeightmap getHeightmap(int chunkX, int chunkZ) {\n ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ);\n if (cachedHeightmaps.containsKey(key)) {\n return cachedHeightmaps.get(key);\n } else if (cachedPrimers.containsKey(key)) {\n ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key));\n cachedHeightmaps.put(key, heightmap);\n return heightmap;\n } else {\n ChunkPrimer primer = generatePrimer(chunkX, chunkZ);\n cachedPrimers.put(key, primer);\n ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key));\n cachedHeightmaps.put(key, heightmap);\n return heightmap;\n }\n }\n\n\n private static Set providedChunks = new HashSet<>();\n\n\n @Override\n public Chunk provideChunk(int chunkX, int chunkZ) {\n LostCitiesTerrainGenerator.setupChars();\n boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this);\n\n ChunkPrimer chunkprimer;\n if (isCity) {\n chunkprimer = new ChunkPrimer();\n } else {\n ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ);\n if (cachedPrimers.containsKey(key)) {\n // We calculated a primer earlier. Reuse it\n chunkprimer = cachedPrimers.get(key);\n cachedPrimers.remove(key);\n } else {\n chunkprimer = generatePrimer(chunkX, chunkZ);\n }\n // Calculate the chunk heightmap in case we need it later\n if (!cachedHeightmaps.containsKey(key)) {\n // We might need this later\n cachedHeightmaps.put(key, new ChunkHeightmap(chunkprimer));\n }\n }\n\n terrainGenerator.generate(chunkX, chunkZ, chunkprimer);\n\n this.biomesForGeneration = this.worldObj.getBiomeProvider().getBiomes(this.biomesForGeneration, chunkX * 16, chunkZ * 16, 16, 16);\n terrainGenerator.replaceBlocksForBiome(chunkX, chunkZ, chunkprimer, this.biomesForGeneration);\n\n if (profile.GENERATE_CAVES) {\n this.caveGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n if (profile.GENERATE_RAVINES) {\n if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) {\n this.ravineGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n }\n\n if (profile.GENERATE_MINESHAFTS) {\n this.mineshaftGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n if (profile.GENERATE_VILLAGES) {\n if (profile.PREVENT_VILLAGES_IN_CITIES) {\n if (!isCity) {\n this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n } else {\n this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n }\n\n if (profile.GENERATE_STRONGHOLDS) {\n this.strongholdGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n if (profile.GENERATE_SCATTERED) {\n this.scatteredFeatureGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n if (profile.GENERATE_OCEANMONUMENTS) {\n this.oceanMonumentGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer);\n }\n\n Chunk chunk = new Chunk(this.worldObj, chunkprimer, chunkX, chunkZ);\n byte[] abyte = chunk.getBiomeArray();\n\n for (int i = 0; i < abyte.length; ++i) {\n abyte[i] = (byte) Biome.getIdForBiome(this.biomesForGeneration[i]);\n }\n\n chunk.generateSkylightMap();\n\n providedChunks.add(new ChunkCoord(dimensionId, chunkX, chunkZ));\n\n return chunk;\n }\n\n private void generateTrees(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) {\n BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider);\n for (BlockPos pos : info.getSaplingTodo()) {\n IBlockState state = world.getBlockState(pos);\n if (state.getBlock() == Blocks.SAPLING) {\n ((BlockSapling)Blocks.SAPLING).generateTree(world, pos, state, random);\n }\n }\n info.clearSaplingTodo();\n }\n\n private void generateVines(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) {\n int cx = chunkX * 16;\n int cz = chunkZ * 16;\n BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider);\n\n if (info.hasBuilding) {\n BuildingInfo adjacent = info.getXmax();\n int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3));\n for (int z = 0; z < 15; z++) {\n for (int y = bottom; y < (info.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.WEST, new BlockPos(cx + 16, y, cz + z), new BlockPos(cx + 15, y, cz + z));\n }\n }\n }\n }\n if (info.getXmax().hasBuilding) {\n BuildingInfo adjacent = info.getXmax();\n int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3));\n for (int z = 0; z < 15; z++) {\n for (int y = bottom; y < (adjacent.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.EAST, new BlockPos(cx + 15, y, cz + z), new BlockPos(cx + 16, y, cz + z));\n }\n }\n }\n }\n\n if (info.hasBuilding) {\n BuildingInfo adjacent = info.getZmax();\n int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3));\n for (int x = 0; x < 15; x++) {\n for (int y = bottom; y < (info.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.NORTH, new BlockPos(cx + x, y, cz + 16), new BlockPos(cx + x, y, cz + 15));\n }\n }\n }\n }\n if (info.getZmax().hasBuilding) {\n BuildingInfo adjacent = info.getZmax();\n int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3));\n for (int x = 0; x < 15; x++) {\n for (int y = bottom; y < (adjacent.getMaxHeight()); y++) {\n if (random.nextFloat() < provider.profile.VINE_CHANCE) {\n createVineStrip(random, world, bottom, BlockVine.SOUTH, new BlockPos(cx + x, y, cz + 15), new BlockPos(cx + x, y, cz + 16));\n }\n }\n }\n }\n }\n\n private void createVineStrip(Random random, World world, int bottom, PropertyBool direction, BlockPos pos, BlockPos vineHolderPos) {\n if (world.isAirBlock(vineHolderPos)) {\n return;\n }\n if (!world.isAirBlock(pos)) {\n return;\n }\n world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true));\n pos = pos.down();\n while (pos.getY() >= bottom && random.nextFloat() < .8f) {\n if (!world.isAirBlock(pos)) {\n return;\n }\n world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true));\n pos = pos.down();\n }\n }\n\n private void generateLootSpawners(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator chunkGenerator) {\n BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, chunkGenerator);\n\n for (Pair pair : info.getMobSpawnerTodo()) {\n BlockPos pos = pair.getKey();\n // Double check that it is still a spawner (could be destroyed by explosion)\n if (world.getBlockState(pos).getBlock() == Blocks.MOB_SPAWNER) {\n TileEntity tileentity = world.getTileEntity(pos);\n if (tileentity instanceof TileEntityMobSpawner) {\n TileEntityMobSpawner spawner = (TileEntityMobSpawner) tileentity;\n String id = pair.getValue();\n String fixedId = EntityTools.fixEntityId(id);\n EntityTools.setSpawnerEntity(world, spawner, new ResourceLocation(fixedId), fixedId);\n }\n }\n }\n info.clearMobSpawnerTodo();\n\n\n for (Pair pair : info.getChestTodo()) {\n BlockPos pos = pair.getKey();\n // Double check that it is still a chest (could be destroyed by explosion)\n IBlockState state = world.getBlockState(pos);\n if (state.getBlock() == Blocks.CHEST) {\n if (chunkGenerator.profile.GENERATE_LOOT) {\n createLootChest(random, world, pos, pair.getRight());\n }\n }\n }\n info.clearChestTodo();\n\n\n for (BlockPos pos : info.getGenericTodo()) {\n IBlockState state = world.getBlockState(pos);\n if (state.getBlock() == Blocks.GLOWSTONE) {\n world.setBlockState(pos, state, 3);\n }\n }\n info.clearGenericTodo();\n }\n\n\n private void createLootChest(Random random, World world, BlockPos pos, String lootTable) {\n world.setBlockState(pos, Blocks.CHEST.getDefaultState().withProperty(BlockChest.FACING, EnumFacing.SOUTH));\n TileEntity tileentity = world.getTileEntity(pos);\n if (tileentity instanceof TileEntityChest) {\n if (lootTable != null) {\n ((TileEntityChest) tileentity).setLootTable(new ResourceLocation(lootTable), random.nextLong());\n } else {\n switch (random.nextInt(30)) {\n case 0:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_DESERT_PYRAMID, random.nextLong());\n break;\n case 1:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_JUNGLE_TEMPLE, random.nextLong());\n break;\n case 2:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_VILLAGE_BLACKSMITH, random.nextLong());\n break;\n case 3:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_ABANDONED_MINESHAFT, random.nextLong());\n break;\n case 4:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_NETHER_BRIDGE, random.nextLong());\n break;\n default:\n ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_SIMPLE_DUNGEON, random.nextLong());\n break;\n }\n }\n }\n }\n\n\n @Override\n public void populate(int chunkX, int chunkZ) {\n BlockFalling.fallInstantly = true;\n int x = chunkX * 16;\n int z = chunkZ * 16;\n World w = this.worldObj;\n Biome Biome = w.getBiomeForCoordsBody(new BlockPos(x + 16, 0, z + 16));\n this.rand.setSeed(w.getSeed());\n long i1 = this.rand.nextLong() / 2L * 2L + 1L;\n long j1 = this.rand.nextLong() / 2L * 2L + 1L;\n this.rand.setSeed(chunkX * i1 + chunkZ * j1 ^ w.getSeed());\n boolean flag = false;\n\n MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Pre(this, w, rand, chunkX, chunkZ, flag));\n\n ChunkPos cp = new ChunkPos(chunkX, chunkZ);\n\n if (profile.GENERATE_MINESHAFTS) {\n this.mineshaftGenerator.generateStructure(w, this.rand, cp);\n }\n if (profile.GENERATE_VILLAGES) {\n if (profile.PREVENT_VILLAGES_IN_CITIES) {\n if (!BuildingInfo.isCity(chunkX, chunkZ, this)) {\n flag = this.villageGenerator.generateStructure(w, this.rand, cp);\n }\n } else {\n flag = this.villageGenerator.generateStructure(w, this.rand, cp);\n }\n }\n if (profile.GENERATE_STRONGHOLDS) {\n this.strongholdGenerator.generateStructure(w, this.rand, cp);\n }\n if (profile.GENERATE_SCATTERED) {\n this.scatteredFeatureGenerator.generateStructure(w, this.rand, cp);\n }\n if (profile.GENERATE_OCEANMONUMENTS) {\n this.oceanMonumentGenerator.generateStructure(w, this.rand, cp);\n }\n\n int k1;\n int l1;\n int i2;\n\n if (profile.GENERATE_LAKES) {\n boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this);\n if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) {\n if (Biome != Biomes.DESERT && Biome != Biomes.DESERT_HILLS && !flag && this.rand.nextInt(4) == 0\n && TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAKE)) {\n k1 = x + this.rand.nextInt(16) + 8;\n l1 = this.rand.nextInt(256);\n i2 = z + this.rand.nextInt(16) + 8;\n (new WorldGenLakes(Blocks.WATER)).generate(w, this.rand, new BlockPos(k1, l1, i2));\n }\n\n if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAVA) && !flag && this.rand.nextInt(8) == 0) {\n k1 = x + this.rand.nextInt(16) + 8;\n l1 = this.rand.nextInt(this.rand.nextInt(248) + 8);\n i2 = z + this.rand.nextInt(16) + 8;\n\n if (l1 < (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET) || this.rand.nextInt(10) == 0) {\n (new WorldGenLakes(Blocks.LAVA)).generate(w, this.rand, new BlockPos(k1, l1, i2));\n }\n }\n }\n }\n\n boolean doGen = false;\n if (profile.GENERATE_DUNGEONS) {\n doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.DUNGEON);\n for (k1 = 0; doGen && k1 < 8; ++k1) {\n l1 = x + this.rand.nextInt(16) + 8;\n i2 = this.rand.nextInt(256);\n int j2 = z + this.rand.nextInt(16) + 8;\n (new WorldGenDungeons()).generate(w, this.rand, new BlockPos(l1, i2, j2));\n }\n }\n\n BlockPos pos = new BlockPos(x, 0, z);\n Biome.decorate(w, this.rand, pos);\n\n if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ANIMALS)) {\n WorldEntitySpawner.performWorldGenSpawning(w, Biome, x + 8, z + 8, 16, 16, this.rand);\n }\n x += 8;\n z += 8;\n\n doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ICE);\n for (k1 = 0; doGen && k1 < 16; ++k1) {\n for (l1 = 0; l1 < 16; ++l1) {\n i2 = w.getPrecipitationHeight(new BlockPos(x + k1, 0, z + l1)).getY();\n\n if (w.canBlockFreeze(new BlockPos(k1 + x, i2 - 1, l1 + z), false)) {\n w.setBlockState(new BlockPos(k1 + x, i2 - 1, l1 + z), Blocks.ICE.getDefaultState(), 2);\n }\n\n if (w.canSnowAt(new BlockPos(k1 + x, i2, l1 + z), true)) {\n w.setBlockState(new BlockPos(k1 + x, i2, l1 + z), Blocks.SNOW_LAYER.getDefaultState(), 2);\n }\n }\n }\n\n generateTrees(rand, chunkX, chunkZ, w, this);\n generateVines(rand, chunkX, chunkZ, w, this);\n generateLootSpawners(rand, chunkX, chunkZ, w, this);\n\n MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Post(this, w, rand, chunkX, chunkZ, flag));\n\n BlockFalling.fallInstantly = false;\n }\n\n @Override\n public boolean generateStructures(Chunk chunkIn, int x, int z) {\n boolean flag = false;\n\n if (profile.GENERATE_OCEANMONUMENTS) {\n if (chunkIn.getInhabitedTime() < 3600L) {\n flag |= this.oceanMonumentGenerator.generateStructure(this.worldObj, this.rand, new ChunkPos(x, z));\n }\n }\n\n return flag;\n }\n\n @Override\n public List getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) {\n return getDefaultCreatures(creatureType, pos);\n }\n\n private List getDefaultCreatures(EnumCreatureType creatureType, BlockPos pos) {\n Biome Biome = this.worldObj.getBiomeForCoordsBody(pos);\n if (creatureType == EnumCreatureType.MONSTER) {\n if (profile.GENERATE_SCATTERED) {\n if (this.scatteredFeatureGenerator.isInsideStructure(pos)) {\n return this.scatteredFeatureGenerator.getScatteredFeatureSpawnList();\n }\n }\n if (profile.GENERATE_OCEANMONUMENTS) {\n if (this.oceanMonumentGenerator.isPositionInStructure(this.worldObj, pos)) {\n return this.oceanMonumentGenerator.getScatteredFeatureSpawnList();\n }\n }\n }\n\n return Biome.getSpawnableList(creatureType);\n }\n\n @Override\n public BlockPos clGetStrongholdGen(World worldIn, String structureName, BlockPos position) {\n return \"Stronghold\".equals(structureName) && this.strongholdGenerator != null\n ? CompatMapGenStructure.getClosestStrongholdPos(this.strongholdGenerator, worldIn, position)\n : null;\n }\n\n @Override\n public void recreateStructures(Chunk chunkIn, int x, int z) {\n if (profile.GENERATE_MINESHAFTS) {\n this.mineshaftGenerator.generate(this.worldObj, x, z, null);\n }\n\n if (profile.GENERATE_VILLAGES) {\n if (profile.PREVENT_VILLAGES_IN_CITIES) {\n if (!BuildingInfo.isCity(x, z, this)) {\n this.villageGenerator.generate(this.worldObj, x, z, null);\n }\n } else {\n this.villageGenerator.generate(this.worldObj, x, z, null);\n }\n }\n\n if (profile.GENERATE_STRONGHOLDS) {\n this.strongholdGenerator.generate(this.worldObj, x, z, null);\n }\n\n if (profile.GENERATE_SCATTERED) {\n this.scatteredFeatureGenerator.generate(this.worldObj, x, z, null);\n }\n\n if (profile.GENERATE_OCEANMONUMENTS) {\n this.oceanMonumentGenerator.generate(this.worldObj, x, z, null);\n }\n }\n\n @Override\n public ILostChunkInfo getChunkInfo(int chunkX, int chunkZ) {\n return BuildingInfo.getBuildingInfo(chunkX, chunkZ, this);\n }\n\n @Override\n public int getRealHeight(int level) {\n return profile.GROUNDLEVEL + level * 6;\n }\n}\n"},"message":{"kind":"string","value":"Removed debug\n"},"old_file":{"kind":"string","value":"src/main/java/mcjty/lostcities/dimensions/world/LostCityChunkGenerator.java"},"subject":{"kind":"string","value":"Removed debug"}}},{"rowIdx":713,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"760faff1d570436112a75f2db6acf369263a521c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jurgendl/jhaws,jurgendl/jhaws,jurgendl/jhaws,jurgendl/jhaws"},"new_contents":{"kind":"string","value":"package org.jhaws.common.lang;\n\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.io.UncheckedIOException;\nimport java.lang.reflect.Array;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayDeque;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Deque;\nimport java.util.EnumSet;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Properties;\nimport java.util.Queue;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.SortedSet;\nimport java.util.Spliterator;\nimport java.util.Spliterators;\nimport java.util.Stack;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\nimport java.util.concurrent.BlockingDeque;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentSkipListMap;\nimport java.util.concurrent.LinkedBlockingDeque;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.LinkedTransferQueue;\nimport java.util.concurrent.TransferQueue;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.BiPredicate;\nimport java.util.function.BinaryOperator;\nimport java.util.function.BooleanSupplier;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleSupplier;\nimport java.util.function.Function;\nimport java.util.function.IntFunction;\nimport java.util.function.IntSupplier;\nimport java.util.function.LongSupplier;\nimport java.util.function.Predicate;\nimport java.util.function.Supplier;\nimport java.util.function.UnaryOperator;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collector;\nimport java.util.stream.Collectors;\nimport java.util.stream.DoubleStream;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\nimport java.util.stream.Stream;\nimport java.util.stream.StreamSupport;\n\nimport org.apache.commons.lang3.builder.CompareToBuilder;\nimport org.apache.commons.lang3.builder.EqualsBuilder;\nimport org.jhaws.common.lang.functions.EBiConsumer;\nimport org.jhaws.common.lang.functions.EBooleanSupplier;\nimport org.jhaws.common.lang.functions.EConsumer;\nimport org.jhaws.common.lang.functions.EDoubleSupplier;\nimport org.jhaws.common.lang.functions.EFunction;\nimport org.jhaws.common.lang.functions.EIntSupplier;\nimport org.jhaws.common.lang.functions.ELongSupplier;\nimport org.jhaws.common.lang.functions.EPredicate;\nimport org.jhaws.common.lang.functions.ERunnable;\nimport org.jhaws.common.lang.functions.ESupplier;\n\n// http://infotechgems.blogspot.be/2011/11/java-collections-performance-time.html\n// TODO https://www.techempower.com/blog/2016/10/19/efficient-multiple-stream-concatenation-in-java/\n/**\n * @see java.util.stream.Stream\n * @see java.util.stream.StreamSupport\n * @see java.util.stream.Collectors\n * @see java.util.stream.Collector\n * @since 1.8\n * @see https://technology.amis.nl/2013/10/05/java-8-collection-enhancements- leveraging-lambda-expressions-or-how-java-emulates-sql/\n */\npublic interface CollectionUtils8 {\n public static class Comparators {\n public static class CaseInsensitiveComparator implements Comparator {\n @Override\n public int compare(String o1, String o2) {\n return (o1 == null ? \"\" : o1).compareToIgnoreCase((o2 == null ? \"\" : o2));\n }\n }\n\n public static class MapEntryKVComparator implements Comparator> {\n @Override\n public int compare(Entry o1, Entry o2) {\n return new CompareToBuilder().append(o1.getKey(), o2.getKey()).append(o1.getValue(), o2.getValue()).toComparison();\n }\n }\n\n public static class MapEntryVKComparator implements Comparator> {\n @Override\n public int compare(Entry o1, Entry o2) {\n return new CompareToBuilder().append(o1.getValue(), o2.getValue()).append(o1.getKey(), o2.getKey()).toComparison();\n }\n }\n }\n\n public static class RegexIterator implements EnhancedIterator {\n protected Pattern pattern;\n\n protected String regex;\n\n protected Matcher matcher;\n\n protected Boolean hasNext = null;\n\n public RegexIterator(String text, String regex) {\n this.pattern = Pattern.compile(regex);\n this.regex = regex;\n this.matcher = pattern.matcher(text);\n }\n\n public RegexIterator(String text, Pattern regex) {\n this.pattern = regex;\n this.regex = regex.toString();\n this.matcher = pattern.matcher(text);\n }\n\n public RegexIterator(Pattern regex, String text) {\n this.pattern = regex;\n this.regex = regex.toString();\n this.matcher = pattern.matcher(text);\n }\n\n @Override\n public boolean hasNext() {\n if (hasNext == null) {\n hasNext = matcher.find();\n }\n return hasNext;\n }\n\n @Override\n public String next() {\n if (hasNext == null) {\n hasNext();\n }\n if (hasNext) {\n hasNext = null;\n return matcher.group();\n }\n return null;\n }\n }\n\n public static class PathIterator implements EnhancedIterator {\n protected Path path;\n\n public PathIterator(Path path) {\n this.path = path;\n }\n\n @Override\n public boolean hasNext() {\n Path parent = this.path.getParent();\n return parent != null;\n }\n\n @Override\n public Path next() {\n this.path = this.path.getParent();\n return this.path;\n }\n }\n\n public static class ProjectionIterator implements EnhancedIterator {\n protected T current;\n\n protected T next;\n\n protected Function projection;\n\n public ProjectionIterator(T object, boolean include, Function projection) {\n this.current = object;\n this.projection = projection;\n if (include) next = current;\n }\n\n @Override\n public boolean hasNext() {\n if (next == null) {\n next = projection.apply(current);\n }\n return next != null;\n }\n\n @Override\n public T next() {\n hasNext();\n if (next == null) {\n throw new NoSuchElementException();\n }\n current = next;\n next = null;\n return current;\n }\n }\n\n public static interface Opt extends Supplier {\n /** default vorig type */\n Opt opt(Function getter);\n\n /** default vorig type */\n default Opt nest(Function getter) {\n return opt(getter);\n }\n\n /** ga verder eager */\n OptEager eager(Function getter);\n\n /** ga verder reusable = lazy */\n OptReusable reusable(Function getter);\n\n /** ga verder reusable = lazy */\n default OptReusable lazy(Function getter) {\n return reusable(getter);\n }\n\n default OptEager map(Function map) {\n T v = get();\n return Opt.eager(/* v == null ? null : */ map.apply(v));\n }\n\n default OptEager mapOrNull(Function map) {\n return mapOr(map, (X) null);\n }\n\n default OptEager mapOr(Function map, X value) {\n return mapOr(map, (Supplier) () -> value);\n }\n\n default OptEager mapOr(Function map, Supplier value) {\n T v = get();\n return Opt.eager(v == null ? value.get() : map.apply(v));\n }\n\n /** default eager */\n public static Opt optional(T value) {\n return eager(value);\n }\n\n /** start eager */\n public static OptEager eager(T value) {\n return new OptEager<>(value);\n }\n\n /** start reusable = lazy */\n public static OptReusable reusable(T value) {\n return new OptReusable<>(value);\n }\n\n /** start reusable = lazy */\n public static OptReusable lazy(T value) {\n return reusable(value);\n }\n\n X first(@SuppressWarnings(\"unchecked\") Function... getters);\n\n default boolean isNull() {\n return CollectionUtils8.isNull().test(get());\n }\n\n default boolean isBlankOrNull() {\n return CollectionUtils8.isBlankOrNull().test(get());\n }\n\n default boolean isNotNull() {\n return CollectionUtils8.isNotNull().test(get());\n }\n\n default boolean isNotBlankAndNotNull() {\n return CollectionUtils8.isNotBlankAndNotNull().test(get());\n }\n\n default void consume(Consumer consumer) {\n T value = get();\n if (value != null) {\n consumer.accept(value);\n }\n }\n\n /** geeft waarde terug */\n @Override\n T get();\n\n /** voert {@link #opt(Function)} uit en dan {@link #get()} */\n default X get(Function get) {\n return opt(get).get();\n }\n\n /**\n * voert {@link #get()} uit en wanneer null, voert {@link Supplier} uit en geeft die waarde\n */\n default T or(Supplier supplier) {\n return Optional.ofNullable(get()).orElseGet(supplier);\n }\n\n /** voert {@link #get()} uit en wanneer null, geeft meegegeven waarde */\n default T or(T value) {\n return Optional.ofNullable(get()).orElse(value);\n }\n\n default T orNull() {\n return or((T) null);\n }\n\n default T or(Opt supplier) {\n return or(supplier.get());\n }\n\n /** wrap in Value */\n default Value getValue() {\n return new Value<>(get());\n }\n\n /** wrap in Value */\n default Value getValue(Function get) {\n return new Value<>(get(get));\n }\n\n /** wrap in Value */\n default Value orValue(Supplier supplier) {\n return new Value<>(or(supplier));\n }\n\n /** wrap in Value */\n default Value orValue(T value) {\n return new Value<>(or(value));\n }\n\n /** wrap in Value */\n default Value orNullValue() {\n return new Value<>(orNull());\n }\n\n /** wrap in Value */\n default Value orValue(Opt supplier) {\n return new Value<>(or(supplier));\n }\n }\n\n static class OptEager implements Opt {\n protected final T value;\n\n protected OptEager(T value) {\n this.value = value;\n }\n\n @Override\n public T get() {\n return value;\n }\n\n @Override\n public

    OptEager

    opt(Function get) {\n return eager(get);\n }\n\n @Override\n public

    OptEager

    eager(Function get) {\n return new OptEager<>(value == null ? null : get.apply(value));\n }\n\n @Override\n public

    OptReusable reusable(Function get) {\n return new OptReusable<>(get()).opt(get);\n }\n\n @Override\n public X first(@SuppressWarnings(\"unchecked\") Function... getters) {\n return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null);\n }\n }\n\n static class OptReusable implements Opt {\n protected final OptReusable parent;\n\n protected final Function getter;\n\n protected final T value;\n\n protected OptReusable(T value) {\n this.value = value;\n this.parent = null;\n this.getter = null;\n }\n\n protected OptReusable(OptReusable parent, Function getter) {\n this.value = null;\n this.parent = parent;\n this.getter = getter;\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public T get() {\n if (value != null) return value;\n Stack stack = new Stack<>();\n stack.add(this);\n OptReusable current = this.parent;\n while (current != null) {\n stack.add(current);\n current = current.parent;\n }\n Object currentValue = stack.pop().value;\n while (!stack.isEmpty() && currentValue != null) {\n current = stack.pop();\n currentValue = current.getter.apply(currentValue);\n }\n return (T) currentValue;\n }\n\n @Override\n public OptReusable opt(Function get) {\n return reusable(get);\n }\n\n @Override\n public OptEager eager(Function get) {\n return new OptEager<>(get()).opt(get);\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public OptReusable reusable(Function get) {\n return new OptReusable<>((OptReusable) this, get);\n }\n\n @Override\n public X first(@SuppressWarnings(\"unchecked\") Function... getters) {\n return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null);\n }\n }\n\n public static class CustomCollector implements Collector {\n protected Supplier supplier;\n\n protected BiConsumer accumulator;\n\n protected BinaryOperator combiner;\n\n protected Function finisher;\n\n protected Set characteristics;\n\n public CustomCollector(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Function finisher,\n Set characteristics) {\n this.supplier = supplier;\n this.accumulator = accumulator;\n this.combiner = combiner;\n this.finisher = finisher;\n this.characteristics = characteristics;\n }\n\n @SuppressWarnings(\"unchecked\")\n public CustomCollector(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Set characteristics) {\n this(supplier, accumulator, combiner, x -> (R) x, characteristics);\n }\n\n @SuppressWarnings(\"unchecked\")\n public CustomCollector(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner) {\n this(supplier, accumulator, combiner, x -> (R) x, Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)));\n }\n\n public CustomCollector() {\n super();\n }\n\n @Override\n public Supplier supplier() {\n return supplier;\n }\n\n @Override\n public BiConsumer accumulator() {\n return accumulator;\n }\n\n @Override\n public BinaryOperator combiner() {\n return combiner;\n }\n\n @Override\n public Function finisher() {\n return finisher;\n }\n\n @Override\n public Set characteristics() {\n return characteristics;\n }\n\n public Supplier getSupplier() {\n return this.supplier;\n }\n\n public void setSupplier(Supplier supplier) {\n this.supplier = supplier;\n }\n\n public BiConsumer getAccumulator() {\n return this.accumulator;\n }\n\n public void setAccumulator(BiConsumer accumulator) {\n this.accumulator = accumulator;\n }\n\n public BinaryOperator getCombiner() {\n return this.combiner;\n }\n\n public void setCombiner(BinaryOperator combiner) {\n this.combiner = combiner;\n }\n\n public Function getFinisher() {\n return this.finisher;\n }\n\n public void setFinisher(Function finisher) {\n this.finisher = finisher;\n }\n\n public Set getCharacteristics() {\n return this.characteristics;\n }\n\n public void setCharacteristics(Set characteristics) {\n this.characteristics = characteristics;\n }\n }\n\n public static class ListCollector extends CustomCollector, List> {\n public ListCollector() {\n setSupplier(newList());\n BiConsumer, T> accumulator0 = elementsListAccumulator();\n setAccumulator(accumulator0);\n setCombiner(elementsListCombiner(accumulator0));\n setFinisher(CollectionUtils8.cast());\n setCharacteristics(Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)));\n }\n }\n\n public static class ListUQCollector extends ListCollector {\n public ListUQCollector() {\n BiConsumer, T> accumulator0 = uniqueElementsListAccumulator();\n setAccumulator(accumulator0);\n setCombiner(elementsListCombiner(accumulator0));\n }\n }\n\n /**\n * always use first value for key\n */\n public static BinaryOperator keepFirst() {\n return (p1, p2) -> p1;\n }\n\n /**\n * always use last value for key\n */\n public static BinaryOperator keepLast() {\n return (p1, p2) -> p2;\n }\n\n public static T last(Stream stream) {\n return stream.reduce(keepLast()).orElse(null);\n }\n\n public static Entry last(SortedMap map) {\n return map.entrySet().stream().reduce(keepLast()).orElse(null);\n }\n\n /**\n * see {@link #keepLast()}\n */\n public static BinaryOperator acceptDuplicateKeys() {\n return keepLast();\n }\n\n /**\n * rejects !different! keys for the same value\n *\n * @throws IllegalArgumentException\n */\n public static BinaryOperator rejectDuplicateKeys() throws IllegalArgumentException {\n return (a, b) -> {\n if (new EqualsBuilder().append(a, b).isEquals()) return a;\n throw new IllegalArgumentException(\"duplicate key: \" + a + \" <> \" + b);\n };\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] array(T item, T... items) {\n if (item == null && (items == null || items.length == 0)) {\n return (T[]) new Object[0];\n }\n if (items == null || items.length == 0) {\n return (T[]) new Object[] { item };\n }\n if (item == null) {\n return items;\n }\n int length = items.length;\n // FIXME cheaper // operation\n T[] newarray = Arrays.copyOf(items, 1 + length);\n newarray[0] = item;\n System.arraycopy(items, 0, newarray, 1, length);\n return newarray;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] array(T[] items, T item) {\n if (item == null && (items == null || items.length == 0)) {\n return (T[]) new Object[0];\n }\n if (items == null || items.length == 0) {\n return (T[]) new Object[] { item };\n }\n if (item == null) {\n return items;\n }\n int length = items.length;\n T[] newarray = Arrays.copyOf(items, 1 + length);\n newarray[newarray.length - 1] = item;\n return newarray;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] array(T[] items1, T[] items2) {\n if ((items1 == null || items1.length == 0) && (items2 == null || items2.length == 0)) {\n return (T[]) new Object[0];\n }\n if (items1 == null || items1.length == 0) {\n return items2;\n }\n if (items2 == null || items2.length == 0) {\n return items1;\n }\n int length1 = items1.length;\n int length2 = items2.length;\n T[] newarray = Arrays.copyOf(items1, length1 + length2);\n System.arraycopy(items2, 0, newarray, length1, length2);\n return newarray;\n }\n\n public static T[] array(Class componentType, Collection collection) {\n return array(componentType, collection.stream());\n }\n\n public static T[] array(Class componentType, Stream stream) {\n return stream.toArray(newArray(componentType));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static IntFunction newArray(Class componentType) {\n return length -> (T[]) Array.newInstance(componentType, length);\n }\n\n public static T[] newArray(Class componentType, int size) {\n return CollectionUtils8. newArray(componentType).apply(size);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Entry[] array(Map map) {\n return map.entrySet().toArray((Map.Entry[]) new Map.Entry[0]);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Function cast() {\n return x -> (T) x;\n }\n\n public static Function cast(Class type) {\n return o -> type.cast(o);\n }\n\n public static T cast(Class type, Object object) {\n return cast(type).apply(object);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static > Collector collector(C collection) {\n if (collection instanceof Deque) {\n return (Collector) CollectionUtils8. collectDeque();\n }\n if (collection instanceof Queue) {\n return (Collector) CollectionUtils8. collectQueue();\n }\n if (collection instanceof List) {\n return (Collector) CollectionUtils8. collectList();\n }\n if (collection instanceof SortedSet) {\n return (Collector) CollectionUtils8. collectSortedSet();\n }\n if (collection instanceof Set) {\n return (Collector) CollectionUtils8. collectSet();\n }\n throw new UnsupportedOperationException(collection.getClass().getName());\n }\n\n @SafeVarargs\n public static > C filter(boolean parallel, C collection, Predicate... predicates) {\n AtomicReference> streamReference = new AtomicReference<>(stream(parallel, collection));\n streamArray(predicates).forEach(predicate -> streamReference.set(streamReference.get().filter(predicate)));\n C collected = streamReference.get().collect(collector(collection));\n return collected;\n }\n\n @SafeVarargs\n public static > C filter(C collection, Predicate... predicates) {\n return filter(false, collection, predicates);\n }\n\n public static T last(List dd) {\n int size = dd.size();\n return size == 0 ? null : dd.get(size - 1);\n }\n\n public static EnhancedMap map(Collection> entries) {\n return map(false, entries);\n }\n\n public static EnhancedMap map(boolean parallel, Collection> entries) {\n return map(stream(parallel, entries));\n }\n\n public static EnhancedMap map(Stream> stream) {\n return map(stream, CollectionUtils8. newLinkedMap());\n }\n\n public static > M map(Stream> stream, Supplier mapSupplier) {\n BinaryOperator keepLast = CollectionUtils8. keepLast();\n return map(stream, mapSupplier, keepLast);\n }\n\n public static > M map(Stream> stream, Supplier mapSupplier, BinaryOperator choice) {\n Function, K> keyMapper = CollectionUtils8. keyMapper();\n Function, V> valueMapper = CollectionUtils8. valueMapper();\n Collector, ?, M> c = Collectors.toMap(keyMapper, valueMapper, choice, mapSupplier);\n return stream.collect(c);\n }\n\n public static Supplier> newLinkedMap() {\n return EnhancedLinkedHashMap::new;\n }\n\n public static Supplier> newMap() {\n return EnhancedHashMap::new;\n }\n\n public static Supplier> newSortedMap() {\n return EnhancedTreeMap::new;\n }\n\n public static Supplier> newNavigableMap() {\n return EnhancedTreeMap::new;\n }\n\n public static Supplier> newConcurrentNavigableMap() {\n return ConcurrentSkipListMap::new;\n }\n\n public static Supplier> newConcurrentMap() {\n return ConcurrentHashMap::new;\n }\n\n public static Supplier> newStack() {\n return Stack::new;\n }\n\n public static Supplier> newDeque() {\n return EnhancedLinkedList::new;\n }\n\n public static Supplier> newList() {\n return EnhancedArrayList::new;\n }\n\n public static Supplier> newQueue() {\n return EnhancedLinkedList::new;\n }\n\n public static Supplier> newSet() {\n return EnhancedHashSet::new;\n }\n\n public static Supplier> newSortedSet() {\n return EnhancedTreeSet::new;\n }\n\n public static Supplier> newBlockingQueue() {\n return LinkedBlockingDeque::new;\n }\n\n public static Supplier> newBlockingDeque() {\n return LinkedBlockingDeque::new;\n }\n\n public static Supplier> newTransferQueue() {\n return LinkedTransferQueue::new;\n }\n\n public static > Collector toCollector(Supplier supplier) {\n return Collectors.toCollection(supplier);\n }\n\n public static Collector> collectStack() {\n return toCollector(newStack());\n }\n\n public static Collector> collectDeque() {\n return toCollector(newDeque());\n }\n\n public static Collector> collectList() {\n return toCollector(newList());\n }\n\n public static > Collector collection(Supplier newCollection) {\n return Collectors.toCollection(newCollection);\n }\n\n public static ListCollector collectListUQ() {\n return new ListUQCollector<>();\n }\n\n public static Collector> collectQueue() {\n return toCollector(newQueue());\n }\n\n public static Collector> collectSet() {\n return Collectors.toSet();\n }\n\n public static Collector> collectSortedSet() {\n return toCollector(newSortedSet());\n }\n\n public static > List sort(Collection collection) {\n return sort(false, collection);\n }\n\n public static > List sort(boolean parallel, Collection collection) {\n return stream(parallel, collection).sorted().collect(toCollector(newList()));\n }\n\n public static List sort(boolean parallel, Collection collection, Comparator comparator) {\n return stream(parallel, collection).sorted(comparator).collect(toCollector(newList()));\n }\n\n public static List sort(Collection collection, Comparator comparator) {\n return sort(false, collection, comparator);\n }\n\n public static List sortBy(Collection collection, List orderByMe, Function map) {\n return collection.stream().sorted(comparator(orderByMe, map)).collect(collectList());\n }\n\n public static Comparator comparator(List orderByMe, Function map) {\n return (x, y) -> Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(x))))\n .compareTo(Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(y)))));\n }\n\n public static Comparator comparator(List orderByMe) {\n return comparator(orderByMe, self());\n }\n\n public static List sortBy(Collection collection, List orderByMe) {\n return sortBy(collection, orderByMe, self());\n }\n\n public static > Stream sortBy(Stream sortMe, Map sortByMe) {\n return sortMe.sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y)));\n }\n\n public static Stream sortBy(Stream collection, List orderByMe, Function map) {\n return collection.sorted(comparator(orderByMe, map));\n }\n\n public static Stream sortBy(Stream collection, List orderByMe) {\n return sortBy(collection, orderByMe, self());\n }\n\n public static > List sortBy(Collection sortMe, Map sortByMe) {\n return sortMe.stream().sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y))).collect(collectList());\n }\n\n public static Function id() {\n return self();\n }\n\n public static Function self() {\n return Function.identity();\n }\n\n public static UnaryOperator idu() {\n return selfu();\n }\n\n public static UnaryOperator selfu() {\n return t -> t;\n }\n\n public static int noNegIndex(int i) {\n return i == -1 ? Integer.MAX_VALUE : i;\n }\n\n public static Stream stream(Collection collection) {\n return stream(false, collection);\n }\n\n public static Stream stream(boolean parallel, Collection collection) {\n return collection == null ? Stream.empty() : StreamSupport.stream(collection.spliterator(), parallel);\n }\n\n public static Stream stream(Iterable iterable) {\n return stream(false, iterable);\n }\n\n public static Stream stream(Iterator iterator) {\n return stream(false, iterator);\n }\n\n public static Stream stream(Enumeration enumeration) {\n return stream(false, enumeration);\n }\n\n public static Stream stream(boolean parallel, Iterable iterable) {\n return iterable == null ? Stream.empty() : StreamSupport.stream(iterable.spliterator(), parallel);\n }\n\n public static Stream stream(boolean parallel, Iterator iterator) {\n return iterator == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), parallel);\n }\n\n public static Stream stream(boolean parallel, Enumeration enumeration) {\n return enumeration == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(asIterator(enumeration), 0), parallel);\n }\n\n public static Iterator asIterator(Enumeration enumeration) {\n return new Iterator() {\n @Override\n public boolean hasNext() {\n return enumeration.hasMoreElements();\n }\n\n @Override\n public E next() {\n return enumeration.nextElement();\n }\n };\n }\n\n public static Stream lines(Path path) {\n try {\n return Files.lines(path);\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n public static Stream streamValues(Map map) {\n return stream(map).map(valueMapper());\n }\n\n public static Stream> streamDeepValues(Map> map) {\n return stream(map).map(valueMapper()).map(collection -> stream(collection));\n }\n\n public static Stream> stream(Map map) {\n return stream(false, map);\n }\n\n public static Stream> stream(boolean parallel, Map map) {\n return map == null ? Stream.empty() : StreamSupport.stream(map.entrySet().spliterator(), parallel);\n }\n\n public static Stream stream(Path path) {\n return stream(false, path);\n }\n\n public static Stream stream(boolean parallel, Path path) {\n return StreamSupport.stream(path.spliterator(), parallel);\n }\n\n @SafeVarargs\n public static Stream streamArray(T... array) {\n return streamArray(false, array);\n }\n\n @SafeVarargs\n public static Stream streamArray(boolean parallel, T... array) {\n if (array == null) return Stream.empty();\n // StreamSupport.stream(Spliterators.spliterator(array, 0, array.length,\n // Spliterator.ORDERED | Spliterator.IMMUTABLE), parallel);\n Stream stream = Arrays.stream(array);\n if (parallel) stream = stream.parallel();\n return stream;\n }\n\n public static Stream streamDetached(Collection collection) {\n return streamDetached(false, collection);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Stream streamDetached(boolean parallel, Collection collection) {\n return streamArray(parallel, array((Class) Object.class, collection));\n }\n\n public static Stream> streamDetached(Map map) {\n return streamDetached(false, map);\n }\n\n public static Stream> streamDetached(boolean parallel, Map map) {\n return streamArray(parallel, array(map));\n }\n\n public static Stream streamFully(Path path) {\n return stream(new PathIterator(path));\n }\n\n public static Stream stream(Collection input, Function> mapping) {\n return input.stream().map(mapping).map(Collection::stream).flatMap(id());\n }\n\n public static List toList(Collection collection) {\n return toList(true, collection);\n }\n\n public static List toList(boolean copy, Collection collection) {\n return !copy && collection instanceof List ? (List) collection : stream(collection).collect(collectList());\n }\n\n public static Map toMap(Map map) {\n return toMap(true, map);\n }\n\n public static Map toMap(boolean copy, Map map) {\n return !copy /* && map instanceof Map */ ? (Map) map : stream(map).collect(collectMap(Entry::getKey, Entry::getValue));\n }\n\n public static SortedMap toSortedMap(Map map) {\n return toSortedMap(true, map);\n }\n\n public static SortedMap toSortedMap(boolean copy, Map map) {\n return !copy && map instanceof SortedMap ? (SortedMap) map : stream(map).collect(collectSortedMap(Entry::getKey, Entry::getValue));\n }\n\n @SafeVarargs\n public static List toList(T... array) {\n return streamArray(array).collect(collectList());\n }\n\n public static Set toSet(Collection collection) {\n return toSet(true, collection);\n }\n\n public static Set toSet(boolean copy, Collection collection) {\n return !copy && collection instanceof Set ? (Set) collection : stream(collection).collect(collectSet());\n }\n\n @SafeVarargs\n public static Set toSet(T... array) {\n return streamArray(array).collect(collectSet());\n }\n\n public static SortedSet toSortedSet(Collection collection) {\n return toSortedSet(true, collection);\n }\n\n public static SortedSet toSortedSet(boolean copy, Collection collection) {\n return !copy && collection instanceof SortedSet ? (SortedSet) collection : stream(collection).collect(collectSortedSet());\n }\n\n @SafeVarargs\n public static SortedSet toSortedSet(T... array) {\n return streamArray(array).collect(collectSortedSet());\n }\n\n public static Queue toQueue(Collection collection) {\n return stream(collection).collect(collectQueue());\n }\n\n @SafeVarargs\n public static Queue toQueue(T... array) {\n return streamArray(array).collect(collectQueue());\n }\n\n public static Deque toDeque(Collection collection) {\n return stream(collection).collect(collectDeque());\n }\n\n @SafeVarargs\n public static Deque toDeque(T... array) {\n return streamArray(array).collect(collectDeque());\n }\n\n public static Stack toStack(Collection collection) {\n return stream(collection).collect(collectStack());\n }\n\n @SafeVarargs\n public static Stack toStack(T... array) {\n return streamArray(array).collect(collectStack());\n }\n\n public static > C to(T[] array, Supplier supplier) {\n return to(array, toCollector(supplier));\n }\n\n public static > C to(T[] array, Collector collector) {\n return streamArray(array).collect(collector);\n }\n\n public static > C to(Collection collection, Supplier supplier) {\n return to(collection, toCollector(supplier));\n }\n\n public static > C to(Collection collection, Collector collector) {\n return stream(collection).collect(collector);\n }\n\n public static boolean containedInAny(Collection c1, Collection c2) {\n return c1.stream().anyMatch(c2::contains);\n }\n\n public static Predicate not(Predicate t) {\n return t.negate();\n }\n\n public static Predicate isNotBlankAndNotNull() {\n return t -> t instanceof String ? isNotBlank().test(String.class.cast(t)) : isNotNull().test(t);\n }\n\n public static Predicate isBlankOrNull() {\n return t -> t instanceof String ? isBlank().test(String.class.cast(t)) : isNull().test(t);\n }\n\n public static Predicate isNotBlank() {\n return org.apache.commons.lang3.StringUtils::isNotBlank;\n }\n\n public static Predicate isBlank() {\n return org.apache.commons.lang3.StringUtils::isBlank;\n }\n\n public static Predicate isNotNull() {\n return Objects::nonNull;\n }\n\n public static Predicate isNull() {\n return Objects::isNull;\n }\n\n public static Predicate is(T x) {\n return t -> isEquals(t, x);\n }\n\n public static Predicate isNot(T x) {\n return not(is(x));\n }\n\n public static Predicate containedIn(Collection collection) {\n return collection::contains;\n }\n\n public static Predicate containedIn(Collection collection, Function converter) {\n return e -> collection.contains(converter.apply(e));\n }\n\n public static Predicate keyContainedIn(Map map) {\n return map::containsKey;\n }\n\n public static Predicate keyContainedIn(Map map, Function converter) {\n return e -> map.containsKey(converter.apply(e));\n }\n\n public static Predicate valueContainedIn(Map map) {\n return map::containsValue;\n }\n\n public static Predicate valueContainedIn(Map map, Function converter) {\n return e -> map.containsValue(converter.apply(e));\n }\n\n public static Predicate notContainedIn(Collection collection) {\n return not(containedIn(collection));\n }\n\n public static Predicate notContainedIn(Collection collection, Function converter) {\n return not(containedIn(collection, converter));\n }\n\n public static Predicate keyNotContainedIn(Map map) {\n return not(keyContainedIn(map));\n }\n\n public static Predicate keyNotContainedIn(Map map, Function converter) {\n return not(keyContainedIn(map, converter));\n }\n\n public static Predicate valueNotContainedIn(Map map) {\n return not(valueContainedIn(map));\n }\n\n public static Predicate valueNotContainedIn(Map map, Function converter) {\n return not(valueContainedIn(map, converter));\n }\n\n public static Function makeNull() {\n return x -> null;\n }\n\n public static Supplier supplyNull() {\n return () -> null;\n }\n\n public static Predicate always() {\n return x -> true;\n }\n\n public static Predicate always(boolean b) {\n return x -> b;\n }\n\n public static Predicate never() {\n return x -> false;\n }\n\n public static Predicate never(boolean b) {\n return x -> !b;\n }\n\n public static BiPredicate always2() {\n return (x, y) -> true;\n }\n\n public static BiPredicate always2(boolean b) {\n return (x, y) -> b;\n }\n\n public static BiPredicate never2() {\n return (x, y) -> false;\n }\n\n public static BiPredicate never2(boolean b) {\n return (x, y) -> !b;\n }\n\n public static IntStream streamp(String text) {\n return text.chars();\n }\n\n public static Stream stream(String text) {\n return streamp(text).mapToObj(i -> (char) i);\n }\n\n public static Stream stream(char[] text) {\n return stream(new String(text));\n }\n\n public static Stream stream(Boolean... b) {\n return IntStream.range(0, b.length).mapToObj(idx -> b[idx]);\n }\n\n public static Stream stream(Character[] text) {\n return Arrays.stream(text);\n }\n\n public static List> match(List keys, List values) {\n return values.stream()\n .parallel()\n .filter(containedIn(keys))\n .map(value -> new Pair<>(keys.get(keys.indexOf(value)), value))\n .collect(collectList());\n }\n\n public static T optional(T value, Supplier orElse) {\n return Optional.ofNullable(value).orElseGet(orElse);\n }\n\n public static T optional(T oldValue, T newValue, Consumer whenDifferent) {\n if (notEquals(oldValue, newValue)) {\n whenDifferent.accept(newValue);\n return newValue;\n }\n return oldValue;\n }\n\n public static Consumer consume() {\n return x -> {\n //\n };\n }\n\n public static BiConsumer biconsume() {\n return (x, y) -> {\n return;\n };\n }\n\n public static String joinArray(String delimiter, T[] strings) {\n return join(delimiter, streamArray(strings));\n }\n\n public static String joinArray(T[] strings) {\n return join(\" \", streamArray(strings));\n }\n\n public static String join(Collection strings) {\n return join(\" \", stream(strings));\n }\n\n public static String join(String delimiter, Collection strings) {\n return join(delimiter, stream(strings));\n }\n\n public static String join(Stream stream) {\n return join(\" \", stream);\n }\n\n public static String join(String delimiter, Stream stream) {\n return stream//\n .filter(Objects::nonNull)//\n .map(String::valueOf)//\n .map(String::trim)//\n .filter(StringUtils::isNotBlank)//\n .collect(Collectors.joining(delimiter));\n }\n\n public static String join(String delimiter, boolean skipNull, boolean trim, Stream stream) {\n if (skipNull) stream = stream.filter(Objects::nonNull);\n Stream stream2 = stream.map(String::valueOf);\n if (trim) stream2 = stream2.map(String::trim);\n if (skipNull) stream2 = stream2.filter(StringUtils::isNotBlank);\n return stream2.collect(Collectors.joining(delimiter));\n }\n\n public static Stream split(String string, String delimiter) {\n return streamArray(string.split(delimiter));\n }\n\n public static String joining(Stream stream, String delimiter) {\n return stream.collect(Collectors.joining(delimiter));\n }\n\n /**\n * !!!!!!!!!!! terminates source stream !!!!!!!!!!!
    \n * !!!!!!!!!!! cannot be used on endless streams !!!!!!!!!!!\n *\n * stackoverflow.com/questions/24010109/java-8-stream-reverse-order\n */\n @SuppressWarnings(\"unchecked\")\n public static Stream reverse(Stream input) {\n Object[] temp = input.toArray();\n return (Stream) IntStream.range(0, temp.length).mapToObj(i -> temp[temp.length - i - 1]);\n }\n\n public static boolean notEquals(Object first, Object second) {\n return !isEquals(first, second);\n }\n\n public static boolean isEquals(Object first, Object second) {\n if (first == second) return true;\n if (first == null && second == null) return true;\n if (first == null || second == null) return false;\n return first.equals(second);\n }\n\n /**\n * staat geen null values in keys toe (alhoewel een map dat wel toe laat)\n */\n public static Map> groupBy(Stream stream, Function groupBy) {\n return stream.collect(Collectors.groupingBy(groupBy));\n }\n\n /**\n * workaround om null values in key toe te laten\n *\n * @see https://stackoverflow.com/questions/22625065/collectors-groupingby-doesnt-accept-null-keys\n */\n public static Map> groupByAcceptsNull(Stream stream, Function groupBy) {\n return stream//\n .collect(//\n Collectors.groupingBy(// Optional can contain null while\n // null itself throws exception\n v -> Optional.ofNullable(groupBy.apply(v))//\n , // order could be important, use LinkedHashMap\n newLinkedMap()//\n , //\n collectList()//\n )//\n )//\n .entrySet()//\n .stream()//\n .collect(//\n Collectors.toMap(// keymapper\n entry -> entry.getKey().orElse(null)//\n , // valuemapper\n entry -> entry.getValue()//\n , // merge function doesn't matter, key is\n // always unique\n keepFirst()//\n , // order could be important, use LinkedHashMap\n newLinkedMap()//\n )//\n );\n }\n\n public static Comparator dummyComparator() {\n return (x, y) -> 0;\n }\n\n public static Function, V> valueMapper() {\n return Entry::getValue;\n }\n\n public static Function, K> keyMapper() {\n return Entry::getKey;\n }\n\n public static Stream regex(String text, String regex) {\n return stream(new RegexIterator(text, regex));\n }\n\n public static T[] copy(T[] array) {\n return copy(array, array.length);\n }\n\n public static T[] copy(T[] array, int length) {\n return Arrays.copyOf(array, length);\n }\n\n @SafeVarargs\n public static Stream> streamMaps(Map... maps) {\n return Stream.of(maps).map(Map::entrySet).flatMap(Collection::stream);\n }\n\n @SafeVarargs\n public static Stream> streamMapsUnique(Map... maps) {\n return stream(streamMaps(maps).collect(Collectors.toMap(Entry::getKey, Entry::getValue, keepLast(), newLinkedMap())));\n }\n\n public static Collector, ?, EnhancedMap> collectMapEntries(Function, V> valueMapper) {\n return Collectors.toMap(Entry::getKey, valueMapper, rejectDuplicateKeys(), newMap());\n }\n\n public static Collector, ?, EnhancedMap> collectMapEntriesAlt(Function, K> keyMapper) {\n return Collectors.toMap(keyMapper, Entry::getValue, rejectDuplicateKeys(), newMap());\n }\n\n public static Collector, ?, EnhancedMap> collectMapEntries() {\n return Collectors.toMap(Entry::getKey, Entry::getValue, rejectDuplicateKeys(), newMap());\n }\n\n public static Collector> collectMap(Function keyMapper, Function valueMapper) {\n return collectMap(keyMapper, valueMapper, rejectDuplicateKeys());\n }\n\n public static Collector> collectMap(Function keyMapper, Function valueMapper,\n BinaryOperator duplicateValues) {\n return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap());\n }\n\n public static Collector> collectMapAlt(Function valueMapper, BinaryOperator duplicateValues) {\n @SuppressWarnings(\"unchecked\")\n Function keyMapper = (Function) id();\n return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap());\n }\n\n public static Collector> collectMap(Function keyMapper, BinaryOperator duplicateValues) {\n return collectMap(keyMapper, self(), duplicateValues);\n }\n\n public static Collector> collectMap(Function keyMapper) {\n return collectMap(keyMapper, rejectDuplicateKeys());\n }\n\n public static Collector> collectSortedMap(Function keyMapper, Function valueMapper) {\n return collectSortedMap(keyMapper, valueMapper, rejectDuplicateKeys());\n }\n\n public static Collector> collectSortedMap(Function keyMapper, Function valueMapper,\n BinaryOperator duplicateValues) {\n return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newSortedMap());\n }\n\n public static Collector> collectSortedMap(Function keyMapper, BinaryOperator duplicateValues) {\n return collectSortedMap(keyMapper, self(), duplicateValues);\n }\n\n public static Collector> collectSortedMap(Function keyMapper) {\n return collectSortedMap(keyMapper, rejectDuplicateKeys());\n }\n\n public static > Comparator natural() {\n return Comparator. naturalOrder();\n }\n\n public static > BinaryOperator keepMin() {\n return keepMin(CollectionUtils8. natural());\n }\n\n public static BinaryOperator keepMin(Comparator comparator) {\n return BinaryOperator.minBy(comparator);\n }\n\n public static > BinaryOperator keepMax() {\n return keepMax(CollectionUtils8. natural());\n }\n\n public static BinaryOperator keepMax(Comparator comparator) {\n return BinaryOperator.maxBy(comparator);\n }\n\n public static IntStream streamInt(int max) {\n return streamInt(0, 1, max);\n }\n\n public static LongStream streamLong(long max) {\n return streamLong(0, 1, max);\n }\n\n public static DoubleStream streamDouble(double max) {\n return streamDouble(0.0, 1.0, max);\n }\n\n public static IntStream streamInt(int start, int max) {\n return streamInt(start, 1, max);\n }\n\n public static LongStream streamLong(long start, long max) {\n return streamLong(start, 1, max);\n }\n\n public static DoubleStream streamDouble(double start, double max) {\n return streamDouble(start, 1.0, max);\n }\n\n public static IntStream streamInt(int start, int step, int max) {\n return IntStream.iterate(start, i -> i + step).limit(max - start);\n }\n\n public static LongStream streamLong(long start, long step, long max) {\n return LongStream.iterate(start, i -> i + step).limit(max - start);\n }\n\n public static DoubleStream streamDouble(double start, double step, double max) {\n return DoubleStream.iterate(start, i -> i + step).limit((long) (max - start));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] toArray(Collection collection) {\n return (T[]) collection.toArray();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] toArray(Stream stream, Class type) {\n return stream.toArray(size -> (T[]) Array.newInstance(type, size));\n }\n\n public static Stream flatMapCollections(Collection> collectionOfCollections) {\n return flatMapStreams(collectionOfCollections.stream().map(Collection::stream));\n }\n\n public static Stream flatMap(Stream> streamOfCollections) {\n return flatMapStreams(streamOfCollections.map(Collection::stream));\n }\n\n public static Stream flatMap(Collection> collentionOfStreams) {\n return flatMapStreams(collentionOfStreams.stream());\n }\n\n public static Stream flatMapStreams(Stream> streamOfStreams) {\n return streamOfStreams.flatMap(id());\n }\n\n public static Stream flatMapArrays(T[][] streamOfStreams) {\n Stream> b = streamArray(streamOfStreams).map(a -> streamArray(a));\n return flatMapStreams(b);\n }\n\n public static Opt eager(T value) {\n return Opt.eager(value);\n }\n\n public static Opt reusable(T value) {\n return Opt.reusable(value);\n }\n\n /**\n * c1 - c2, does not change input collections, returns new collection (list)\n */\n public static List subtract(Collection c1, Collection c2) {\n if (c1 == null) {\n return Collections.emptyList();\n }\n List tmp = new ArrayList<>(c1);\n if (c2 != null) {\n tmp.removeAll(c2);\n }\n return tmp;\n }\n\n /**\n * intersection of c1 and c2, does not change input collections, returns new collection (list)\n */\n public static List intersection(Collection c1, Collection c2) {\n if (c1 == null || c2 == null) {\n return Collections.emptyList();\n }\n return c1.stream().filter(c2::contains).collect(collectList());\n }\n\n /**\n * intersection of c1 and c2, does not change input collections, returns new collection (list)\n */\n public static List union(Collection c1, Collection c2) {\n if (c1 == null && c2 == null) {\n return Collections.emptyList();\n }\n if (c1 == null) {\n return new ArrayList<>(c2);\n }\n if (c2 == null) {\n return new ArrayList<>(c1);\n }\n List tmp = new ArrayList<>(c1.size() + c2.size());\n tmp.addAll(c1);\n tmp.addAll(c2);\n return tmp;\n }\n\n /**\n * @see https://stackoverflow.com/questions/42214519/java-intersection-of-multiple-collections-using-stream-lambdas\n */\n public static > Collector> intersecting() {\n class IntersectAcc {\n Set result;\n\n void accept(S s) {\n if (result == null)\n result = new HashSet<>(s);\n else\n result.retainAll(s);\n }\n\n IntersectAcc combine(IntersectAcc other) {\n if (result == null) return other;\n if (other.result != null) result.retainAll(other.result);\n return this;\n }\n }\n return Collector.of(IntersectAcc::new, IntersectAcc::accept, IntersectAcc::combine,\n acc -> acc.result == null ? Collections.emptySet() : acc.result, Collector.Characteristics.UNORDERED);\n }\n\n /**\n * aanTeMakenAct roept teBewaren op met als nieuw object aangeboden door param constructor, constructor en teBewaren zijn niet nullable\n *\n * @see #sync(Map, Map, BiConsumer, BiConsumer, BiConsumer)\n */\n public static void sync(//\n Map nieuwe, //\n Map bestaande, //\n BiConsumer teVerwijderenAct, //\n Supplier constructor, //\n BiConsumer teBewaren//\n ) {\n if (constructor == null || teBewaren == null) throw new NullPointerException();\n sync(nieuwe, bestaande, teVerwijderenAct, (k, i) -> teBewaren.accept(i, constructor.get()), teBewaren);\n }\n\n /**\n * synchroniseer een nieuwe collectie met een bestaande collecte\n *\n * @param nieuwe nieuwe collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)}\n * @param bestaande bestaande collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)}\n * @param teVerwijderenAct nullable, actie op te roepen indien verwijderen, krijgt key en bestaand object binnen\n * @param aanTeMakenAct nullable, actie op te roepen indien nieuw object aan te maken, krijgt key en nieuw object binnen\n * @param teBewaren nullable, actie op te roepen indien overeenkomst, krijgt key en nieuw en bestaand object binnen\n *\n * @param key waarop vergeleken moet worden\n * @param nieuwe object\n * @param bestaand object\n */\n public static void sync(//\n Map nieuwe, //\n Map bestaande, //\n BiConsumer teVerwijderenAct, //\n BiConsumer aanTeMakenAct, //\n BiConsumer teBewaren//\n ) {\n Map teVerwijderen = subtract(bestaande.keySet(), nieuwe.keySet()).stream().collect(Collectors.toMap(id(), bestaande::get));\n Map aanTeMaken = subtract(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(id(), nieuwe::get));\n Map overeenkomst = intersection(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(nieuwe::get, bestaande::get));\n if (teBewaren != null) overeenkomst.forEach(teBewaren);\n if (aanTeMakenAct != null) aanTeMaken.forEach(aanTeMakenAct);\n if (teVerwijderenAct != null) teVerwijderen.forEach(teVerwijderenAct);\n }\n\n public static Map getMap(Stream values, Function keyMapper) {\n return values.collect(Collectors.toMap(keyMapper, self()));\n }\n\n public static Map getMap(Collection values, Function keyMapper) {\n return getMap(values.stream(), keyMapper);\n }\n\n public static Map getMap(Stream values, Supplier keyMapper) {\n return values.collect(Collectors.toMap(supplierToFunction(keyMapper), self()));\n }\n\n public static Map getMap(Collection values, Supplier keyMapper) {\n return getMap(values.stream(), keyMapper);\n }\n\n public static Map getKeyMap(Collection values, Function valueMapper) {\n return values.stream().collect(Collectors.toMap(self(), valueMapper));\n }\n\n public static Map getKeyMap(Collection values, Supplier valueMapper) {\n return values.stream().collect(Collectors.toMap(self(), supplierToFunction(valueMapper)));\n }\n\n public static Function supplierToFunction(Supplier supplier) {\n return any -> supplier.get();\n }\n\n public static Supplier supplyAny(T object) {\n return () -> object;\n }\n\n public static BiConsumer, T> elementsListAccumulator() {\n return (List a, T t) -> a.add(t);\n }\n\n public static BiConsumer, T> uniqueElementsListAccumulator() {\n return (List a, T t) -> {\n if (!a.contains(t)) a.add(t);\n };\n }\n\n public static BinaryOperator> elementsListCombiner(BiConsumer, T> elementsListAccumulator) {\n return (List a1, List a2) -> {\n a2.stream().forEach(a2e -> elementsListAccumulator.accept(a1, a2e));\n return a1;\n };\n }\n\n public static Consumer when(Predicate restriction, Consumer whenTrue, Consumer whenFalse) {\n return t -> (restriction.test(t) ? whenTrue : whenFalse).accept(t);\n }\n\n public static Consumer when(boolean restriction, Consumer whenTrue, Consumer whenFalse) {\n return when(always(restriction), whenTrue, whenFalse);\n }\n\n public static void when(Predicate restriction, Consumer whenTrue, Consumer whenFalse, T subject) {\n when(restriction, whenTrue, whenFalse).accept(subject);\n }\n\n public static void when(boolean restriction, Consumer whenTrue, Consumer whenFalse, T subject) {\n when(restriction, whenTrue, whenFalse).accept(subject);\n }\n\n public static Collection> split(Collection all, int maxSize) {\n if (maxSize < 1) throw new IllegalArgumentException(\"maxSize<1\");\n if (all.size() <= maxSize) return Arrays.asList(all);\n int totalSize = all.size();\n AtomicInteger ai = new AtomicInteger(0);\n int groups = (totalSize / maxSize) + (totalSize % maxSize > 0 ? 1 : 0);\n Map> g = all.stream().parallel().collect(Collectors.groupingBy(s -> ai.addAndGet(1) % groups));\n return stream(g).map(valueMapper()).collect(collectList());\n }\n\n public static Stream> split(List elements, int count) {\n return elements.stream().collect(Collectors.groupingBy(c -> elements.indexOf(c) / count)).values().stream();\n }\n\n public static Function, T> first() {\n return list -> list.isEmpty() ? null : list.get(0);\n }\n\n public static T first(List list) {\n return list.get(0);\n }\n\n public static T first(LinkedBlockingDeque dq) {\n return dq.iterator().next();\n }\n\n public static T first(LinkedBlockingQueue q) {\n return q.iterator().next();\n }\n\n public static T first(LinkedHashSet set) {\n return set.iterator().next();\n }\n\n public static Entry first(LinkedHashMap map) {\n return map.entrySet().iterator().next();\n }\n\n @SafeVarargs\n public static List sortBy(Collection collection, Function> map,\n Function>... mapAdditional) {\n return collection.stream().sorted(comparator(map, mapAdditional)).collect(collectList());\n }\n\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public static > List sortInPlace(List list) {\n Collections.sort((List) list);\n return list;\n }\n\n @SafeVarargs\n public static List sortInPlace(List list, Function> map,\n Function>... mapAdditional) {\n list.sort(comparator(map, mapAdditional));\n return list;\n }\n\n @SafeVarargs\n public static Comparator comparator(Function> compare,\n Function>... compareAdditional) {\n return (t1, t2) -> {\n CompareToBuilder cb = new CompareToBuilder();\n cb.append(compare.apply(t1), compare.apply(t2));\n streamArray(compareAdditional).forEach(compareThisEl -> cb.append(compareThisEl.apply(t1), compareThisEl.apply(t2)));\n return cb.toComparison();\n };\n }\n\n public static Stream filterClass(Stream stream, Class type) {\n return stream.filter(t -> type.isAssignableFrom(t.getClass())).map(t -> type.cast(t));\n }\n\n public static Stream> stream(Properties properties) {\n return stream(false, properties).map(entry -> new Pair<>(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())));\n }\n\n public static Function, K> mapKey() {\n return Entry::getKey;\n }\n\n public static Function, V> mapValue() {\n return Entry::getValue;\n }\n\n public static Map map(Map map, Function valueMapper) {\n return stream(map).collect(collectMap(mapKey(), e -> valueMapper.apply(e.getValue())));\n }\n\n public static Map mapKey(Map map, Function keyMapper) {\n return stream(map).collect(collectMap(e -> keyMapper.apply(e.getKey()), mapValue()));\n }\n\n public static Comparator comparatorCaseInsensitive(Function compare) {\n Comparators.CaseInsensitiveComparator comparator = new Comparators.CaseInsensitiveComparator();\n return (t1, t2) -> {\n return comparator.compare(compare.apply(t1), compare.apply(t2));\n };\n }\n\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public static EnhancedMap> groupByValue(Properties properties) {\n return groupByValue((Map) (Map) properties);\n }\n\n public static EnhancedMap> groupByValue(Map map) {\n return stream(map.entrySet())\n .collect(Collectors.groupingBy(e -> e.getValue(), newMap(), Collectors.mapping(e -> e.getKey(), Collectors.toList())));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Function functions(Function... functions) {\n Value> returningFunction = new Value<>(functions[0]);\n Arrays.stream(functions).skip(1).forEach(f -> returningFunction.set(returningFunction.get().andThen(Function.class.cast(f))));\n return returningFunction.get();\n }\n\n public static X nn(X nullable, X defaultValue) {\n return nullable == null ? defaultValue : nullable;\n }\n\n public static Function getDefaulted(Function getter, T defaultValue) {\n return ((Function) s -> getter.apply(s)).andThen(e -> nn(e, defaultValue));\n }\n\n public static Y getMapValue(Map, Y> map, X in) {\n return map.entrySet().stream().filter(entry -> entry.getKey().test(in)).map(Map.Entry::getValue).findFirst().orElse(null);\n }\n\n public static List emptyList() {\n return Collections.emptyList();\n }\n\n public static Stream emptyStream() {\n return Stream.empty();\n }\n\n public static Map emptyMap() {\n return Collections.emptyMap();\n }\n\n public static Set emptySet() {\n return Collections.emptySet();\n }\n\n public static String toString(IntStream s) {\n return s.mapToObj(String::valueOf).collect(Collectors.joining());\n }\n\n @SafeVarargs\n public static BiPredicate equals(Function... methods) {\n return (a, b) -> {\n EqualsBuilder eb = new EqualsBuilder();\n Arrays.asList(methods).forEach(g -> eb.append(g.apply(a), g.apply(b)));\n return eb.isEquals();\n };\n }\n\n @SafeVarargs\n public static BiFunction bifunction(Function... methods) {\n return (a, b) -> {\n if (methods == null || methods.length == 0) {\n return 0;\n }\n CompareToBuilder ctb = new CompareToBuilder();\n Arrays.asList(methods).forEach(g -> ctb.append(g.apply(a), g.apply(b)));\n return ctb.toComparison();\n };\n }\n\n @SafeVarargs\n public static Comparator comparatorFor(Function... methods) {\n return comparatorFor(bifunction(methods));\n }\n\n public static Comparator comparatorFor(BiFunction method) {\n return method::apply;\n }\n\n public static Collection toUnmodifiableCollection(Collection collection) {\n return Collections.unmodifiableCollection(toList(true, collection));\n }\n\n public static List toUnmodifiableList(Collection collection) {\n return Collections.unmodifiableList(toList(true, collection));\n }\n\n public static Map toUnmodifiableMap(Map map) {\n return Collections.unmodifiableMap(toMap(true, map));\n }\n\n public static Set toUnmodifiableSet(Collection collection) {\n return Collections.unmodifiableSet(toSet(true, collection));\n }\n\n public static SortedMap toUnmodifiableSortedMap(SortedMap map) {\n return Collections.unmodifiableSortedMap(toSortedMap(true, map));\n }\n\n public static SortedSet toUnmodifiableSortedSet(Collection collection) {\n return Collections.unmodifiableSortedSet(toSortedSet(true, collection));\n }\n\n public static Collection toSynchronizedCollection(Collection collection) {\n return Collections.synchronizedCollection(toList(true, collection));\n }\n\n public static List toSynchronizedList(Collection collection) {\n return Collections.synchronizedList(toList(true, collection));\n }\n\n public static Map toSynchronizedMap(Map map) {\n return Collections.synchronizedMap(toMap(true, map));\n }\n\n public static Set toSynchronizedSet(Collection collection) {\n return Collections.synchronizedSet(toSet(true, collection));\n }\n\n public static SortedMap toSynchronizedSortedMap(SortedMap map) {\n return Collections.synchronizedSortedMap(toSortedMap(true, map));\n }\n\n public static SortedSet toSynchronizedSortedSet(Collection collection) {\n return Collections.synchronizedSortedSet(toSortedSet(true, collection));\n }\n\n public static Stream> index(Stream stream) {\n IntegerValue index = new IntegerValue(-1);\n return stream.map(t -> new KeyValue<>(index.add().get(), t));\n }\n\n public static Map countBy(Stream stream) {\n return stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n }\n\n /**\n * @see http://stackoverflow.com/questions/26403319/skip-last-x-elements-in-streamt\n */\n public static Stream skip(Stream s, int first, int last) {\n if (last <= 0 && first <= 0) {\n return s;\n }\n if (last <= 0) {\n return s.skip(first);\n }\n if (first > 0) {\n s = s.skip(first);\n }\n ArrayDeque pending = new ArrayDeque<>(last + 1);\n Spliterator src = s.spliterator();\n return StreamSupport.stream(new Spliterator() {\n @Override\n public boolean tryAdvance(Consumer action) {\n while (pending.size() <= last && src.tryAdvance(pending::add))\n ;\n if (pending.size() > last) {\n action.accept(pending.remove());\n return true;\n }\n return false;\n }\n\n @Override\n public Spliterator trySplit() {\n return null;\n }\n\n @Override\n public long estimateSize() {\n return src.estimateSize() - last;\n }\n\n @Override\n public int characteristics() {\n return src.characteristics();\n }\n }, false);\n }\n\n public static Stream skip(Integer first, Integer last, Stream s) {\n return skip(s, first == null ? 0 : first, last == null ? 0 : last);\n }\n\n public static T merge(List list, int index, T object, BinaryOperator operate) {\n return list.set(index, operate.apply(list.get(index), object));\n }\n\n public static String append(List list, int index, String string, String seperator) {\n return merge(list, index, string, (a, b) -> StringUtils.isBlank(a) ? b : a + seperator + b);\n }\n\n public static String firstNotBlank(String... strings) {\n return streamArray(strings).filter(isNotBlank()).findFirst().orElse(null);\n }\n\n @SafeVarargs\n public static T firstNotBlankAndNotNull(T... o) {\n return streamArray(o).filter(isNotBlankAndNotNull()).findFirst().orElse(null);\n }\n\n @SafeVarargs\n public static T firstNotNull(T... o) {\n return streamArray(o).filter(isNotNull()).findFirst().orElse(null);\n }\n\n public static List copy(List list, int maxSize) {\n if (list.size() <= maxSize) return list;\n return list.stream().limit(maxSize).collect(collectList());\n }\n\n public static List listLI(List list, T item) {\n list.add(item);\n return list;\n }\n\n public static List listIL(T item, List list) {\n list.add(0, item);\n return list;\n }\n\n public static List listLL(List list1, List list2) {\n list1.addAll(list2);\n return list1;\n }\n\n public static List listCLI(List list, T item) {\n List tmp = new ArrayList<>();\n tmp.addAll(list);\n tmp.add(item);\n return tmp;\n }\n\n public static List listCIL(T item, List list) {\n List tmp = new ArrayList<>();\n tmp.add(item);\n tmp.addAll(list);\n return tmp;\n }\n\n public static List listCLL(List list1, List list2) {\n List tmp = new ArrayList<>();\n tmp.addAll(list1);\n tmp.addAll(list2);\n return tmp;\n }\n\n public static List flatten(Collection records, Function toKey, Function toValue, BinaryOperator mergeValue,\n BiFunction mergeToRecord) {\n Map> map = records.stream().collect(Collectors.groupingBy(toKey));\n return map.entrySet().stream().map(entry -> {\n return new KeyValue<>(entry.getKey(), entry.getValue().stream().map(toValue).reduce(mergeValue).get());\n }).map(entry -> {\n return mergeToRecord.apply(entry.getKey(), entry.getValue());\n }).collect(Collectors.toList());\n }\n\n public static Collector> groupingByCount() {\n return Collectors.groupingBy(id(), newMap(), Collectors.reducing(0, e -> 1, Integer::sum));\n }\n\n public static Collector> groupingByCountMany() {\n return Collectors.groupingBy(id(), newMap(), Collectors.counting());\n }\n\n public static Comparator ascFloat() {\n return (a, b) -> new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator descFloat() {\n return (a, b) -> -new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator ascDouble() {\n return (a, b) -> new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator descDouble() {\n return (a, b) -> -new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator ascByte() {\n return (a, b) -> a - b;\n }\n\n public static Comparator descByte() {\n return (a, b) -> b - a;\n }\n\n public static Comparator ascShort() {\n return (a, b) -> a - b;\n }\n\n public static Comparator descShort() {\n return (a, b) -> b - a;\n }\n\n public static Comparator ascInt() {\n return (a, b) -> a - b;\n }\n\n public static Comparator descInt() {\n return (a, b) -> b - a;\n }\n\n public static Comparator ascLong() {\n return (a, b) -> new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator descLong() {\n return (a, b) -> -new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static LinkedHashMap sortByValue(Map map, Comparator comparator) {\n return map.entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue(comparator))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));\n }\n\n public static List repeat(int times, T object) {\n return IntStream.range(0, times).mapToObj(i -> object).collect(Collectors.toList());\n }\n\n public static Stream stream(Optional optional) {\n return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();\n }\n\n public static List serializable(List list) {\n return list instanceof Serializable ? list : new ArrayList<>(list);\n }\n\n public static Set serializable(Set set) {\n return set instanceof Serializable ? set : new HashSet<>(set);\n }\n\n public static SortedSet serializable(SortedSet set) {\n return set instanceof Serializable ? set : new TreeSet<>(set);\n }\n\n public static Map serializable(Map set) {\n return set instanceof Serializable ? set : new HashMap<>(set);\n }\n\n public static SortedMap serializable(SortedMap set) {\n return set instanceof Serializable ? set : new TreeMap<>(set);\n }\n\n public static IntStream stream(byte[] bytes) {\n return IntStream.range(0, bytes.length).map(idx -> bytes[idx]);\n }\n\n public static IntStream stream(Byte[] bytes) {\n return IntStream.range(0, bytes.length).map(idx -> bytes[idx]);\n }\n\n public static
    Predicate notNullPredicate() {\n return a -> a instanceof String ? StringUtils.isNotBlank((String) a) : a != null;\n }\n\n public static BiPredicate notNullBiPredicate() {\n return (a, b) -> notNullPredicate().test(a) || notNullPredicate().test(b);\n }\n\n public static TriplePredicate notNullTriplePredicate() {\n return (a, b, c) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c);\n }\n\n public static QuadruplePredicate notNullQuadruplePredicate() {\n return (a, b, c, d) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d);\n }\n\n public static QuintuplePredicate notNullQuintuplePredicate() {\n return (a, b, c, d, e) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d)\n || notNullPredicate().test(e);\n }\n\n public static List replaceOrAdd(List list, T object) {\n if (list == null || object == null) return list;\n int i = list.indexOf(object);\n if (i != -1) {\n list.remove(object);\n list.add(i, object);\n } else {\n list.add(object);\n }\n return list;\n }\n\n public static Consumer throwing(Supplier exception) {\n return t -> {\n throw exception.get();\n };\n }\n\n public static Consumer throwing(RuntimeException exception) {\n return t -> {\n throw exception;\n };\n }\n\n public static Consumer throwing(Function exception) {\n return t -> {\n throw exception.apply(t);\n };\n }\n\n public static BooleanSupplier enhanceBooleanSupplier(EBooleanSupplier supplier) {\n return EBooleanSupplier.enhance(supplier);\n }\n\n public static Consumer enhanceConsumer(EConsumer consumer) {\n return EConsumer.enhance(consumer);\n }\n\n public static BiConsumer enhanceBiConsumer(EBiConsumer consumer) {\n return EBiConsumer.enhance(consumer);\n }\n\n public static DoubleSupplier enhanceDoubleSupplier(EDoubleSupplier supplier) {\n return EDoubleSupplier.enhance(supplier);\n }\n\n public static Function enhanceFunction(EFunction function) {\n return EFunction.enhance(function);\n }\n\n public static IntSupplier enhanceIntegerSupplier(EIntSupplier supplier) {\n return EIntSupplier.enhance(supplier);\n }\n\n public static LongSupplier enhanceLongSupplier(ELongSupplier supplier) {\n return ELongSupplier.enhance(supplier);\n }\n\n public static Predicate enhancePredicate(EPredicate predicate) {\n return EPredicate.enhance(predicate);\n }\n\n public static Runnable enhanceRunnable(ERunnable runnable) {\n return ERunnable.enhance(runnable);\n }\n\n public static Supplier enhanceSupplier(ESupplier predicate) {\n return ESupplier.enhance(predicate);\n }\n\n public static List> entryList(Map map) {\n return map.entrySet().stream().map(KeyValue::new).collect(collectList());\n }\n\n public static T[] merge(T[] a, T[] b) {\n int aLen = a.length;\n int bLen = b.length;\n\n @SuppressWarnings(\"unchecked\")\n T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);\n System.arraycopy(a, 0, c, 0, aLen);\n System.arraycopy(b, 0, c, aLen, bLen);\n return c;\n }\n\n public static T[] append(T[] a, @SuppressWarnings(\"unchecked\") T... b) {\n return merge(a, b);\n }\n\n public static T[] prepend(T[] a, @SuppressWarnings(\"unchecked\") T... b) {\n return merge(b, a);\n }\n\n public static UnaryOperator unaryOperator(Consumer consumer) {\n UnaryOperator a = b -> {\n consumer.accept(b);\n return b;\n };\n return a;\n }\n\n public static Stream> ofSubLists(List source, int length) {\n if (length <= 0) throw new IllegalArgumentException(\"length = \" + length);\n int size = source.size();\n if (size <= 0) return Stream.empty();\n int fullChunks = (size - 1) / length;\n return IntStream.range(0, fullChunks + 1).mapToObj(n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));\n }\n}"},"new_file":{"kind":"string","value":"jhaws/lang/src/main/java/org/jhaws/common/lang/CollectionUtils8.java"},"old_contents":{"kind":"string","value":"package org.jhaws.common.lang;\n\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.io.UncheckedIOException;\nimport java.lang.reflect.Array;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayDeque;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Deque;\nimport java.util.EnumSet;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Properties;\nimport java.util.Queue;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.SortedSet;\nimport java.util.Spliterator;\nimport java.util.Spliterators;\nimport java.util.Stack;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\nimport java.util.concurrent.BlockingDeque;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentSkipListMap;\nimport java.util.concurrent.LinkedBlockingDeque;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.LinkedTransferQueue;\nimport java.util.concurrent.TransferQueue;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.BiPredicate;\nimport java.util.function.BinaryOperator;\nimport java.util.function.BooleanSupplier;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleSupplier;\nimport java.util.function.Function;\nimport java.util.function.IntFunction;\nimport java.util.function.IntSupplier;\nimport java.util.function.LongSupplier;\nimport java.util.function.Predicate;\nimport java.util.function.Supplier;\nimport java.util.function.UnaryOperator;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collector;\nimport java.util.stream.Collectors;\nimport java.util.stream.DoubleStream;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\nimport java.util.stream.Stream;\nimport java.util.stream.StreamSupport;\n\nimport org.apache.commons.lang3.builder.CompareToBuilder;\nimport org.apache.commons.lang3.builder.EqualsBuilder;\nimport org.jhaws.common.lang.functions.EBiConsumer;\nimport org.jhaws.common.lang.functions.EBooleanSupplier;\nimport org.jhaws.common.lang.functions.EConsumer;\nimport org.jhaws.common.lang.functions.EDoubleSupplier;\nimport org.jhaws.common.lang.functions.EFunction;\nimport org.jhaws.common.lang.functions.EIntSupplier;\nimport org.jhaws.common.lang.functions.ELongSupplier;\nimport org.jhaws.common.lang.functions.EPredicate;\nimport org.jhaws.common.lang.functions.ERunnable;\nimport org.jhaws.common.lang.functions.ESupplier;\n\n// http://infotechgems.blogspot.be/2011/11/java-collections-performance-time.html\n// TODO https://www.techempower.com/blog/2016/10/19/efficient-multiple-stream-concatenation-in-java/\n/**\n * @see java.util.stream.Stream\n * @see java.util.stream.StreamSupport\n * @see java.util.stream.Collectors\n * @see java.util.stream.Collector\n * @since 1.8\n * @see https://technology.amis.nl/2013/10/05/java-8-collection-enhancements- leveraging-lambda-expressions-or-how-java-emulates-sql/\n */\npublic interface CollectionUtils8 {\n public static class Comparators {\n public static class CaseInsensitiveComparator implements Comparator {\n @Override\n public int compare(String o1, String o2) {\n return (o1 == null ? \"\" : o1).compareToIgnoreCase((o2 == null ? \"\" : o2));\n }\n }\n\n public static class MapEntryKVComparator implements Comparator> {\n @Override\n public int compare(Entry o1, Entry o2) {\n return new CompareToBuilder().append(o1.getKey(), o2.getKey()).append(o1.getValue(), o2.getValue()).toComparison();\n }\n }\n\n public static class MapEntryVKComparator implements Comparator> {\n @Override\n public int compare(Entry o1, Entry o2) {\n return new CompareToBuilder().append(o1.getValue(), o2.getValue()).append(o1.getKey(), o2.getKey()).toComparison();\n }\n }\n }\n\n public static class RegexIterator implements EnhancedIterator {\n protected Pattern pattern;\n\n protected String regex;\n\n protected Matcher matcher;\n\n protected Boolean hasNext = null;\n\n public RegexIterator(String text, String regex) {\n this.pattern = Pattern.compile(regex);\n this.regex = regex;\n this.matcher = pattern.matcher(text);\n }\n\n public RegexIterator(String text, Pattern regex) {\n this.pattern = regex;\n this.regex = regex.toString();\n this.matcher = pattern.matcher(text);\n }\n\n public RegexIterator(Pattern regex, String text) {\n this.pattern = regex;\n this.regex = regex.toString();\n this.matcher = pattern.matcher(text);\n }\n\n @Override\n public boolean hasNext() {\n if (hasNext == null) {\n hasNext = matcher.find();\n }\n return hasNext;\n }\n\n @Override\n public String next() {\n if (hasNext == null) {\n hasNext();\n }\n if (hasNext) {\n hasNext = null;\n return matcher.group();\n }\n return null;\n }\n }\n\n public static class PathIterator implements EnhancedIterator {\n protected Path path;\n\n public PathIterator(Path path) {\n this.path = path;\n }\n\n @Override\n public boolean hasNext() {\n Path parent = this.path.getParent();\n return parent != null;\n }\n\n @Override\n public Path next() {\n this.path = this.path.getParent();\n return this.path;\n }\n }\n\n public static class ProjectionIterator implements EnhancedIterator {\n protected T current;\n\n protected T next;\n\n protected Function projection;\n\n public ProjectionIterator(T object, boolean include, Function projection) {\n this.current = object;\n this.projection = projection;\n if (include) next = current;\n }\n\n @Override\n public boolean hasNext() {\n if (next == null) {\n next = projection.apply(current);\n }\n return next != null;\n }\n\n @Override\n public T next() {\n hasNext();\n if (next == null) {\n throw new NoSuchElementException();\n }\n current = next;\n next = null;\n return current;\n }\n }\n\n public static interface Opt extends Supplier {\n /** default vorig type */\n Opt opt(Function getter);\n\n /** default vorig type */\n default Opt nest(Function getter) {\n return opt(getter);\n }\n\n /** ga verder eager */\n OptEager eager(Function getter);\n\n /** ga verder reusable = lazy */\n OptReusable reusable(Function getter);\n\n /** ga verder reusable = lazy */\n default OptReusable lazy(Function getter) {\n return reusable(getter);\n }\n\n default OptEager map(Function map) {\n T v = get();\n return Opt.eager(/* v == null ? null : */ map.apply(v));\n }\n\n default OptEager mapOrNull(Function map) {\n return mapOr(map, (X) null);\n }\n\n default OptEager mapOr(Function map, X value) {\n return mapOr(map, (Supplier) () -> value);\n }\n\n default OptEager mapOr(Function map, Supplier value) {\n T v = get();\n return Opt.eager(v == null ? value.get() : map.apply(v));\n }\n\n /** default eager */\n public static Opt optional(T value) {\n return eager(value);\n }\n\n /** start eager */\n public static OptEager eager(T value) {\n return new OptEager<>(value);\n }\n\n /** start reusable = lazy */\n public static OptReusable reusable(T value) {\n return new OptReusable<>(value);\n }\n\n /** start reusable = lazy */\n public static OptReusable lazy(T value) {\n return reusable(value);\n }\n\n X first(@SuppressWarnings(\"unchecked\") Function... getters);\n\n default boolean isNull() {\n return CollectionUtils8.isNull().test(get());\n }\n\n default boolean isBlankOrNull() {\n return CollectionUtils8.isBlankOrNull().test(get());\n }\n\n default boolean isNotNull() {\n return CollectionUtils8.isNotNull().test(get());\n }\n\n default boolean isNotBlankAndNotNull() {\n return CollectionUtils8.isNotBlankAndNotNull().test(get());\n }\n\n default void consume(Consumer consumer) {\n T value = get();\n if (value != null) {\n consumer.accept(value);\n }\n }\n\n /** geeft waarde terug */\n @Override\n T get();\n\n /** voert {@link #opt(Function)} uit en dan {@link #get()} */\n default X get(Function get) {\n return opt(get).get();\n }\n\n /**\n * voert {@link #get()} uit en wanneer null, voert {@link Supplier} uit en geeft die waarde\n */\n default T or(Supplier supplier) {\n return Optional.ofNullable(get()).orElseGet(supplier);\n }\n\n /** voert {@link #get()} uit en wanneer null, geeft meegegeven waarde */\n default T or(T value) {\n return Optional.ofNullable(get()).orElse(value);\n }\n\n default T orNull() {\n return or((T) null);\n }\n\n default T or(Opt supplier) {\n return or(supplier.get());\n }\n\n /** wrap in Value */\n default Value getValue() {\n return new Value<>(get());\n }\n\n /** wrap in Value */\n default Value getValue(Function get) {\n return new Value<>(get(get));\n }\n\n /** wrap in Value */\n default Value orValue(Supplier supplier) {\n return new Value<>(or(supplier));\n }\n\n /** wrap in Value */\n default Value orValue(T value) {\n return new Value<>(or(value));\n }\n\n /** wrap in Value */\n default Value orNullValue() {\n return new Value<>(orNull());\n }\n\n /** wrap in Value */\n default Value orValue(Opt supplier) {\n return new Value<>(or(supplier));\n }\n }\n\n static class OptEager implements Opt {\n protected final T value;\n\n protected OptEager(T value) {\n this.value = value;\n }\n\n @Override\n public T get() {\n return value;\n }\n\n @Override\n public

    OptEager

    opt(Function get) {\n return eager(get);\n }\n\n @Override\n public

    OptEager

    eager(Function get) {\n return new OptEager<>(value == null ? null : get.apply(value));\n }\n\n @Override\n public

    OptReusable reusable(Function get) {\n return new OptReusable<>(get()).opt(get);\n }\n\n @Override\n public X first(@SuppressWarnings(\"unchecked\") Function... getters) {\n return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null);\n }\n }\n\n static class OptReusable implements Opt {\n protected final OptReusable parent;\n\n protected final Function getter;\n\n protected final T value;\n\n protected OptReusable(T value) {\n this.value = value;\n this.parent = null;\n this.getter = null;\n }\n\n protected OptReusable(OptReusable parent, Function getter) {\n this.value = null;\n this.parent = parent;\n this.getter = getter;\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public T get() {\n if (value != null) return value;\n Stack stack = new Stack<>();\n stack.add(this);\n OptReusable current = this.parent;\n while (current != null) {\n stack.add(current);\n current = current.parent;\n }\n Object currentValue = stack.pop().value;\n while (!stack.isEmpty() && currentValue != null) {\n current = stack.pop();\n currentValue = current.getter.apply(currentValue);\n }\n return (T) currentValue;\n }\n\n @Override\n public OptReusable opt(Function get) {\n return reusable(get);\n }\n\n @Override\n public OptEager eager(Function get) {\n return new OptEager<>(get()).opt(get);\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public OptReusable reusable(Function get) {\n return new OptReusable<>((OptReusable) this, get);\n }\n\n @Override\n public X first(@SuppressWarnings(\"unchecked\") Function... getters) {\n return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null);\n }\n }\n\n public static class CustomCollector implements Collector {\n protected Supplier supplier;\n\n protected BiConsumer accumulator;\n\n protected BinaryOperator combiner;\n\n protected Function finisher;\n\n protected Set characteristics;\n\n public CustomCollector(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Function finisher,\n Set characteristics) {\n this.supplier = supplier;\n this.accumulator = accumulator;\n this.combiner = combiner;\n this.finisher = finisher;\n this.characteristics = characteristics;\n }\n\n @SuppressWarnings(\"unchecked\")\n public CustomCollector(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Set characteristics) {\n this(supplier, accumulator, combiner, x -> (R) x, characteristics);\n }\n\n @SuppressWarnings(\"unchecked\")\n public CustomCollector(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner) {\n this(supplier, accumulator, combiner, x -> (R) x, Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)));\n }\n\n public CustomCollector() {\n super();\n }\n\n @Override\n public Supplier supplier() {\n return supplier;\n }\n\n @Override\n public BiConsumer accumulator() {\n return accumulator;\n }\n\n @Override\n public BinaryOperator combiner() {\n return combiner;\n }\n\n @Override\n public Function finisher() {\n return finisher;\n }\n\n @Override\n public Set characteristics() {\n return characteristics;\n }\n\n public Supplier getSupplier() {\n return this.supplier;\n }\n\n public void setSupplier(Supplier supplier) {\n this.supplier = supplier;\n }\n\n public BiConsumer getAccumulator() {\n return this.accumulator;\n }\n\n public void setAccumulator(BiConsumer accumulator) {\n this.accumulator = accumulator;\n }\n\n public BinaryOperator getCombiner() {\n return this.combiner;\n }\n\n public void setCombiner(BinaryOperator combiner) {\n this.combiner = combiner;\n }\n\n public Function getFinisher() {\n return this.finisher;\n }\n\n public void setFinisher(Function finisher) {\n this.finisher = finisher;\n }\n\n public Set getCharacteristics() {\n return this.characteristics;\n }\n\n public void setCharacteristics(Set characteristics) {\n this.characteristics = characteristics;\n }\n }\n\n public static class ListCollector extends CustomCollector, List> {\n public ListCollector() {\n setSupplier(newList());\n BiConsumer, T> accumulator0 = elementsListAccumulator();\n setAccumulator(accumulator0);\n setCombiner(elementsListCombiner(accumulator0));\n setFinisher(CollectionUtils8.cast());\n setCharacteristics(Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)));\n }\n }\n\n public static class ListUQCollector extends ListCollector {\n public ListUQCollector() {\n BiConsumer, T> accumulator0 = uniqueElementsListAccumulator();\n setAccumulator(accumulator0);\n setCombiner(elementsListCombiner(accumulator0));\n }\n }\n\n /**\n * always use first value for key\n */\n public static BinaryOperator keepFirst() {\n return (p1, p2) -> p1;\n }\n\n /**\n * always use last value for key\n */\n public static BinaryOperator keepLast() {\n return (p1, p2) -> p2;\n }\n\n public static T last(Stream stream) {\n return stream.reduce(keepLast()).orElse(null);\n }\n\n public static Entry last(SortedMap map) {\n return map.entrySet().stream().reduce(keepLast()).orElse(null);\n }\n\n /**\n * see {@link #keepLast()}\n */\n public static BinaryOperator acceptDuplicateKeys() {\n return keepLast();\n }\n\n /**\n * rejects !different! keys for the same value\n *\n * @throws IllegalArgumentException\n */\n public static BinaryOperator rejectDuplicateKeys() throws IllegalArgumentException {\n return (a, b) -> {\n if (new EqualsBuilder().append(a, b).isEquals()) return a;\n throw new IllegalArgumentException(\"duplicate key: \" + a + \" <> \" + b);\n };\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] array(T item, T... items) {\n if (item == null && (items == null || items.length == 0)) {\n return (T[]) new Object[0];\n }\n if (items == null || items.length == 0) {\n return (T[]) new Object[] { item };\n }\n if (item == null) {\n return items;\n }\n int length = items.length;\n // FIXME cheaper // operation\n T[] newarray = Arrays.copyOf(items, 1 + length);\n newarray[0] = item;\n System.arraycopy(items, 0, newarray, 1, length);\n return newarray;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] array(T[] items, T item) {\n if (item == null && (items == null || items.length == 0)) {\n return (T[]) new Object[0];\n }\n if (items == null || items.length == 0) {\n return (T[]) new Object[] { item };\n }\n if (item == null) {\n return items;\n }\n int length = items.length;\n T[] newarray = Arrays.copyOf(items, 1 + length);\n newarray[newarray.length - 1] = item;\n return newarray;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] array(T[] items1, T[] items2) {\n if ((items1 == null || items1.length == 0) && (items2 == null || items2.length == 0)) {\n return (T[]) new Object[0];\n }\n if (items1 == null || items1.length == 0) {\n return items2;\n }\n if (items2 == null || items2.length == 0) {\n return items1;\n }\n int length1 = items1.length;\n int length2 = items2.length;\n T[] newarray = Arrays.copyOf(items1, length1 + length2);\n System.arraycopy(items2, 0, newarray, length1, length2);\n return newarray;\n }\n\n public static T[] array(Class componentType, Collection collection) {\n return array(componentType, collection.stream());\n }\n\n public static T[] array(Class componentType, Stream stream) {\n return stream.toArray(newArray(componentType));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static IntFunction newArray(Class componentType) {\n return length -> (T[]) Array.newInstance(componentType, length);\n }\n\n public static T[] newArray(Class componentType, int size) {\n return CollectionUtils8. newArray(componentType).apply(size);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Entry[] array(Map map) {\n return map.entrySet().toArray((Map.Entry[]) new Map.Entry[0]);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Function cast() {\n return x -> (T) x;\n }\n\n public static Function cast(Class type) {\n return o -> type.cast(o);\n }\n\n public static T cast(Class type, Object object) {\n return cast(type).apply(object);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static > Collector collector(C collection) {\n if (collection instanceof Deque) {\n return (Collector) CollectionUtils8. collectDeque();\n }\n if (collection instanceof Queue) {\n return (Collector) CollectionUtils8. collectQueue();\n }\n if (collection instanceof List) {\n return (Collector) CollectionUtils8. collectList();\n }\n if (collection instanceof SortedSet) {\n return (Collector) CollectionUtils8. collectSortedSet();\n }\n if (collection instanceof Set) {\n return (Collector) CollectionUtils8. collectSet();\n }\n throw new UnsupportedOperationException(collection.getClass().getName());\n }\n\n @SafeVarargs\n public static > C filter(boolean parallel, C collection, Predicate... predicates) {\n AtomicReference> streamReference = new AtomicReference<>(stream(parallel, collection));\n streamArray(predicates).forEach(predicate -> streamReference.set(streamReference.get().filter(predicate)));\n C collected = streamReference.get().collect(collector(collection));\n return collected;\n }\n\n @SafeVarargs\n public static > C filter(C collection, Predicate... predicates) {\n return filter(false, collection, predicates);\n }\n\n public static T last(List dd) {\n int size = dd.size();\n return size == 0 ? null : dd.get(size - 1);\n }\n\n public static EnhancedMap map(Collection> entries) {\n return map(false, entries);\n }\n\n public static EnhancedMap map(boolean parallel, Collection> entries) {\n return map(stream(parallel, entries));\n }\n\n public static EnhancedMap map(Stream> stream) {\n return map(stream, CollectionUtils8. newLinkedMap());\n }\n\n public static > M map(Stream> stream, Supplier mapSupplier) {\n BinaryOperator keepLast = CollectionUtils8. keepLast();\n return map(stream, mapSupplier, keepLast);\n }\n\n public static > M map(Stream> stream, Supplier mapSupplier, BinaryOperator choice) {\n Function, K> keyMapper = CollectionUtils8. keyMapper();\n Function, V> valueMapper = CollectionUtils8. valueMapper();\n Collector, ?, M> c = Collectors.toMap(keyMapper, valueMapper, choice, mapSupplier);\n return stream.collect(c);\n }\n\n public static Supplier> newLinkedMap() {\n return EnhancedLinkedHashMap::new;\n }\n\n public static Supplier> newMap() {\n return EnhancedHashMap::new;\n }\n\n public static Supplier> newSortedMap() {\n return EnhancedTreeMap::new;\n }\n\n public static Supplier> newNavigableMap() {\n return EnhancedTreeMap::new;\n }\n\n public static Supplier> newConcurrentNavigableMap() {\n return ConcurrentSkipListMap::new;\n }\n\n public static Supplier> newConcurrentMap() {\n return ConcurrentHashMap::new;\n }\n\n public static Supplier> newStack() {\n return Stack::new;\n }\n\n public static Supplier> newDeque() {\n return EnhancedLinkedList::new;\n }\n\n public static Supplier> newList() {\n return EnhancedArrayList::new;\n }\n\n public static Supplier> newQueue() {\n return EnhancedLinkedList::new;\n }\n\n public static Supplier> newSet() {\n return EnhancedHashSet::new;\n }\n\n public static Supplier> newSortedSet() {\n return EnhancedTreeSet::new;\n }\n\n public static Supplier> newBlockingQueue() {\n return LinkedBlockingDeque::new;\n }\n\n public static Supplier> newBlockingDeque() {\n return LinkedBlockingDeque::new;\n }\n\n public static Supplier> newTransferQueue() {\n return LinkedTransferQueue::new;\n }\n\n public static > Collector toCollector(Supplier supplier) {\n return Collectors.toCollection(supplier);\n }\n\n public static Collector> collectStack() {\n return toCollector(newStack());\n }\n\n public static Collector> collectDeque() {\n return toCollector(newDeque());\n }\n\n public static Collector> collectList() {\n return toCollector(newList());\n }\n\n public static > Collector collection(Supplier newCollection) {\n return Collectors.toCollection(newCollection);\n }\n\n public static ListCollector collectListUQ() {\n return new ListUQCollector<>();\n }\n\n public static Collector> collectQueue() {\n return toCollector(newQueue());\n }\n\n public static Collector> collectSet() {\n return Collectors.toSet();\n }\n\n public static Collector> collectSortedSet() {\n return toCollector(newSortedSet());\n }\n\n public static > List sort(Collection collection) {\n return sort(false, collection);\n }\n\n public static > List sort(boolean parallel, Collection collection) {\n return stream(parallel, collection).sorted().collect(toCollector(newList()));\n }\n\n public static List sort(boolean parallel, Collection collection, Comparator comparator) {\n return stream(parallel, collection).sorted(comparator).collect(toCollector(newList()));\n }\n\n public static List sort(Collection collection, Comparator comparator) {\n return sort(false, collection, comparator);\n }\n\n public static List sortBy(Collection collection, List orderByMe, Function map) {\n return collection.stream().sorted(comparator(orderByMe, map)).collect(collectList());\n }\n\n public static Comparator comparator(List orderByMe, Function map) {\n return (x, y) -> Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(x))))\n .compareTo(Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(y)))));\n }\n\n public static Comparator comparator(List orderByMe) {\n return comparator(orderByMe, self());\n }\n\n public static List sortBy(Collection collection, List orderByMe) {\n return sortBy(collection, orderByMe, self());\n }\n\n public static > Stream sortBy(Stream sortMe, Map sortByMe) {\n return sortMe.sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y)));\n }\n\n public static Stream sortBy(Stream collection, List orderByMe, Function map) {\n return collection.sorted(comparator(orderByMe, map));\n }\n\n public static Stream sortBy(Stream collection, List orderByMe) {\n return sortBy(collection, orderByMe, self());\n }\n\n public static > List sortBy(Collection sortMe, Map sortByMe) {\n return sortMe.stream().sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y))).collect(collectList());\n }\n\n public static Function id() {\n return self();\n }\n\n public static Function self() {\n return Function.identity();\n }\n\n public static UnaryOperator idu() {\n return selfu();\n }\n\n public static UnaryOperator selfu() {\n return t -> t;\n }\n\n public static int noNegIndex(int i) {\n return i == -1 ? Integer.MAX_VALUE : i;\n }\n\n public static Stream stream(Collection collection) {\n return stream(false, collection);\n }\n\n public static Stream stream(boolean parallel, Collection collection) {\n return collection == null ? Stream.empty() : StreamSupport.stream(collection.spliterator(), parallel);\n }\n\n public static Stream stream(Iterable iterable) {\n return stream(false, iterable);\n }\n\n public static Stream stream(Iterator iterator) {\n return stream(false, iterator);\n }\n\n public static Stream stream(Enumeration enumeration) {\n return stream(false, enumeration);\n }\n\n public static Stream stream(boolean parallel, Iterable iterable) {\n return iterable == null ? Stream.empty() : StreamSupport.stream(iterable.spliterator(), parallel);\n }\n\n public static Stream stream(boolean parallel, Iterator iterator) {\n return iterator == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), parallel);\n }\n\n public static Stream stream(boolean parallel, Enumeration enumeration) {\n return enumeration == null ? Stream.empty()\n : StreamSupport.stream(Spliterators.spliteratorUnknownSize(enumeration.asIterator(), 0), parallel);\n }\n\n public static Stream lines(Path path) {\n try {\n return Files.lines(path);\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n public static Stream streamValues(Map map) {\n return stream(map).map(valueMapper());\n }\n\n public static Stream> streamDeepValues(Map> map) {\n return stream(map).map(valueMapper()).map(collection -> stream(collection));\n }\n\n public static Stream> stream(Map map) {\n return stream(false, map);\n }\n\n public static Stream> stream(boolean parallel, Map map) {\n return map == null ? Stream.empty() : StreamSupport.stream(map.entrySet().spliterator(), parallel);\n }\n\n public static Stream stream(Path path) {\n return stream(false, path);\n }\n\n public static Stream stream(boolean parallel, Path path) {\n return StreamSupport.stream(path.spliterator(), parallel);\n }\n\n @SafeVarargs\n public static Stream streamArray(T... array) {\n return streamArray(false, array);\n }\n\n @SafeVarargs\n public static Stream streamArray(boolean parallel, T... array) {\n if (array == null) return Stream.empty();\n // StreamSupport.stream(Spliterators.spliterator(array, 0, array.length,\n // Spliterator.ORDERED | Spliterator.IMMUTABLE), parallel);\n Stream stream = Arrays.stream(array);\n if (parallel) stream = stream.parallel();\n return stream;\n }\n\n public static Stream streamDetached(Collection collection) {\n return streamDetached(false, collection);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Stream streamDetached(boolean parallel, Collection collection) {\n return streamArray(parallel, array((Class) Object.class, collection));\n }\n\n public static Stream> streamDetached(Map map) {\n return streamDetached(false, map);\n }\n\n public static Stream> streamDetached(boolean parallel, Map map) {\n return streamArray(parallel, array(map));\n }\n\n public static Stream streamFully(Path path) {\n return stream(new PathIterator(path));\n }\n\n public static Stream stream(Collection input, Function> mapping) {\n return input.stream().map(mapping).map(Collection::stream).flatMap(id());\n }\n\n public static List toList(Collection collection) {\n return toList(true, collection);\n }\n\n public static List toList(boolean copy, Collection collection) {\n return !copy && collection instanceof List ? (List) collection : stream(collection).collect(collectList());\n }\n\n public static Map toMap(Map map) {\n return toMap(true, map);\n }\n\n public static Map toMap(boolean copy, Map map) {\n return !copy /* && map instanceof Map */ ? (Map) map : stream(map).collect(collectMap(Entry::getKey, Entry::getValue));\n }\n\n public static SortedMap toSortedMap(Map map) {\n return toSortedMap(true, map);\n }\n\n public static SortedMap toSortedMap(boolean copy, Map map) {\n return !copy && map instanceof SortedMap ? (SortedMap) map : stream(map).collect(collectSortedMap(Entry::getKey, Entry::getValue));\n }\n\n @SafeVarargs\n public static List toList(T... array) {\n return streamArray(array).collect(collectList());\n }\n\n public static Set toSet(Collection collection) {\n return toSet(true, collection);\n }\n\n public static Set toSet(boolean copy, Collection collection) {\n return !copy && collection instanceof Set ? (Set) collection : stream(collection).collect(collectSet());\n }\n\n @SafeVarargs\n public static Set toSet(T... array) {\n return streamArray(array).collect(collectSet());\n }\n\n public static SortedSet toSortedSet(Collection collection) {\n return toSortedSet(true, collection);\n }\n\n public static SortedSet toSortedSet(boolean copy, Collection collection) {\n return !copy && collection instanceof SortedSet ? (SortedSet) collection : stream(collection).collect(collectSortedSet());\n }\n\n @SafeVarargs\n public static SortedSet toSortedSet(T... array) {\n return streamArray(array).collect(collectSortedSet());\n }\n\n public static Queue toQueue(Collection collection) {\n return stream(collection).collect(collectQueue());\n }\n\n @SafeVarargs\n public static Queue toQueue(T... array) {\n return streamArray(array).collect(collectQueue());\n }\n\n public static Deque toDeque(Collection collection) {\n return stream(collection).collect(collectDeque());\n }\n\n @SafeVarargs\n public static Deque toDeque(T... array) {\n return streamArray(array).collect(collectDeque());\n }\n\n public static Stack toStack(Collection collection) {\n return stream(collection).collect(collectStack());\n }\n\n @SafeVarargs\n public static Stack toStack(T... array) {\n return streamArray(array).collect(collectStack());\n }\n\n public static > C to(T[] array, Supplier supplier) {\n return to(array, toCollector(supplier));\n }\n\n public static > C to(T[] array, Collector collector) {\n return streamArray(array).collect(collector);\n }\n\n public static > C to(Collection collection, Supplier supplier) {\n return to(collection, toCollector(supplier));\n }\n\n public static > C to(Collection collection, Collector collector) {\n return stream(collection).collect(collector);\n }\n\n public static boolean containedInAny(Collection c1, Collection c2) {\n return c1.stream().anyMatch(c2::contains);\n }\n\n public static Predicate not(Predicate t) {\n return t.negate();\n }\n\n public static Predicate isNotBlankAndNotNull() {\n return t -> t instanceof String ? isNotBlank().test(String.class.cast(t)) : isNotNull().test(t);\n }\n\n public static Predicate isBlankOrNull() {\n return t -> t instanceof String ? isBlank().test(String.class.cast(t)) : isNull().test(t);\n }\n\n public static Predicate isNotBlank() {\n return org.apache.commons.lang3.StringUtils::isNotBlank;\n }\n\n public static Predicate isBlank() {\n return org.apache.commons.lang3.StringUtils::isBlank;\n }\n\n public static Predicate isNotNull() {\n return Objects::nonNull;\n }\n\n public static Predicate isNull() {\n return Objects::isNull;\n }\n\n public static Predicate is(T x) {\n return t -> isEquals(t, x);\n }\n\n public static Predicate isNot(T x) {\n return not(is(x));\n }\n\n public static Predicate containedIn(Collection collection) {\n return collection::contains;\n }\n\n public static Predicate containedIn(Collection collection, Function converter) {\n return e -> collection.contains(converter.apply(e));\n }\n\n public static Predicate keyContainedIn(Map map) {\n return map::containsKey;\n }\n\n public static Predicate keyContainedIn(Map map, Function converter) {\n return e -> map.containsKey(converter.apply(e));\n }\n\n public static Predicate valueContainedIn(Map map) {\n return map::containsValue;\n }\n\n public static Predicate valueContainedIn(Map map, Function converter) {\n return e -> map.containsValue(converter.apply(e));\n }\n\n public static Predicate notContainedIn(Collection collection) {\n return not(containedIn(collection));\n }\n\n public static Predicate notContainedIn(Collection collection, Function converter) {\n return not(containedIn(collection, converter));\n }\n\n public static Predicate keyNotContainedIn(Map map) {\n return not(keyContainedIn(map));\n }\n\n public static Predicate keyNotContainedIn(Map map, Function converter) {\n return not(keyContainedIn(map, converter));\n }\n\n public static Predicate valueNotContainedIn(Map map) {\n return not(valueContainedIn(map));\n }\n\n public static Predicate valueNotContainedIn(Map map, Function converter) {\n return not(valueContainedIn(map, converter));\n }\n\n public static Function makeNull() {\n return x -> null;\n }\n\n public static Supplier supplyNull() {\n return () -> null;\n }\n\n public static Predicate always() {\n return x -> true;\n }\n\n public static Predicate always(boolean b) {\n return x -> b;\n }\n\n public static Predicate never() {\n return x -> false;\n }\n\n public static Predicate never(boolean b) {\n return x -> !b;\n }\n\n public static BiPredicate always2() {\n return (x, y) -> true;\n }\n\n public static BiPredicate always2(boolean b) {\n return (x, y) -> b;\n }\n\n public static BiPredicate never2() {\n return (x, y) -> false;\n }\n\n public static BiPredicate never2(boolean b) {\n return (x, y) -> !b;\n }\n\n public static IntStream streamp(String text) {\n return text.chars();\n }\n\n public static Stream stream(String text) {\n return streamp(text).mapToObj(i -> (char) i);\n }\n\n public static Stream stream(char[] text) {\n return stream(new String(text));\n }\n\n public static Stream stream(Boolean... b) {\n return IntStream.range(0, b.length).mapToObj(idx -> b[idx]);\n }\n\n public static Stream stream(Character[] text) {\n return Arrays.stream(text);\n }\n\n public static List> match(List keys, List values) {\n return values.stream()\n .parallel()\n .filter(containedIn(keys))\n .map(value -> new Pair<>(keys.get(keys.indexOf(value)), value))\n .collect(collectList());\n }\n\n public static T optional(T value, Supplier orElse) {\n return Optional.ofNullable(value).orElseGet(orElse);\n }\n\n public static T optional(T oldValue, T newValue, Consumer whenDifferent) {\n if (notEquals(oldValue, newValue)) {\n whenDifferent.accept(newValue);\n return newValue;\n }\n return oldValue;\n }\n\n public static Consumer consume() {\n return x -> {\n //\n };\n }\n\n public static BiConsumer biconsume() {\n return (x, y) -> {\n return;\n };\n }\n\n public static String joinArray(String delimiter, T[] strings) {\n return join(delimiter, streamArray(strings));\n }\n\n public static String joinArray(T[] strings) {\n return join(\" \", streamArray(strings));\n }\n\n public static String join(Collection strings) {\n return join(\" \", stream(strings));\n }\n\n public static String join(String delimiter, Collection strings) {\n return join(delimiter, stream(strings));\n }\n\n public static String join(Stream stream) {\n return join(\" \", stream);\n }\n\n public static String join(String delimiter, Stream stream) {\n return stream//\n .filter(Objects::nonNull)//\n .map(String::valueOf)//\n .map(String::trim)//\n .filter(StringUtils::isNotBlank)//\n .collect(Collectors.joining(delimiter));\n }\n\n public static String join(String delimiter, boolean skipNull, boolean trim, Stream stream) {\n if (skipNull) stream = stream.filter(Objects::nonNull);\n Stream stream2 = stream.map(String::valueOf);\n if (trim) stream2 = stream2.map(String::trim);\n if (skipNull) stream2 = stream2.filter(StringUtils::isNotBlank);\n return stream2.collect(Collectors.joining(delimiter));\n }\n\n public static Stream split(String string, String delimiter) {\n return streamArray(string.split(delimiter));\n }\n\n public static String joining(Stream stream, String delimiter) {\n return stream.collect(Collectors.joining(delimiter));\n }\n\n /**\n * !!!!!!!!!!! terminates source stream !!!!!!!!!!!
    \n * !!!!!!!!!!! cannot be used on endless streams !!!!!!!!!!!\n *\n * stackoverflow.com/questions/24010109/java-8-stream-reverse-order\n */\n @SuppressWarnings(\"unchecked\")\n public static Stream reverse(Stream input) {\n Object[] temp = input.toArray();\n return (Stream) IntStream.range(0, temp.length).mapToObj(i -> temp[temp.length - i - 1]);\n }\n\n public static boolean notEquals(Object first, Object second) {\n return !isEquals(first, second);\n }\n\n public static boolean isEquals(Object first, Object second) {\n if (first == second) return true;\n if (first == null && second == null) return true;\n if (first == null || second == null) return false;\n return first.equals(second);\n }\n\n /**\n * staat geen null values in keys toe (alhoewel een map dat wel toe laat)\n */\n public static Map> groupBy(Stream stream, Function groupBy) {\n return stream.collect(Collectors.groupingBy(groupBy));\n }\n\n /**\n * workaround om null values in key toe te laten\n *\n * @see https://stackoverflow.com/questions/22625065/collectors-groupingby-doesnt-accept-null-keys\n */\n public static Map> groupByAcceptsNull(Stream stream, Function groupBy) {\n return stream//\n .collect(//\n Collectors.groupingBy(// Optional can contain null while\n // null itself throws exception\n v -> Optional.ofNullable(groupBy.apply(v))//\n , // order could be important, use LinkedHashMap\n newLinkedMap()//\n , //\n collectList()//\n )//\n )//\n .entrySet()//\n .stream()//\n .collect(//\n Collectors.toMap(// keymapper\n entry -> entry.getKey().orElse(null)//\n , // valuemapper\n entry -> entry.getValue()//\n , // merge function doesn't matter, key is\n // always unique\n keepFirst()//\n , // order could be important, use LinkedHashMap\n newLinkedMap()//\n )//\n );\n }\n\n public static Comparator dummyComparator() {\n return (x, y) -> 0;\n }\n\n public static Function, V> valueMapper() {\n return Entry::getValue;\n }\n\n public static Function, K> keyMapper() {\n return Entry::getKey;\n }\n\n public static Stream regex(String text, String regex) {\n return stream(new RegexIterator(text, regex));\n }\n\n public static T[] copy(T[] array) {\n return copy(array, array.length);\n }\n\n public static T[] copy(T[] array, int length) {\n return Arrays.copyOf(array, length);\n }\n\n @SafeVarargs\n public static Stream> streamMaps(Map... maps) {\n return Stream.of(maps).map(Map::entrySet).flatMap(Collection::stream);\n }\n\n @SafeVarargs\n public static Stream> streamMapsUnique(Map... maps) {\n return stream(streamMaps(maps).collect(Collectors.toMap(Entry::getKey, Entry::getValue, keepLast(), newLinkedMap())));\n }\n\n public static Collector, ?, EnhancedMap> collectMapEntries(Function, V> valueMapper) {\n return Collectors.toMap(Entry::getKey, valueMapper, rejectDuplicateKeys(), newMap());\n }\n\n public static Collector, ?, EnhancedMap> collectMapEntriesAlt(Function, K> keyMapper) {\n return Collectors.toMap(keyMapper, Entry::getValue, rejectDuplicateKeys(), newMap());\n }\n\n public static Collector, ?, EnhancedMap> collectMapEntries() {\n return Collectors.toMap(Entry::getKey, Entry::getValue, rejectDuplicateKeys(), newMap());\n }\n\n public static Collector> collectMap(Function keyMapper, Function valueMapper) {\n return collectMap(keyMapper, valueMapper, rejectDuplicateKeys());\n }\n\n public static Collector> collectMap(Function keyMapper, Function valueMapper,\n BinaryOperator duplicateValues) {\n return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap());\n }\n\n public static Collector> collectMapAlt(Function valueMapper, BinaryOperator duplicateValues) {\n @SuppressWarnings(\"unchecked\")\n Function keyMapper = (Function) id();\n return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap());\n }\n\n public static Collector> collectMap(Function keyMapper, BinaryOperator duplicateValues) {\n return collectMap(keyMapper, self(), duplicateValues);\n }\n\n public static Collector> collectMap(Function keyMapper) {\n return collectMap(keyMapper, rejectDuplicateKeys());\n }\n\n public static Collector> collectSortedMap(Function keyMapper, Function valueMapper) {\n return collectSortedMap(keyMapper, valueMapper, rejectDuplicateKeys());\n }\n\n public static Collector> collectSortedMap(Function keyMapper, Function valueMapper,\n BinaryOperator duplicateValues) {\n return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newSortedMap());\n }\n\n public static Collector> collectSortedMap(Function keyMapper, BinaryOperator duplicateValues) {\n return collectSortedMap(keyMapper, self(), duplicateValues);\n }\n\n public static Collector> collectSortedMap(Function keyMapper) {\n return collectSortedMap(keyMapper, rejectDuplicateKeys());\n }\n\n public static > Comparator natural() {\n return Comparator. naturalOrder();\n }\n\n public static > BinaryOperator keepMin() {\n return keepMin(CollectionUtils8. natural());\n }\n\n public static BinaryOperator keepMin(Comparator comparator) {\n return BinaryOperator.minBy(comparator);\n }\n\n public static > BinaryOperator keepMax() {\n return keepMax(CollectionUtils8. natural());\n }\n\n public static BinaryOperator keepMax(Comparator comparator) {\n return BinaryOperator.maxBy(comparator);\n }\n\n public static IntStream streamInt(int max) {\n return streamInt(0, 1, max);\n }\n\n public static LongStream streamLong(long max) {\n return streamLong(0, 1, max);\n }\n\n public static DoubleStream streamDouble(double max) {\n return streamDouble(0.0, 1.0, max);\n }\n\n public static IntStream streamInt(int start, int max) {\n return streamInt(start, 1, max);\n }\n\n public static LongStream streamLong(long start, long max) {\n return streamLong(start, 1, max);\n }\n\n public static DoubleStream streamDouble(double start, double max) {\n return streamDouble(start, 1.0, max);\n }\n\n public static IntStream streamInt(int start, int step, int max) {\n return IntStream.iterate(start, i -> i + step).limit(max - start);\n }\n\n public static LongStream streamLong(long start, long step, long max) {\n return LongStream.iterate(start, i -> i + step).limit(max - start);\n }\n\n public static DoubleStream streamDouble(double start, double step, double max) {\n return DoubleStream.iterate(start, i -> i + step).limit((long) (max - start));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] toArray(Collection collection) {\n return (T[]) collection.toArray();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T[] toArray(Stream stream, Class type) {\n return stream.toArray(size -> (T[]) Array.newInstance(type, size));\n }\n\n public static Stream flatMapCollections(Collection> collectionOfCollections) {\n return flatMapStreams(collectionOfCollections.stream().map(Collection::stream));\n }\n\n public static Stream flatMap(Stream> streamOfCollections) {\n return flatMapStreams(streamOfCollections.map(Collection::stream));\n }\n\n public static Stream flatMap(Collection> collentionOfStreams) {\n return flatMapStreams(collentionOfStreams.stream());\n }\n\n public static Stream flatMapStreams(Stream> streamOfStreams) {\n return streamOfStreams.flatMap(id());\n }\n\n public static Stream flatMapArrays(T[][] streamOfStreams) {\n Stream> b = streamArray(streamOfStreams).map(a -> streamArray(a));\n return flatMapStreams(b);\n }\n\n public static Opt eager(T value) {\n return Opt.eager(value);\n }\n\n public static Opt reusable(T value) {\n return Opt.reusable(value);\n }\n\n /**\n * c1 - c2, does not change input collections, returns new collection (list)\n */\n public static List subtract(Collection c1, Collection c2) {\n if (c1 == null) {\n return Collections.emptyList();\n }\n List tmp = new ArrayList<>(c1);\n if (c2 != null) {\n tmp.removeAll(c2);\n }\n return tmp;\n }\n\n /**\n * intersection of c1 and c2, does not change input collections, returns new collection (list)\n */\n public static List intersection(Collection c1, Collection c2) {\n if (c1 == null || c2 == null) {\n return Collections.emptyList();\n }\n return c1.stream().filter(c2::contains).collect(collectList());\n }\n\n /**\n * intersection of c1 and c2, does not change input collections, returns new collection (list)\n */\n public static List union(Collection c1, Collection c2) {\n if (c1 == null && c2 == null) {\n return Collections.emptyList();\n }\n if (c1 == null) {\n return new ArrayList<>(c2);\n }\n if (c2 == null) {\n return new ArrayList<>(c1);\n }\n List tmp = new ArrayList<>(c1.size() + c2.size());\n tmp.addAll(c1);\n tmp.addAll(c2);\n return tmp;\n }\n\n /**\n * @see https://stackoverflow.com/questions/42214519/java-intersection-of-multiple-collections-using-stream-lambdas\n */\n public static > Collector> intersecting() {\n class IntersectAcc {\n Set result;\n\n void accept(S s) {\n if (result == null)\n result = new HashSet<>(s);\n else\n result.retainAll(s);\n }\n\n IntersectAcc combine(IntersectAcc other) {\n if (result == null) return other;\n if (other.result != null) result.retainAll(other.result);\n return this;\n }\n }\n return Collector.of(IntersectAcc::new, IntersectAcc::accept, IntersectAcc::combine,\n acc -> acc.result == null ? Collections.emptySet() : acc.result, Collector.Characteristics.UNORDERED);\n }\n\n /**\n * aanTeMakenAct roept teBewaren op met als nieuw object aangeboden door param constructor, constructor en teBewaren zijn niet nullable\n *\n * @see #sync(Map, Map, BiConsumer, BiConsumer, BiConsumer)\n */\n public static void sync(//\n Map nieuwe, //\n Map bestaande, //\n BiConsumer teVerwijderenAct, //\n Supplier constructor, //\n BiConsumer teBewaren//\n ) {\n if (constructor == null || teBewaren == null) throw new NullPointerException();\n sync(nieuwe, bestaande, teVerwijderenAct, (k, i) -> teBewaren.accept(i, constructor.get()), teBewaren);\n }\n\n /**\n * synchroniseer een nieuwe collectie met een bestaande collecte\n *\n * @param nieuwe nieuwe collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)}\n * @param bestaande bestaande collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)}\n * @param teVerwijderenAct nullable, actie op te roepen indien verwijderen, krijgt key en bestaand object binnen\n * @param aanTeMakenAct nullable, actie op te roepen indien nieuw object aan te maken, krijgt key en nieuw object binnen\n * @param teBewaren nullable, actie op te roepen indien overeenkomst, krijgt key en nieuw en bestaand object binnen\n *\n * @param key waarop vergeleken moet worden\n * @param nieuwe object\n * @param bestaand object\n */\n public static void sync(//\n Map nieuwe, //\n Map bestaande, //\n BiConsumer teVerwijderenAct, //\n BiConsumer aanTeMakenAct, //\n BiConsumer teBewaren//\n ) {\n Map teVerwijderen = subtract(bestaande.keySet(), nieuwe.keySet()).stream().collect(Collectors.toMap(id(), bestaande::get));\n Map aanTeMaken = subtract(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(id(), nieuwe::get));\n Map overeenkomst = intersection(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(nieuwe::get, bestaande::get));\n if (teBewaren != null) overeenkomst.forEach(teBewaren);\n if (aanTeMakenAct != null) aanTeMaken.forEach(aanTeMakenAct);\n if (teVerwijderenAct != null) teVerwijderen.forEach(teVerwijderenAct);\n }\n\n public static Map getMap(Stream values, Function keyMapper) {\n return values.collect(Collectors.toMap(keyMapper, self()));\n }\n\n public static Map getMap(Collection values, Function keyMapper) {\n return getMap(values.stream(), keyMapper);\n }\n\n public static Map getMap(Stream values, Supplier keyMapper) {\n return values.collect(Collectors.toMap(supplierToFunction(keyMapper), self()));\n }\n\n public static Map getMap(Collection values, Supplier keyMapper) {\n return getMap(values.stream(), keyMapper);\n }\n\n public static Map getKeyMap(Collection values, Function valueMapper) {\n return values.stream().collect(Collectors.toMap(self(), valueMapper));\n }\n\n public static Map getKeyMap(Collection values, Supplier valueMapper) {\n return values.stream().collect(Collectors.toMap(self(), supplierToFunction(valueMapper)));\n }\n\n public static Function supplierToFunction(Supplier supplier) {\n return any -> supplier.get();\n }\n\n public static Supplier supplyAny(T object) {\n return () -> object;\n }\n\n public static BiConsumer, T> elementsListAccumulator() {\n return (List a, T t) -> a.add(t);\n }\n\n public static BiConsumer, T> uniqueElementsListAccumulator() {\n return (List a, T t) -> {\n if (!a.contains(t)) a.add(t);\n };\n }\n\n public static BinaryOperator> elementsListCombiner(BiConsumer, T> elementsListAccumulator) {\n return (List a1, List a2) -> {\n a2.stream().forEach(a2e -> elementsListAccumulator.accept(a1, a2e));\n return a1;\n };\n }\n\n public static Consumer when(Predicate restriction, Consumer whenTrue, Consumer whenFalse) {\n return t -> (restriction.test(t) ? whenTrue : whenFalse).accept(t);\n }\n\n public static Consumer when(boolean restriction, Consumer whenTrue, Consumer whenFalse) {\n return when(always(restriction), whenTrue, whenFalse);\n }\n\n public static void when(Predicate restriction, Consumer whenTrue, Consumer whenFalse, T subject) {\n when(restriction, whenTrue, whenFalse).accept(subject);\n }\n\n public static void when(boolean restriction, Consumer whenTrue, Consumer whenFalse, T subject) {\n when(restriction, whenTrue, whenFalse).accept(subject);\n }\n\n public static Collection> split(Collection all, int maxSize) {\n if (maxSize < 1) throw new IllegalArgumentException(\"maxSize<1\");\n if (all.size() <= maxSize) return Arrays.asList(all);\n int totalSize = all.size();\n AtomicInteger ai = new AtomicInteger(0);\n int groups = (totalSize / maxSize) + (totalSize % maxSize > 0 ? 1 : 0);\n Map> g = all.stream().parallel().collect(Collectors.groupingBy(s -> ai.addAndGet(1) % groups));\n return stream(g).map(valueMapper()).collect(collectList());\n }\n\n public static Stream> split(List elements, int count) {\n return elements.stream().collect(Collectors.groupingBy(c -> elements.indexOf(c) / count)).values().stream();\n }\n\n public static Function, T> first() {\n return list -> list.isEmpty() ? null : list.get(0);\n }\n\n public static T first(List list) {\n return list.get(0);\n }\n\n public static T first(LinkedBlockingDeque dq) {\n return dq.iterator().next();\n }\n\n public static T first(LinkedBlockingQueue q) {\n return q.iterator().next();\n }\n\n public static T first(LinkedHashSet set) {\n return set.iterator().next();\n }\n\n public static Entry first(LinkedHashMap map) {\n return map.entrySet().iterator().next();\n }\n\n @SafeVarargs\n public static List sortBy(Collection collection, Function> map,\n Function>... mapAdditional) {\n return collection.stream().sorted(comparator(map, mapAdditional)).collect(collectList());\n }\n\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public static > List sortInPlace(List list) {\n Collections.sort((List) list);\n return list;\n }\n\n @SafeVarargs\n public static List sortInPlace(List list, Function> map,\n Function>... mapAdditional) {\n list.sort(comparator(map, mapAdditional));\n return list;\n }\n\n @SafeVarargs\n public static Comparator comparator(Function> compare,\n Function>... compareAdditional) {\n return (t1, t2) -> {\n CompareToBuilder cb = new CompareToBuilder();\n cb.append(compare.apply(t1), compare.apply(t2));\n streamArray(compareAdditional).forEach(compareThisEl -> cb.append(compareThisEl.apply(t1), compareThisEl.apply(t2)));\n return cb.toComparison();\n };\n }\n\n public static Stream filterClass(Stream stream, Class type) {\n return stream.filter(t -> type.isAssignableFrom(t.getClass())).map(t -> type.cast(t));\n }\n\n public static Stream> stream(Properties properties) {\n return stream(false, properties).map(entry -> new Pair<>(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())));\n }\n\n public static Function, K> mapKey() {\n return Entry::getKey;\n }\n\n public static Function, V> mapValue() {\n return Entry::getValue;\n }\n\n public static Map map(Map map, Function valueMapper) {\n return stream(map).collect(collectMap(mapKey(), e -> valueMapper.apply(e.getValue())));\n }\n\n public static Map mapKey(Map map, Function keyMapper) {\n return stream(map).collect(collectMap(e -> keyMapper.apply(e.getKey()), mapValue()));\n }\n\n public static Comparator comparatorCaseInsensitive(Function compare) {\n Comparators.CaseInsensitiveComparator comparator = new Comparators.CaseInsensitiveComparator();\n return (t1, t2) -> {\n return comparator.compare(compare.apply(t1), compare.apply(t2));\n };\n }\n\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public static EnhancedMap> groupByValue(Properties properties) {\n return groupByValue((Map) (Map) properties);\n }\n\n public static EnhancedMap> groupByValue(Map map) {\n return stream(map.entrySet())\n .collect(Collectors.groupingBy(e -> e.getValue(), newMap(), Collectors.mapping(e -> e.getKey(), Collectors.toList())));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Function functions(Function... functions) {\n Value> returningFunction = new Value<>(functions[0]);\n Arrays.stream(functions).skip(1).forEach(f -> returningFunction.set(returningFunction.get().andThen(Function.class.cast(f))));\n return returningFunction.get();\n }\n\n public static X nn(X nullable, X defaultValue) {\n return nullable == null ? defaultValue : nullable;\n }\n\n public static Function getDefaulted(Function getter, T defaultValue) {\n return ((Function) s -> getter.apply(s)).andThen(e -> nn(e, defaultValue));\n }\n\n public static Y getMapValue(Map, Y> map, X in) {\n return map.entrySet().stream().filter(entry -> entry.getKey().test(in)).map(Map.Entry::getValue).findFirst().orElse(null);\n }\n\n public static List emptyList() {\n return Collections.emptyList();\n }\n\n public static Stream emptyStream() {\n return Stream.empty();\n }\n\n public static Map emptyMap() {\n return Collections.emptyMap();\n }\n\n public static Set emptySet() {\n return Collections.emptySet();\n }\n\n public static String toString(IntStream s) {\n return s.mapToObj(String::valueOf).collect(Collectors.joining());\n }\n\n @SafeVarargs\n public static BiPredicate equals(Function... methods) {\n return (a, b) -> {\n EqualsBuilder eb = new EqualsBuilder();\n Arrays.asList(methods).forEach(g -> eb.append(g.apply(a), g.apply(b)));\n return eb.isEquals();\n };\n }\n\n @SafeVarargs\n public static BiFunction bifunction(Function... methods) {\n return (a, b) -> {\n if (methods == null || methods.length == 0) {\n return 0;\n }\n CompareToBuilder ctb = new CompareToBuilder();\n Arrays.asList(methods).forEach(g -> ctb.append(g.apply(a), g.apply(b)));\n return ctb.toComparison();\n };\n }\n\n @SafeVarargs\n public static Comparator comparatorFor(Function... methods) {\n return comparatorFor(bifunction(methods));\n }\n\n public static Comparator comparatorFor(BiFunction method) {\n return method::apply;\n }\n\n public static Collection toUnmodifiableCollection(Collection collection) {\n return Collections.unmodifiableCollection(toList(true, collection));\n }\n\n public static List toUnmodifiableList(Collection collection) {\n return Collections.unmodifiableList(toList(true, collection));\n }\n\n public static Map toUnmodifiableMap(Map map) {\n return Collections.unmodifiableMap(toMap(true, map));\n }\n\n public static Set toUnmodifiableSet(Collection collection) {\n return Collections.unmodifiableSet(toSet(true, collection));\n }\n\n public static SortedMap toUnmodifiableSortedMap(SortedMap map) {\n return Collections.unmodifiableSortedMap(toSortedMap(true, map));\n }\n\n public static SortedSet toUnmodifiableSortedSet(Collection collection) {\n return Collections.unmodifiableSortedSet(toSortedSet(true, collection));\n }\n\n public static Collection toSynchronizedCollection(Collection collection) {\n return Collections.synchronizedCollection(toList(true, collection));\n }\n\n public static List toSynchronizedList(Collection collection) {\n return Collections.synchronizedList(toList(true, collection));\n }\n\n public static Map toSynchronizedMap(Map map) {\n return Collections.synchronizedMap(toMap(true, map));\n }\n\n public static Set toSynchronizedSet(Collection collection) {\n return Collections.synchronizedSet(toSet(true, collection));\n }\n\n public static SortedMap toSynchronizedSortedMap(SortedMap map) {\n return Collections.synchronizedSortedMap(toSortedMap(true, map));\n }\n\n public static SortedSet toSynchronizedSortedSet(Collection collection) {\n return Collections.synchronizedSortedSet(toSortedSet(true, collection));\n }\n\n public static Stream> index(Stream stream) {\n IntegerValue index = new IntegerValue(-1);\n return stream.map(t -> new KeyValue<>(index.add().get(), t));\n }\n\n public static Map countBy(Stream stream) {\n return stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n }\n\n /**\n * @see http://stackoverflow.com/questions/26403319/skip-last-x-elements-in-streamt\n */\n public static Stream skip(Stream s, int first, int last) {\n if (last <= 0 && first <= 0) {\n return s;\n }\n if (last <= 0) {\n return s.skip(first);\n }\n if (first > 0) {\n s = s.skip(first);\n }\n ArrayDeque pending = new ArrayDeque<>(last + 1);\n Spliterator src = s.spliterator();\n return StreamSupport.stream(new Spliterator() {\n @Override\n public boolean tryAdvance(Consumer action) {\n while (pending.size() <= last && src.tryAdvance(pending::add))\n ;\n if (pending.size() > last) {\n action.accept(pending.remove());\n return true;\n }\n return false;\n }\n\n @Override\n public Spliterator trySplit() {\n return null;\n }\n\n @Override\n public long estimateSize() {\n return src.estimateSize() - last;\n }\n\n @Override\n public int characteristics() {\n return src.characteristics();\n }\n }, false);\n }\n\n public static Stream skip(Integer first, Integer last, Stream s) {\n return skip(s, first == null ? 0 : first, last == null ? 0 : last);\n }\n\n public static T merge(List list, int index, T object, BinaryOperator operate) {\n return list.set(index, operate.apply(list.get(index), object));\n }\n\n public static String append(List list, int index, String string, String seperator) {\n return merge(list, index, string, (a, b) -> StringUtils.isBlank(a) ? b : a + seperator + b);\n }\n\n public static String firstNotBlank(String... strings) {\n return streamArray(strings).filter(isNotBlank()).findFirst().orElse(null);\n }\n\n @SafeVarargs\n public static T firstNotBlankAndNotNull(T... o) {\n return streamArray(o).filter(isNotBlankAndNotNull()).findFirst().orElse(null);\n }\n\n @SafeVarargs\n public static T firstNotNull(T... o) {\n return streamArray(o).filter(isNotNull()).findFirst().orElse(null);\n }\n\n public static List copy(List list, int maxSize) {\n if (list.size() <= maxSize) return list;\n return list.stream().limit(maxSize).collect(collectList());\n }\n\n public static List listLI(List list, T item) {\n list.add(item);\n return list;\n }\n\n public static List listIL(T item, List list) {\n list.add(0, item);\n return list;\n }\n\n public static List listLL(List list1, List list2) {\n list1.addAll(list2);\n return list1;\n }\n\n public static List listCLI(List list, T item) {\n List tmp = new ArrayList<>();\n tmp.addAll(list);\n tmp.add(item);\n return tmp;\n }\n\n public static List listCIL(T item, List list) {\n List tmp = new ArrayList<>();\n tmp.add(item);\n tmp.addAll(list);\n return tmp;\n }\n\n public static List listCLL(List list1, List list2) {\n List tmp = new ArrayList<>();\n tmp.addAll(list1);\n tmp.addAll(list2);\n return tmp;\n }\n\n public static List flatten(Collection records, Function toKey, Function toValue, BinaryOperator mergeValue,\n BiFunction mergeToRecord) {\n Map> map = records.stream().collect(Collectors.groupingBy(toKey));\n return map.entrySet().stream().map(entry -> {\n return new KeyValue<>(entry.getKey(), entry.getValue().stream().map(toValue).reduce(mergeValue).get());\n }).map(entry -> {\n return mergeToRecord.apply(entry.getKey(), entry.getValue());\n }).collect(Collectors.toList());\n }\n\n public static Collector> groupingByCount() {\n return Collectors.groupingBy(id(), newMap(), Collectors.reducing(0, e -> 1, Integer::sum));\n }\n\n public static Collector> groupingByCountMany() {\n return Collectors.groupingBy(id(), newMap(), Collectors.counting());\n }\n\n public static Comparator ascFloat() {\n return (a, b) -> new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator descFloat() {\n return (a, b) -> -new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator ascDouble() {\n return (a, b) -> new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator descDouble() {\n return (a, b) -> -new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator ascByte() {\n return (a, b) -> a - b;\n }\n\n public static Comparator descByte() {\n return (a, b) -> b - a;\n }\n\n public static Comparator ascShort() {\n return (a, b) -> a - b;\n }\n\n public static Comparator descShort() {\n return (a, b) -> b - a;\n }\n\n public static Comparator ascInt() {\n return (a, b) -> a - b;\n }\n\n public static Comparator descInt() {\n return (a, b) -> b - a;\n }\n\n public static Comparator ascLong() {\n return (a, b) -> new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static Comparator descLong() {\n return (a, b) -> -new CompareToBuilder().append(a, b).toComparison();\n }\n\n public static LinkedHashMap sortByValue(Map map, Comparator comparator) {\n return map.entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue(comparator))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));\n }\n\n public static List repeat(int times, T object) {\n return IntStream.range(0, times).mapToObj(i -> object).collect(Collectors.toList());\n }\n\n public static Stream stream(Optional optional) {\n return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();\n }\n\n public static List serializable(List list) {\n return list instanceof Serializable ? list : new ArrayList<>(list);\n }\n\n public static Set serializable(Set set) {\n return set instanceof Serializable ? set : new HashSet<>(set);\n }\n\n public static SortedSet serializable(SortedSet set) {\n return set instanceof Serializable ? set : new TreeSet<>(set);\n }\n\n public static Map serializable(Map set) {\n return set instanceof Serializable ? set : new HashMap<>(set);\n }\n\n public static SortedMap serializable(SortedMap set) {\n return set instanceof Serializable ? set : new TreeMap<>(set);\n }\n\n public static IntStream stream(byte[] bytes) {\n return IntStream.range(0, bytes.length).map(idx -> bytes[idx]);\n }\n\n public static IntStream stream(Byte[] bytes) {\n return IntStream.range(0, bytes.length).map(idx -> bytes[idx]);\n }\n\n public static
    Predicate notNullPredicate() {\n return a -> a instanceof String ? StringUtils.isNotBlank((String) a) : a != null;\n }\n\n public static BiPredicate notNullBiPredicate() {\n return (a, b) -> notNullPredicate().test(a) || notNullPredicate().test(b);\n }\n\n public static TriplePredicate notNullTriplePredicate() {\n return (a, b, c) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c);\n }\n\n public static QuadruplePredicate notNullQuadruplePredicate() {\n return (a, b, c, d) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d);\n }\n\n public static QuintuplePredicate notNullQuintuplePredicate() {\n return (a, b, c, d, e) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d)\n || notNullPredicate().test(e);\n }\n\n public static List replaceOrAdd(List list, T object) {\n if (list == null || object == null) return list;\n int i = list.indexOf(object);\n if (i != -1) {\n list.remove(object);\n list.add(i, object);\n } else {\n list.add(object);\n }\n return list;\n }\n\n public static Consumer throwing(Supplier exception) {\n return t -> {\n throw exception.get();\n };\n }\n\n public static Consumer throwing(RuntimeException exception) {\n return t -> {\n throw exception;\n };\n }\n\n public static Consumer throwing(Function exception) {\n return t -> {\n throw exception.apply(t);\n };\n }\n\n public static BooleanSupplier enhanceBooleanSupplier(EBooleanSupplier supplier) {\n return EBooleanSupplier.enhance(supplier);\n }\n\n public static Consumer enhanceConsumer(EConsumer consumer) {\n return EConsumer.enhance(consumer);\n }\n\n public static BiConsumer enhanceBiConsumer(EBiConsumer consumer) {\n return EBiConsumer.enhance(consumer);\n }\n\n public static DoubleSupplier enhanceDoubleSupplier(EDoubleSupplier supplier) {\n return EDoubleSupplier.enhance(supplier);\n }\n\n public static Function enhanceFunction(EFunction function) {\n return EFunction.enhance(function);\n }\n\n public static IntSupplier enhanceIntegerSupplier(EIntSupplier supplier) {\n return EIntSupplier.enhance(supplier);\n }\n\n public static LongSupplier enhanceLongSupplier(ELongSupplier supplier) {\n return ELongSupplier.enhance(supplier);\n }\n\n public static Predicate enhancePredicate(EPredicate predicate) {\n return EPredicate.enhance(predicate);\n }\n\n public static Runnable enhanceRunnable(ERunnable runnable) {\n return ERunnable.enhance(runnable);\n }\n\n public static Supplier enhanceSupplier(ESupplier predicate) {\n return ESupplier.enhance(predicate);\n }\n\n public static List> entryList(Map map) {\n return map.entrySet().stream().map(KeyValue::new).collect(collectList());\n }\n\n public static T[] merge(T[] a, T[] b) {\n int aLen = a.length;\n int bLen = b.length;\n\n @SuppressWarnings(\"unchecked\")\n T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);\n System.arraycopy(a, 0, c, 0, aLen);\n System.arraycopy(b, 0, c, aLen, bLen);\n return c;\n }\n\n public static T[] append(T[] a, @SuppressWarnings(\"unchecked\") T... b) {\n return merge(a, b);\n }\n\n public static T[] prepend(T[] a, @SuppressWarnings(\"unchecked\") T... b) {\n return merge(b, a);\n }\n\n public static UnaryOperator unaryOperator(Consumer consumer) {\n UnaryOperator a = b -> {\n consumer.accept(b);\n return b;\n };\n return a;\n }\n\n public static Stream> ofSubLists(List source, int length) {\n if (length <= 0) throw new IllegalArgumentException(\"length = \" + length);\n int size = source.size();\n if (size <= 0) return Stream.empty();\n int fullChunks = (size - 1) / length;\n return IntStream.range(0, fullChunks + 1).mapToObj(n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));\n }\n}"},"message":{"kind":"string","value":"backwards compatibility\n"},"old_file":{"kind":"string","value":"jhaws/lang/src/main/java/org/jhaws/common/lang/CollectionUtils8.java"},"subject":{"kind":"string","value":"backwards compatibility"}}},{"rowIdx":714,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"34a809f4a9e7ae9b58372f09fdb9bd82627d0809"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"testpress/android,testpress/android,testpress/android,testpress/android,testpress/android"},"new_contents":{"kind":"string","value":"package in.testpress.testpress.ui.adapters;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Color;\nimport androidx.recyclerview.widget.RecyclerView;\n\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport in.testpress.core.TestpressSdk;\nimport in.testpress.core.TestpressSession;\nimport in.testpress.course.TestpressCourse;\nimport in.testpress.models.greendao.Chapter;\nimport in.testpress.models.greendao.Content;\nimport in.testpress.models.greendao.CourseAttempt;\nimport in.testpress.models.greendao.Exam;\nimport in.testpress.models.greendao.HtmlContent;\nimport in.testpress.models.greendao.VideoAttempt;\nimport in.testpress.models.greendao.Video;\nimport in.testpress.testpress.R;\nimport in.testpress.testpress.models.pojo.DashboardResponse;\nimport in.testpress.testpress.models.pojo.DashboardSection;\nimport in.testpress.testpress.util.UIUtils;\nimport in.testpress.testpress.util.ImageUtils;\nimport in.testpress.util.IntegerList;\n\npublic class ContentsCarouselAdapter extends RecyclerView.Adapter {\n private DashboardResponse response;\n private DashboardSection section;\n private List contents = new ArrayList<>();\n private ImageLoader imageLoader;\n private DisplayImageOptions options;\n private Context context;\n\n public ContentsCarouselAdapter(DashboardResponse response, DashboardSection currentSection, Context context) {\n this.response = response;\n this.section = currentSection;\n populateContents();\n this.context = context;\n imageLoader = in.testpress.util.ImageUtils.initImageLoader(context);\n options = ImageUtils.getPlaceholdersOption();\n }\n\n private void populateContents() {\n IntegerList items = section.getItems();\n if (section.getContentType().equals(\"chapter_content\")) {\n for (Integer item : items) {\n this.contents.add(this.response.getContentHashMap().get(Long.valueOf(item)));\n }\n } else {\n for (Integer item : items) {\n CourseAttempt attempt = this.response.getContentAttemptHashMap().get(Long.valueOf(item));\n this.contents.add(this.response.getContentHashMap().get(attempt.getChapterContentId()));\n }\n }\n }\n\n @Override\n public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_carousel_item, parent, false);\n return new ItemViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(ItemViewHolder holder, final int position) {\n final Content content = contents.get(position);\n\n showThumbnail(content, holder);\n setIconAndChapterTitle(content, holder);\n showOrHideVideoAccessories(content, holder);\n showOrHideExamAccessories(content, holder);\n showReadTimeForHtmlContent(content, holder);\n showIconForAttachmentContent(content, holder);\n showProgressBarForResumeVideos(position, holder);\n\n\n holder.title.setText(content.getName());\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n Activity activity = (Activity) context;\n TestpressSession session = TestpressSdk.getTestpressSession(context);\n TestpressCourse.showContentDetail(activity, content.getId().toString(), session);\n }\n });\n }\n\n private void showThumbnail(Content content, ItemViewHolder holder) {\n if (content.getCoverImageMedium() != null) {\n imageLoader.displayImage(content.getCoverImageMedium(), holder.image, options);\n } else {\n showThumbnailForVideo(content, holder);\n }\n holder.image.setColorFilter(Color.parseColor(\"#22000000\"));\n\n }\n\n private void showThumbnailForVideo(Content content, ItemViewHolder holder) {\n imageLoader.displayImage(null, holder.image, options);\n if (content.getVideoId() != null) {\n Video video = response.getVideoHashMap().get(content.getVideoId());\n\n if (video.getThumbnailMedium() != null) {\n imageLoader.displayImage(video.getThumbnailMedium(), holder.image, options);\n } else {\n holder.image.setBackgroundColor(Color.parseColor(\"#77000000\"));\n }\n }\n }\n\n private void showIconForAttachmentContent(Content content, ItemViewHolder holder) {\n if (content.getAttachmentId() != null) {\n holder.playIcon.setImageResource(R.drawable.ic_attachment);\n holder.playIcon.setVisibility(View.VISIBLE);\n }\n }\n\n private void showReadTimeForHtmlContent(Content content, ItemViewHolder holder) {\n if (content.getHtmlId() != null) {\n HtmlContent htmlContent = response.getHtmlContentHashMap().get(content.getHtmlId());\n holder.infoLayout.setVisibility(View.VISIBLE);\n holder.numberOfQuestions.setText(htmlContent.getReadTime());\n holder.infoSubtitle.setVisibility(View.GONE);\n }\n }\n \n private void showProgressBarForResumeVideos(int position, ItemViewHolder holder) {\n holder.videoProgressLayout.setVisibility(View.GONE);\n if (section.getSlug().equals(\"resume\")) {\n Long attemptId = Long.valueOf(section.getItems().get(position));\n CourseAttempt attempt = this.response.getContentAttemptHashMap().get(attemptId);\n\n if (attempt.getUserVideoId() != null) {\n VideoAttempt userVideo = response.getUserVideoHashMap().get(attempt.getUserVideoId());\n\n if (userVideo != null && userVideo.getRawVideoContent() != null && userVideo.getRawVideoContent().getDuration() != null) {\n float lastPosition = Float.parseFloat(userVideo.getLastPosition());\n float totalDuration = Float.parseFloat(userVideo.getRawVideoContent().getDuration());\n float watchPercentage = (lastPosition / totalDuration) * 100;\n holder.videoProgress.setProgress((int) watchPercentage);\n holder.videoProgressLayout.setVisibility(View.VISIBLE);\n }\n }\n } else {\n holder.videoProgressLayout.setVisibility(View.GONE);\n }\n }\n\n private void setIconAndChapterTitle(Content content, ItemViewHolder holder) {\n if (response.getChapterHashMap().get(content.getChapterId()) != null) {\n Chapter chapter = response.getChapterHashMap().get(content.getChapterId());\n holder.subtitle.setText(chapter.getName());\n }\n\n switch (content.getContentType().toLowerCase()) {\n case \"video\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_video_white);\n break;\n case \"exam\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_exam_white);\n break;\n case \"notes\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_news_white);\n break;\n case \"attachment\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_attachment);\n break;\n }\n }\n\n private void showOrHideVideoAccessories(Content content, ItemViewHolder holder) {\n if (content.getVideoId() != null) {\n holder.playIcon.setVisibility(View.VISIBLE);\n holder.playIcon.setImageResource(R.drawable.play);\n } else {\n holder.playIcon.setVisibility(View.GONE);\n }\n }\n\n private void showOrHideExamAccessories(Content content, ItemViewHolder holder) {\n if (content.getExamId() != null) {\n Exam exam = response.getExamHashMap().get(content.getExamId());\n holder.infoLayout.setVisibility(View.VISIBLE);\n holder.infoSubtitle.setVisibility(View.VISIBLE);\n holder.numberOfQuestions.setText(exam.getNumberOfQuestions().toString());\n } else {\n holder.infoLayout.setVisibility(View.GONE);\n }\n }\n\n @Override\n public int getItemCount() {\n return contents.size();\n }\n\n public class ItemViewHolder extends RecyclerView.ViewHolder {\n ImageView image, playIcon, contentTypeIcon;\n TextView title, numberOfQuestions, subtitle, infoSubtitle;\n LinearLayout infoLayout, videoProgressLayout;\n ProgressBar videoProgress;\n\n public ItemViewHolder(View itemView) {\n super(itemView);\n image = (ImageView) itemView.findViewById(R.id.image_view);\n playIcon = (ImageView) itemView.findViewById(R.id.play_icon);\n contentTypeIcon = (ImageView) itemView.findViewById(R.id.content_type_icon);\n infoLayout = (LinearLayout) itemView.findViewById(R.id.info_layout);\n videoProgressLayout = (LinearLayout) itemView.findViewById(R.id.video_progress_layout);\n title = (TextView) itemView.findViewById(R.id.title);\n subtitle = (TextView) itemView.findViewById(R.id.subtitle);\n numberOfQuestions = (TextView) itemView.findViewById(R.id.number_of_questions);\n numberOfQuestions.setTypeface(TestpressSdk.getRubikMediumFont(context));\n infoSubtitle = (TextView) itemView.findViewById(R.id.info_subtitle);\n videoProgress = (ProgressBar) itemView.findViewById(R.id.video_progress);\n\n title.setTypeface(UIUtils.getLatoSemiBoldFont(context));\n }\n }\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/in/testpress/testpress/ui/adapters/ContentsCarouselAdapter.java"},"old_contents":{"kind":"string","value":"package in.testpress.testpress.ui.adapters;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Color;\nimport androidx.recyclerview.widget.RecyclerView;\n\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport in.testpress.core.TestpressSdk;\nimport in.testpress.core.TestpressSession;\nimport in.testpress.course.TestpressCourse;\nimport in.testpress.models.greendao.Chapter;\nimport in.testpress.models.greendao.Content;\nimport in.testpress.models.greendao.CourseAttempt;\nimport in.testpress.models.greendao.Exam;\nimport in.testpress.models.greendao.HtmlContent;\nimport in.testpress.models.greendao.VideoAttempt;\nimport in.testpress.models.greendao.Video;\nimport in.testpress.testpress.R;\nimport in.testpress.testpress.models.pojo.DashboardResponse;\nimport in.testpress.testpress.models.pojo.DashboardSection;\nimport in.testpress.testpress.util.UIUtils;\nimport in.testpress.testpress.util.ImageUtils;\nimport in.testpress.util.IntegerList;\n\npublic class ContentsCarouselAdapter extends RecyclerView.Adapter {\n private DashboardResponse response;\n private DashboardSection section;\n private List contents = new ArrayList<>();\n private ImageLoader imageLoader;\n private DisplayImageOptions options;\n private Context context;\n\n public ContentsCarouselAdapter(DashboardResponse response, DashboardSection currentSection, Context context) {\n this.response = response;\n this.section = currentSection;\n populateContents();\n this.context = context;\n imageLoader = in.testpress.util.ImageUtils.initImageLoader(context);\n options = ImageUtils.getPlaceholdersOption();\n }\n\n private void populateContents() {\n IntegerList items = section.getItems();\n if (section.getContentType().equals(\"chapter_content\")) {\n for (Integer item : items) {\n this.contents.add(this.response.getContentHashMap().get(Long.valueOf(item)));\n }\n } else {\n for (Integer item : items) {\n CourseAttempt attempt = this.response.getContentAttemptHashMap().get(Long.valueOf(item));\n this.contents.add(this.response.getContentHashMap().get(attempt.getChapterContentId()));\n }\n }\n }\n\n @Override\n public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_carousel_item, parent, false);\n return new ItemViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(ItemViewHolder holder, final int position) {\n final Content content = contents.get(position);\n\n showThumbnail(content, holder);\n setIconAndChapterTitle(content, holder);\n showOrHideVideoAccessories(content, holder);\n showOrHideExamAccessories(content, holder);\n showReadTimeForHtmlContent(content, holder);\n showIconForAttachmentContent(content, holder);\n showProgressBarForResumeVideos(position, holder);\n\n\n holder.title.setText(content.getName());\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n Activity activity = (Activity) context;\n TestpressSession session = TestpressSdk.getTestpressSession(context);\n TestpressCourse.showContentDetail(activity, content.getId().toString(), session);\n }\n });\n }\n\n private void showThumbnail(Content content, ItemViewHolder holder) {\n if (content.getCoverImageMedium() != null) {\n imageLoader.displayImage(content.getCoverImageMedium(), holder.image, options);\n } else {\n showThumbnailForVideo(content, holder);\n }\n holder.image.setColorFilter(Color.parseColor(\"#22000000\"));\n\n }\n\n private void showThumbnailForVideo(Content content, ItemViewHolder holder) {\n imageLoader.displayImage(null, holder.image, options);\n if (content.getVideoId() != null) {\n Video video = response.getVideoHashMap().get(content.getVideoId());\n\n if (video.getThumbnailMedium() != null) {\n imageLoader.displayImage(video.getThumbnailMedium(), holder.image, options);\n } else {\n holder.image.setBackgroundColor(Color.parseColor(\"#77000000\"));\n }\n }\n }\n\n private void showIconForAttachmentContent(Content content, ItemViewHolder holder) {\n if (content.getAttachmentId() != null) {\n holder.playIcon.setImageResource(R.drawable.ic_attachment);\n holder.playIcon.setVisibility(View.VISIBLE);\n }\n }\n\n private void showReadTimeForHtmlContent(Content content, ItemViewHolder holder) {\n if (content.getHtmlId() != null) {\n HtmlContent htmlContent = response.getHtmlContentHashMap().get(content.getHtmlId());\n holder.infoLayout.setVisibility(View.VISIBLE);\n holder.numberOfQuestions.setText(htmlContent.getReadTime());\n holder.infoSubtitle.setVisibility(View.GONE);\n }\n }\n \n private void showProgressBarForResumeVideos(int position, ItemViewHolder holder) {\n holder.videoProgressLayout.setVisibility(View.GONE);\n if (section.getSlug().equals(\"resume\")) {\n Long attemptId = Long.valueOf(section.getItems().get(position));\n CourseAttempt attempt = this.response.getContentAttemptHashMap().get(attemptId);\n\n if (attempt.getUserVideoId() != null) {\n VideoAttempt userVideo = response.getUserVideoHashMap().get(attempt.getUserVideoId());\n\n if (userVideo.getRawVideoContent() != null && userVideo.getRawVideoContent().getDuration() != null) {\n float lastPosition = Float.parseFloat(userVideo.getLastPosition());\n float totalDuration = Float.parseFloat(userVideo.getRawVideoContent().getDuration());\n float watchPercentage = (lastPosition / totalDuration) * 100;\n holder.videoProgress.setProgress((int) watchPercentage);\n holder.videoProgressLayout.setVisibility(View.VISIBLE);\n }\n }\n } else {\n holder.videoProgressLayout.setVisibility(View.GONE);\n }\n }\n\n private void setIconAndChapterTitle(Content content, ItemViewHolder holder) {\n if (response.getChapterHashMap().get(content.getChapterId()) != null) {\n Chapter chapter = response.getChapterHashMap().get(content.getChapterId());\n holder.subtitle.setText(chapter.getName());\n }\n\n switch (content.getContentType().toLowerCase()) {\n case \"video\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_video_white);\n break;\n case \"exam\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_exam_white);\n break;\n case \"notes\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_news_white);\n break;\n case \"attachment\":\n holder.contentTypeIcon.setImageResource(R.drawable.ic_attachment);\n break;\n }\n }\n\n private void showOrHideVideoAccessories(Content content, ItemViewHolder holder) {\n if (content.getVideoId() != null) {\n holder.playIcon.setVisibility(View.VISIBLE);\n holder.playIcon.setImageResource(R.drawable.play);\n } else {\n holder.playIcon.setVisibility(View.GONE);\n }\n }\n\n private void showOrHideExamAccessories(Content content, ItemViewHolder holder) {\n if (content.getExamId() != null) {\n Exam exam = response.getExamHashMap().get(content.getExamId());\n holder.infoLayout.setVisibility(View.VISIBLE);\n holder.infoSubtitle.setVisibility(View.VISIBLE);\n holder.numberOfQuestions.setText(exam.getNumberOfQuestions().toString());\n } else {\n holder.infoLayout.setVisibility(View.GONE);\n }\n }\n\n @Override\n public int getItemCount() {\n return contents.size();\n }\n\n public class ItemViewHolder extends RecyclerView.ViewHolder {\n ImageView image, playIcon, contentTypeIcon;\n TextView title, numberOfQuestions, subtitle, infoSubtitle;\n LinearLayout infoLayout, videoProgressLayout;\n ProgressBar videoProgress;\n\n public ItemViewHolder(View itemView) {\n super(itemView);\n image = (ImageView) itemView.findViewById(R.id.image_view);\n playIcon = (ImageView) itemView.findViewById(R.id.play_icon);\n contentTypeIcon = (ImageView) itemView.findViewById(R.id.content_type_icon);\n infoLayout = (LinearLayout) itemView.findViewById(R.id.info_layout);\n videoProgressLayout = (LinearLayout) itemView.findViewById(R.id.video_progress_layout);\n title = (TextView) itemView.findViewById(R.id.title);\n subtitle = (TextView) itemView.findViewById(R.id.subtitle);\n numberOfQuestions = (TextView) itemView.findViewById(R.id.number_of_questions);\n numberOfQuestions.setTypeface(TestpressSdk.getRubikMediumFont(context));\n infoSubtitle = (TextView) itemView.findViewById(R.id.info_subtitle);\n videoProgress = (ProgressBar) itemView.findViewById(R.id.video_progress);\n\n title.setTypeface(UIUtils.getLatoSemiBoldFont(context));\n }\n }\n}\n"},"message":{"kind":"string","value":"Fix app crash on incomplete dashboard data\n\nIf dashboard data does not have user video app will crash. This is fixed by checking is uservideo is present or not\n"},"old_file":{"kind":"string","value":"app/src/main/java/in/testpress/testpress/ui/adapters/ContentsCarouselAdapter.java"},"subject":{"kind":"string","value":"Fix app crash on incomplete dashboard data"}}},{"rowIdx":715,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d4de09c4a3f2fcb60c635afe3b618a935d524894"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ThorbenKuck/NetCom2"},"new_contents":{"kind":"string","value":"package com.github.thorbenkuck.netcom2.auto.annotations.processor;\n\nimport javax.annotation.processing.AbstractProcessor;\nimport javax.annotation.processing.Filer;\nimport javax.annotation.processing.ProcessingEnvironment;\nimport javax.annotation.processing.RoundEnvironment;\nimport javax.lang.model.SourceVersion;\nimport javax.lang.model.element.Element;\nimport javax.lang.model.element.TypeElement;\nimport javax.lang.model.util.Elements;\nimport javax.lang.model.util.Types;\nimport java.lang.annotation.Annotation;\nimport java.util.ArrayList;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic abstract class AnnotationProcessor extends AbstractProcessor {\n\n\tprivate final List alreadyProcessed = new ArrayList<>();\n\tprotected Types types;\n\tprotected Elements elements;\n\tprotected Filer filer;\n\tprotected CompilationLogger logger;\n\n\tprivate List filter(Set input) {\n\t\tList value = new ArrayList<>();\n\n\t\tfor (Element element : input) {\n\t\t\tif (!alreadyProcessed.contains(element)) {\n\t\t\t\tlogger.log(\"Will process \" + element.getSimpleName(), element);\n\t\t\t\talreadyProcessed.add(element);\n\t\t\t\tvalue.add(element);\n\t\t\t}\n\t\t}\n\n\t\treturn value;\n\t}\n\n\tprotected abstract void pre();\n\n\tprotected abstract Class supported();\n\n\tprotected abstract boolean process(Element element);\n\n\tprotected void post(List handled) {\n\t}\n\n\t@Override\n\tpublic final Set getSupportedAnnotationTypes() {\n\t\tSet annotations = new LinkedHashSet<>();\n\t\tannotations.add(supported().getCanonicalName());\n\t\treturn annotations;\n\t}\n\n\t@Override\n\tpublic final SourceVersion getSupportedSourceVersion() {\n\t\treturn SourceVersion.latestSupported();\n\t}\n\n\t@Override\n\tpublic final synchronized void init(ProcessingEnvironment processingEnv) {\n\t\tsuper.init(processingEnv);\n\t\ttypes = processingEnv.getTypeUtils();\n\t\telements = processingEnv.getElementUtils();\n\t\tfiler = processingEnv.getFiler();\n\t\tlogger = new CompilationLogger(processingEnv.getMessager());\n\t}\n\n\t@Override\n\tpublic final boolean process(Set annotations, RoundEnvironment roundEnv) {\n\t\tpre();\n\n\t\tboolean error = false;\n\t\tList toProcess = filter(roundEnv.getElementsAnnotatedWith(supported()));\n\n\t\tfor (Element element : toProcess) {\n\t\t\tboolean success;\n\t\t\ttry {\n\t\t\t\tsuccess = process(element);\n\t\t\t} catch (Throwable throwable) {\n\t\t\t\tlogger.error(throwable.getMessage(), element);\n\t\t\t\tthrowable.printStackTrace();\n\t\t\t\tsuccess = false;\n\t\t\t}\n\n\t\t\tif (!success) {\n\t\t\t\terror = true;\n\t\t\t}\n\t\t}\n\n\t\tpost(alreadyProcessed);\n\n\t\treturn !error;\n\t}\n}\n"},"new_file":{"kind":"string","value":"auto/src/main/java/com/github/thorbenkuck/netcom2/auto/annotations/processor/AnnotationProcessor.java"},"old_contents":{"kind":"string","value":"package com.github.thorbenkuck.netcom2.auto.annotations.processor;\n\nimport javax.annotation.processing.AbstractProcessor;\nimport javax.annotation.processing.Filer;\nimport javax.annotation.processing.ProcessingEnvironment;\nimport javax.annotation.processing.RoundEnvironment;\nimport javax.lang.model.SourceVersion;\nimport javax.lang.model.element.Element;\nimport javax.lang.model.element.TypeElement;\nimport javax.lang.model.util.Elements;\nimport javax.lang.model.util.Types;\nimport java.lang.annotation.Annotation;\nimport java.util.ArrayList;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic abstract class AnnotationProcessor extends AbstractProcessor {\n\n\tprivate final List alreadyProcessed = new ArrayList<>();\n\tprotected Types types;\n\tprotected Elements elements;\n\tprotected Filer filer;\n\tprotected CompilationLogger logger;\n\n\tprivate List filter(Set input) {\n\t\tList value = new ArrayList<>();\n\n\t\tfor (Element element : input) {\n\t\t\tif (!alreadyProcessed.contains(element)) {\n\t\t\t\tlogger.log(\"Will process \" + element.getSimpleName(), element);\n\t\t\t\talreadyProcessed.add(element);\n\t\t\t\tvalue.add(element);\n\t\t\t}\n\t\t}\n\n\t\treturn value;\n\t}\n\n\tprotected abstract void pre();\n\n\tprotected abstract Class supported();\n\n\tprotected abstract boolean process(Element element);\n\n\t@Override\n\tpublic final Set getSupportedAnnotationTypes() {\n\t\tSet annotations = new LinkedHashSet<>();\n\t\tannotations.add(supported().getCanonicalName());\n\t\treturn annotations;\n\t}\n\n\t@Override\n\tpublic final SourceVersion getSupportedSourceVersion() {\n\t\treturn SourceVersion.latestSupported();\n\t}\n\n\t@Override\n\tpublic final synchronized void init(ProcessingEnvironment processingEnv) {\n\t\tsuper.init(processingEnv);\n\t\ttypes = processingEnv.getTypeUtils();\n\t\telements = processingEnv.getElementUtils();\n\t\tfiler = processingEnv.getFiler();\n\t\tlogger = new CompilationLogger(processingEnv.getMessager());\n\t}\n\n\t@Override\n\tpublic final boolean process(Set annotations, RoundEnvironment roundEnv) {\n\t\tpre();\n\n\t\tboolean error = false;\n\t\tList toProcess = filter(roundEnv.getElementsAnnotatedWith(supported()));\n\n\t\tfor (Element element : toProcess) {\n\t\t\tboolean success;\n\t\t\ttry {\n\t\t\t\tsuccess = process(element);\n\t\t\t} catch (Throwable throwable) {\n\t\t\t\tlogger.error(throwable.getMessage(), element);\n\t\t\t\tthrowable.printStackTrace();\n\t\t\t\tsuccess = false;\n\t\t\t}\n\n\t\t\tif (!success) {\n\t\t\t\terror = true;\n\t\t\t}\n\t\t}\n\t\treturn !error;\n\t}\n}\n"},"message":{"kind":"string","value":"added post method to abstract AnnotationProcessor\n"},"old_file":{"kind":"string","value":"auto/src/main/java/com/github/thorbenkuck/netcom2/auto/annotations/processor/AnnotationProcessor.java"},"subject":{"kind":"string","value":"added post method to abstract AnnotationProcessor"}}},{"rowIdx":716,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mpl-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e675ab3596da2255df864b44aaed33c55b51822b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"powsybl/powsybl-core,itesla/ipst-core,powsybl/powsybl-core,itesla/ipst-core,itesla/ipst-core,itesla/ipst-core,powsybl/powsybl-core"},"new_contents":{"kind":"string","value":"/**\n * Copyright (c) 2016, RTE (http://www.rte-france.com)\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/.\n */\npackage eu.itesla_project.iidm.network.impl;\n\nimport eu.itesla_project.iidm.network.*;\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * ArrayIndexOutOfBoundsException fix test\n * @author Geoffroy Jamgotchian \n */\npublic class EmptyCalculatedBusBugTest {\n\n private Network createNetwork(boolean retainded) {\n Network network = NetworkFactory.create(\"test\", \"test\");\n Substation s = network.newSubstation()\n .setId(\"S\")\n .setCountry(Country.FR)\n .add();\n VoltageLevel vl = s.newVoltageLevel()\n .setId(\"VL\")\n .setNominalV(400f)\n .setTopologyKind(TopologyKind.NODE_BREAKER)\n .add();\n vl.getNodeBreakerView().setNodeCount(2);\n vl.getNodeBreakerView().newBreaker()\n .setId(\"SW1\")\n .setNode1(0)\n .setNode2(1)\n .setOpen(false)\n .setRetained(retainded)\n .add();\n\n return network;\n }\n\n @Test\n public void test() {\n Network network = createNetwork(false);\n assertEquals(1, network.getVoltageLevel(\"VL\").getBusBreakerView().getBusStream().count());\n\n network = createNetwork(true);\n assertEquals(2, network.getVoltageLevel(\"VL\").getBusBreakerView().getBusStream().count());\n }\n}\n"},"new_file":{"kind":"string","value":"iidm-network-impl/src/test/java/eu/itesla_project/iidm/network/impl/EmptyCalculatedBusBugTest.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (c) 2016, RTE (http://www.rte-france.com)\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/.\n */\npackage eu.itesla_project.iidm.network.impl;\n\nimport eu.itesla_project.iidm.network.*;\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * ArrayIndexOutOfBoundsException fix test\n * @author Geoffroy Jamgotchian \n */\npublic class EmptyCalculatedBusBugTest {\n\n @Test\n public void test() {\n Network network = NetworkFactory.create(\"test\", \"test\");\n Substation s = network.newSubstation()\n .setId(\"S\")\n .setCountry(Country.FR)\n .add();\n VoltageLevel vl = s.newVoltageLevel()\n .setId(\"VL\")\n .setNominalV(400f)\n .setTopologyKind(TopologyKind.NODE_BREAKER)\n .add();\n vl.getNodeBreakerView().setNodeCount(2);\n vl.getNodeBreakerView().newBreaker()\n .setId(\"SW1\")\n .setNode1(0)\n .setNode2(1)\n .setOpen(false)\n .setRetained(false)\n .add();\n assertEquals(2, vl.getBusBreakerView().getBusStream().count());\n }\n}\n"},"message":{"kind":"string","value":"Fix compilation and add another test\n"},"old_file":{"kind":"string","value":"iidm-network-impl/src/test/java/eu/itesla_project/iidm/network/impl/EmptyCalculatedBusBugTest.java"},"subject":{"kind":"string","value":"Fix compilation and add another test"}}},{"rowIdx":717,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"107954a67ba0dd167b25e07c18e82838631ed6b0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms"},"new_contents":{"kind":"string","value":"/*\n * This file is part of the OpenNMS(R) Application.\n *\n * OpenNMS(R) is Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved.\n * OpenNMS(R) is a derivative work, containing both original code, included code and modified\n * code that was published under the GNU General Public License. Copyrights for modified\n * and included code are below.\n *\n * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.\n *\n * Modifications:\n * \n * Created: January 7, 2009\n *\n * Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * For more information contact:\n * OpenNMS Licensing \n * http://www.opennms.org/\n * http://www.opennms.com/\n */\npackage org.opennms.netmgt.ackd;\n\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.opennms.netmgt.EventConstants;\nimport org.opennms.netmgt.dao.AcknowledgmentDao;\nimport org.opennms.netmgt.dao.AlarmDao;\nimport org.opennms.netmgt.dao.DatabasePopulator;\nimport org.opennms.netmgt.dao.EventDao;\nimport org.opennms.netmgt.dao.JavaMailConfigurationDao;\nimport org.opennms.netmgt.dao.NodeDao;\nimport org.opennms.netmgt.dao.NotificationDao;\nimport org.opennms.netmgt.dao.UserNotificationDao;\nimport org.opennms.netmgt.dao.db.JUnitTemporaryDatabase;\nimport org.opennms.netmgt.dao.db.OpenNMSConfigurationExecutionListener;\nimport org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener;\nimport org.opennms.netmgt.mock.MockEventIpcManager;\nimport org.opennms.netmgt.model.AckType;\nimport org.opennms.netmgt.model.OnmsAcknowledgment;\nimport org.opennms.netmgt.model.OnmsAlarm;\nimport org.opennms.netmgt.model.OnmsEvent;\nimport org.opennms.netmgt.model.OnmsNode;\nimport org.opennms.netmgt.model.OnmsNotification;\nimport org.opennms.netmgt.model.OnmsSeverity;\nimport org.opennms.netmgt.model.OnmsUserNotification;\nimport org.opennms.netmgt.model.events.EventBuilder;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.TestExecutionListeners;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\nimport org.springframework.test.context.support.DependencyInjectionTestExecutionListener;\nimport org.springframework.test.context.support.DirtiesContextTestExecutionListener;\nimport org.springframework.test.context.transaction.TransactionalTestExecutionListener;\nimport org.springframework.transaction.annotation.Transactional;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@TestExecutionListeners({\n OpenNMSConfigurationExecutionListener.class,\n TemporaryDatabaseExecutionListener.class,\n DependencyInjectionTestExecutionListener.class,\n DirtiesContextTestExecutionListener.class,\n TransactionalTestExecutionListener.class\n})\n@ContextConfiguration(locations={\n \"classpath:/META-INF/opennms/applicationContext-dao.xml\",\n \"classpath:/META-INF/opennms/applicationContext-daemon.xml\",\n \"classpath:/META-INF/opennms/mockEventIpcManager.xml\",\n \"classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml\",\n \"classpath:/META-INF/opennms/applicationContext-ackd.xml\",\n \"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml\"\n})\n\n/**\n * Acknowledgment Daemon tests\n * \n * @author David Hustace\n */\n@JUnitTemporaryDatabase(populate=true)\n@Transactional\npublic class AckdTest {\n\n @Autowired\n private AckService m_ackService;\n \n @Autowired\n private MockEventIpcManager m_mockEventIpcManager;\n \n @Autowired\n private AlarmDao m_alarmDao;\n \n @Autowired\n private EventDao m_eventDao;\n \n @Autowired\n private Ackd m_daemon;\n\n @Autowired\n private AcknowledgmentDao m_ackDao;\n\n @Autowired\n private NodeDao m_nodeDao;\n \n @Autowired\n private DatabasePopulator m_populator;\n\n @Autowired\n private NotificationDao m_notificationDao;\n \n @Autowired\n private UserNotificationDao m_userNotificationDao;\n \n @Autowired\n private JavaMailConfigurationDao m_jmConfigDao;\n\n\n @Before\n public void setUp() throws Exception {\n Properties props = new Properties();\n props.setProperty(\"log4j.logger.org.hibernate\", \"INFO\");\n props.setProperty(\"log4j.logger.org.springframework\", \"INFO\");\n props.setProperty(\"log4j.logger.org.hibernate.SQL\", \"DEBUG\");\n \n m_populator.populateDatabase();\n }\n \n @Test\n public void testWiring() {\n Assert.assertNotNull(m_ackDao);\n Assert.assertNotNull(m_alarmDao);\n Assert.assertNotNull(m_eventDao);\n Assert.assertNotNull(m_nodeDao);\n Assert.assertNotNull(m_notificationDao);\n Assert.assertNotNull(m_userNotificationDao);\n Assert.assertNotNull(m_mockEventIpcManager);\n Assert.assertNotNull(m_ackService);\n Assert.assertNotNull(m_daemon);\n Assert.assertNotNull(m_populator);\n Assert.assertNotNull(m_jmConfigDao);\n \n Assert.assertSame(\"dao from populator should refer to same dao from local properties\", m_populator.getAcknowledgmentDao(), m_ackDao);\n }\n \n\n /**\n * Make sure the DB is not empty\n */\n @Test\n public void testDbState() {\n Assert.assertFalse(m_nodeDao.findAll().isEmpty());\n }\n\n \n /**\n * This tests the acknowledgment of an alarm and any related notifications.\n */\n @Test\n public void testAcknowledgeAlarm() {\n \n VerificationObject vo = createAckStructure();\n Assert.assertTrue(vo.m_nodeId > 0);\n Assert.assertTrue(vo.m_alarmId > 0);\n Assert.assertTrue(vo.m_eventID > 0);\n Assert.assertTrue(vo.m_userNotifId > 0);\n \n OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId);\n\n OnmsAcknowledgment ack = new OnmsAcknowledgment(m_alarmDao.get(vo.m_alarmId));\n\n m_ackDao.save(ack);\n m_ackDao.flush();\n \n m_ackService.processAck(ack);\n \n alarm = m_alarmDao.get(ack.getRefId());\n Assert.assertNotNull(alarm.getAlarmAckUser());\n Assert.assertEquals(\"admin\", alarm.getAlarmAckUser());\n \n OnmsNotification notif = m_notificationDao.get(vo.m_notifId);\n Assert.assertNotNull(notif);\n Assert.assertEquals(\"admin\", notif.getAnsweredBy());\n \n Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime());\n \n }\n \n \n /**\n * This tests acknowledging a notification and a related alarm. If events are being deduplicated\n * they should all have the same alarm ID.\n */\n @Test\n public void testAcknowledgeNotification() {\n \n VerificationObject vo = createAckStructure();\n Assert.assertTrue(vo.m_nodeId > 0);\n Assert.assertTrue(vo.m_alarmId > 0);\n Assert.assertTrue(vo.m_eventID > 0);\n Assert.assertTrue(vo.m_userNotifId > 0);\n \n OnmsAcknowledgment ack = new OnmsAcknowledgment(m_notificationDao.get(vo.m_notifId));\n\n m_ackDao.save(ack);\n m_ackDao.flush();\n \n m_ackService.processAck(ack);\n \n OnmsNotification notif = m_notificationDao.get(ack.getRefId());\n Assert.assertNotNull(notif.getAnsweredBy());\n Assert.assertEquals(\"admin\", notif.getAnsweredBy());\n \n OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId);\n Assert.assertNotNull(alarm);\n Assert.assertEquals(\"admin\", alarm.getAlarmAckUser());\n \n Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime());\n \n }\n \n @Test\n public void testHandelEvent() throws InterruptedException {\n \n VerificationObject vo = createAckStructure();\n EventBuilder bldr = new EventBuilder(\"uei.opennms.org/internal/ackd/Acknowledge\", \"AckdTest\");\n bldr.addParam(\"ackType\", String.valueOf(AckType.ALARM));\n bldr.addParam(\"refId\", vo.m_alarmId);\n final String user = \"ackd-test-user\";\n bldr.addParam(\"user\", user);\n\n m_daemon.handleAckEvent(bldr.getEvent());\n \n OnmsNotification notif = m_notificationDao.get(vo.m_notifId);\n Assert.assertEquals(notif.getAckUser(), user);\n// Assert.assertEquals(notif.getAckTime(), bldr.getEvent().getTime());\n \n OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId);\n Assert.assertEquals(alarm.getAckUser(), user);\n// Assert.assertEquals(alarm.getAckTime(), bldr.getEvent().getTime());\n }\n \n \n class VerificationObject {\n int m_eventID;\n int m_alarmId;\n int m_nodeId;\n int m_notifId;\n int m_userNotifId;\n }\n \n private VerificationObject createAckStructure() {\n \n final Date time = new Date();\n VerificationObject vo = new VerificationObject();\n \n List nodes = m_nodeDao.findAll();\n Assert.assertTrue(\"List of nodes should not be empty\", nodes.size() > 0);\n OnmsNode node = m_nodeDao.get(nodes.get(0).getId());\n vo.m_nodeId = node.getId();\n \n OnmsEvent event = new OnmsEvent();\n event.setDistPoller(node.getDistPoller());\n event.setNode(node);\n \n event.setEventCreateTime(time);\n event.setEventDescr(\"Test node down event.\");\n event.setEventSeverity(6);\n event.setEventSource(\"AckdTest\");\n event.setEventTime(time);\n event.setEventUei(EventConstants.NODE_DOWN_EVENT_UEI);\n event.setIpAddr(node.getPrimaryInterface().getIpAddress());\n event.setEventLog(\"Y\");\n event.setEventDisplay(\"Y\");\n event.setEventLogMsg(\"Testing node down event from AckdTest.\");\n m_eventDao.save(event);\n vo.m_eventID = event.getId();\n \n OnmsAlarm alarm = new OnmsAlarm();\n alarm.setAlarmType(1);\n alarm.setClearKey(\"abc\");\n alarm.setClearUei(EventConstants.NODE_UP_EVENT_UEI);\n alarm.setCounter(1);\n alarm.setDescription(event.getEventDescr());\n alarm.setDistPoller(event.getDistPoller());\n alarm.setFirstEventTime(event.getEventTime());\n alarm.setIpAddr(event.getIpAddr());\n alarm.setLastEvent(event);\n alarm.setLastEventTime(event.getEventTime());\n alarm.setLogMsg(\"Some Log Message\");\n alarm.setNode(event.getNode());\n alarm.setReductionKey(\"xyz\");\n alarm.setServiceType(event.getServiceType());\n alarm.setSeverity(OnmsSeverity.get(event.getEventSeverity()));\n alarm.setUei(event.getEventUei());\n m_alarmDao.save(alarm);\n vo.m_alarmId = alarm.getId();\n event.setAlarm(alarm);\n \n OnmsNotification notif = new OnmsNotification();\n notif.setEvent(event);\n notif.setEventUei(event.getEventUei());\n notif.setIpAddress(event.getIpAddr());\n notif.setNode(event.getNode());\n notif.setNotifConfigName(\"abc\");\n notif.setNumericMsg(event.getEventLogMsg());\n notif.setPageTime(event.getEventTime());\n notif.setServiceType(event.getServiceType());\n notif.setSubject(\"notifyid: 1, node down\");\n notif.setTextMsg(event.getEventLogMsg());\n m_notificationDao.save(notif);\n vo.m_notifId = notif.getNotifyId();\n \n OnmsUserNotification userNotif = new OnmsUserNotification();\n userNotif.setAutoNotify(\"Y\");\n userNotif.setContactInfo(\"me@yourock.com\");\n userNotif.setMedia(\"page\");\n userNotif.setNotification(notif);\n userNotif.setNotifyTime(event.getEventTime());\n userNotif.setUserId(\"me\");\n \n Set usersnotifieds = new HashSet();\n usersnotifieds.add(userNotif);\n m_userNotificationDao.save(userNotif);\n vo.m_userNotifId = userNotif.getId();\n \n notif.setUsersNotified(usersnotifieds);\n m_notificationDao.update(notif);\n \n m_eventDao.update(event);\n m_eventDao.flush();\n \n return vo;\n }\n \n \n}\n"},"new_file":{"kind":"string","value":"opennms-ackd/src/test/java/org/opennms/netmgt/ackd/AckdTest.java"},"old_contents":{"kind":"string","value":"/*\n * This file is part of the OpenNMS(R) Application.\n *\n * OpenNMS(R) is Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved.\n * OpenNMS(R) is a derivative work, containing both original code, included code and modified\n * code that was published under the GNU General Public License. Copyrights for modified\n * and included code are below.\n *\n * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.\n *\n * Modifications:\n * \n * Created: January 7, 2009\n *\n * Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * For more information contact:\n * OpenNMS Licensing \n * http://www.opennms.org/\n * http://www.opennms.com/\n */\npackage org.opennms.netmgt.ackd;\n\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.opennms.netmgt.EventConstants;\nimport org.opennms.netmgt.dao.AcknowledgmentDao;\nimport org.opennms.netmgt.dao.AlarmDao;\nimport org.opennms.netmgt.dao.DatabasePopulator;\nimport org.opennms.netmgt.dao.EventDao;\nimport org.opennms.netmgt.dao.JavaMailConfigurationDao;\nimport org.opennms.netmgt.dao.NodeDao;\nimport org.opennms.netmgt.dao.NotificationDao;\nimport org.opennms.netmgt.dao.UserNotificationDao;\nimport org.opennms.netmgt.dao.db.JUnitTemporaryDatabase;\nimport org.opennms.netmgt.dao.db.OpenNMSConfigurationExecutionListener;\nimport org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener;\nimport org.opennms.netmgt.mock.MockEventIpcManager;\nimport org.opennms.netmgt.model.AckType;\nimport org.opennms.netmgt.model.OnmsAcknowledgment;\nimport org.opennms.netmgt.model.OnmsAlarm;\nimport org.opennms.netmgt.model.OnmsEvent;\nimport org.opennms.netmgt.model.OnmsNode;\nimport org.opennms.netmgt.model.OnmsNotification;\nimport org.opennms.netmgt.model.OnmsSeverity;\nimport org.opennms.netmgt.model.OnmsUserNotification;\nimport org.opennms.netmgt.model.events.EventBuilder;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.TestExecutionListeners;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\nimport org.springframework.test.context.support.DependencyInjectionTestExecutionListener;\nimport org.springframework.test.context.support.DirtiesContextTestExecutionListener;\nimport org.springframework.test.context.transaction.TransactionalTestExecutionListener;\nimport org.springframework.transaction.annotation.Transactional;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@TestExecutionListeners({\n OpenNMSConfigurationExecutionListener.class,\n TemporaryDatabaseExecutionListener.class,\n DependencyInjectionTestExecutionListener.class,\n DirtiesContextTestExecutionListener.class,\n TransactionalTestExecutionListener.class\n})\n@ContextConfiguration(locations={\n \"classpath:/META-INF/opennms/applicationContext-dao.xml\",\n \"classpath:/META-INF/opennms/applicationContext-daemon.xml\",\n \"classpath:/META-INF/opennms/mockEventIpcManager.xml\",\n \"classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml\",\n \"classpath:/META-INF/opennms/applicationContext-ackd.xml\",\n \"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml\"\n})\n\n/**\n * Acknowledgment Daemon tests\n * \n * @author David Hustace\n */\n@JUnitTemporaryDatabase(populate=true)\npublic class AckdTest {\n\n @Autowired\n private AckService m_ackService;\n \n @Autowired\n private MockEventIpcManager m_mockEventIpcManager;\n \n @Autowired\n private AlarmDao m_alarmDao;\n \n @Autowired\n private EventDao m_eventDao;\n \n @Autowired\n private Ackd m_daemon;\n\n @Autowired\n private AcknowledgmentDao m_ackDao;\n\n @Autowired\n private NodeDao m_nodeDao;\n \n @Autowired\n private DatabasePopulator m_populator;\n\n @Autowired\n private NotificationDao m_notificationDao;\n \n @Autowired\n private UserNotificationDao m_userNotificationDao;\n \n @Autowired\n private JavaMailConfigurationDao m_jmConfigDao;\n\n\n @Before\n public void setUp() throws Exception {\n Properties props = new Properties();\n props.setProperty(\"log4j.logger.org.hibernate\", \"INFO\");\n props.setProperty(\"log4j.logger.org.springframework\", \"INFO\");\n props.setProperty(\"log4j.logger.org.hibernate.SQL\", \"DEBUG\");\n \n m_populator.populateDatabase();\n }\n \n @Transactional\n @Test\n public void testWiring() {\n Assert.assertNotNull(m_ackDao);\n Assert.assertNotNull(m_alarmDao);\n Assert.assertNotNull(m_eventDao);\n Assert.assertNotNull(m_nodeDao);\n Assert.assertNotNull(m_notificationDao);\n Assert.assertNotNull(m_userNotificationDao);\n Assert.assertNotNull(m_mockEventIpcManager);\n Assert.assertNotNull(m_ackService);\n Assert.assertNotNull(m_daemon);\n Assert.assertNotNull(m_populator);\n Assert.assertNotNull(m_jmConfigDao);\n \n Assert.assertSame(\"dao from populator should refer to same dao from local properties\", m_populator.getAcknowledgmentDao(), m_ackDao);\n }\n \n\n /**\n * Make sure the DB is not empty\n */\n @Transactional\n @Test\n public void testDbState() {\n Assert.assertFalse(m_nodeDao.findAll().isEmpty());\n }\n\n \n /**\n * This tests the acknowledgment of an alarm and any related notifications.\n */\n @Transactional\n @Test\n public void testAcknowledgeAlarm() {\n \n VerificationObject vo = createAckStructure();\n Assert.assertTrue(vo.m_nodeId > 0);\n Assert.assertTrue(vo.m_alarmId > 0);\n Assert.assertTrue(vo.m_eventID > 0);\n Assert.assertTrue(vo.m_userNotifId > 0);\n \n OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId);\n\n OnmsAcknowledgment ack = new OnmsAcknowledgment(m_alarmDao.get(vo.m_alarmId));\n\n m_ackDao.save(ack);\n m_ackDao.flush();\n \n m_ackService.processAck(ack);\n \n alarm = m_alarmDao.get(ack.getRefId());\n Assert.assertNotNull(alarm.getAlarmAckUser());\n Assert.assertEquals(\"admin\", alarm.getAlarmAckUser());\n \n OnmsNotification notif = m_notificationDao.get(vo.m_notifId);\n Assert.assertNotNull(notif);\n Assert.assertEquals(\"admin\", notif.getAnsweredBy());\n \n Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime());\n \n }\n \n \n /**\n * This tests acknowledging a notification and a related alarm. If events are being deduplicated\n * they should all have the same alarm ID.\n */\n @Transactional\n @Test\n public void testAcknowledgeNotification() {\n \n VerificationObject vo = createAckStructure();\n Assert.assertTrue(vo.m_nodeId > 0);\n Assert.assertTrue(vo.m_alarmId > 0);\n Assert.assertTrue(vo.m_eventID > 0);\n Assert.assertTrue(vo.m_userNotifId > 0);\n \n OnmsAcknowledgment ack = new OnmsAcknowledgment(m_notificationDao.get(vo.m_notifId));\n\n m_ackDao.save(ack);\n m_ackDao.flush();\n \n m_ackService.processAck(ack);\n \n OnmsNotification notif = m_notificationDao.get(ack.getRefId());\n Assert.assertNotNull(notif.getAnsweredBy());\n Assert.assertEquals(\"admin\", notif.getAnsweredBy());\n \n OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId);\n Assert.assertNotNull(alarm);\n Assert.assertEquals(\"admin\", alarm.getAlarmAckUser());\n \n Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime());\n \n }\n \n @Transactional\n @Test\n public void testHandelEvent() throws InterruptedException {\n \n VerificationObject vo = createAckStructure();\n EventBuilder bldr = new EventBuilder(\"uei.opennms.org/internal/ackd/Acknowledge\", \"AckdTest\");\n bldr.addParam(\"ackType\", String.valueOf(AckType.ALARM));\n bldr.addParam(\"refId\", vo.m_alarmId);\n final String user = \"ackd-test-user\";\n bldr.addParam(\"user\", user);\n\n m_daemon.handleAckEvent(bldr.getEvent());\n \n OnmsNotification notif = m_notificationDao.get(vo.m_notifId);\n Assert.assertEquals(notif.getAckUser(), user);\n// Assert.assertEquals(notif.getAckTime(), bldr.getEvent().getTime());\n \n OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId);\n Assert.assertEquals(alarm.getAckUser(), user);\n// Assert.assertEquals(alarm.getAckTime(), bldr.getEvent().getTime());\n }\n \n \n class VerificationObject {\n int m_eventID;\n int m_alarmId;\n int m_nodeId;\n int m_notifId;\n int m_userNotifId;\n }\n \n private VerificationObject createAckStructure() {\n \n final Date time = new Date();\n VerificationObject vo = new VerificationObject();\n \n List nodes = m_nodeDao.findAll();\n Assert.assertTrue(\"List of nodes should not be empty\", nodes.size() > 0);\n OnmsNode node = m_nodeDao.get(nodes.get(0).getId());\n vo.m_nodeId = node.getId();\n \n OnmsEvent event = new OnmsEvent();\n event.setDistPoller(node.getDistPoller());\n event.setNode(node);\n \n event.setEventCreateTime(time);\n event.setEventDescr(\"Test node down event.\");\n event.setEventSeverity(6);\n event.setEventSource(\"AckdTest\");\n event.setEventTime(time);\n event.setEventUei(EventConstants.NODE_DOWN_EVENT_UEI);\n event.setIpAddr(node.getPrimaryInterface().getIpAddress());\n event.setEventLog(\"Y\");\n event.setEventDisplay(\"Y\");\n event.setEventLogMsg(\"Testing node down event from AckdTest.\");\n m_eventDao.save(event);\n vo.m_eventID = event.getId();\n \n OnmsAlarm alarm = new OnmsAlarm();\n alarm.setAlarmType(1);\n alarm.setClearKey(\"abc\");\n alarm.setClearUei(EventConstants.NODE_UP_EVENT_UEI);\n alarm.setCounter(1);\n alarm.setDescription(event.getEventDescr());\n alarm.setDistPoller(event.getDistPoller());\n alarm.setFirstEventTime(event.getEventTime());\n alarm.setIpAddr(event.getIpAddr());\n alarm.setLastEvent(event);\n alarm.setLastEventTime(event.getEventTime());\n alarm.setLogMsg(\"Some Log Message\");\n alarm.setNode(event.getNode());\n alarm.setReductionKey(\"xyz\");\n alarm.setServiceType(event.getServiceType());\n alarm.setSeverity(OnmsSeverity.get(event.getEventSeverity()));\n alarm.setUei(event.getEventUei());\n m_alarmDao.save(alarm);\n vo.m_alarmId = alarm.getId();\n event.setAlarm(alarm);\n \n OnmsNotification notif = new OnmsNotification();\n notif.setEvent(event);\n notif.setEventUei(event.getEventUei());\n notif.setIpAddress(event.getIpAddr());\n notif.setNode(event.getNode());\n notif.setNotifConfigName(\"abc\");\n notif.setNumericMsg(event.getEventLogMsg());\n notif.setPageTime(event.getEventTime());\n notif.setServiceType(event.getServiceType());\n notif.setSubject(\"notifyid: 1, node down\");\n notif.setTextMsg(event.getEventLogMsg());\n m_notificationDao.save(notif);\n vo.m_notifId = notif.getNotifyId();\n \n OnmsUserNotification userNotif = new OnmsUserNotification();\n userNotif.setAutoNotify(\"Y\");\n userNotif.setContactInfo(\"me@yourock.com\");\n userNotif.setMedia(\"page\");\n userNotif.setNotification(notif);\n userNotif.setNotifyTime(event.getEventTime());\n userNotif.setUserId(\"me\");\n \n Set usersnotifieds = new HashSet();\n usersnotifieds.add(userNotif);\n m_userNotificationDao.save(userNotif);\n vo.m_userNotifId = userNotif.getId();\n \n notif.setUsersNotified(usersnotifieds);\n m_notificationDao.update(notif);\n \n m_eventDao.update(event);\n m_eventDao.flush();\n \n return vo;\n }\n \n \n}\n"},"message":{"kind":"string","value":"matt suggested I just mark the whole class transactional instead, since setUp() basically means it's required anyways\n"},"old_file":{"kind":"string","value":"opennms-ackd/src/test/java/org/opennms/netmgt/ackd/AckdTest.java"},"subject":{"kind":"string","value":"matt suggested I just mark the whole class transactional instead, since setUp() basically means it's required anyways"}}},{"rowIdx":718,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"3d98570cd8c800d3d344b56a311dfe283879ce7c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2015, Red Hat, Inc. and individual contributors\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage org.zanata.dao;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.queryparser.classic.MultiFieldQueryParser;\nimport org.apache.lucene.queryparser.classic.ParseException;\nimport org.apache.lucene.queryparser.classic.QueryParser;\nimport org.apache.lucene.search.BooleanClause;\nimport org.apache.lucene.search.BooleanQuery;\nimport org.apache.lucene.search.TermQuery;\nimport org.hibernate.Query;\nimport org.hibernate.Session;\nimport org.hibernate.search.jpa.FullTextEntityManager;\nimport org.hibernate.search.jpa.FullTextQuery;\n\nimport javax.enterprise.context.RequestScoped;\nimport javax.inject.Inject;\nimport org.zanata.common.EntityStatus;\nimport org.zanata.hibernate.search.Analyzers;\nimport org.zanata.hibernate.search.CaseInsensitiveWhitespaceAnalyzer;\nimport org.zanata.hibernate.search.IndexFieldLabels;\nimport org.zanata.jpa.FullText;\nimport org.zanata.model.HAccount;\nimport org.zanata.model.HPerson;\nimport org.zanata.model.HProject;\nimport org.zanata.model.HProjectIteration;\nimport org.zanata.model.ProjectRole;\n\n@RequestScoped\npublic class ProjectDAO extends AbstractDAOImpl {\n @Inject @FullText\n private FullTextEntityManager entityManager;\n\n public ProjectDAO() {\n super(HProject.class);\n }\n\n public ProjectDAO(Session session) {\n super(HProject.class, session);\n }\n\n public @Nullable\n HProject getBySlug(@Nonnull String slug) {\n if (!StringUtils.isEmpty(slug)) {\n return (HProject) getSession().byNaturalId(HProject.class)\n .using(\"slug\", slug).load();\n }\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getOffsetList(int offset, int count,\n boolean filterOutActive, boolean filterOutReadOnly,\n boolean filterOutObsolete) {\n\n String condition =\n constructFilterCondition(filterOutActive, filterOutReadOnly,\n filterOutObsolete);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"from HProject p \")\n .append(condition)\n .append(\"order by UPPER(p.name) asc\");\n Query q = getSession().createQuery(sb.toString());\n\n if (count > 0) {\n q.setMaxResults(count);\n }\n if (offset > 0) {\n q.setFirstResult(offset);\n }\n q.setCacheable(true)\n .setComment(\"ProjectDAO.getOffsetList\");\n return q.list();\n }\n\n public int getFilterProjectSize(boolean filterOutActive,\n boolean filterOutReadOnly, boolean filterOutObsolete) {\n String condition = constructFilterCondition(filterOutActive,\n filterOutReadOnly, filterOutObsolete);\n String query = \"select count(*) from HProject p \" + condition;\n Query q = getSession().createQuery(query);\n q.setCacheable(true).setComment(\"ProjectDAO.getFilterProjectSize\");\n Long totalCount = (Long) q.uniqueResult();\n\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n private String constructFilterCondition(boolean filterOutActive,\n boolean filterOutReadOnly, boolean filterOutObsolete) {\n StringBuilder condition = new StringBuilder();\n if (filterOutActive || filterOutReadOnly || filterOutObsolete) {\n condition.append(\"where \");\n }\n\n if (filterOutActive) {\n // TODO bind this as a parameter\n condition.append(\"p.status <> '\" + EntityStatus.ACTIVE.getInitial()\n + \"' \");\n }\n\n if (filterOutReadOnly) {\n if (filterOutActive) {\n condition.append(\"and \");\n }\n\n // TODO bind this as a parameter\n condition.append(\"p.status <> '\"\n + EntityStatus.READONLY.getInitial() + \"' \");\n }\n\n if (filterOutObsolete) {\n if (filterOutActive || filterOutReadOnly) {\n condition.append(\"and \");\n }\n\n // TODO bind this as a parameter\n condition.append(\"p.status <> '\"\n + EntityStatus.OBSOLETE.getInitial() + \"' \");\n }\n return condition.toString();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getAllIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug order by t.creationDate\");\n q.setParameter(\"projectSlug\", slug);\n q.setCacheable(true).setComment(\"ProjectDAO.getAllIterations\");\n return q.list();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getActiveIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status\");\n q.setParameter(\"projectSlug\", slug).setParameter(\"status\",\n EntityStatus.ACTIVE);\n q.setCacheable(true).setComment(\"ProjectDAO.getActiveIterations\");\n return q.list();\n }\n\n /**\n * @param projectId\n * project id\n * @return number of non-obsolete (active and read only) iterations under given project\n */\n public int getTranslationCandidateCount(Long projectId) {\n Query q = getSession()\n .createQuery(\n \"select count(*) from HProjectIteration it where it.project.id = :projectId and it.status <> :status\")\n .setParameter(\"projectId\", projectId)\n .setParameter(\"status\", EntityStatus.OBSOLETE).setCacheable(true)\n .setComment(\"ProjectDAO.getTranslationCandidateCount\");\n return ((Long) q.uniqueResult()).intValue();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getReadOnlyIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status\");\n q.setParameter(\"projectSlug\", slug).setParameter(\"status\",\n EntityStatus.READONLY);\n q.setCacheable(true).setComment(\"ProjectDAO.getReadOnlyIterations\");\n return q.list();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getObsoleteIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status\");\n q.setParameter(\"projectSlug\", slug).setParameter(\"status\",\n EntityStatus.OBSOLETE);\n q.setCacheable(true).setComment(\"ProjectDAO.getObsoleteIterations\");\n return q.list();\n }\n\n public int getTotalProjectCount() {\n String query = \"select count(*) from HProject\";\n Query q = getSession().createQuery(query.toString());\n q.setCacheable(true).setComment(\"ProjectDAO.getTotalProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public int getTotalActiveProjectCount() {\n Query q =\n getSession()\n .createQuery(\n \"select count(*) from HProject p where p.status = :status\");\n q.setParameter(\"status\", EntityStatus.ACTIVE);\n q.setCacheable(true)\n .setComment(\"ProjectDAO.getTotalActiveProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public int getTotalReadOnlyProjectCount() {\n Query q =\n getSession()\n .createQuery(\n \"select count(*) from HProject p where p.status = :status\");\n q.setParameter(\"status\", EntityStatus.READONLY);\n q.setCacheable(true).setComment(\n \"ProjectDAO.getTotalReadOnlyProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public int getTotalObsoleteProjectCount() {\n Query q =\n getSession()\n .createQuery(\n \"select count(*) from HProject p where p.status = :status\");\n q.setParameter(\"status\", EntityStatus.OBSOLETE);\n q.setCacheable(true).setComment(\n \"ProjectDAO.getTotalObsoleteProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public List searchProjects(@Nonnull String searchQuery,\n int maxResult, int firstResult, boolean includeObsolete)\n throws ParseException {\n FullTextQuery query = buildSearchQuery(searchQuery, includeObsolete);\n if(maxResult > 0) {\n query.setMaxResults(maxResult);\n }\n return query.setFirstResult(firstResult)\n .getResultList();\n }\n\n public int getQueryProjectSize(@Nonnull String searchQuery,\n boolean includeObsolete) throws ParseException {\n return searchProjects(searchQuery, -1, 0, includeObsolete).size();\n }\n\n private FullTextQuery buildSearchQuery(@Nonnull String searchQuery,\n boolean includeObsolete) throws ParseException {\n String queryText = QueryParser.escape(searchQuery);\n Analyzer sourceAnalyzer = entityManager.getSearchFactory()\n .getAnalyzer(Analyzers.DEFAULT);\n MultiFieldQueryParser queryParser = new MultiFieldQueryParser(\n new String[]{ \"slug\", \"name\", \"description\" }, sourceAnalyzer);\n queryParser.setDefaultOperator(QueryParser.Operator.OR);\n\n BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();\n booleanQuery.add(queryParser.parse(queryText), BooleanClause.Occur.SHOULD);\n if (!includeObsolete) {\n TermQuery obsoleteStateQuery =\n new TermQuery(new Term(IndexFieldLabels.ENTITY_STATUS,\n EntityStatus.OBSOLETE.toString().toLowerCase()));\n booleanQuery.add(obsoleteStateQuery, BooleanClause.Occur.MUST_NOT);\n }\n\n return entityManager.createFullTextQuery(booleanQuery.build(), HProject.class);\n }\n\n /**\n * Build BooleanQuery on single lucene field by splitting searchQuery with\n * white space.\n *\n * @param searchQuery\n * - query string, will replace hypen with space and escape\n * special char\n * @param field\n * - lucene field\n */\n private BooleanQuery buildSearchFieldQuery(@Nonnull String searchQuery,\n @Nonnull String field) throws ParseException {\n BooleanQuery query = new BooleanQuery();\n\n //escape special character search\n searchQuery = QueryParser.escape(searchQuery);\n\n for(String searchString: searchQuery.split(\"\\\\s+\")) {\n QueryParser parser = new QueryParser(field,\n new CaseInsensitiveWhitespaceAnalyzer());\n query.add(parser.parse(searchString + \"*\"), BooleanClause.Occur.MUST);\n }\n return query;\n }\n\n public List findAllTranslatedProjects(HAccount account, int maxResults) {\n Query q =\n getSession()\n .createQuery(\n \"select distinct tft.textFlow.document.projectIteration.project \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.translator = :translator\")\n .setParameter(\"translator\", account)\n .setMaxResults(maxResults);\n return q.list();\n }\n\n public int getTranslatedProjectCount(HAccount account) {\n Query q =\n getSession()\n .createQuery(\n \"select count(distinct tft.textFlow.document.projectIteration.project) \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.translator = :translator\"\n )\n .setParameter(\"translator\", account);\n return ((Long) q.uniqueResult()).intValue();\n }\n\n\n\n /**\n * @param project A project\n * @param account The user for which the last translated date.\n * @return A date indicating the last time on which account's user\n * translated project.\n */\n public Date getLastTranslatedDate(HProject project, HAccount account) {\n Query q =\n getSession()\n .createQuery(\n \"select max (tft.lastChanged) \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.translator = :translator \" +\n \"and tft.textFlow.document.projectIteration.project = :project\"\n )\n .setParameter(\"translator\", account)\n .setParameter(\"project\", project)\n .setCacheable(true);\n return (Date) q.uniqueResult();\n }\n\n /**\n * @param project A project\n * @return A date indicating the last time when any user translated project\n */\n public Date getLastTranslatedDate(HProject project) {\n Query q =\n getSession()\n .createQuery(\n \"select max (tft.lastChanged) \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.textFlow.document.projectIteration.project = :project\"\n )\n .setParameter(\"project\", project)\n .setCacheable(true);\n return (Date) q.uniqueResult();\n }\n\n /**\n * @param project A project\n * @return A date indicating the last time when any user translated project\n */\n public HPerson getLastTranslator(HProject project) {\n Query q =\n getSession()\n .createQuery(\n \"select tft.translator \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.textFlow.document.projectIteration.project = :project \" +\n \"order by tft.lastChanged desc\"\n )\n .setParameter(\"project\", project)\n .setMaxResults(1)\n .setCacheable(true);\n List results = q.list();\n if (results.isEmpty()) {\n return null;\n } else {\n return (HPerson) results.get(0);\n }\n }\n\n public List getProjectsForMaintainer(HPerson maintainer,\n String filter, int firstResult, int maxResults) {\n final String sqlFilter = filter == null ? \"\" : filter.toLowerCase();\n Query q = getSession().createQuery(\n \"select m.project from HProjectMember m \" +\n \"where m.person = :maintainer \" +\n \"and m.role = :role \" +\n \"and m.project.status <> :obsolete \" +\n \"and (lower(m.project.name) like :filter \" +\n \"or lower(m.project.slug) like :filter) \" +\n \"order by m.project.name\")\n .setParameter(\"maintainer\", maintainer)\n .setParameter(\"role\", ProjectRole.Maintainer)\n .setParameter(\"obsolete\", EntityStatus.OBSOLETE)\n .setParameter(\"filter\", \"%\" + sqlFilter + \"%\")\n .setFirstResult(firstResult)\n .setMaxResults(maxResults);\n return q.list();\n }\n\n public int getMaintainedProjectCount(HPerson maintainer, String filter) {\n final String sqlFilter = filter == null ? \"\" : filter.toLowerCase();\n Query q = getSession().createQuery(\n \"select count(m) from HProjectMember m \" +\n \"where m.person = :maintainer \" +\n \"and m.role = :role \" +\n \"and m.project.status <> :obsolete \" +\n \"and (lower(m.project.name) like :filter \" +\n \"or lower(m.project.slug) like :filter)\")\n .setParameter(\"maintainer\", maintainer)\n .setParameter(\"role\", ProjectRole.Maintainer)\n .setParameter(\"obsolete\", EntityStatus.OBSOLETE)\n .setParameter(\"filter\", \"%\" + sqlFilter + \"%\");\n return ((Long) q.uniqueResult()).intValue();\n }\n}\n"},"new_file":{"kind":"string","value":"server/zanata-war/src/main/java/org/zanata/dao/ProjectDAO.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2015, Red Hat, Inc. and individual contributors\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage org.zanata.dao;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.queryparser.classic.ParseException;\nimport org.apache.lucene.queryparser.classic.QueryParser;\nimport org.apache.lucene.search.BooleanClause;\nimport org.apache.lucene.search.BooleanQuery;\nimport org.apache.lucene.search.TermQuery;\nimport org.hibernate.Query;\nimport org.hibernate.Session;\nimport org.hibernate.search.jpa.FullTextEntityManager;\nimport org.hibernate.search.jpa.FullTextQuery;\n\nimport javax.enterprise.context.RequestScoped;\nimport javax.inject.Inject;\nimport org.zanata.common.EntityStatus;\nimport org.zanata.hibernate.search.CaseInsensitiveWhitespaceAnalyzer;\nimport org.zanata.hibernate.search.IndexFieldLabels;\nimport org.zanata.jpa.FullText;\nimport org.zanata.model.HAccount;\nimport org.zanata.model.HPerson;\nimport org.zanata.model.HProject;\nimport org.zanata.model.HProjectIteration;\nimport org.zanata.model.ProjectRole;\n\n@RequestScoped\npublic class ProjectDAO extends AbstractDAOImpl {\n @Inject @FullText\n private FullTextEntityManager entityManager;\n\n public ProjectDAO() {\n super(HProject.class);\n }\n\n public ProjectDAO(Session session) {\n super(HProject.class, session);\n }\n\n public @Nullable\n HProject getBySlug(@Nonnull String slug) {\n if (!StringUtils.isEmpty(slug)) {\n return (HProject) getSession().byNaturalId(HProject.class)\n .using(\"slug\", slug).load();\n }\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getOffsetList(int offset, int count,\n boolean filterOutActive, boolean filterOutReadOnly,\n boolean filterOutObsolete) {\n\n String condition =\n constructFilterCondition(filterOutActive, filterOutReadOnly,\n filterOutObsolete);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"from HProject p \")\n .append(condition)\n .append(\"order by UPPER(p.name) asc\");\n Query q = getSession().createQuery(sb.toString());\n\n if (count > 0) {\n q.setMaxResults(count);\n }\n if (offset > 0) {\n q.setFirstResult(offset);\n }\n q.setCacheable(true)\n .setComment(\"ProjectDAO.getOffsetList\");\n return q.list();\n }\n\n public int getFilterProjectSize(boolean filterOutActive,\n boolean filterOutReadOnly, boolean filterOutObsolete) {\n String condition = constructFilterCondition(filterOutActive,\n filterOutReadOnly, filterOutObsolete);\n String query = \"select count(*) from HProject p \" + condition;\n Query q = getSession().createQuery(query);\n q.setCacheable(true).setComment(\"ProjectDAO.getFilterProjectSize\");\n Long totalCount = (Long) q.uniqueResult();\n\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n private String constructFilterCondition(boolean filterOutActive,\n boolean filterOutReadOnly, boolean filterOutObsolete) {\n StringBuilder condition = new StringBuilder();\n if (filterOutActive || filterOutReadOnly || filterOutObsolete) {\n condition.append(\"where \");\n }\n\n if (filterOutActive) {\n // TODO bind this as a parameter\n condition.append(\"p.status <> '\" + EntityStatus.ACTIVE.getInitial()\n + \"' \");\n }\n\n if (filterOutReadOnly) {\n if (filterOutActive) {\n condition.append(\"and \");\n }\n\n // TODO bind this as a parameter\n condition.append(\"p.status <> '\"\n + EntityStatus.READONLY.getInitial() + \"' \");\n }\n\n if (filterOutObsolete) {\n if (filterOutActive || filterOutReadOnly) {\n condition.append(\"and \");\n }\n\n // TODO bind this as a parameter\n condition.append(\"p.status <> '\"\n + EntityStatus.OBSOLETE.getInitial() + \"' \");\n }\n return condition.toString();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getAllIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug order by t.creationDate\");\n q.setParameter(\"projectSlug\", slug);\n q.setCacheable(true).setComment(\"ProjectDAO.getAllIterations\");\n return q.list();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getActiveIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status\");\n q.setParameter(\"projectSlug\", slug).setParameter(\"status\",\n EntityStatus.ACTIVE);\n q.setCacheable(true).setComment(\"ProjectDAO.getActiveIterations\");\n return q.list();\n }\n\n /**\n * @param projectId\n * project id\n * @return number of non-obsolete (active and read only) iterations under given project\n */\n public int getTranslationCandidateCount(Long projectId) {\n Query q = getSession()\n .createQuery(\n \"select count(*) from HProjectIteration it where it.project.id = :projectId and it.status <> :status\")\n .setParameter(\"projectId\", projectId)\n .setParameter(\"status\", EntityStatus.OBSOLETE).setCacheable(true)\n .setComment(\"ProjectDAO.getTranslationCandidateCount\");\n return ((Long) q.uniqueResult()).intValue();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getReadOnlyIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status\");\n q.setParameter(\"projectSlug\", slug).setParameter(\"status\",\n EntityStatus.READONLY);\n q.setCacheable(true).setComment(\"ProjectDAO.getReadOnlyIterations\");\n return q.list();\n }\n\n @SuppressWarnings(\"unchecked\")\n public List getObsoleteIterations(String slug) {\n Query q =\n getSession()\n .createQuery(\n \"from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status\");\n q.setParameter(\"projectSlug\", slug).setParameter(\"status\",\n EntityStatus.OBSOLETE);\n q.setCacheable(true).setComment(\"ProjectDAO.getObsoleteIterations\");\n return q.list();\n }\n\n public int getTotalProjectCount() {\n String query = \"select count(*) from HProject\";\n Query q = getSession().createQuery(query.toString());\n q.setCacheable(true).setComment(\"ProjectDAO.getTotalProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public int getTotalActiveProjectCount() {\n Query q =\n getSession()\n .createQuery(\n \"select count(*) from HProject p where p.status = :status\");\n q.setParameter(\"status\", EntityStatus.ACTIVE);\n q.setCacheable(true)\n .setComment(\"ProjectDAO.getTotalActiveProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public int getTotalReadOnlyProjectCount() {\n Query q =\n getSession()\n .createQuery(\n \"select count(*) from HProject p where p.status = :status\");\n q.setParameter(\"status\", EntityStatus.READONLY);\n q.setCacheable(true).setComment(\n \"ProjectDAO.getTotalReadOnlyProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public int getTotalObsoleteProjectCount() {\n Query q =\n getSession()\n .createQuery(\n \"select count(*) from HProject p where p.status = :status\");\n q.setParameter(\"status\", EntityStatus.OBSOLETE);\n q.setCacheable(true).setComment(\n \"ProjectDAO.getTotalObsoleteProjectCount\");\n Long totalCount = (Long) q.uniqueResult();\n if (totalCount == null)\n return 0;\n return totalCount.intValue();\n }\n\n public List searchProjects(@Nonnull String searchQuery,\n int maxResult, int firstResult, boolean includeObsolete)\n throws ParseException {\n FullTextQuery query = buildSearchQuery(searchQuery, includeObsolete);\n if(maxResult > 0) {\n query.setMaxResults(maxResult);\n }\n return query.setFirstResult(firstResult)\n .getResultList();\n }\n\n public int getQueryProjectSize(@Nonnull String searchQuery,\n boolean includeObsolete) throws ParseException {\n return searchProjects(searchQuery, -1, 0, includeObsolete).size();\n }\n\n private FullTextQuery buildSearchQuery(@Nonnull String searchQuery,\n boolean includeObsolete) throws ParseException {\n String queryText = QueryParser.escape(searchQuery);\n\n BooleanQuery booleanQuery = new BooleanQuery();\n booleanQuery.add(buildSearchFieldQuery(queryText, \"slug\"), BooleanClause.Occur.SHOULD);\n booleanQuery.add(buildSearchFieldQuery(queryText, \"name\"), BooleanClause.Occur.SHOULD);\n booleanQuery.add(buildSearchFieldQuery(queryText, \"description\"), BooleanClause.Occur.SHOULD);\n\n if (!includeObsolete) {\n TermQuery obsoleteStateQuery =\n new TermQuery(new Term(IndexFieldLabels.ENTITY_STATUS,\n EntityStatus.OBSOLETE.toString().toLowerCase()));\n booleanQuery.add(obsoleteStateQuery, BooleanClause.Occur.MUST_NOT);\n }\n\n return entityManager.createFullTextQuery(booleanQuery, HProject.class);\n }\n\n /**\n * Build BooleanQuery on single lucene field by splitting searchQuery with\n * white space.\n *\n * @param searchQuery\n * - query string, will replace hypen with space and escape\n * special char\n * @param field\n * - lucene field\n */\n private BooleanQuery buildSearchFieldQuery(@Nonnull String searchQuery,\n @Nonnull String field) throws ParseException {\n BooleanQuery query = new BooleanQuery();\n\n //escape special character search\n searchQuery = QueryParser.escape(searchQuery);\n\n for(String searchString: searchQuery.split(\"\\\\s+\")) {\n QueryParser parser = new QueryParser(field,\n new CaseInsensitiveWhitespaceAnalyzer());\n query.add(parser.parse(searchString + \"*\"), BooleanClause.Occur.MUST);\n }\n return query;\n }\n\n public List findAllTranslatedProjects(HAccount account, int maxResults) {\n Query q =\n getSession()\n .createQuery(\n \"select distinct tft.textFlow.document.projectIteration.project \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.translator = :translator\")\n .setParameter(\"translator\", account)\n .setMaxResults(maxResults);\n return q.list();\n }\n\n public int getTranslatedProjectCount(HAccount account) {\n Query q =\n getSession()\n .createQuery(\n \"select count(distinct tft.textFlow.document.projectIteration.project) \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.translator = :translator\"\n )\n .setParameter(\"translator\", account);\n return ((Long) q.uniqueResult()).intValue();\n }\n\n\n\n /**\n * @param project A project\n * @param account The user for which the last translated date.\n * @return A date indicating the last time on which account's user\n * translated project.\n */\n public Date getLastTranslatedDate(HProject project, HAccount account) {\n Query q =\n getSession()\n .createQuery(\n \"select max (tft.lastChanged) \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.translator = :translator \" +\n \"and tft.textFlow.document.projectIteration.project = :project\"\n )\n .setParameter(\"translator\", account)\n .setParameter(\"project\", project)\n .setCacheable(true);\n return (Date) q.uniqueResult();\n }\n\n /**\n * @param project A project\n * @return A date indicating the last time when any user translated project\n */\n public Date getLastTranslatedDate(HProject project) {\n Query q =\n getSession()\n .createQuery(\n \"select max (tft.lastChanged) \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.textFlow.document.projectIteration.project = :project\"\n )\n .setParameter(\"project\", project)\n .setCacheable(true);\n return (Date) q.uniqueResult();\n }\n\n /**\n * @param project A project\n * @return A date indicating the last time when any user translated project\n */\n public HPerson getLastTranslator(HProject project) {\n Query q =\n getSession()\n .createQuery(\n \"select tft.translator \" +\n \"from HTextFlowTarget tft \" +\n \"where tft.textFlow.document.projectIteration.project = :project \" +\n \"order by tft.lastChanged desc\"\n )\n .setParameter(\"project\", project)\n .setMaxResults(1)\n .setCacheable(true);\n List results = q.list();\n if (results.isEmpty()) {\n return null;\n } else {\n return (HPerson) results.get(0);\n }\n }\n\n public List getProjectsForMaintainer(HPerson maintainer,\n String filter, int firstResult, int maxResults) {\n final String sqlFilter = filter == null ? \"\" : filter.toLowerCase();\n Query q = getSession().createQuery(\n \"select m.project from HProjectMember m \" +\n \"where m.person = :maintainer \" +\n \"and m.role = :role \" +\n \"and m.project.status <> :obsolete \" +\n \"and (lower(m.project.name) like :filter \" +\n \"or lower(m.project.slug) like :filter) \" +\n \"order by m.project.name\")\n .setParameter(\"maintainer\", maintainer)\n .setParameter(\"role\", ProjectRole.Maintainer)\n .setParameter(\"obsolete\", EntityStatus.OBSOLETE)\n .setParameter(\"filter\", \"%\" + sqlFilter + \"%\")\n .setFirstResult(firstResult)\n .setMaxResults(maxResults);\n return q.list();\n }\n\n public int getMaintainedProjectCount(HPerson maintainer, String filter) {\n final String sqlFilter = filter == null ? \"\" : filter.toLowerCase();\n Query q = getSession().createQuery(\n \"select count(m) from HProjectMember m \" +\n \"where m.person = :maintainer \" +\n \"and m.role = :role \" +\n \"and m.project.status <> :obsolete \" +\n \"and (lower(m.project.name) like :filter \" +\n \"or lower(m.project.slug) like :filter)\")\n .setParameter(\"maintainer\", maintainer)\n .setParameter(\"role\", ProjectRole.Maintainer)\n .setParameter(\"obsolete\", EntityStatus.OBSOLETE)\n .setParameter(\"filter\", \"%\" + sqlFilter + \"%\");\n return ((Long) q.uniqueResult()).intValue();\n }\n}\n"},"message":{"kind":"string","value":"ZNTA-2056 use same analyzer to parse search query\n"},"old_file":{"kind":"string","value":"server/zanata-war/src/main/java/org/zanata/dao/ProjectDAO.java"},"subject":{"kind":"string","value":"ZNTA-2056 use same analyzer to parse search query"}}},{"rowIdx":719,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b98a6caa705f502f593f2813f07bb9395dd4cd64"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ksfzhaohui/spring-loaded,spring-projects/spring-loaded,witekcc/spring-loaded,ksfzhaohui/spring-loaded,witekcc/spring-loaded,drunklite/spring-loaded,spring-projects/spring-loaded,drunklite/spring-loaded"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2010-2012 VMware and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.springsource.loaded.agent;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.security.ProtectionDomain;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.objectweb.asm.ClassReader;\nimport org.springsource.loaded.GlobalConfiguration;\nimport org.springsource.loaded.LoadtimeInstrumentationPlugin;\nimport org.springsource.loaded.ReloadEventProcessorPlugin;\n\n\n/**\n * First stab at the Spring plugin for Spring-Loaded. Notes...
    \n *

      \n *
    • On reload, removes the Class entry in\n * org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.methodResolverCache. This enables us to add/changes\n * request mappings in controllers.\n *
    • That was for Roo, if we create a simple spring template project and run it, this doesn't work. It seems we need to redrive\n * detectHandlers() on the DefaultAnnotationHandlerMapping type which will rediscover the URL mappings and add them into the handler\n * list. We don't clear old ones out (yet) but the old mappings appear not to work anyway.\n *
    \n * \n * @author Andy Clement\n * @since 0.5.0\n */\npublic class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventProcessorPlugin {\n\n\tprivate static final String THIS_CLASS = \"org/springsource/loaded/agent/SpringPlugin\";\n\n\tprivate static Logger log = Logger.getLogger(SpringPlugin.class.getName());\n\n\tprivate static boolean debug = true;\n\t\n\t// TODO [gc] what about GC here - how do we know when they are finished with?\n\tpublic static List instancesOf_AnnotationMethodHandlerAdapter = new ArrayList();\n\tpublic static List instancesOf_DefaultAnnotationHandlerMapping = new ArrayList();\n\tpublic static List instancesOf_RequestMappingHandlerMapping = new ArrayList();\n\tpublic static List instancesOf_LocalVariableTableParameterNameDiscoverer = null;\n\n\tClassLoader springLoader = null;\n\t\n\tpublic static boolean support305 = true;\n\n\tprivate Field classCacheField;\n\tprivate Field strongClassCacheField;\n\tprivate Field softClassCacheField;\n\n\tprivate Field field_parameterNamesCache; // From LocalVariableTableParameterNameDiscoverer\n\n\tprivate boolean cachedIntrospectionResultsClassLoaded = false;\n\t\n\tprivate Class cachedIntrospectionResultsClass = null;\n\n\tpublic boolean accept(String slashedTypeName, ClassLoader classLoader, ProtectionDomain protectionDomain, byte[] bytes) {\n\t\t// TODO take classloader into account?\n\t\tif (slashedTypeName == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (slashedTypeName.equals(\"org/springframework/core/LocalVariableTableParameterNameDiscoverer\")) {\n\t\t\treturn true;\n\t\t}\n\t\t// Just interested in whether this type got loaded\n\t\tif (slashedTypeName.equals(\"org/springframework/beans/CachedIntrospectionResults\")) {\n\t\t\tcachedIntrospectionResultsClassLoaded = true;\n\t\t}\n\t\treturn slashedTypeName.equals(\"org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter\") ||\n\t\t\t\tslashedTypeName.equals(\"org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping\") || // 3.1\n\t\t\t\t(support305 && slashedTypeName\n\t\t\t\t\t\t.equals(\"org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping\"));\n\t}\n\t\n\n\tpublic byte[] modify(String slashedClassName, ClassLoader classLoader, byte[] bytes) {\n\t\tif (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {\n\t\t\tlog.info(\"loadtime modifying \" + slashedClassName);\n\t\t}\n\t\tif (slashedClassName.equals(\"org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter\")) {\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\n\t\t\t\t\t\"recordAnnotationMethodHandlerAdapterInstance\");\n\t\t} \n\t\telse if (slashedClassName.equals(\"org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping\")) {\n\t\t\t// springmvc spring 3.1 - doesnt work on 3.1 post M2 snapshots\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\n\t\t\t\t\t\"recordRequestMappingHandlerMappingInstance\");\n\t\t}\n\t\telse if (slashedClassName.equals(\"org/springframework/core/LocalVariableTableParameterNameDiscoverer\")) {\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\"recordLocalVariableTableParameterNameDiscoverer\");\n\t\t}\n\t\telse { // \"org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping\"\n\t\t\t// springmvc spring 3.0\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\n\t\t\t\t\t\"recordDefaultAnnotationHandlerMappingInstance\");\n\t\t}\n\t}\n\n\t// called by the modified code\n\tpublic static void recordAnnotationMethodHandlerAdapterInstance(Object obj) {\n\t\tinstancesOf_AnnotationMethodHandlerAdapter.add(obj);\n\t}\n\n\tpublic static void recordRequestMappingHandlerMappingInstance(Object obj) {\n\t\tinstancesOf_RequestMappingHandlerMapping.add(obj);\n\t}\n\n\tpublic static void recordLocalVariableTableParameterNameDiscoverer(Object obj) {\n\t\tif (instancesOf_LocalVariableTableParameterNameDiscoverer == null) {\n\t\t\tinstancesOf_LocalVariableTableParameterNameDiscoverer = new ArrayList();\n\t\t}\n\t\tinstancesOf_LocalVariableTableParameterNameDiscoverer.add(obj);\n\t}\n\n\tstatic {\n\t\ttry {\n\t\t\tString debugString = System.getProperty(\"springloaded.plugins.spring.debug\",\"false\");\n\t\t\tdebug = Boolean.valueOf(debugString);\n\t\t} catch (Exception e) {\n\t\t\t// likely security exception\n\t\t}\n\t}\n\n\t// called by the modified code\n\tpublic static void recordDefaultAnnotationHandlerMappingInstance(Object obj) {\n\t\tif (debug) {\n\t\t\tSystem.out.println(\"Recording new instance of DefaultAnnotationHandlerMappingInstance\");\n\t\t}\n\t\tinstancesOf_DefaultAnnotationHandlerMapping.add(obj);\n\t}\n\n\tpublic void reloadEvent(String typename, Class clazz, String versionsuffix) {\n\t\tremoveClazzFromMethodResolverCache(clazz);\n\t\tclearCachedIntrospectionResults(clazz);\n\t\treinvokeDetectHandlers(); // Spring 3.0\n\t\treinvokeInitHandlerMethods(); // Spring 3.1\n\t\tclearLocalVariableTableParameterNameDiscovererCache(clazz);\n\t}\n\n\t/**\n\t * The Spring class LocalVariableTableParameterNameDiscoverer holds a cache of parameter names discovered for members within\n\t * classes and needs clearing if the class changes.\n\t * @param clazz the class being reloaded, which may exist in a parameter name discoverer cache\n\t */\n\tprivate void clearLocalVariableTableParameterNameDiscovererCache(Class clazz) {\n\t\tif (instancesOf_LocalVariableTableParameterNameDiscoverer == null) {\n\t\t\treturn;\n\t\t}\n\t\tif (debug) {\n\t\t\tSystem.out.println(\"ParameterNamesCache: Clearing parameter name discoverer caches\");\n\t\t}\n\t\tif (field_parameterNamesCache == null) {\n\t\t\ttry {\n\t\t\t\tfield_parameterNamesCache = instancesOf_LocalVariableTableParameterNameDiscoverer.get(0).getClass().getDeclaredField(\"parameterNamesCache\");\n\t\t\t} catch (NoSuchFieldException nsfe) {\n\t\t\t\tlog.log(Level.SEVERE, \"Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\");\n\t\t\t}\n\t\t}\n\t\tfor (Object instance: instancesOf_LocalVariableTableParameterNameDiscoverer) {\n\t\t\tfield_parameterNamesCache.setAccessible(true);\n\t\t\ttry {\n\t\t\t\tMap parameterNamesCache = (Map)field_parameterNamesCache.get(instance);\n\t\t\t\tObject o = parameterNamesCache.remove(clazz);\n\t\t\t\tif (debug) {\n\t\t\t\t\tSystem.out.println(\"ParameterNamesCache: Removed \"+clazz.getName()+\" from cache?\"+(o!=null));\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tlog.log(Level.SEVERE, \"Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void removeClazzFromMethodResolverCache(Class clazz) {\n\t\tfor (Object o : instancesOf_AnnotationMethodHandlerAdapter) {\n\t\t\ttry {\n\t\t\t\tField f = o.getClass().getDeclaredField(\"methodResolverCache\");\n\t\t\t\tf.setAccessible(true);\n\t\t\t\tMap map = (Map) f.get(o);\n\t\t\t\tMethod removeMethod = Map.class.getDeclaredMethod(\"remove\", Object.class);\n\t\t\t\tObject ret = removeMethod.invoke(map, clazz);\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\tSystem.err.println(\"SpringPlugin: clearing methodResolverCache for \" + clazz.getName());\n\t\t\t\t}\n\t\t\t\tif (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {\n\t\t\t\t\tlog.info(\"cleared a cache entry? \" + (ret != null));\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.log(Level.SEVERE, \"Unexpected problem accessing methodResolverCache on \" + o, e);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void clearCachedIntrospectionResults(Class clazz) {\n\t\tif (cachedIntrospectionResultsClassLoaded) {\n\t\t\ttry {\n\t\t\t\t// TODO not a fan of classloading like this\n\t\t\t\tif (cachedIntrospectionResultsClass == null) {\n\t\t\t\t\t// TODO what about two apps using reloading and diff versions of spring?\n\t\t\t\t\tcachedIntrospectionResultsClass = clazz.getClassLoader().loadClass(\n\t\t\t\t\t\t\t\"org.springframework.beans.CachedIntrospectionResults\");\n\t\t\t\t}\n\n\t\t\t\tif (classCacheField == null && strongClassCacheField == null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tclassCacheField = cachedIntrospectionResultsClass.getDeclaredField(\"classCache\");\n\t\t\t\t\t} catch(NoSuchFieldException e) {\n\t\t\t\t\t\tstrongClassCacheField = cachedIntrospectionResultsClass.getDeclaredField(\"strongClassCache\");\n\t\t\t\t\t\tsoftClassCacheField = cachedIntrospectionResultsClass.getDeclaredField(\"softClassCache\");\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tif(classCacheField != null) {\n\t\t\t\t\tclassCacheField.setAccessible(true);\n\t\t\t\t\tMap m = (Map) classCacheField.get(null);\n\t\t\t\t\tObject o = m.remove(clazz);\n\t\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\t\tSystem.err.println(\"SpringPlugin: clearing CachedIntrospectionResults.classCache for \" + clazz.getName() + \" removed=\" + o);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(strongClassCacheField != null) {\n\t\t\t\t\tstrongClassCacheField.setAccessible(true);\n\t\t\t\t\tMap m = (Map) strongClassCacheField.get(null);\n\t\t\t\t\tObject o = m.remove(clazz);\n\t\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\t\tSystem.err.println(\"SpringPlugin: clearing CachedIntrospectionResults.strongClassCache for \" + clazz.getName() + \" removed=\" + o);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(softClassCacheField != null) {\n\t\t\t\t\tsoftClassCacheField.setAccessible(true);\n\t\t\t\t\tMap m = (Map) softClassCacheField.get(null);\n\t\t\t\t\tObject o = m.remove(clazz);\n\t\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\t\tSystem.err.println(\"SpringPlugin: clearing CachedIntrospectionResults.softClassCache for \" + clazz.getName() + \" removed=\" + o);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} catch (Exception e) {\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void reinvokeDetectHandlers() {\n\t\t// want to call detectHandlers on the DefaultAnnotationHandlerMapping type\n\t\t// protected void detectHandlers() throws BeansException { is defined on AbstractDetectingUrlHandlerMapping\n\t\tfor (Object o : instancesOf_DefaultAnnotationHandlerMapping) {\n\t\t\tif (debug) {\n\t\t\t\tSystem.out.println(\"Invoking detectHandlers on instance of DefaultAnnotationHandlerMappingInstance\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tClass clazz_AbstractDetectingUrlHandlerMapping = o.getClass().getSuperclass();\n\t\t\t\tMethod method_detectHandlers = clazz_AbstractDetectingUrlHandlerMapping.getDeclaredMethod(\"detectHandlers\");\n\t\t\t\tmethod_detectHandlers.setAccessible(true);\n\t\t\t\tmethod_detectHandlers.invoke(o);\n\t\t\t} catch (Exception e) {\n\t\t\t\t// if debugging then print it\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\tprivate void reinvokeInitHandlerMethods() {\n\t\t//\t\torg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (super AbstractHandlerMethodMapping) - call protected void initHandlerMethods() on it.\n\n\t\tfor (Object o : instancesOf_RequestMappingHandlerMapping) {\n\t\t\tif (debug) {\n\t\t\t\tSystem.out.println(\"Invoking initHandlerMethods on instance of RequestMappingHandlerMapping\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tClass clazz_AbstractHandlerMethodMapping = o.getClass().getSuperclass().getSuperclass();\n\n\t\t\t\t// private final Map handlerMethods = new LinkedHashMap();\n\t\t\t\tField field_handlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredField(\"handlerMethods\");\n\t\t\t\tfield_handlerMethods.setAccessible(true);\n\t\t\t\tMap m = (Map) field_handlerMethods.get(o);\n\t\t\t\tm.clear();\n\n\t\t\t\tField field_urlMap = clazz_AbstractHandlerMethodMapping.getDeclaredField(\"urlMap\");\n\t\t\t\tfield_urlMap.setAccessible(true);\n\t\t\t\tm = (Map) field_urlMap.get(o);\n\t\t\t\tm.clear();\n\n\t\t\t\tMethod method_initHandlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredMethod(\"initHandlerMethods\");\n\t\t\t\tmethod_initHandlerMethods.setAccessible(true);\n\t\t\t\tmethod_initHandlerMethods.invoke(o);\n\t\t\t} catch (NoSuchFieldException nsfe) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tif (nsfe.getMessage().equals(\"handlerMethods\")) {\n\t\t\t\t\t\tSystem.out.println(\"problem resetting request mapping handlers - unable to find field 'handlerMethods' on type 'AbstractHandlerMethodMapping' - you probably are not on Spring 3.1\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"problem resetting request mapping handlers - NoSuchFieldException: \"+nsfe.getMessage());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean shouldRerunStaticInitializer(String typename, Class clazz, String encodedTimestamp) {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Modify the supplied bytes such that constructors are intercepted and will invoke the specified class/method so that the\n\t * instances can be tracked.\n\t * \n\t * @return modified bytes for the class\n\t */\n\tprivate byte[] bytesWithInstanceCreationCaptured(byte[] bytes, String classToCall, String methodToCall) {\n\t\tClassReader cr = new ClassReader(bytes);\n\t\tClassVisitingConstructorAppender ca = new ClassVisitingConstructorAppender(classToCall, methodToCall);\n\t\tcr.accept(ca, 0);\n\t\tbyte[] newbytes = ca.getBytes();\n\t\treturn newbytes;\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2010-2012 VMware and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.springsource.loaded.agent;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.security.ProtectionDomain;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.objectweb.asm.ClassReader;\nimport org.springsource.loaded.GlobalConfiguration;\nimport org.springsource.loaded.LoadtimeInstrumentationPlugin;\nimport org.springsource.loaded.ReloadEventProcessorPlugin;\n\n\n/**\n * First stab at the Spring plugin for Spring-Loaded. Notes...
    \n *
      \n *
    • On reload, removes the Class entry in\n * org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.methodResolverCache. This enables us to add/changes\n * request mappings in controllers.\n *
    • That was for Roo, if we create a simple spring template project and run it, this doesn't work. It seems we need to redrive\n * detectHandlers() on the DefaultAnnotationHandlerMapping type which will rediscover the URL mappings and add them into the handler\n * list. We don't clear old ones out (yet) but the old mappings appear not to work anyway.\n *
    \n * \n * @author Andy Clement\n * @since 0.5.0\n */\npublic class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventProcessorPlugin {\n\n\tprivate static final String THIS_CLASS = \"org/springsource/loaded/agent/SpringPlugin\";\n\n\tprivate static Logger log = Logger.getLogger(SpringPlugin.class.getName());\n\n\tprivate static boolean debug = true;\n\t\n\t// TODO [gc] what about GC here - how do we know when they are finished with?\n\tpublic static List instancesOf_AnnotationMethodHandlerAdapter = new ArrayList();\n\tpublic static List instancesOf_DefaultAnnotationHandlerMapping = new ArrayList();\n\tpublic static List instancesOf_RequestMappingHandlerMapping = new ArrayList();\n\tpublic static List instancesOf_LocalVariableTableParameterNameDiscoverer = null;\n\n\tClassLoader springLoader = null;\n\t\n\tpublic static boolean support305 = true;\n\n\tprivate Field classCacheField;\n\tprivate Field field_parameterNamesCache; // From LocalVariableTableParameterNameDiscoverer\n\n\tprivate boolean cachedIntrospectionResultsClassLoaded = false;\n\t\n\tprivate Class cachedIntrospectionResultsClass = null;\n\n\tpublic boolean accept(String slashedTypeName, ClassLoader classLoader, ProtectionDomain protectionDomain, byte[] bytes) {\n\t\t// TODO take classloader into account?\n\t\tif (slashedTypeName == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (slashedTypeName.equals(\"org/springframework/core/LocalVariableTableParameterNameDiscoverer\")) {\n\t\t\treturn true;\n\t\t}\n\t\t// Just interested in whether this type got loaded\n\t\tif (slashedTypeName.equals(\"org/springframework/beans/CachedIntrospectionResults\")) {\n\t\t\tcachedIntrospectionResultsClassLoaded = true;\n\t\t}\n\t\treturn slashedTypeName.equals(\"org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter\") ||\n\t\t\t\tslashedTypeName.equals(\"org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping\") || // 3.1\n\t\t\t\t(support305 && slashedTypeName\n\t\t\t\t\t\t.equals(\"org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping\"));\n\t}\n\t\n\n\tpublic byte[] modify(String slashedClassName, ClassLoader classLoader, byte[] bytes) {\n\t\tif (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {\n\t\t\tlog.info(\"loadtime modifying \" + slashedClassName);\n\t\t}\n\t\tif (slashedClassName.equals(\"org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter\")) {\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\n\t\t\t\t\t\"recordAnnotationMethodHandlerAdapterInstance\");\n\t\t} \n\t\telse if (slashedClassName.equals(\"org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping\")) {\n\t\t\t// springmvc spring 3.1 - doesnt work on 3.1 post M2 snapshots\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\n\t\t\t\t\t\"recordRequestMappingHandlerMappingInstance\");\n\t\t}\n\t\telse if (slashedClassName.equals(\"org/springframework/core/LocalVariableTableParameterNameDiscoverer\")) {\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\"recordLocalVariableTableParameterNameDiscoverer\");\n\t\t}\n\t\telse { // \"org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping\"\n\t\t\t// springmvc spring 3.0\n\t\t\treturn bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,\n\t\t\t\t\t\"recordDefaultAnnotationHandlerMappingInstance\");\n\t\t}\n\t}\n\n\t// called by the modified code\n\tpublic static void recordAnnotationMethodHandlerAdapterInstance(Object obj) {\n\t\tinstancesOf_AnnotationMethodHandlerAdapter.add(obj);\n\t}\n\n\tpublic static void recordRequestMappingHandlerMappingInstance(Object obj) {\n\t\tinstancesOf_RequestMappingHandlerMapping.add(obj);\n\t}\n\n\tpublic static void recordLocalVariableTableParameterNameDiscoverer(Object obj) {\n\t\tif (instancesOf_LocalVariableTableParameterNameDiscoverer == null) {\n\t\t\tinstancesOf_LocalVariableTableParameterNameDiscoverer = new ArrayList();\n\t\t}\n\t\tinstancesOf_LocalVariableTableParameterNameDiscoverer.add(obj);\n\t}\n\n\tstatic {\n\t\ttry {\n\t\t\tString debugString = System.getProperty(\"springloaded.plugins.spring.debug\",\"false\");\n\t\t\tdebug = Boolean.valueOf(debugString);\n\t\t} catch (Exception e) {\n\t\t\t// likely security exception\n\t\t}\n\t}\n\n\t// called by the modified code\n\tpublic static void recordDefaultAnnotationHandlerMappingInstance(Object obj) {\n\t\tif (debug) {\n\t\t\tSystem.out.println(\"Recording new instance of DefaultAnnotationHandlerMappingInstance\");\n\t\t}\n\t\tinstancesOf_DefaultAnnotationHandlerMapping.add(obj);\n\t}\n\n\tpublic void reloadEvent(String typename, Class clazz, String versionsuffix) {\n\t\tremoveClazzFromMethodResolverCache(clazz);\n\t\tclearCachedIntrospectionResults(clazz);\n\t\treinvokeDetectHandlers(); // Spring 3.0\n\t\treinvokeInitHandlerMethods(); // Spring 3.1\n\t\tclearLocalVariableTableParameterNameDiscovererCache(clazz);\n\t}\n\n\t/**\n\t * The Spring class LocalVariableTableParameterNameDiscoverer holds a cache of parameter names discovered for members within\n\t * classes and needs clearing if the class changes.\n\t * @param clazz the class being reloaded, which may exist in a parameter name discoverer cache\n\t */\n\tprivate void clearLocalVariableTableParameterNameDiscovererCache(Class clazz) {\n\t\tif (instancesOf_LocalVariableTableParameterNameDiscoverer == null) {\n\t\t\treturn;\n\t\t}\n\t\tif (debug) {\n\t\t\tSystem.out.println(\"ParameterNamesCache: Clearing parameter name discoverer caches\");\n\t\t}\n\t\tif (field_parameterNamesCache == null) {\n\t\t\ttry {\n\t\t\t\tfield_parameterNamesCache = instancesOf_LocalVariableTableParameterNameDiscoverer.get(0).getClass().getDeclaredField(\"parameterNamesCache\");\n\t\t\t} catch (NoSuchFieldException nsfe) {\n\t\t\t\tlog.log(Level.SEVERE, \"Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\");\n\t\t\t}\n\t\t}\n\t\tfor (Object instance: instancesOf_LocalVariableTableParameterNameDiscoverer) {\n\t\t\tfield_parameterNamesCache.setAccessible(true);\n\t\t\ttry {\n\t\t\t\tMap parameterNamesCache = (Map)field_parameterNamesCache.get(instance);\n\t\t\t\tObject o = parameterNamesCache.remove(clazz);\n\t\t\t\tif (debug) {\n\t\t\t\t\tSystem.out.println(\"ParameterNamesCache: Removed \"+clazz.getName()+\" from cache?\"+(o!=null));\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tlog.log(Level.SEVERE, \"Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void removeClazzFromMethodResolverCache(Class clazz) {\n\t\tfor (Object o : instancesOf_AnnotationMethodHandlerAdapter) {\n\t\t\ttry {\n\t\t\t\tField f = o.getClass().getDeclaredField(\"methodResolverCache\");\n\t\t\t\tf.setAccessible(true);\n\t\t\t\tMap map = (Map) f.get(o);\n\t\t\t\tMethod removeMethod = Map.class.getDeclaredMethod(\"remove\", Object.class);\n\t\t\t\tObject ret = removeMethod.invoke(map, clazz);\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\tSystem.err.println(\"SpringPlugin: clearing methodResolverCache for \" + clazz.getName());\n\t\t\t\t}\n\t\t\t\tif (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {\n\t\t\t\t\tlog.info(\"cleared a cache entry? \" + (ret != null));\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.log(Level.SEVERE, \"Unexpected problem accessing methodResolverCache on \" + o, e);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void clearCachedIntrospectionResults(Class clazz) {\n\t\tif (cachedIntrospectionResultsClassLoaded) {\n\t\t\ttry {\n\t\t\t\t// TODO not a fan of classloading like this\n\t\t\t\tif (cachedIntrospectionResultsClass == null) {\n\t\t\t\t\t// TODO what about two apps using reloading and diff versions of spring?\n\t\t\t\t\tcachedIntrospectionResultsClass = clazz.getClassLoader().loadClass(\n\t\t\t\t\t\t\t\"org.springframework.beans.CachedIntrospectionResults\");\n\t\t\t\t}\n\t\t\t\tif (classCacheField == null) {\n\t\t\t\t\tclassCacheField = cachedIntrospectionResultsClass.getDeclaredField(\"classCache\");\n\t\t\t\t}\n\t\t\t\tclassCacheField.setAccessible(true);\n\t\t\t\tMap m = (Map) classCacheField.get(null);\n\t\t\t\tObject o = m.remove(clazz);\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\tSystem.err\n\t\t\t\t\t\t\t.println(\"SpringPlugin: clearing CachedIntrospectionResults for \" + clazz.getName() + \" removed=\" + o);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void reinvokeDetectHandlers() {\n\t\t// want to call detectHandlers on the DefaultAnnotationHandlerMapping type\n\t\t// protected void detectHandlers() throws BeansException { is defined on AbstractDetectingUrlHandlerMapping\n\t\tfor (Object o : instancesOf_DefaultAnnotationHandlerMapping) {\n\t\t\tif (debug) {\n\t\t\t\tSystem.out.println(\"Invoking detectHandlers on instance of DefaultAnnotationHandlerMappingInstance\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tClass clazz_AbstractDetectingUrlHandlerMapping = o.getClass().getSuperclass();\n\t\t\t\tMethod method_detectHandlers = clazz_AbstractDetectingUrlHandlerMapping.getDeclaredMethod(\"detectHandlers\");\n\t\t\t\tmethod_detectHandlers.setAccessible(true);\n\t\t\t\tmethod_detectHandlers.invoke(o);\n\t\t\t} catch (Exception e) {\n\t\t\t\t// if debugging then print it\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\tprivate void reinvokeInitHandlerMethods() {\n\t\t//\t\torg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (super AbstractHandlerMethodMapping) - call protected void initHandlerMethods() on it.\n\n\t\tfor (Object o : instancesOf_RequestMappingHandlerMapping) {\n\t\t\tif (debug) {\n\t\t\t\tSystem.out.println(\"Invoking initHandlerMethods on instance of RequestMappingHandlerMapping\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tClass clazz_AbstractHandlerMethodMapping = o.getClass().getSuperclass().getSuperclass();\n\n\t\t\t\t// private final Map handlerMethods = new LinkedHashMap();\n\t\t\t\tField field_handlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredField(\"handlerMethods\");\n\t\t\t\tfield_handlerMethods.setAccessible(true);\n\t\t\t\tMap m = (Map) field_handlerMethods.get(o);\n\t\t\t\tm.clear();\n\n\t\t\t\tField field_urlMap = clazz_AbstractHandlerMethodMapping.getDeclaredField(\"urlMap\");\n\t\t\t\tfield_urlMap.setAccessible(true);\n\t\t\t\tm = (Map) field_urlMap.get(o);\n\t\t\t\tm.clear();\n\n\t\t\t\tMethod method_initHandlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredMethod(\"initHandlerMethods\");\n\t\t\t\tmethod_initHandlerMethods.setAccessible(true);\n\t\t\t\tmethod_initHandlerMethods.invoke(o);\n\t\t\t} catch (NoSuchFieldException nsfe) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tif (nsfe.getMessage().equals(\"handlerMethods\")) {\n\t\t\t\t\t\tSystem.out.println(\"problem resetting request mapping handlers - unable to find field 'handlerMethods' on type 'AbstractHandlerMethodMapping' - you probably are not on Spring 3.1\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(\"problem resetting request mapping handlers - NoSuchFieldException: \"+nsfe.getMessage());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tif (GlobalConfiguration.debugplugins) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean shouldRerunStaticInitializer(String typename, Class clazz, String encodedTimestamp) {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Modify the supplied bytes such that constructors are intercepted and will invoke the specified class/method so that the\n\t * instances can be tracked.\n\t * \n\t * @return modified bytes for the class\n\t */\n\tprivate byte[] bytesWithInstanceCreationCaptured(byte[] bytes, String classToCall, String methodToCall) {\n\t\tClassReader cr = new ClassReader(bytes);\n\t\tClassVisitingConstructorAppender ca = new ClassVisitingConstructorAppender(classToCall, methodToCall);\n\t\tcr.accept(ca, 0);\n\t\tbyte[] newbytes = ca.getBytes();\n\t\treturn newbytes;\n\t}\n\n}\n"},"message":{"kind":"string","value":"Fix #80: NoSuchFieldException with Spring 4.1\n"},"old_file":{"kind":"string","value":"springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java"},"subject":{"kind":"string","value":"Fix #80: NoSuchFieldException with Spring 4.1"}}},{"rowIdx":720,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"34440e06efa3f157b6131d9244f6b9197237acc3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"DataTorrent/incubator-apex-malhar,ananthc/apex-malhar,PramodSSImmaneni/apex-malhar,prasannapramod/apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/incubator-apex-malhar,siyuanh/apex-malhar,ilganeli/incubator-apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar,DataTorrent/Megh,chandnisingh/apex-malhar,siyuanh/apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chandnisingh/apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,brightchen/apex-malhar,siyuanh/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,siyuanh/incubator-apex-malhar,brightchen/apex-malhar,chandnisingh/apex-malhar,trusli/apex-malhar,trusli/apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,skekre98/apex-mlhr,tushargosavi/incubator-apex-malhar,chandnisingh/apex-malhar,apache/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar,vrozov/apex-malhar,prasannapramod/apex-malhar,apache/incubator-apex-malhar,ananthc/apex-malhar,skekre98/apex-mlhr,siyuanh/incubator-apex-malhar,patilvikram/apex-malhar,apache/incubator-apex-malhar,skekre98/apex-mlhr,siyuanh/apex-malhar,yogidevendra/apex-malhar,siyuanh/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,ananthc/apex-malhar,vrozov/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,trusli/apex-malhar,tushargosavi/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,siyuanh/apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,trusli/apex-malhar,DataTorrent/Megh,vrozov/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,yogidevendra/apex-malhar,ilganeli/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,davidyan74/apex-malhar,vrozov/apex-malhar,apache/incubator-apex-malhar,prasannapramod/apex-malhar,vrozov/apex-malhar,prasannapramod/apex-malhar,sandeep-n/incubator-apex-malhar,yogidevendra/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/apex-malhar,brightchen/apex-malhar,siyuanh/apex-malhar,prasannapramod/apex-malhar,tweise/apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,patilvikram/apex-malhar,tweise/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,tweise/apex-malhar,yogidevendra/incubator-apex-malhar,tweise/apex-malhar,davidyan74/apex-malhar,brightchen/apex-malhar,skekre98/apex-mlhr,trusli/apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,DataTorrent/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/incubator-apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,siyuanh/incubator-apex-malhar,brightchen/apex-malhar,tweise/incubator-apex-malhar,tweise/incubator-apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,ananthc/apex-malhar,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,vrozov/apex-malhar,vrozov/incubator-apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,tweise/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,trusli/apex-malhar,brightchen/apex-malhar,tweise/apex-malhar,ananthc/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,davidyan74/apex-malhar,sandeep-n/incubator-apex-malhar,ilganeli/incubator-apex-malhar,siyuanh/incubator-apex-malhar"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) 2012-2013 Malhar, Inc.\n * All Rights Reserved.\n */\npackage com.malhartech.demos.yahoofinance;\n\nimport com.malhartech.api.ApplicationFactory;\nimport com.malhartech.api.DAG;\nimport com.malhartech.contrib.sqlite.SqliteStreamOperator;\nimport com.malhartech.lib.io.SmtpOutputOperator;\nimport com.malhartech.lib.util.Alert;\nimport java.util.HashMap;\nimport org.apache.hadoop.conf.Configuration;\n\n/**\n * This demo will output the stock market data from yahoo finance\n *\n * @author David Yan \n */\npublic class ApplicationWithAlert implements ApplicationFactory\n{\n @Override\n public DAG getApplication(Configuration conf)\n {\n String[] symbols = {\"YHOO\", \"GOOG\", \"AAPL\", \"FB\", \"AMZN\", \"NFLX\", \"IBM\"};\n DAG dag = new DAG();\n\n YahooFinanceCSVInputOperator input1 = dag.addOperator(\"input1\", new YahooFinanceCSVInputOperator());\n SqliteStreamOperator sqlOper = dag.addOperator(\"sqlOper\", new SqliteStreamOperator());\n Alert> alertOper = dag.addOperator(\"alert\", new Alert>());\n //ConsoleOutputOperator consoleOperator = dag.addOperator(\"console\", new ConsoleOutputOperator());\n SmtpOutputOperator> mailOper = dag.addOperator(\"mail\", new SmtpOutputOperator>());\n\n mailOper.setFrom(\"jenkins@malhar-inc.com\");\n mailOper.addRecipient(SmtpOutputOperator.RecipientType.TO, \"jenkins@malhar-inc.com\");\n mailOper.setContent(\"AAPL: {}\\nThis is an auto-generated message. Do not reply.\");\n mailOper.setSubject(\"ALERT: AAPL is less than 450\");\n mailOper.setSmtpHost(\"secure.emailsrvr.com\");\n mailOper.setSmtpPort(465);\n mailOper.setSmtpUserName(\"jenkins@malhar-inc.com\");\n mailOper.setSmtpPassword(\"Testing1\");\n mailOper.setUseSsl(true);\n\n alertOper.setAlertFrequency(60000); // 30 seconds\n\n for (String symbol: symbols) {\n input1.addSymbol(symbol);\n }\n input1.addFormat(\"s0\");\n input1.addFormat(\"l1\");\n\n SqliteStreamOperator.InputSchema inputSchema1 = new SqliteStreamOperator.InputSchema(\"t1\");\n inputSchema1.setColumnInfo(\"s0\", \"string\", true); // symbol\n inputSchema1.setColumnInfo(\"l1\", \"float\", false); // last trade\n\n sqlOper.setInputSchema(0, inputSchema1);\n\n // select the alert using SQL\n sqlOper.setStatement(\"SELECT t1.s0 AS symbol, t1.l1 AS last_trade FROM t1 WHERE t1.s0 = 'AAPL' AND t1.l1 < 450\");\n\n dag.addStream(\"input1_sql\", input1.outputPort, sqlOper.in1);\n dag.addStream(\"sql_alert\", sqlOper.result, alertOper.in);\n //dag.addStream(\"alert_console\", alertOper.alert1, consoleOperator.input);\n dag.addStream(\"alert_mail\", alertOper.alert1, mailOper.input);\n\n return dag;\n }\n\n}\n"},"new_file":{"kind":"string","value":"demos/src/main/java/com/malhartech/demos/yahoofinance/ApplicationWithAlert.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2012-2013 Malhar, Inc.\n * All Rights Reserved.\n */\npackage com.malhartech.demos.yahoofinance;\n\nimport com.malhartech.api.ApplicationFactory;\nimport com.malhartech.api.DAG;\nimport com.malhartech.contrib.sqlite.SqliteStreamOperator;\nimport com.malhartech.lib.io.SmtpOutputOperator;\nimport com.malhartech.lib.util.Alert;\nimport java.util.HashMap;\nimport org.apache.hadoop.conf.Configuration;\n\n/**\n * This demo will output the stock market data from yahoo finance\n *\n * @author David Yan \n */\npublic class ApplicationWithAlert implements ApplicationFactory\n{\n @Override\n public DAG getApplication(Configuration conf)\n {\n String[] symbols = {\"YHOO\", \"GOOG\", \"AAPL\", \"FB\", \"AMZN\", \"NFLX\", \"IBM\"};\n DAG dag = new DAG();\n\n YahooFinanceCSVInputOperator input1 = dag.addOperator(\"input1\", new YahooFinanceCSVInputOperator());\n SqliteStreamOperator sqlOper = dag.addOperator(\"sqlOper\", new SqliteStreamOperator());\n Alert> alertOper = dag.addOperator(\"alert\", new Alert>());\n //ConsoleOutputOperator consoleOperator = dag.addOperator(\"console\", new ConsoleOutputOperator());\n SmtpOutputOperator> mailOper = dag.addOperator(\"mail\", new SmtpOutputOperator>());\n\n mailOper.setFrom(\"jenkins@malhar-inc.com\");\n mailOper.addRecipient(SmtpOutputOperator.RecipientType.TO, \"jenkins@malhar-inc.com\");\n mailOper.setContent(\"AAPL: {}\\nThis is an auto-generated message. Do not reply.\");\n mailOper.setSubject(\"ALERT: AAPL is less than 450\");\n mailOper.setSmtpHost(\"secure.emailsrvr.com\");\n mailOper.setSmtpPort(465);\n mailOper.setSmtpUserName(\"jenkins@malhar-inc.com\");\n mailOper.setSmtpPassword(\"Testing1\");\n mailOper.setUseSsl(true);\n\n alertOper.setAlertFrequency(60000); // 30 seconds\n\n for (String symbol: symbols) {\n input1.addSymbol(symbol);\n }\n input1.addFormat(\"s0\");\n input1.addFormat(\"l1\");\n\n SqliteStreamOperator.InputSchema inputSchema1 = new SqliteStreamOperator.InputSchema(\"t1\");\n inputSchema1.setColumnInfo(\"s0\", \"string\", true); // symbol\n inputSchema1.setColumnInfo(\"l1\", \"float\", false); // last trade\n\n sqlOper.setInputSchema(0, inputSchema1);\n\n // Calculate PE Ratio and PB Ratio using SQL\n sqlOper.setStatement(\"SELECT t1.s0 AS symbol, t1.l1 AS last_trade FROM t1 WHERE t1.s0 = 'AAPL' AND t1.l1 < 450\");\n\n dag.addStream(\"input1_sql\", input1.outputPort, sqlOper.in1);\n dag.addStream(\"sql_alert\", sqlOper.result, alertOper.in);\n //dag.addStream(\"alert_console\", alertOper.alert1, consoleOperator.input);\n dag.addStream(\"alert_mail\", alertOper.alert1, mailOper.input);\n\n return dag;\n }\n\n}\n"},"message":{"kind":"string","value":"corrected comment\n"},"old_file":{"kind":"string","value":"demos/src/main/java/com/malhartech/demos/yahoofinance/ApplicationWithAlert.java"},"subject":{"kind":"string","value":"corrected comment"}}},{"rowIdx":721,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"bc6101d49ed305cfb290910d0038446ad84f72b3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Devlight/NavigationTabBar,DevLight-Mobile-Agency/NavigationTabBar"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2015 Basil Miller\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.gigamole.library;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.PorterDuff;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.PorterDuffXfermode;\nimport android.graphics.Rect;\nimport android.graphics.RectF;\nimport android.graphics.Typeface;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.support.v4.view.ViewPager;\nimport android.text.TextPaint;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.animation.AccelerateDecelerateInterpolator;\nimport android.view.animation.AccelerateInterpolator;\nimport android.view.animation.DecelerateInterpolator;\nimport android.view.animation.Interpolator;\nimport android.view.animation.LinearInterpolator;\nimport android.widget.Scroller;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Random;\n\n/**\n * Created by GIGAMOLE on 24.03.2016.\n */\npublic class NavigationTabBar extends View implements ViewPager.OnPageChangeListener {\n\n // NTP constants\n private final static String PREVIEW_BADGE = \"0\";\n private final static String PREVIEW_TITLE = \"Title\";\n private final static int INVALID_INDEX = -1;\n\n private final static int DEFAULT_BADGE_ANIMATION_DURATION = 200;\n private final static int DEFAULT_BADGE_REFRESH_ANIMATION_DURATION = 100;\n private final static int DEFAULT_ANIMATION_DURATION = 300;\n private final static int DEFAULT_INACTIVE_COLOR = Color.parseColor(\"#9f90af\");\n private final static int DEFAULT_ACTIVE_COLOR = Color.WHITE;\n\n private final static float MIN_FRACTION = 0.0f;\n private final static float MAX_FRACTION = 1.0f;\n\n private final static int MIN_ALPHA = 0;\n private final static int MAX_ALPHA = 255;\n\n private final static float ACTIVE_ICON_SCALE_BY = 0.35f;\n private final static float ICON_SIZE_FRACTION = 0.4f;\n\n private final static float TITLE_ACTIVE_ICON_SCALE_BY = 0.25f;\n private final static float TITLE_ICON_SIZE_FRACTION = 0.4f;\n private final static float TITLE_ACTIVE_SCALE_BY = 0.2f;\n private final static float TITLE_SIZE_FRACTION = 0.2f;\n private final static float TITLE_MARGIN_FRACTION = 0.15f;\n\n private final static float BADGE_HORIZONTAL_FRACTION = 0.5f;\n private final static float BADGE_VERTICAL_FRACTION = 0.75f;\n private final static float BADGE_TITLE_SIZE_FRACTION = 0.85f;\n\n private final static int ALL_INDEX = 0;\n private final static int ACTIVE_INDEX = 1;\n\n private final static int LEFT_INDEX = 0;\n private final static int CENTER_INDEX = 1;\n private final static int RIGHT_INDEX = 2;\n\n private final static int TOP_INDEX = 0;\n private final static int BOTTOM_INDEX = 1;\n\n private final static float LEFT_FRACTION = 0.25f;\n private final static float CENTER_FRACTION = 0.5f;\n private final static float RIGHT_FRACTION = 0.75f;\n\n private final static Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator();\n private final static Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();\n\n // NTP and pointer bounds\n private RectF mBounds = new RectF();\n private RectF mPointerBounds = new RectF();\n // Badge bounds and bg badge bounds\n final Rect mBadgeBounds = new Rect();\n final RectF mBgBadgeBounds = new RectF();\n\n // Canvas, where all of other canvas will be merged\n private Bitmap mBitmap;\n private Canvas mCanvas;\n\n // Canvas with icons\n private Bitmap mIconsBitmap;\n private Canvas mIconsCanvas;\n\n // Canvas for our rect pointer\n private Bitmap mPointerBitmap;\n private Canvas mPointerCanvas;\n\n // Main paint\n private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setStyle(Style.FILL);\n }\n };\n\n // Pointer paint\n private Paint mPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));\n }\n };\n\n // Icons paint\n private Paint mIconPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n }\n };\n\n // Paint for icon mask pointer\n final Paint mIconPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setStyle(Style.FILL);\n setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));\n }\n };\n\n // Paint for model title\n final Paint mModelTitlePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setColor(Color.WHITE);\n setTextAlign(Align.CENTER);\n }\n };\n\n // Paint for badge\n final Paint mBadgePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setTextAlign(Align.CENTER);\n setFakeBoldText(true);\n }\n };\n\n // Variables for animator\n private ValueAnimator mAnimator = new ValueAnimator();\n private ResizeInterpolator mResizeInterpolator = new ResizeInterpolator();\n private int mAnimationDuration;\n\n // NTP models\n private ArrayList mModels = new ArrayList<>();\n\n // Variables for ViewPager\n private ViewPager mViewPager;\n private ViewPager.OnPageChangeListener mOnPageChangeListener;\n private int mScrollState;\n\n // Tab listener\n private OnTabBarSelectedIndexListener mOnTabBarSelectedIndexListener;\n private ValueAnimator.AnimatorListener mAnimatorListener;\n\n // Variables for sizes\n private float mModelSize;\n private int mIconSize;\n // Corners radius for rect mode\n private float mCornersRadius;\n\n // Model title size and margin\n private float mModelTitleSize;\n private float mTitleMargin;\n\n // Model badge title size and margin\n private float mBadgeMargin;\n private float mBadgeTitleSize;\n\n // Model title mode: active ar all\n private TitleMode mTitleMode;\n // Model badge position: left, center or right\n private BadgePosition mBadgePosition;\n // Model badge gravity: top or bottom\n private BadgeGravity mBadgeGravity;\n\n // Indexes\n private int mLastIndex = INVALID_INDEX;\n private int mIndex = INVALID_INDEX;\n // General fraction value\n private float mFraction;\n\n // Coordinates of pointer\n private float mStartPointerX;\n private float mEndPointerX;\n private float mPointerLeftTop;\n private float mPointerRightBottom;\n\n // Detect if model has title\n private boolean mIsTitled;\n // Detect if model has badge\n private boolean mIsBadged;\n // Detect if model badge have custom typeface\n private boolean mIsBadgeUseTypeface;\n // Detect if is bar mode or indicator pager mode\n private boolean mIsViewPagerMode;\n // Detect whether the horizontal orientation\n private boolean mIsHorizontalOrientation;\n // Detect if we move from left to right\n private boolean mIsResizeIn;\n // Detect if we get action down event\n private boolean mIsActionDown;\n // Detect if we get action down event on pointer\n private boolean mIsPointerActionDown;\n // Detect when we set index from tab bar nor from ViewPager\n private boolean mIsSetIndexFromTabBar;\n\n // Color variables\n private int mInactiveColor;\n private int mActiveColor;\n\n // Custom typeface\n private Typeface mTypeface;\n\n public NavigationTabBar(final Context context) {\n this(context, null);\n }\n\n public NavigationTabBar(final Context context, final AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public NavigationTabBar(final Context context, final AttributeSet attrs, final int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n //Init NTB\n\n // Always draw\n setWillNotDraw(false);\n // More speed!\n setLayerType(LAYER_TYPE_HARDWARE, null);\n\n final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationTabBar);\n try {\n setIsTitled(\n typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_titled, false)\n );\n setIsBadged(\n typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badged, false)\n );\n setIsBadgeUseTypeface(\n typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badge_use_typeface, false)\n );\n setTitleMode(\n typedArray.getInt(R.styleable.NavigationTabBar_ntb_title_mode, ALL_INDEX)\n );\n setBadgePosition(\n typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_position, RIGHT_INDEX)\n );\n setBadgeGravity(\n typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_gravity, TOP_INDEX)\n );\n setTypeface(\n typedArray.getString(R.styleable.NavigationTabBar_ntb_typeface)\n );\n setInactiveColor(\n typedArray.getColor(\n R.styleable.NavigationTabBar_ntb_inactive_color, DEFAULT_INACTIVE_COLOR\n )\n );\n setActiveColor(\n typedArray.getColor(\n R.styleable.NavigationTabBar_ntb_active_color, DEFAULT_ACTIVE_COLOR\n )\n );\n setAnimationDuration(\n typedArray.getInteger(\n R.styleable.NavigationTabBar_ntb_animation_duration, DEFAULT_ANIMATION_DURATION\n )\n );\n setCornersRadius(\n typedArray.getDimension(R.styleable.NavigationTabBar_ntb_corners_radius, 0.0f)\n );\n\n // Init animator\n mAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION);\n mAnimator.setInterpolator(new LinearInterpolator());\n mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n @Override\n public void onAnimationUpdate(final ValueAnimator animation) {\n updateIndicatorPosition((Float) animation.getAnimatedValue());\n }\n });\n\n // Set preview models\n if (isInEditMode()) {\n // Get preview colors\n String[] previewColors = null;\n try {\n final int previewColorsId = typedArray.getResourceId(\n R.styleable.NavigationTabBar_ntb_preview_colors, 0\n );\n previewColors = previewColorsId == 0 ? null :\n typedArray.getResources().getStringArray(previewColorsId);\n } catch (Exception exception) {\n previewColors = null;\n exception.printStackTrace();\n } finally {\n if (previewColors == null)\n previewColors = typedArray.getResources().getStringArray(R.array.default_preview);\n\n for (String previewColor : previewColors)\n mModels.add(new Model(null, Color.parseColor(previewColor)));\n requestLayout();\n }\n }\n } finally {\n typedArray.recycle();\n }\n }\n\n public int getAnimationDuration() {\n return mAnimationDuration;\n }\n\n public void setAnimationDuration(final int animationDuration) {\n mAnimationDuration = animationDuration;\n mAnimator.setDuration(mAnimationDuration);\n resetScroller();\n }\n\n public ArrayList getModels() {\n return mModels;\n }\n\n public void setModels(final ArrayList models) {\n //Set update listeners to badge model animation\n for (final Model model : models) {\n model.mBadgeAnimator.removeAllUpdateListeners();\n model.mBadgeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n @Override\n public void onAnimationUpdate(final ValueAnimator animation) {\n model.mBadgeFraction = (float) animation.getAnimatedValue();\n postInvalidate();\n }\n });\n }\n\n mModels.clear();\n mModels = models;\n requestLayout();\n }\n\n public boolean isTitled() {\n return mIsTitled;\n }\n\n public void setIsTitled(final boolean isTitled) {\n mIsTitled = isTitled;\n requestLayout();\n }\n\n public boolean isBadged() {\n return mIsBadged;\n }\n\n public void setIsBadged(final boolean isBadged) {\n mIsBadged = isBadged;\n requestLayout();\n }\n\n public boolean isBadgeUseTypeface() {\n return mIsBadgeUseTypeface;\n }\n\n public void setIsBadgeUseTypeface(final boolean isBadgeUseTypeface) {\n mIsBadgeUseTypeface = isBadgeUseTypeface;\n setBadgeTypeface();\n postInvalidate();\n }\n\n public TitleMode getTitleMode() {\n return mTitleMode;\n }\n\n private void setTitleMode(final int index) {\n switch (index) {\n case ACTIVE_INDEX:\n setTitleMode(TitleMode.ACTIVE);\n break;\n case ALL_INDEX:\n default:\n setTitleMode(TitleMode.ALL);\n }\n }\n\n public void setTitleMode(final TitleMode titleMode) {\n mTitleMode = titleMode;\n postInvalidate();\n }\n\n public BadgePosition getBadgePosition() {\n return mBadgePosition;\n }\n\n private void setBadgePosition(final int index) {\n switch (index) {\n case LEFT_INDEX:\n setBadgePosition(BadgePosition.LEFT);\n break;\n case CENTER_INDEX:\n setBadgePosition(BadgePosition.CENTER);\n break;\n case RIGHT_INDEX:\n default:\n setBadgePosition(BadgePosition.RIGHT);\n }\n }\n\n public void setBadgePosition(final BadgePosition badgePosition) {\n mBadgePosition = badgePosition;\n postInvalidate();\n }\n\n public BadgeGravity getBadgeGravity() {\n return mBadgeGravity;\n }\n\n private void setBadgeGravity(final int index) {\n switch (index) {\n case BOTTOM_INDEX:\n setBadgeGravity(BadgeGravity.BOTTOM);\n break;\n case TOP_INDEX:\n default:\n setBadgeGravity(BadgeGravity.TOP);\n }\n }\n\n public void setBadgeGravity(final BadgeGravity badgeGravity) {\n mBadgeGravity = badgeGravity;\n requestLayout();\n }\n\n public Typeface getTypeface() {\n return mTypeface;\n }\n\n public void setTypeface(final String typeface) {\n Typeface tempTypeface;\n try {\n tempTypeface = Typeface.createFromAsset(getContext().getAssets(), typeface);\n } catch (Exception e) {\n tempTypeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL);\n e.printStackTrace();\n }\n\n setTypeface(tempTypeface);\n }\n\n public void setTypeface(final Typeface typeface) {\n mTypeface = typeface;\n mModelTitlePaint.setTypeface(typeface);\n setBadgeTypeface();\n postInvalidate();\n }\n\n private void setBadgeTypeface() {\n mBadgePaint.setTypeface(\n mIsBadgeUseTypeface ? mTypeface : Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)\n );\n }\n\n public int getActiveColor() {\n return mActiveColor;\n }\n\n public void setActiveColor(final int activeColor) {\n mActiveColor = activeColor;\n mIconPointerPaint.setColor(activeColor);\n postInvalidate();\n }\n\n public int getInactiveColor() {\n return mInactiveColor;\n }\n\n public void setInactiveColor(final int inactiveColor) {\n mInactiveColor = inactiveColor;\n\n // Set color filter to wrap icons with inactive color\n mIconPaint.setColorFilter(new PorterDuffColorFilter(inactiveColor, PorterDuff.Mode.SRC_IN));\n mModelTitlePaint.setColor(mInactiveColor);\n postInvalidate();\n }\n\n public float getCornersRadius() {\n return mCornersRadius;\n }\n\n public void setCornersRadius(final float cornersRadius) {\n mCornersRadius = cornersRadius;\n postInvalidate();\n }\n\n public float getBadgeMargin() {\n return mBadgeMargin;\n }\n\n public float getBarHeight() {\n return mBounds.height();\n }\n\n public OnTabBarSelectedIndexListener getOnTabBarSelectedIndexListener() {\n return mOnTabBarSelectedIndexListener;\n }\n\n // Set on tab bar selected index listener where you can trigger action onStart or onEnd\n public void setOnTabBarSelectedIndexListener(final OnTabBarSelectedIndexListener onTabBarSelectedIndexListener) {\n mOnTabBarSelectedIndexListener = onTabBarSelectedIndexListener;\n\n if (mAnimatorListener == null)\n mAnimatorListener = new Animator.AnimatorListener() {\n @Override\n public void onAnimationStart(final Animator animation) {\n if (mOnTabBarSelectedIndexListener != null)\n mOnTabBarSelectedIndexListener.onStartTabSelected(mModels.get(mIndex), mIndex);\n }\n\n @Override\n public void onAnimationEnd(final Animator animation) {\n if (mOnTabBarSelectedIndexListener != null)\n mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex);\n }\n\n @Override\n public void onAnimationCancel(final Animator animation) {\n\n }\n\n @Override\n public void onAnimationRepeat(final Animator animation) {\n\n }\n };\n mAnimator.removeListener(mAnimatorListener);\n mAnimator.addListener(mAnimatorListener);\n }\n\n public void setViewPager(final ViewPager viewPager) {\n // Detect whether ViewPager mode\n if (viewPager == null) {\n mIsViewPagerMode = false;\n return;\n }\n\n if (mViewPager == viewPager) return;\n if (mViewPager != null) mViewPager.setOnPageChangeListener(null);\n if (viewPager.getAdapter() == null)\n throw new IllegalStateException(\"ViewPager does not provide adapter instance.\");\n\n mIsViewPagerMode = true;\n mViewPager = viewPager;\n mViewPager.addOnPageChangeListener(this);\n\n resetScroller();\n postInvalidate();\n }\n\n public void setViewPager(final ViewPager viewPager, int index) {\n setViewPager(viewPager);\n\n mIndex = index;\n if (mIsViewPagerMode) mViewPager.setCurrentItem(index, true);\n postInvalidate();\n }\n\n // Reset scroller and reset scroll duration equals to animation duration\n private void resetScroller() {\n if (mViewPager == null) return;\n try {\n final Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n final ResizeViewPagerScroller scroller = new ResizeViewPagerScroller(getContext());\n scrollerField.set(mViewPager, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void setOnPageChangeListener(final ViewPager.OnPageChangeListener listener) {\n mOnPageChangeListener = listener;\n }\n\n public int getModelIndex() {\n return mIndex;\n }\n\n public void setModelIndex(int index) {\n setModelIndex(index, false);\n }\n\n // Set model index from touch or programmatically\n public void setModelIndex(int index, boolean force) {\n if (mAnimator.isRunning()) return;\n if (mModels.isEmpty()) return;\n\n // This check gives us opportunity to have an non selected model\n if (mIndex == INVALID_INDEX) force = true;\n\n // Detect if last is the same\n if (index == mIndex) return;\n\n // Snap index to models size\n index = Math.max(0, Math.min(index, mModels.size() - 1));\n\n mIsResizeIn = index < mIndex;\n mLastIndex = mIndex;\n mIndex = index;\n\n mIsSetIndexFromTabBar = true;\n if (mIsViewPagerMode) {\n if (mViewPager == null) throw new IllegalStateException(\"ViewPager is null.\");\n mViewPager.setCurrentItem(index, true);\n }\n\n // Set startX and endX for animation, where we animate two sides of rect with different interpolation\n mStartPointerX = mPointerLeftTop;\n mEndPointerX = mIndex * mModelSize;\n\n // If it force, so update immediately, else animate\n // This happens if we set index onCreate or something like this\n // You can use force param or call this method in some post()\n if (force) updateIndicatorPosition(MAX_FRACTION);\n else mAnimator.start();\n }\n\n private void updateIndicatorPosition(final float fraction) {\n // Update general fraction\n mFraction = fraction;\n\n // Set the pointer left top side coordinate\n mPointerLeftTop =\n mStartPointerX + (mResizeInterpolator.getResizeInterpolation(fraction, mIsResizeIn) *\n (mEndPointerX - mStartPointerX));\n // Set the pointer right bottom side coordinate\n mPointerRightBottom =\n (mStartPointerX + mModelSize) +\n (mResizeInterpolator.getResizeInterpolation(fraction, !mIsResizeIn) *\n (mEndPointerX - mStartPointerX));\n\n // Update pointer\n postInvalidate();\n }\n\n // Update NTP\n private void notifyDataSetChanged() {\n postInvalidate();\n }\n\n @Override\n public boolean onTouchEvent(final MotionEvent event) {\n // Return if animation is running\n if (mAnimator.isRunning()) return true;\n // If is not idle state, return\n if (mScrollState != ViewPager.SCROLL_STATE_IDLE) return true;\n\n switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n // Action down touch\n mIsActionDown = true;\n if (!mIsViewPagerMode) break;\n // Detect if we touch down on pointer, later to move\n if (mIsHorizontalOrientation)\n mIsPointerActionDown = (int) (event.getX() / mModelSize) == mIndex;\n else\n mIsPointerActionDown = (int) (event.getY() / mModelSize) == mIndex;\n break;\n case MotionEvent.ACTION_MOVE:\n // If pointer touched, so move\n if (mIsPointerActionDown) {\n if (mIsHorizontalOrientation)\n mViewPager.setCurrentItem((int) (event.getX() / mModelSize), true);\n else\n mViewPager.setCurrentItem((int) (event.getY() / mModelSize), true);\n break;\n }\n if (mIsActionDown) break;\n case MotionEvent.ACTION_UP:\n // Press up and set model index relative to current coordinate\n if (mIsActionDown) {\n if (mIsHorizontalOrientation) setModelIndex((int) (event.getX() / mModelSize));\n else setModelIndex((int) (event.getY() / mModelSize));\n }\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_OUTSIDE:\n default:\n // Reset action touch variables\n mIsPointerActionDown = false;\n mIsActionDown = false;\n break;\n }\n\n return true;\n }\n\n @Override\n protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n\n // Get measure size\n final int width = MeasureSpec.getSize(widthMeasureSpec);\n final int height = MeasureSpec.getSize(heightMeasureSpec);\n\n if (mModels.isEmpty() || width == 0 || height == 0) return;\n\n // Detect orientation and calculate icon size\n if (width > height) {\n mIsHorizontalOrientation = true;\n\n // Get smaller side\n float side = mModelSize > height ? height : mModelSize;\n if (mIsBadged) side -= side * TITLE_SIZE_FRACTION;\n\n mModelSize = (float) width / (float) mModels.size();\n mIconSize = (int) (side * (mIsTitled ? TITLE_ICON_SIZE_FRACTION : ICON_SIZE_FRACTION));\n\n mModelTitleSize = side * TITLE_SIZE_FRACTION;\n mTitleMargin = side * TITLE_MARGIN_FRACTION;\n\n // If is badged mode, so get vars and set paint with default bounds\n if (mIsBadged) {\n mBadgeTitleSize = mModelTitleSize * BADGE_TITLE_SIZE_FRACTION;\n\n final Rect badgeBounds = new Rect();\n mBadgePaint.setTextSize(mBadgeTitleSize);\n mBadgePaint.getTextBounds(PREVIEW_BADGE, 0, 1, badgeBounds);\n mBadgeMargin = (badgeBounds.height() * 0.5f) +\n (mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION * BADGE_VERTICAL_FRACTION);\n }\n } else {\n mIsHorizontalOrientation = false;\n mIsTitled = false;\n mIsBadged = false;\n\n mModelSize = (float) height / (float) mModels.size();\n mIconSize = (int) ((mModelSize > width ? width : mModelSize) * ICON_SIZE_FRACTION);\n }\n\n // Set bounds for NTB\n mBounds.set(0.0f, 0.0f, width, height - mBadgeMargin);\n\n // Set main bitmap\n mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n mCanvas = new Canvas(mBitmap);\n\n // Set pointer canvas\n mPointerBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n mPointerCanvas = new Canvas(mPointerBitmap);\n\n // Set icons canvas\n mIconsBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n mIconsCanvas = new Canvas(mIconsBitmap);\n\n // Set scale fraction for icons\n for (Model model : mModels) {\n final float originalIconSize = model.mIcon.getWidth() > model.mIcon.getHeight() ?\n model.mIcon.getWidth() : model.mIcon.getHeight();\n model.mInactiveIconScale = (float) mIconSize / originalIconSize;\n model.mActiveIconScaleBy = model.mInactiveIconScale *\n (mIsTitled ? TITLE_ACTIVE_ICON_SCALE_BY : ACTIVE_ICON_SCALE_BY);\n }\n\n // Set start position of pointer for preview or on start\n if (isInEditMode() || !mIsViewPagerMode) {\n mIsSetIndexFromTabBar = true;\n\n // Set random in preview mode\n if (isInEditMode()) {\n mIndex = new Random().nextInt(mModels.size());\n\n if (mIsBadged)\n for (int i = 0; i < mModels.size(); i++) {\n final Model model = mModels.get(i);\n\n if (i == mIndex) {\n model.mBadgeFraction = MAX_FRACTION;\n model.showBadge();\n } else {\n model.mBadgeFraction = MIN_FRACTION;\n model.hideBadge();\n }\n }\n }\n\n mStartPointerX = mIndex * mModelSize;\n mEndPointerX = mStartPointerX;\n updateIndicatorPosition(MAX_FRACTION);\n }\n }\n\n @Override\n protected void onDraw(final Canvas canvas) {\n if (mCanvas == null || mPointerCanvas == null || mIconsCanvas == null) return;\n\n // Reset and clear canvases\n mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);\n mPointerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);\n mIconsCanvas.drawColor(0, PorterDuff.Mode.CLEAR);\n\n // Get pointer badge margin for gravity\n final float pointerBadgeMargin = mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : 0.0f;\n\n // Draw our model colors\n for (int i = 0; i < mModels.size(); i++) {\n mPaint.setColor(mModels.get(i).getColor());\n\n if (mIsHorizontalOrientation) {\n final float left = mModelSize * i;\n final float right = left + mModelSize;\n mCanvas.drawRect(\n left, pointerBadgeMargin, right, mBounds.height() + pointerBadgeMargin, mPaint\n );\n } else {\n final float top = mModelSize * i;\n final float bottom = top + mModelSize;\n mCanvas.drawRect(0.0f, top, mBounds.width(), bottom, mPaint);\n }\n }\n\n // Set bound of pointer\n if (mIsHorizontalOrientation)\n mPointerBounds.set(\n mPointerLeftTop, pointerBadgeMargin,\n mPointerRightBottom, mBounds.height() + pointerBadgeMargin\n );\n else mPointerBounds.set(0.0f, mPointerLeftTop, mBounds.width(), mPointerRightBottom);\n\n // Draw pointer for model colors\n if (mCornersRadius == 0) mPointerCanvas.drawRect(mPointerBounds, mPaint);\n else mPointerCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mPaint);\n\n // Draw pointer into main canvas\n mCanvas.drawBitmap(mPointerBitmap, 0.0f, 0.0f, mPointerPaint);\n\n // Draw model icons\n for (int i = 0; i < mModels.size(); i++) {\n final Model model = mModels.get(i);\n\n // Variables to center our icons\n final float leftOffset;\n final float topOffset;\n final float matrixCenterX;\n final float matrixCenterY;\n\n // Set vars for icon when model with title or without\n final float iconMarginTitleHeight = mIconSize + mTitleMargin + mModelTitleSize;\n final float leftTitleOffset = (mModelSize * i) + (mModelSize * 0.5f);\n final float topTitleOffset =\n mBounds.height() - (mBounds.height() - iconMarginTitleHeight) * 0.5f;\n\n if (mIsHorizontalOrientation) {\n leftOffset = (mModelSize * i) + (mModelSize - model.mIcon.getWidth()) * 0.5f;\n topOffset = (mBounds.height() - model.mIcon.getHeight()) * 0.5f;\n\n matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f;\n matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f +\n (mIsTitled && mTitleMode == TitleMode.ALL ? mTitleMargin * 0.5f : 0.0f);\n } else {\n leftOffset = (mBounds.width() - model.mIcon.getWidth()) * 0.5f;\n topOffset = (mModelSize * i) + (mModelSize - model.mIcon.getHeight()) * 0.5f;\n\n matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f;\n matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f;\n }\n\n // Title translate position\n final float titleTranslate = -model.mIcon.getHeight() + topTitleOffset - mTitleMargin * 0.5f;\n\n // Translate icon to model center\n model.mIconMatrix.setTranslate(\n leftOffset,\n (mIsTitled && mTitleMode == TitleMode.ALL) ? titleTranslate : topOffset\n );\n\n // Get interpolated fraction for left last and current models\n final float interpolation = mResizeInterpolator.getResizeInterpolation(mFraction, true);\n final float lastInterpolation = mResizeInterpolator.getResizeInterpolation(mFraction, false);\n\n // Scale value relative to interpolation\n final float matrixScale = model.mActiveIconScaleBy * interpolation;\n final float matrixLastScale = model.mActiveIconScaleBy * lastInterpolation;\n\n // Get title alpha relative to interpolation\n final int titleAlpha = (int) (MAX_ALPHA * interpolation);\n final int titleLastAlpha = MAX_ALPHA - (int) (MAX_ALPHA * lastInterpolation);\n // Get title scale relative to interpolation\n final float titleScale = MAX_FRACTION + (interpolation * TITLE_ACTIVE_SCALE_BY);\n final float titleLastScale = (MAX_FRACTION + TITLE_ACTIVE_SCALE_BY) -\n (lastInterpolation * TITLE_ACTIVE_SCALE_BY);\n\n // Check if we handle models from touch on NTP or from ViewPager\n // There is a strange logic of ViewPager onPageScrolled method, so it is\n if (mIsSetIndexFromTabBar) {\n if (mIndex == i)\n updateCurrentModel(\n model, leftOffset, topOffset, titleTranslate, interpolation,\n matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha\n );\n else if (mLastIndex == i)\n updateLastModel(\n model, leftOffset, topOffset, titleTranslate, lastInterpolation,\n matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha\n );\n else\n updateInactiveModel(\n model, leftOffset, topOffset, matrixCenterX, matrixCenterY\n );\n } else {\n if (i != mIndex && i != mIndex + 1)\n updateInactiveModel(\n model, leftOffset, topOffset, matrixCenterX, matrixCenterY\n );\n else if (i == mIndex + 1)\n updateCurrentModel(\n model, leftOffset, topOffset, titleTranslate, interpolation,\n matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha\n );\n else if (i == mIndex)\n updateLastModel(\n model, leftOffset, topOffset, titleTranslate, lastInterpolation,\n matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha\n );\n }\n\n // Draw model icon\n mIconsCanvas.drawBitmap(model.mIcon, model.mIconMatrix, mIconPaint);\n if (mIsTitled)\n mIconsCanvas.drawText(\n isInEditMode() ? PREVIEW_TITLE : model.getTitle(),\n leftTitleOffset, topTitleOffset, mModelTitlePaint\n );\n }\n\n // Draw pointer with active color to wrap out active icon\n if (mCornersRadius == 0) mIconsCanvas.drawRect(mPointerBounds, mIconPointerPaint);\n else mIconsCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mIconPointerPaint);\n\n // Draw general bitmap\n canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);\n // Draw icons bitmap on top\n canvas.drawBitmap( mIconsBitmap, 0.0f, pointerBadgeMargin, null);\n\n // If is not badged, exit\n if (!mIsBadged) return;\n\n // Model badge margin and offset relative to gravity mode\n final float modelBadgeMargin =\n mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : mBounds.height();\n final float modelBadgeOffset =\n mBadgeGravity == BadgeGravity.TOP ? 0.0f : mBounds.height() - mBadgeMargin;\n\n for (int i = 0; i < mModels.size(); i++) {\n final Model model = mModels.get(i);\n\n // Set preview badge title\n if (isInEditMode() || TextUtils.isEmpty(model.getBadgeTitle()))\n model.setBadgeTitle(PREVIEW_BADGE);\n\n // Set badge title bounds\n mBadgePaint.setTextSize(mBadgeTitleSize * model.mBadgeFraction);\n mBadgePaint.getTextBounds(\n model.getBadgeTitle(), 0, model.getBadgeTitle().length(), mBadgeBounds\n );\n\n // Get horizontal and vertical padding for bg\n final float horizontalPadding = mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION;\n final float verticalPadding = horizontalPadding * BADGE_VERTICAL_FRACTION;\n\n // Set horizontal badge offset\n final float badgeBoundsHorizontalOffset =\n (mModelSize * i) + (mModelSize * mBadgePosition.mPositionFraction);\n\n // If is badge title only one char, so create circle else round rect\n if (model.getBadgeTitle().length() == 1) {\n final float badgeMargin = mBadgeMargin * model.mBadgeFraction;\n mBgBadgeBounds.set(\n badgeBoundsHorizontalOffset - badgeMargin, modelBadgeMargin - badgeMargin,\n badgeBoundsHorizontalOffset + badgeMargin, modelBadgeMargin + badgeMargin\n );\n } else\n mBgBadgeBounds.set(\n badgeBoundsHorizontalOffset - mBadgeBounds.centerX() - horizontalPadding,\n modelBadgeMargin - (mBadgeMargin * model.mBadgeFraction),\n badgeBoundsHorizontalOffset + mBadgeBounds.centerX() + horizontalPadding,\n modelBadgeOffset + (verticalPadding * 2.0f) + mBadgeBounds.height()\n );\n\n // Set color and alpha for badge bg\n if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT);\n else mBadgePaint.setColor(mActiveColor);\n mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction));\n\n // Set corners to round rect for badge bg and draw\n final float cornerRadius = mBgBadgeBounds.height() * 0.5f;\n canvas.drawRoundRect(mBgBadgeBounds, cornerRadius, cornerRadius, mBadgePaint);\n\n // Set color and alpha for badge title\n if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT);\n else mBadgePaint.setColor(model.getColor());\n mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction));\n\n // Set badge title center position and draw title\n final float badgeHalfHeight = mBadgeBounds.height() * 0.5f;\n float badgeVerticalOffset = (mBgBadgeBounds.height() * 0.5f) + badgeHalfHeight -\n mBadgeBounds.bottom + modelBadgeOffset;\n canvas.drawText(\n model.getBadgeTitle(), badgeBoundsHorizontalOffset, badgeVerticalOffset +\n mBadgeBounds.height() - (mBadgeBounds.height() * model.mBadgeFraction),\n mBadgePaint\n );\n }\n }\n\n // Method to transform current fraction of NTB and position\n private void updateCurrentModel(\n final Model model,\n final float leftOffset,\n final float topOffset,\n final float titleTranslate,\n final float interpolation,\n final float matrixCenterX,\n final float matrixCenterY,\n final float matrixScale,\n final float textScale,\n final int textAlpha\n ) {\n if (mIsTitled && mTitleMode == TitleMode.ACTIVE)\n model.mIconMatrix.setTranslate(\n leftOffset, topOffset - (interpolation * (topOffset - titleTranslate))\n );\n\n model.mIconMatrix.postScale(\n model.mInactiveIconScale + matrixScale, model.mInactiveIconScale + matrixScale,\n matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ?\n mTitleMargin * 0.5f * interpolation : 0.0f)\n );\n\n mModelTitlePaint.setTextSize(mModelTitleSize * textScale);\n if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textAlpha);\n }\n\n // Method to transform last fraction of NTB and position\n private void updateLastModel(\n final Model model,\n final float leftOffset,\n final float topOffset,\n final float titleTranslate,\n final float lastInterpolation,\n final float matrixCenterX,\n final float matrixCenterY,\n final float matrixLastScale,\n final float textLastScale,\n final int textLastAlpha\n ) {\n if (mIsTitled && mTitleMode == TitleMode.ACTIVE)\n model.mIconMatrix.setTranslate(\n leftOffset, titleTranslate + (lastInterpolation * (topOffset - titleTranslate))\n );\n\n model.mIconMatrix.postScale(\n model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale,\n model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale,\n matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ?\n mTitleMargin * 0.5f - (mTitleMargin * 0.5f * lastInterpolation) : 0.0f)\n );\n\n mModelTitlePaint.setTextSize(mModelTitleSize * textLastScale);\n if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textLastAlpha);\n }\n\n // Method to transform others fraction of NTB and position\n private void updateInactiveModel(\n final Model model,\n final float leftOffset,\n final float topOffset,\n final float matrixCenterX,\n final float matrixCenterY\n ) {\n if (mIsTitled && mTitleMode == TitleMode.ACTIVE)\n model.mIconMatrix.setTranslate(leftOffset, topOffset);\n\n model.mIconMatrix.postScale(\n model.mInactiveIconScale, model.mInactiveIconScale, matrixCenterX, matrixCenterY\n );\n\n mModelTitlePaint.setTextSize(mModelTitleSize);\n if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(MIN_ALPHA);\n }\n\n @Override\n public void onPageScrolled(int position, float positionOffset, final int positionOffsetPixels) {\n // If we animate, don`t call this\n if (!mIsSetIndexFromTabBar) {\n mIsResizeIn = position < mIndex;\n mLastIndex = mIndex;\n mIndex = position;\n\n mStartPointerX = position * mModelSize;\n mEndPointerX = mStartPointerX + mModelSize;\n updateIndicatorPosition(positionOffset);\n }\n\n if (mOnPageChangeListener != null)\n mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);\n }\n\n @Override\n public void onPageSelected(final int position) {\n // If VP idle, so update\n if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n mIsResizeIn = position < mIndex;\n mLastIndex = mIndex;\n mIndex = position;\n postInvalidate();\n }\n }\n\n @Override\n public void onPageScrollStateChanged(final int state) {\n // If VP idle, reset to MIN_FRACTION\n if (state == ViewPager.SCROLL_STATE_IDLE) {\n mFraction = MIN_FRACTION;\n mIsSetIndexFromTabBar = false;\n\n if (mOnPageChangeListener != null) mOnPageChangeListener.onPageSelected(mIndex);\n else {\n if (mOnTabBarSelectedIndexListener != null)\n mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex);\n }\n }\n mScrollState = state;\n\n if (mOnPageChangeListener != null) mOnPageChangeListener.onPageScrollStateChanged(state);\n }\n\n @Override\n public void onRestoreInstanceState(Parcelable state) {\n final SavedState savedState = (SavedState) state;\n super.onRestoreInstanceState(savedState.getSuperState());\n mIndex = savedState.index;\n requestLayout();\n }\n\n @Override\n public Parcelable onSaveInstanceState() {\n final Parcelable superState = super.onSaveInstanceState();\n final SavedState savedState = new SavedState(superState);\n savedState.index = mIndex;\n return savedState;\n }\n\n static class SavedState extends BaseSavedState {\n int index;\n\n public SavedState(Parcelable superState) {\n super(superState);\n }\n\n private SavedState(Parcel in) {\n super(in);\n index = in.readInt();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeInt(index);\n }\n\n @SuppressWarnings(\"UnusedDeclaration\")\n public static final Creator CREATOR = new Creator() {\n @Override\n public SavedState createFromParcel(Parcel in) {\n return new SavedState(in);\n }\n\n @Override\n public SavedState[] newArray(int size) {\n return new SavedState[size];\n }\n };\n }\n\n // Model class\n public static class Model {\n\n private String mTitle = \"\";\n private int mColor;\n\n private Bitmap mIcon;\n private Matrix mIconMatrix = new Matrix();\n\n private String mBadgeTitle = \"\";\n private String mTempBadgeTitle = \"\";\n private float mBadgeFraction;\n\n private boolean mIsBadgeShowed;\n private boolean mIsBadgeUpdated;\n\n private ValueAnimator mBadgeAnimator = new ValueAnimator();\n\n private float mInactiveIconScale;\n private float mActiveIconScaleBy;\n\n public Model(final Drawable icon, final int color) {\n mColor = color;\n if (icon != null) {\n if(icon instanceof BitmapDrawable) {\n mIcon = ((BitmapDrawable) icon).getBitmap();\n } else {\n mIcon = Bitmap.createBitmap(icon.getIntrinsicWidth(),icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);\n Canvas canvas = new Canvas(mIcon);\n icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n icon.draw(canvas);\n }\n } else {\n mIcon = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);\n }\n mBadgeAnimator.addListener(new Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(final Animator animation) {\n }\n\n @Override\n public void onAnimationEnd(final Animator animation) {\n // Detect whether we just update text and don`t reset show state\n if (!mIsBadgeUpdated) mIsBadgeShowed = !mIsBadgeShowed;\n else mIsBadgeUpdated = false;\n }\n\n @Override\n public void onAnimationCancel(final Animator animation) {\n\n }\n\n @Override\n public void onAnimationRepeat(final Animator animation) {\n // Change title when we update and don`t see the title\n if (mIsBadgeUpdated) mBadgeTitle = mTempBadgeTitle;\n }\n });\n }\n\n public Model(final Drawable icon, final int color, final String title) {\n this(icon, color);\n mTitle = title;\n }\n\n public Model(final Drawable icon, final int color, final String title, final String badgeTitle) {\n this(icon, color, title);\n mBadgeTitle = badgeTitle;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public void setTitle(final String title) {\n mTitle = title;\n }\n\n public int getColor() {\n return mColor;\n }\n\n public void setColor(final int color) {\n mColor = color;\n }\n\n public boolean isBadgeShowed() {\n return mIsBadgeShowed;\n }\n\n public String getBadgeTitle() {\n return mBadgeTitle;\n }\n\n public void setBadgeTitle(final String badgeTitle) {\n mBadgeTitle = badgeTitle;\n }\n\n // If your badge is visible on screen, so you can update title with animation\n public void updateBadgeTitle(final String badgeTitle) {\n if (!mIsBadgeShowed) return;\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n\n mTempBadgeTitle = badgeTitle;\n mIsBadgeUpdated = true;\n\n mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION);\n mBadgeAnimator.setDuration(DEFAULT_BADGE_REFRESH_ANIMATION_DURATION);\n mBadgeAnimator.setRepeatMode(ValueAnimator.REVERSE);\n mBadgeAnimator.setRepeatCount(1);\n mBadgeAnimator.start();\n }\n\n public void toggleBadge() {\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n if (mIsBadgeShowed) hideBadge();\n else showBadge();\n }\n\n public void showBadge() {\n mIsBadgeUpdated = false;\n\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n if (mIsBadgeShowed) return;\n\n mBadgeAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION);\n mBadgeAnimator.setInterpolator(DECELERATE_INTERPOLATOR);\n mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION);\n mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART);\n mBadgeAnimator.setRepeatCount(0);\n mBadgeAnimator.start();\n }\n\n public void hideBadge() {\n mIsBadgeUpdated = false;\n\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n if (!mIsBadgeShowed) return;\n\n mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION);\n mBadgeAnimator.setInterpolator(ACCELERATE_INTERPOLATOR);\n mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION);\n mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART);\n mBadgeAnimator.setRepeatCount(0);\n mBadgeAnimator.start();\n }\n }\n\n // Custom scroller with custom scroll duration\n private class ResizeViewPagerScroller extends Scroller {\n\n public ResizeViewPagerScroller(Context context) {\n super(context, new AccelerateDecelerateInterpolator());\n }\n\n @Override\n public void startScroll(int startX, int startY, int dx, int dy, int duration) {\n super.startScroll(startX, startY, dx, dy, mAnimationDuration);\n }\n\n @Override\n public void startScroll(int startX, int startY, int dx, int dy) {\n super.startScroll(startX, startY, dx, dy, mAnimationDuration);\n }\n }\n\n // Resize interpolator to create smooth effect on pointer according to inspiration design\n // This is like improved accelerated and decelerated interpolator\n private class ResizeInterpolator implements Interpolator {\n\n // Spring factor\n private final float mFactor = 1.0f;\n // Check whether side we move\n private boolean mResizeIn;\n\n @Override\n public float getInterpolation(final float input) {\n if (mResizeIn) return (float) (1.0f - Math.pow((1.0f - input), 2.0f * mFactor));\n else return (float) (Math.pow(input, 2.0f * mFactor));\n }\n\n public float getResizeInterpolation(final float input, final boolean resizeIn) {\n mResizeIn = resizeIn;\n return getInterpolation(input);\n }\n }\n\n // Model title mode\n public enum TitleMode {\n ALL, ACTIVE\n }\n\n // Model badge position\n public enum BadgePosition {\n\n LEFT(LEFT_FRACTION), CENTER(CENTER_FRACTION), RIGHT(RIGHT_FRACTION);\n\n private float mPositionFraction;\n\n BadgePosition() {\n mPositionFraction = RIGHT_FRACTION;\n }\n\n BadgePosition(final float positionFraction) {\n mPositionFraction = positionFraction;\n }\n }\n\n // Model badge gravity\n public enum BadgeGravity {\n TOP, BOTTOM\n }\n\n // Out listener for selected index\n public interface OnTabBarSelectedIndexListener {\n void onStartTabSelected(final Model model, final int index);\n\n void onEndTabSelected(final Model model, final int index);\n }\n}\n"},"new_file":{"kind":"string","value":"library/src/main/java/com/gigamole/library/NavigationTabBar.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2015 Basil Miller\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.gigamole.library;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.PorterDuff;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.PorterDuffXfermode;\nimport android.graphics.Rect;\nimport android.graphics.RectF;\nimport android.graphics.Typeface;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.support.v4.view.ViewPager;\nimport android.text.TextPaint;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.animation.AccelerateDecelerateInterpolator;\nimport android.view.animation.AccelerateInterpolator;\nimport android.view.animation.DecelerateInterpolator;\nimport android.view.animation.Interpolator;\nimport android.view.animation.LinearInterpolator;\nimport android.widget.Scroller;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Random;\n\n/**\n * Created by GIGAMOLE on 24.03.2016.\n */\npublic class NavigationTabBar extends View implements ViewPager.OnPageChangeListener {\n\n // NTP constants\n private final static String PREVIEW_BADGE = \"0\";\n private final static String PREVIEW_TITLE = \"Title\";\n private final static int INVALID_INDEX = -1;\n\n private final static int DEFAULT_BADGE_ANIMATION_DURATION = 200;\n private final static int DEFAULT_BADGE_REFRESH_ANIMATION_DURATION = 100;\n private final static int DEFAULT_ANIMATION_DURATION = 300;\n private final static int DEFAULT_INACTIVE_COLOR = Color.parseColor(\"#9f90af\");\n private final static int DEFAULT_ACTIVE_COLOR = Color.WHITE;\n\n private final static float MIN_FRACTION = 0.0f;\n private final static float MAX_FRACTION = 1.0f;\n\n private final static int MIN_ALPHA = 0;\n private final static int MAX_ALPHA = 255;\n\n private final static float ACTIVE_ICON_SCALE_BY = 0.35f;\n private final static float ICON_SIZE_FRACTION = 0.4f;\n\n private final static float TITLE_ACTIVE_ICON_SCALE_BY = 0.25f;\n private final static float TITLE_ICON_SIZE_FRACTION = 0.4f;\n private final static float TITLE_ACTIVE_SCALE_BY = 0.2f;\n private final static float TITLE_SIZE_FRACTION = 0.2f;\n private final static float TITLE_MARGIN_FRACTION = 0.15f;\n\n private final static float BADGE_HORIZONTAL_FRACTION = 0.5f;\n private final static float BADGE_VERTICAL_FRACTION = 0.75f;\n private final static float BADGE_TITLE_SIZE_FRACTION = 0.85f;\n\n private final static int ALL_INDEX = 0;\n private final static int ACTIVE_INDEX = 1;\n\n private final static int LEFT_INDEX = 0;\n private final static int CENTER_INDEX = 1;\n private final static int RIGHT_INDEX = 2;\n\n private final static int TOP_INDEX = 0;\n private final static int BOTTOM_INDEX = 1;\n\n private final static float LEFT_FRACTION = 0.25f;\n private final static float CENTER_FRACTION = 0.5f;\n private final static float RIGHT_FRACTION = 0.75f;\n\n private final static Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator();\n private final static Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();\n\n // NTP and pointer bounds\n private RectF mBounds = new RectF();\n private RectF mPointerBounds = new RectF();\n // Badge bounds and bg badge bounds\n final Rect mBadgeBounds = new Rect();\n final RectF mBgBadgeBounds = new RectF();\n\n // Canvas, where all of other canvas will be merged\n private Bitmap mBitmap;\n private Canvas mCanvas;\n\n // Canvas with icons\n private Bitmap mIconsBitmap;\n private Canvas mIconsCanvas;\n\n // Canvas for our rect pointer\n private Bitmap mPointerBitmap;\n private Canvas mPointerCanvas;\n\n // Main paint\n private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setStyle(Style.FILL);\n }\n };\n\n // Pointer paint\n private Paint mPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));\n }\n };\n\n // Icons paint\n private Paint mIconPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n }\n };\n\n // Paint for icon mask pointer\n final Paint mIconPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {\n {\n setStyle(Style.FILL);\n setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));\n }\n };\n\n // Paint for model title\n final Paint mModelTitlePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setColor(Color.WHITE);\n setTextAlign(Align.CENTER);\n }\n };\n\n // Paint for badge\n final Paint mBadgePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) {\n {\n setDither(true);\n setTextAlign(Align.CENTER);\n setFakeBoldText(true);\n }\n };\n\n // Variables for animator\n private ValueAnimator mAnimator = new ValueAnimator();\n private ResizeInterpolator mResizeInterpolator = new ResizeInterpolator();\n private int mAnimationDuration;\n\n // NTP models\n private ArrayList mModels = new ArrayList<>();\n\n // Variables for ViewPager\n private ViewPager mViewPager;\n private ViewPager.OnPageChangeListener mOnPageChangeListener;\n private int mScrollState;\n\n // Tab listener\n private OnTabBarSelectedIndexListener mOnTabBarSelectedIndexListener;\n private ValueAnimator.AnimatorListener mAnimatorListener;\n\n // Variables for sizes\n private float mModelSize;\n private int mIconSize;\n // Corners radius for rect mode\n private float mCornersRadius;\n\n // Model title size and margin\n private float mModelTitleSize;\n private float mTitleMargin;\n\n // Model badge title size and margin\n private float mBadgeMargin;\n private float mBadgeTitleSize;\n\n // Model title mode: active ar all\n private TitleMode mTitleMode;\n // Model badge position: left, center or right\n private BadgePosition mBadgePosition;\n // Model badge gravity: top or bottom\n private BadgeGravity mBadgeGravity;\n\n // Indexes\n private int mLastIndex = INVALID_INDEX;\n private int mIndex = INVALID_INDEX;\n // General fraction value\n private float mFraction;\n\n // Coordinates of pointer\n private float mStartPointerX;\n private float mEndPointerX;\n private float mPointerLeftTop;\n private float mPointerRightBottom;\n\n // Detect if model has title\n private boolean mIsTitled;\n // Detect if model has badge\n private boolean mIsBadged;\n // Detect if model badge have custom typeface\n private boolean mIsBadgeUseTypeface;\n // Detect if is bar mode or indicator pager mode\n private boolean mIsViewPagerMode;\n // Detect whether the horizontal orientation\n private boolean mIsHorizontalOrientation;\n // Detect if we move from left to right\n private boolean mIsResizeIn;\n // Detect if we get action down event\n private boolean mIsActionDown;\n // Detect if we get action down event on pointer\n private boolean mIsPointerActionDown;\n // Detect when we set index from tab bar nor from ViewPager\n private boolean mIsSetIndexFromTabBar;\n\n // Color variables\n private int mInactiveColor;\n private int mActiveColor;\n\n // Custom typeface\n private Typeface mTypeface;\n\n public NavigationTabBar(final Context context) {\n this(context, null);\n }\n\n public NavigationTabBar(final Context context, final AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public NavigationTabBar(final Context context, final AttributeSet attrs, final int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n //Init NTB\n\n // Always draw\n setWillNotDraw(false);\n // More speed!\n setLayerType(LAYER_TYPE_HARDWARE, null);\n\n final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationTabBar);\n try {\n setIsTitled(\n typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_titled, false)\n );\n setIsBadged(\n typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badged, false)\n );\n setIsBadgeUseTypeface(\n typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badge_use_typeface, false)\n );\n setTitleMode(\n typedArray.getInt(R.styleable.NavigationTabBar_ntb_title_mode, ALL_INDEX)\n );\n setBadgePosition(\n typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_position, RIGHT_INDEX)\n );\n setBadgeGravity(\n typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_gravity, TOP_INDEX)\n );\n setTypeface(\n typedArray.getString(R.styleable.NavigationTabBar_ntb_typeface)\n );\n setInactiveColor(\n typedArray.getColor(\n R.styleable.NavigationTabBar_ntb_inactive_color, DEFAULT_INACTIVE_COLOR\n )\n );\n setActiveColor(\n typedArray.getColor(\n R.styleable.NavigationTabBar_ntb_active_color, DEFAULT_ACTIVE_COLOR\n )\n );\n setAnimationDuration(\n typedArray.getInteger(\n R.styleable.NavigationTabBar_ntb_animation_duration, DEFAULT_ANIMATION_DURATION\n )\n );\n setCornersRadius(\n typedArray.getDimension(R.styleable.NavigationTabBar_ntb_corners_radius, 0.0f)\n );\n\n // Init animator\n mAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION);\n mAnimator.setInterpolator(new LinearInterpolator());\n mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n @Override\n public void onAnimationUpdate(final ValueAnimator animation) {\n updateIndicatorPosition((Float) animation.getAnimatedValue());\n }\n });\n\n // Set preview models\n if (isInEditMode()) {\n // Get preview colors\n String[] previewColors = null;\n try {\n final int previewColorsId = typedArray.getResourceId(\n R.styleable.NavigationTabBar_ntb_preview_colors, 0\n );\n previewColors = previewColorsId == 0 ? null :\n typedArray.getResources().getStringArray(previewColorsId);\n } catch (Exception exception) {\n previewColors = null;\n exception.printStackTrace();\n } finally {\n if (previewColors == null)\n previewColors = typedArray.getResources().getStringArray(R.array.default_preview);\n\n for (String previewColor : previewColors)\n mModels.add(new Model(null, Color.parseColor(previewColor)));\n requestLayout();\n }\n }\n } finally {\n typedArray.recycle();\n }\n }\n\n public int getAnimationDuration() {\n return mAnimationDuration;\n }\n\n public void setAnimationDuration(final int animationDuration) {\n mAnimationDuration = animationDuration;\n mAnimator.setDuration(mAnimationDuration);\n resetScroller();\n }\n\n public ArrayList getModels() {\n return mModels;\n }\n\n public void setModels(final ArrayList models) {\n //Set update listeners to badge model animation\n for (final Model model : models) {\n model.mBadgeAnimator.removeAllUpdateListeners();\n model.mBadgeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n @Override\n public void onAnimationUpdate(final ValueAnimator animation) {\n model.mBadgeFraction = (float) animation.getAnimatedValue();\n postInvalidate();\n }\n });\n }\n\n mModels.clear();\n mModels = models;\n requestLayout();\n }\n\n public boolean isTitled() {\n return mIsTitled;\n }\n\n public void setIsTitled(final boolean isTitled) {\n mIsTitled = isTitled;\n requestLayout();\n }\n\n public boolean isBadged() {\n return mIsBadged;\n }\n\n public void setIsBadged(final boolean isBadged) {\n mIsBadged = isBadged;\n requestLayout();\n }\n\n public boolean isBadgeUseTypeface() {\n return mIsBadgeUseTypeface;\n }\n\n public void setIsBadgeUseTypeface(final boolean isBadgeUseTypeface) {\n mIsBadgeUseTypeface = isBadgeUseTypeface;\n setBadgeTypeface();\n postInvalidate();\n }\n\n public TitleMode getTitleMode() {\n return mTitleMode;\n }\n\n private void setTitleMode(final int index) {\n switch (index) {\n case ACTIVE_INDEX:\n setTitleMode(TitleMode.ACTIVE);\n break;\n case ALL_INDEX:\n default:\n setTitleMode(TitleMode.ALL);\n }\n }\n\n public void setTitleMode(final TitleMode titleMode) {\n mTitleMode = titleMode;\n postInvalidate();\n }\n\n public BadgePosition getBadgePosition() {\n return mBadgePosition;\n }\n\n private void setBadgePosition(final int index) {\n switch (index) {\n case LEFT_INDEX:\n setBadgePosition(BadgePosition.LEFT);\n break;\n case CENTER_INDEX:\n setBadgePosition(BadgePosition.CENTER);\n break;\n case RIGHT_INDEX:\n default:\n setBadgePosition(BadgePosition.RIGHT);\n }\n }\n\n public void setBadgePosition(final BadgePosition badgePosition) {\n mBadgePosition = badgePosition;\n postInvalidate();\n }\n\n public BadgeGravity getBadgeGravity() {\n return mBadgeGravity;\n }\n\n private void setBadgeGravity(final int index) {\n switch (index) {\n case BOTTOM_INDEX:\n setBadgeGravity(BadgeGravity.BOTTOM);\n break;\n case TOP_INDEX:\n default:\n setBadgeGravity(BadgeGravity.TOP);\n }\n }\n\n public void setBadgeGravity(final BadgeGravity badgeGravity) {\n mBadgeGravity = badgeGravity;\n requestLayout();\n }\n\n public Typeface getTypeface() {\n return mTypeface;\n }\n\n public void setTypeface(final String typeface) {\n Typeface tempTypeface;\n try {\n tempTypeface = Typeface.createFromAsset(getContext().getAssets(), typeface);\n } catch (Exception e) {\n tempTypeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL);\n e.printStackTrace();\n }\n\n setTypeface(tempTypeface);\n }\n\n public void setTypeface(final Typeface typeface) {\n mTypeface = typeface;\n mModelTitlePaint.setTypeface(typeface);\n setBadgeTypeface();\n postInvalidate();\n }\n\n private void setBadgeTypeface() {\n mBadgePaint.setTypeface(\n mIsBadgeUseTypeface ? mTypeface : Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)\n );\n }\n\n public int getActiveColor() {\n return mActiveColor;\n }\n\n public void setActiveColor(final int activeColor) {\n mActiveColor = activeColor;\n mIconPointerPaint.setColor(activeColor);\n postInvalidate();\n }\n\n public int getInactiveColor() {\n return mInactiveColor;\n }\n\n public void setInactiveColor(final int inactiveColor) {\n mInactiveColor = inactiveColor;\n\n // Set color filter to wrap icons with inactive color\n mIconPaint.setColorFilter(new PorterDuffColorFilter(inactiveColor, PorterDuff.Mode.SRC_IN));\n mModelTitlePaint.setColor(mInactiveColor);\n postInvalidate();\n }\n\n public float getCornersRadius() {\n return mCornersRadius;\n }\n\n public void setCornersRadius(final float cornersRadius) {\n mCornersRadius = cornersRadius;\n postInvalidate();\n }\n\n public float getBadgeMargin() {\n return mBadgeMargin;\n }\n\n public float getBarHeight() {\n return mBounds.height();\n }\n\n public OnTabBarSelectedIndexListener getOnTabBarSelectedIndexListener() {\n return mOnTabBarSelectedIndexListener;\n }\n\n // Set on tab bar selected index listener where you can trigger action onStart or onEnd\n public void setOnTabBarSelectedIndexListener(final OnTabBarSelectedIndexListener onTabBarSelectedIndexListener) {\n mOnTabBarSelectedIndexListener = onTabBarSelectedIndexListener;\n\n if (mAnimatorListener == null)\n mAnimatorListener = new Animator.AnimatorListener() {\n @Override\n public void onAnimationStart(final Animator animation) {\n if (mOnTabBarSelectedIndexListener != null)\n mOnTabBarSelectedIndexListener.onStartTabSelected(mModels.get(mIndex), mIndex);\n }\n\n @Override\n public void onAnimationEnd(final Animator animation) {\n if (mOnTabBarSelectedIndexListener != null)\n mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex);\n }\n\n @Override\n public void onAnimationCancel(final Animator animation) {\n\n }\n\n @Override\n public void onAnimationRepeat(final Animator animation) {\n\n }\n };\n mAnimator.removeListener(mAnimatorListener);\n mAnimator.addListener(mAnimatorListener);\n }\n\n public void setViewPager(final ViewPager viewPager) {\n // Detect whether ViewPager mode\n if (viewPager == null) {\n mIsViewPagerMode = false;\n return;\n }\n\n if (mViewPager == viewPager) return;\n if (mViewPager != null) mViewPager.setOnPageChangeListener(null);\n if (viewPager.getAdapter() == null)\n throw new IllegalStateException(\"ViewPager does not provide adapter instance.\");\n\n mIsViewPagerMode = true;\n mViewPager = viewPager;\n mViewPager.addOnPageChangeListener(this);\n\n resetScroller();\n postInvalidate();\n }\n\n public void setViewPager(final ViewPager viewPager, int index) {\n setViewPager(viewPager);\n\n mIndex = index;\n if (mIsViewPagerMode) mViewPager.setCurrentItem(index, true);\n postInvalidate();\n }\n\n // Reset scroller and reset scroll duration equals to animation duration\n private void resetScroller() {\n if (mViewPager == null) return;\n try {\n final Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n final ResizeViewPagerScroller scroller = new ResizeViewPagerScroller(getContext());\n scrollerField.set(mViewPager, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void setOnPageChangeListener(final ViewPager.OnPageChangeListener listener) {\n mOnPageChangeListener = listener;\n }\n\n public int getModelIndex() {\n return mIndex;\n }\n\n public void setModelIndex(int index) {\n setModelIndex(index, false);\n }\n\n // Set model index from touch or programmatically\n public void setModelIndex(int index, boolean force) {\n if (mAnimator.isRunning()) return;\n if (mModels.isEmpty()) return;\n\n // This check gives us opportunity to have an non selected model\n if (mIndex == INVALID_INDEX) force = true;\n\n // Detect if last is the same\n if (index == mIndex) return;\n\n // Snap index to models size\n index = Math.max(0, Math.min(index, mModels.size() - 1));\n\n mIsResizeIn = index < mIndex;\n mLastIndex = mIndex;\n mIndex = index;\n\n mIsSetIndexFromTabBar = true;\n if (mIsViewPagerMode) {\n if (mViewPager == null) throw new IllegalStateException(\"ViewPager is null.\");\n mViewPager.setCurrentItem(index, true);\n }\n\n // Set startX and endX for animation, where we animate two sides of rect with different interpolation\n mStartPointerX = mPointerLeftTop;\n mEndPointerX = mIndex * mModelSize;\n\n // If it force, so update immediately, else animate\n // This happens if we set index onCreate or something like this\n // You can use force param or call this method in some post()\n if (force) updateIndicatorPosition(MAX_FRACTION);\n else mAnimator.start();\n }\n\n private void updateIndicatorPosition(final float fraction) {\n // Update general fraction\n mFraction = fraction;\n\n // Set the pointer left top side coordinate\n mPointerLeftTop =\n mStartPointerX + (mResizeInterpolator.getResizeInterpolation(fraction, mIsResizeIn) *\n (mEndPointerX - mStartPointerX));\n // Set the pointer right bottom side coordinate\n mPointerRightBottom =\n (mStartPointerX + mModelSize) +\n (mResizeInterpolator.getResizeInterpolation(fraction, !mIsResizeIn) *\n (mEndPointerX - mStartPointerX));\n\n // Update pointer\n postInvalidate();\n }\n\n // Update NTP\n private void notifyDataSetChanged() {\n postInvalidate();\n }\n\n @Override\n public boolean onTouchEvent(final MotionEvent event) {\n // Return if animation is running\n if (mAnimator.isRunning()) return true;\n // If is not idle state, return\n if (mScrollState != ViewPager.SCROLL_STATE_IDLE) return true;\n\n switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n // Action down touch\n mIsActionDown = true;\n if (!mIsViewPagerMode) break;\n // Detect if we touch down on pointer, later to move\n if (mIsHorizontalOrientation)\n mIsPointerActionDown = (int) (event.getX() / mModelSize) == mIndex;\n else\n mIsPointerActionDown = (int) (event.getY() / mModelSize) == mIndex;\n break;\n case MotionEvent.ACTION_MOVE:\n // If pointer touched, so move\n if (mIsPointerActionDown) {\n if (mIsHorizontalOrientation)\n mViewPager.setCurrentItem((int) (event.getX() / mModelSize), true);\n else\n mViewPager.setCurrentItem((int) (event.getY() / mModelSize), true);\n break;\n }\n if (mIsActionDown) break;\n case MotionEvent.ACTION_UP:\n // Press up and set model index relative to current coordinate\n if (mIsActionDown) {\n if (mIsHorizontalOrientation) setModelIndex((int) (event.getX() / mModelSize));\n else setModelIndex((int) (event.getY() / mModelSize));\n }\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_OUTSIDE:\n default:\n // Reset action touch variables\n mIsPointerActionDown = false;\n mIsActionDown = false;\n break;\n }\n\n return true;\n }\n\n @Override\n protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n\n // Get measure size\n final int width = MeasureSpec.getSize(widthMeasureSpec);\n final int height = MeasureSpec.getSize(heightMeasureSpec);\n\n if (mModels.isEmpty() || width == 0 || height == 0) return;\n\n // Detect orientation and calculate icon size\n if (width > height) {\n mIsHorizontalOrientation = true;\n\n // Get smaller side\n float side = mModelSize > height ? height : mModelSize;\n if (mIsBadged) side -= side * TITLE_SIZE_FRACTION;\n\n mModelSize = (float) width / (float) mModels.size();\n mIconSize = (int) (side * (mIsTitled ? TITLE_ICON_SIZE_FRACTION : ICON_SIZE_FRACTION));\n\n mModelTitleSize = side * TITLE_SIZE_FRACTION;\n mTitleMargin = side * TITLE_MARGIN_FRACTION;\n\n // If is badged mode, so get vars and set paint with default bounds\n if (mIsBadged) {\n mBadgeTitleSize = mModelTitleSize * BADGE_TITLE_SIZE_FRACTION;\n\n final Rect badgeBounds = new Rect();\n mBadgePaint.setTextSize(mBadgeTitleSize);\n mBadgePaint.getTextBounds(PREVIEW_BADGE, 0, 1, badgeBounds);\n mBadgeMargin = (badgeBounds.height() * 0.5f) +\n (mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION * BADGE_VERTICAL_FRACTION);\n }\n } else {\n mIsHorizontalOrientation = false;\n mIsTitled = false;\n mIsBadged = false;\n\n mModelSize = (float) height / (float) mModels.size();\n mIconSize = (int) ((mModelSize > width ? width : mModelSize) * ICON_SIZE_FRACTION);\n }\n\n // Set bounds for NTB\n mBounds.set(0.0f, 0.0f, width, height - mBadgeMargin);\n\n // Set main bitmap\n mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n mCanvas = new Canvas(mBitmap);\n\n // Set pointer canvas\n mPointerBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n mPointerCanvas = new Canvas(mPointerBitmap);\n\n // Set icons canvas\n mIconsBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n mIconsCanvas = new Canvas(mIconsBitmap);\n\n // Set scale fraction for icons\n for (Model model : mModels) {\n final float originalIconSize = model.mIcon.getWidth() > model.mIcon.getHeight() ?\n model.mIcon.getWidth() : model.mIcon.getHeight();\n model.mInactiveIconScale = (float) mIconSize / originalIconSize;\n model.mActiveIconScaleBy = model.mInactiveIconScale *\n (mIsTitled ? TITLE_ACTIVE_ICON_SCALE_BY : ACTIVE_ICON_SCALE_BY);\n }\n\n // Set start position of pointer for preview or on start\n if (isInEditMode() || !mIsViewPagerMode) {\n mIsSetIndexFromTabBar = true;\n\n // Set random in preview mode\n if (isInEditMode()) {\n mIndex = new Random().nextInt(mModels.size());\n\n if (mIsBadged)\n for (int i = 0; i < mModels.size(); i++) {\n final Model model = mModels.get(i);\n\n if (i == mIndex) {\n model.mBadgeFraction = MAX_FRACTION;\n model.showBadge();\n } else {\n model.mBadgeFraction = MIN_FRACTION;\n model.hideBadge();\n }\n }\n }\n\n mStartPointerX = mIndex * mModelSize;\n mEndPointerX = mStartPointerX;\n updateIndicatorPosition(MAX_FRACTION);\n }\n }\n\n @Override\n protected void onDraw(final Canvas canvas) {\n if (mCanvas == null || mPointerCanvas == null || mIconsCanvas == null) return;\n\n // Reset and clear canvases\n mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);\n mPointerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);\n mIconsCanvas.drawColor(0, PorterDuff.Mode.CLEAR);\n\n // Get pointer badge margin for gravity\n final float pointerBadgeMargin = mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : 0.0f;\n\n // Draw our model colors\n for (int i = 0; i < mModels.size(); i++) {\n mPaint.setColor(mModels.get(i).getColor());\n\n if (mIsHorizontalOrientation) {\n final float left = mModelSize * i;\n final float right = left + mModelSize;\n mCanvas.drawRect(\n left, pointerBadgeMargin, right, mBounds.height() + pointerBadgeMargin, mPaint\n );\n } else {\n final float top = mModelSize * i;\n final float bottom = top + mModelSize;\n mCanvas.drawRect(0.0f, top, mBounds.width(), bottom, mPaint);\n }\n }\n\n // Set bound of pointer\n if (mIsHorizontalOrientation)\n mPointerBounds.set(\n mPointerLeftTop, pointerBadgeMargin,\n mPointerRightBottom, mBounds.height() + pointerBadgeMargin\n );\n else mPointerBounds.set(0.0f, mPointerLeftTop, mBounds.width(), mPointerRightBottom);\n\n // Draw pointer for model colors\n if (mCornersRadius == 0) mPointerCanvas.drawRect(mPointerBounds, mPaint);\n else mPointerCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mPaint);\n\n // Draw pointer into main canvas\n mCanvas.drawBitmap(mPointerBitmap, 0.0f, 0.0f, mPointerPaint);\n\n // Draw model icons\n for (int i = 0; i < mModels.size(); i++) {\n final Model model = mModels.get(i);\n\n // Variables to center our icons\n final float leftOffset;\n final float topOffset;\n final float matrixCenterX;\n final float matrixCenterY;\n\n // Set vars for icon when model with title or without\n final float iconMarginTitleHeight = mIconSize + mTitleMargin + mModelTitleSize;\n final float leftTitleOffset = (mModelSize * i) + (mModelSize * 0.5f);\n final float topTitleOffset =\n mBounds.height() - (mBounds.height() - iconMarginTitleHeight) * 0.5f;\n\n if (mIsHorizontalOrientation) {\n leftOffset = (mModelSize * i) + (mModelSize - model.mIcon.getWidth()) * 0.5f;\n topOffset = (mBounds.height() - model.mIcon.getHeight()) * 0.5f;\n\n matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f;\n matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f +\n (mIsTitled && mTitleMode == TitleMode.ALL ? mTitleMargin * 0.5f : 0.0f);\n } else {\n leftOffset = (mBounds.width() - model.mIcon.getWidth()) * 0.5f;\n topOffset = (mModelSize * i) + (mModelSize - model.mIcon.getHeight()) * 0.5f;\n\n matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f;\n matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f;\n }\n\n // Title translate position\n final float titleTranslate = -model.mIcon.getHeight() + topTitleOffset - mTitleMargin * 0.5f;\n\n // Translate icon to model center\n model.mIconMatrix.setTranslate(\n leftOffset,\n (mIsTitled && mTitleMode == TitleMode.ALL) ? titleTranslate : topOffset\n );\n\n // Get interpolated fraction for left last and current models\n final float interpolation = mResizeInterpolator.getResizeInterpolation(mFraction, true);\n final float lastInterpolation = mResizeInterpolator.getResizeInterpolation(mFraction, false);\n\n // Scale value relative to interpolation\n final float matrixScale = model.mActiveIconScaleBy * interpolation;\n final float matrixLastScale = model.mActiveIconScaleBy * lastInterpolation;\n\n // Get title alpha relative to interpolation\n final int titleAlpha = (int) (MAX_ALPHA * interpolation);\n final int titleLastAlpha = MAX_ALPHA - (int) (MAX_ALPHA * lastInterpolation);\n // Get title scale relative to interpolation\n final float titleScale = MAX_FRACTION + (interpolation * TITLE_ACTIVE_SCALE_BY);\n final float titleLastScale = (MAX_FRACTION + TITLE_ACTIVE_SCALE_BY) -\n (lastInterpolation * TITLE_ACTIVE_SCALE_BY);\n\n // Check if we handle models from touch on NTP or from ViewPager\n // There is a strange logic of ViewPager onPageScrolled method, so it is\n if (mIsSetIndexFromTabBar) {\n if (mIndex == i)\n updateCurrentModel(\n model, leftOffset, topOffset, titleTranslate, interpolation,\n matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha\n );\n else if (mLastIndex == i)\n updateLastModel(\n model, leftOffset, topOffset, titleTranslate, lastInterpolation,\n matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha\n );\n else\n updateInactiveModel(\n model, leftOffset, topOffset, matrixCenterX, matrixCenterY\n );\n } else {\n if (i != mIndex && i != mIndex + 1)\n updateInactiveModel(\n model, leftOffset, topOffset, matrixCenterX, matrixCenterY\n );\n else if (i == mIndex + 1)\n updateCurrentModel(\n model, leftOffset, topOffset, titleTranslate, interpolation,\n matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha\n );\n else if (i == mIndex)\n updateLastModel(\n model, leftOffset, topOffset, titleTranslate, lastInterpolation,\n matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha\n );\n }\n\n // Draw model icon\n mIconsCanvas.drawBitmap(model.mIcon, model.mIconMatrix, mIconPaint);\n if (mIsTitled)\n mIconsCanvas.drawText(\n isInEditMode() ? PREVIEW_TITLE : model.getTitle(),\n leftTitleOffset, topTitleOffset, mModelTitlePaint\n );\n }\n\n // Draw pointer with active color to wrap out active icon\n if (mCornersRadius == 0) mIconsCanvas.drawRect(mPointerBounds, mIconPointerPaint);\n else mIconsCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mIconPointerPaint);\n\n // Draw general bitmap\n canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);\n // Draw icons bitmap on top\n canvas.drawBitmap( mIconsBitmap, 0.0f, pointerBadgeMargin, null);\n\n // If is not badged, exit\n if (!mIsBadged) return;\n\n // Model badge margin and offset relative to gravity mode\n final float modelBadgeMargin =\n mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : mBounds.height();\n final float modelBadgeOffset =\n mBadgeGravity == BadgeGravity.TOP ? 0.0f : mBounds.height() - mBadgeMargin;\n\n for (int i = 0; i < mModels.size(); i++) {\n final Model model = mModels.get(i);\n\n // Set preview badge title\n if (isInEditMode() || TextUtils.isEmpty(model.getBadgeTitle()))\n model.setBadgeTitle(PREVIEW_BADGE);\n\n // Set badge title bounds\n mBadgePaint.setTextSize(mBadgeTitleSize * model.mBadgeFraction);\n mBadgePaint.getTextBounds(\n model.getBadgeTitle(), 0, model.getBadgeTitle().length(), mBadgeBounds\n );\n\n // Get horizontal and vertical padding for bg\n final float horizontalPadding = mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION;\n final float verticalPadding = horizontalPadding * BADGE_VERTICAL_FRACTION;\n\n // Set horizontal badge offset\n final float badgeBoundsHorizontalOffset =\n (mModelSize * i) + (mModelSize * mBadgePosition.mPositionFraction);\n\n // If is badge title only one char, so create circle else round rect\n if (model.getBadgeTitle().length() == 1) {\n final float badgeMargin = mBadgeMargin * model.mBadgeFraction;\n mBgBadgeBounds.set(\n badgeBoundsHorizontalOffset - badgeMargin, modelBadgeMargin - badgeMargin,\n badgeBoundsHorizontalOffset + badgeMargin, modelBadgeMargin + badgeMargin\n );\n } else\n mBgBadgeBounds.set(\n badgeBoundsHorizontalOffset - mBadgeBounds.centerX() - horizontalPadding,\n modelBadgeMargin - (mBadgeMargin * model.mBadgeFraction),\n badgeBoundsHorizontalOffset + mBadgeBounds.centerX() + horizontalPadding,\n modelBadgeOffset + (verticalPadding * 2.0f) + mBadgeBounds.height()\n );\n\n // Set color and alpha for badge bg\n if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT);\n else mBadgePaint.setColor(mActiveColor);\n mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction));\n\n // Set corners to round rect for badge bg and draw\n final float cornerRadius = mBgBadgeBounds.height() * 0.5f;\n canvas.drawRoundRect(mBgBadgeBounds, cornerRadius, cornerRadius, mBadgePaint);\n\n // Set color and alpha for badge title\n if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT);\n else mBadgePaint.setColor(model.getColor());\n mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction));\n\n // Set badge title center position and draw title\n final float badgeHalfHeight = mBadgeBounds.height() * 0.5f;\n float badgeVerticalOffset = (mBgBadgeBounds.height() * 0.5f) + badgeHalfHeight -\n mBadgeBounds.bottom + modelBadgeOffset;\n canvas.drawText(\n model.getBadgeTitle(), badgeBoundsHorizontalOffset, badgeVerticalOffset +\n mBadgeBounds.height() - (mBadgeBounds.height() * model.mBadgeFraction),\n mBadgePaint\n );\n }\n }\n\n // Method to transform current fraction of NTB and position\n private void updateCurrentModel(\n final Model model,\n final float leftOffset,\n final float topOffset,\n final float titleTranslate,\n final float interpolation,\n final float matrixCenterX,\n final float matrixCenterY,\n final float matrixScale,\n final float textScale,\n final int textAlpha\n ) {\n if (mIsTitled && mTitleMode == TitleMode.ACTIVE)\n model.mIconMatrix.setTranslate(\n leftOffset, topOffset - (interpolation * (topOffset - titleTranslate))\n );\n\n model.mIconMatrix.postScale(\n model.mInactiveIconScale + matrixScale, model.mInactiveIconScale + matrixScale,\n matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ?\n mTitleMargin * 0.5f * interpolation : 0.0f)\n );\n\n mModelTitlePaint.setTextSize(mModelTitleSize * textScale);\n if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textAlpha);\n }\n\n // Method to transform last fraction of NTB and position\n private void updateLastModel(\n final Model model,\n final float leftOffset,\n final float topOffset,\n final float titleTranslate,\n final float lastInterpolation,\n final float matrixCenterX,\n final float matrixCenterY,\n final float matrixLastScale,\n final float textLastScale,\n final int textLastAlpha\n ) {\n if (mIsTitled && mTitleMode == TitleMode.ACTIVE)\n model.mIconMatrix.setTranslate(\n leftOffset, titleTranslate + (lastInterpolation * (topOffset - titleTranslate))\n );\n\n model.mIconMatrix.postScale(\n model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale,\n model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale,\n matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ?\n mTitleMargin * 0.5f - (mTitleMargin * 0.5f * lastInterpolation) : 0.0f)\n );\n\n mModelTitlePaint.setTextSize(mModelTitleSize * textLastScale);\n if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textLastAlpha);\n }\n\n // Method to transform others fraction of NTB and position\n private void updateInactiveModel(\n final Model model,\n final float leftOffset,\n final float topOffset,\n final float matrixCenterX,\n final float matrixCenterY\n ) {\n if (mIsTitled && mTitleMode == TitleMode.ACTIVE)\n model.mIconMatrix.setTranslate(leftOffset, topOffset);\n\n model.mIconMatrix.postScale(\n model.mInactiveIconScale, model.mInactiveIconScale, matrixCenterX, matrixCenterY\n );\n\n mModelTitlePaint.setTextSize(mModelTitleSize);\n if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(MIN_ALPHA);\n }\n\n @Override\n public void onPageScrolled(int position, float positionOffset, final int positionOffsetPixels) {\n // If we animate, don`t call this\n if (!mIsSetIndexFromTabBar) {\n mIsResizeIn = position < mIndex;\n mLastIndex = mIndex;\n mIndex = position;\n\n mStartPointerX = position * mModelSize;\n mEndPointerX = mStartPointerX + mModelSize;\n updateIndicatorPosition(positionOffset);\n }\n\n if (mOnPageChangeListener != null)\n mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);\n }\n\n @Override\n public void onPageSelected(final int position) {\n // If VP idle, so update\n if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n mIsResizeIn = position < mIndex;\n mLastIndex = mIndex;\n mIndex = position;\n postInvalidate();\n }\n }\n\n @Override\n public void onPageScrollStateChanged(final int state) {\n // If VP idle, reset to MIN_FRACTION\n if (state == ViewPager.SCROLL_STATE_IDLE) {\n mFraction = MIN_FRACTION;\n mIsSetIndexFromTabBar = false;\n\n if (mOnPageChangeListener != null) mOnPageChangeListener.onPageSelected(mIndex);\n else {\n if (mOnTabBarSelectedIndexListener != null)\n mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex);\n }\n }\n mScrollState = state;\n\n if (mOnPageChangeListener != null) mOnPageChangeListener.onPageScrollStateChanged(state);\n }\n\n @Override\n public void onRestoreInstanceState(Parcelable state) {\n final SavedState savedState = (SavedState) state;\n super.onRestoreInstanceState(savedState.getSuperState());\n mIndex = savedState.index;\n requestLayout();\n }\n\n @Override\n public Parcelable onSaveInstanceState() {\n final Parcelable superState = super.onSaveInstanceState();\n final SavedState savedState = new SavedState(superState);\n savedState.index = mIndex;\n return savedState;\n }\n\n static class SavedState extends BaseSavedState {\n int index;\n\n public SavedState(Parcelable superState) {\n super(superState);\n }\n\n private SavedState(Parcel in) {\n super(in);\n index = in.readInt();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeInt(index);\n }\n\n @SuppressWarnings(\"UnusedDeclaration\")\n public static final Creator CREATOR = new Creator() {\n @Override\n public SavedState createFromParcel(Parcel in) {\n return new SavedState(in);\n }\n\n @Override\n public SavedState[] newArray(int size) {\n return new SavedState[size];\n }\n };\n }\n\n // Model class\n public static class Model {\n\n private String mTitle = \"\";\n private int mColor;\n\n private Bitmap mIcon;\n private Matrix mIconMatrix = new Matrix();\n\n private String mBadgeTitle = \"\";\n private String mTempBadgeTitle = \"\";\n private float mBadgeFraction;\n\n private boolean mIsBadgeShowed;\n private boolean mIsBadgeUpdated;\n\n private ValueAnimator mBadgeAnimator = new ValueAnimator();\n\n private float mInactiveIconScale;\n private float mActiveIconScaleBy;\n\n public Model(final Drawable icon, final int color) {\n mColor = color;\n mIcon = icon != null ? ((BitmapDrawable) icon).getBitmap() :\n Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);\n\n mBadgeAnimator.addListener(new Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(final Animator animation) {\n }\n\n @Override\n public void onAnimationEnd(final Animator animation) {\n // Detect whether we just update text and don`t reset show state\n if (!mIsBadgeUpdated) mIsBadgeShowed = !mIsBadgeShowed;\n else mIsBadgeUpdated = false;\n }\n\n @Override\n public void onAnimationCancel(final Animator animation) {\n\n }\n\n @Override\n public void onAnimationRepeat(final Animator animation) {\n // Change title when we update and don`t see the title\n if (mIsBadgeUpdated) mBadgeTitle = mTempBadgeTitle;\n }\n });\n }\n\n public Model(final Drawable icon, final int color, final String title) {\n this(icon, color);\n mTitle = title;\n }\n\n public Model(final Drawable icon, final int color, final String title, final String badgeTitle) {\n this(icon, color, title);\n mBadgeTitle = badgeTitle;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public void setTitle(final String title) {\n mTitle = title;\n }\n\n public int getColor() {\n return mColor;\n }\n\n public void setColor(final int color) {\n mColor = color;\n }\n\n public boolean isBadgeShowed() {\n return mIsBadgeShowed;\n }\n\n public String getBadgeTitle() {\n return mBadgeTitle;\n }\n\n public void setBadgeTitle(final String badgeTitle) {\n mBadgeTitle = badgeTitle;\n }\n\n // If your badge is visible on screen, so you can update title with animation\n public void updateBadgeTitle(final String badgeTitle) {\n if (!mIsBadgeShowed) return;\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n\n mTempBadgeTitle = badgeTitle;\n mIsBadgeUpdated = true;\n\n mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION);\n mBadgeAnimator.setDuration(DEFAULT_BADGE_REFRESH_ANIMATION_DURATION);\n mBadgeAnimator.setRepeatMode(ValueAnimator.REVERSE);\n mBadgeAnimator.setRepeatCount(1);\n mBadgeAnimator.start();\n }\n\n public void toggleBadge() {\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n if (mIsBadgeShowed) hideBadge();\n else showBadge();\n }\n\n public void showBadge() {\n mIsBadgeUpdated = false;\n\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n if (mIsBadgeShowed) return;\n\n mBadgeAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION);\n mBadgeAnimator.setInterpolator(DECELERATE_INTERPOLATOR);\n mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION);\n mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART);\n mBadgeAnimator.setRepeatCount(0);\n mBadgeAnimator.start();\n }\n\n public void hideBadge() {\n mIsBadgeUpdated = false;\n\n if (mBadgeAnimator.isRunning()) mBadgeAnimator.end();\n if (!mIsBadgeShowed) return;\n\n mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION);\n mBadgeAnimator.setInterpolator(ACCELERATE_INTERPOLATOR);\n mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION);\n mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART);\n mBadgeAnimator.setRepeatCount(0);\n mBadgeAnimator.start();\n }\n }\n\n // Custom scroller with custom scroll duration\n private class ResizeViewPagerScroller extends Scroller {\n\n public ResizeViewPagerScroller(Context context) {\n super(context, new AccelerateDecelerateInterpolator());\n }\n\n @Override\n public void startScroll(int startX, int startY, int dx, int dy, int duration) {\n super.startScroll(startX, startY, dx, dy, mAnimationDuration);\n }\n\n @Override\n public void startScroll(int startX, int startY, int dx, int dy) {\n super.startScroll(startX, startY, dx, dy, mAnimationDuration);\n }\n }\n\n // Resize interpolator to create smooth effect on pointer according to inspiration design\n // This is like improved accelerated and decelerated interpolator\n private class ResizeInterpolator implements Interpolator {\n\n // Spring factor\n private final float mFactor = 1.0f;\n // Check whether side we move\n private boolean mResizeIn;\n\n @Override\n public float getInterpolation(final float input) {\n if (mResizeIn) return (float) (1.0f - Math.pow((1.0f - input), 2.0f * mFactor));\n else return (float) (Math.pow(input, 2.0f * mFactor));\n }\n\n public float getResizeInterpolation(final float input, final boolean resizeIn) {\n mResizeIn = resizeIn;\n return getInterpolation(input);\n }\n }\n\n // Model title mode\n public enum TitleMode {\n ALL, ACTIVE\n }\n\n // Model badge position\n public enum BadgePosition {\n\n LEFT(LEFT_FRACTION), CENTER(CENTER_FRACTION), RIGHT(RIGHT_FRACTION);\n\n private float mPositionFraction;\n\n BadgePosition() {\n mPositionFraction = RIGHT_FRACTION;\n }\n\n BadgePosition(final float positionFraction) {\n mPositionFraction = positionFraction;\n }\n }\n\n // Model badge gravity\n public enum BadgeGravity {\n TOP, BOTTOM\n }\n\n // Out listener for selected index\n public interface OnTabBarSelectedIndexListener {\n void onStartTabSelected(final Model model, final int index);\n\n void onEndTabSelected(final Model model, final int index);\n }\n}\n"},"message":{"kind":"string","value":"Add support for Vector Drawables\n"},"old_file":{"kind":"string","value":"library/src/main/java/com/gigamole/library/NavigationTabBar.java"},"subject":{"kind":"string","value":"Add support for Vector Drawables"}}},{"rowIdx":722,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"c2f49b7fe9b5508a835bc919b0cecc9996acd3bc"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"kobakei/Android-RateThisApp"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2013-2015 Keisuke Kobayashi\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.kobakei.ratethisapp;\n\nimport java.lang.ref.WeakReference;\nimport java.util.Date;\n\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.DialogInterface.OnCancelListener;\nimport android.content.DialogInterface.OnClickListener;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.SharedPreferences.Editor;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.support.annotation.StringRes;\nimport android.support.v7.app.AlertDialog;\nimport android.text.TextUtils;\nimport android.util.Log;\n\n/**\n * RateThisApp
    \n * A library to show the app rate dialog\n * @author Keisuke Kobayashi (k.kobayashi.122@gmail.com)\n *\n */\npublic class RateThisApp {\n\n private static final String TAG = RateThisApp.class.getSimpleName();\n\n private static final String PREF_NAME = \"RateThisApp\";\n private static final String KEY_INSTALL_DATE = \"rta_install_date\";\n private static final String KEY_LAUNCH_TIMES = \"rta_launch_times\";\n private static final String KEY_OPT_OUT = \"rta_opt_out\";\n private static final String KEY_ASK_LATER_DATE = \"rta_ask_later_date\";\n\n private static Date mInstallDate = new Date();\n private static int mLaunchTimes = 0;\n private static boolean mOptOut = false;\n private static Date mAskLaterDate = new Date();\n\n private static Config sConfig = new Config();\n private static Callback sCallback = null;\n // Weak ref to avoid leaking the context\n private static WeakReference sDialogRef = null;\n\n /**\n * If true, print LogCat\n */\n public static final boolean DEBUG = false;\n\n /**\n * Initialize RateThisApp configuration.\n * @param config Configuration object.\n */\n public static void init(Config config) {\n sConfig = config;\n }\n\n /**\n * Set callback instance.\n * The callback will receive yes/no/later events.\n * @param callback\n */\n public static void setCallback(Callback callback) {\n sCallback = callback;\n }\n\n /**\n * Call this API when the launcher activity is launched.
    \n * It is better to call this API in onStart() of the launcher activity.\n * @param context Context\n */\n public static void onStart(Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n // If it is the first launch, save the date in shared preference.\n if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) {\n storeInstallDate(context, editor);\n }\n // Increment launch times\n int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);\n launchTimes++;\n editor.putInt(KEY_LAUNCH_TIMES, launchTimes);\n log(\"Launch times; \" + launchTimes);\n\n editor.commit();\n\n mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0));\n mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);\n mOptOut = pref.getBoolean(KEY_OPT_OUT, false);\n mAskLaterDate = new Date(pref.getLong(KEY_ASK_LATER_DATE, 0));\n\n printStatus(context);\n }\n\n /**\n * Show the rate dialog if the criteria is satisfied.\n * @param context Context\n * @return true if shown, false otherwise.\n */\n public static boolean showRateDialogIfNeeded(final Context context) {\n if (shouldShowRateDialog()) {\n showRateDialog(context);\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Show the rate dialog if the criteria is satisfied.\n * @param context Context\n * @param themeId Theme ID\n * @return true if shown, false otherwise.\n */\n public static boolean showRateDialogIfNeeded(final Context context, int themeId) {\n if (shouldShowRateDialog()) {\n showRateDialog(context, themeId);\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Check whether the rate dialog should be shown or not.\n * Developers may call this method directly if they want to show their own view instead of\n * dialog provided by this library.\n * @return\n */\n public static boolean shouldShowRateDialog() {\n if (mOptOut) {\n return false;\n } else {\n if (mLaunchTimes >= sConfig.mCriteriaLaunchTimes) {\n return true;\n }\n long threshold = sConfig.mCriteriaInstallDays * 24 * 60 * 60 * 1000L;\t// msec\n if (new Date().getTime() - mInstallDate.getTime() >= threshold &&\n new Date().getTime() - mAskLaterDate.getTime() >= threshold) {\n return true;\n }\n return false;\n }\n }\n\n /**\n * Show the rate dialog\n * @param context\n */\n public static void showRateDialog(final Context context) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context);\n showRateDialog(context, builder);\n }\n\n /**\n * Show the rate dialog\n * @param context\n * @param themeId\n */\n public static void showRateDialog(final Context context, int themeId) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context, themeId);\n showRateDialog(context, builder);\n }\n\n /**\n * Stop showing the rate dialog\n * @param context\n */\n public static void stopRateDialog(final Context context){\n setOptOut(context, true);\n }\n\n private static void showRateDialog(final Context context, AlertDialog.Builder builder) {\n if (sDialogRef != null && sDialogRef.get() != null) {\n // Dialog is already present\n return;\n }\n\n int titleId = sConfig.mTitleId != 0 ? sConfig.mTitleId : R.string.rta_dialog_title;\n int messageId = sConfig.mMessageId != 0 ? sConfig.mMessageId : R.string.rta_dialog_message;\n int cancelButtonID = sConfig.mCancelButton != 0 ? sConfig.mCancelButton : R.string.rta_dialog_cancel;\n int thanksButtonID = sConfig.mNoButtonId != 0 ? sConfig.mNoButtonId : R.string.rta_dialog_no;\n int rateButtonID = sConfig.mYesButtonId != 0 ? sConfig.mYesButtonId : R.string.rta_dialog_ok;\n builder.setTitle(titleId);\n builder.setMessage(messageId);\n builder.setCancelable(sConfig.mCancelable);\n builder.setPositiveButton(rateButtonID, new OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (sCallback != null) {\n sCallback.onYesClicked();\n }\n String appPackage = context.getPackageName();\n String url = \"https://play.google.com/store/apps/details?id=\" + appPackage;\n if (!TextUtils.isEmpty(sConfig.mUrl)) {\n url = sConfig.mUrl;\n }\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));\n context.startActivity(intent);\n setOptOut(context, true);\n }\n });\n builder.setNeutralButton(cancelButtonID, new OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (sCallback != null) {\n sCallback.onCancelClicked();\n }\n clearSharedPreferences(context);\n storeAskLaterDate(context);\n }\n });\n builder.setNegativeButton(thanksButtonID, new OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (sCallback != null) {\n sCallback.onNoClicked();\n }\n setOptOut(context, true);\n }\n });\n builder.setOnCancelListener(new OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialog) {\n if (sCallback != null) {\n sCallback.onCancelClicked();\n }\n clearSharedPreferences(context);\n storeAskLaterDate(context);\n }\n });\n builder.setOnDismissListener(new DialogInterface.OnDismissListener() {\n @Override\n public void onDismiss(DialogInterface dialog) {\n sDialogRef.clear();\n }\n });\n sDialogRef = new WeakReference<>(builder.show());\n }\n\n /**\n * Clear data in shared preferences.
    \n * This API is called when the rate dialog is approved or canceled.\n * @param context\n */\n private static void clearSharedPreferences(Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n editor.remove(KEY_INSTALL_DATE);\n editor.remove(KEY_LAUNCH_TIMES);\n editor.commit();\n }\n\n /**\n * Set opt out flag. If it is true, the rate dialog will never shown unless app data is cleared.\n * @param context\n * @param optOut\n */\n private static void setOptOut(final Context context, boolean optOut) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n editor.putBoolean(KEY_OPT_OUT, optOut);\n editor.commit();\n mOptOut = optOut;\n }\n\n /**\n * Store install date.\n * Install date is retrieved from package manager if possible.\n * @param context\n * @param editor\n */\n private static void storeInstallDate(final Context context, SharedPreferences.Editor editor) {\n Date installDate = new Date();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {\n PackageManager packMan = context.getPackageManager();\n try {\n PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0);\n installDate = new Date(pkgInfo.firstInstallTime);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n }\n editor.putLong(KEY_INSTALL_DATE, installDate.getTime());\n log(\"First install: \" + installDate.toString());\n }\n\n /**\n * Store the date the user asked for being asked again later.\n * @param context\n */\n private static void storeAskLaterDate(final Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis());\n editor.commit();\n }\n\n /**\n * Print values in SharedPreferences (used for debug)\n * @param context\n */\n private static void printStatus(final Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n log(\"*** RateThisApp Status ***\");\n log(\"Install Date: \" + new Date(pref.getLong(KEY_INSTALL_DATE, 0)));\n log(\"Launch Times: \" + pref.getInt(KEY_LAUNCH_TIMES, 0));\n log(\"Opt out: \" + pref.getBoolean(KEY_OPT_OUT, false));\n }\n\n /**\n * Print log if enabled\n * @param message\n */\n private static void log(String message) {\n if (DEBUG) {\n Log.v(TAG, message);\n }\n }\n\n /**\n * RateThisApp configuration.\n */\n public static class Config {\n private String mUrl = null;\n private int mCriteriaInstallDays;\n private int mCriteriaLaunchTimes;\n private int mTitleId = 0;\n private int mMessageId = 0;\n private int mYesButtonId = 0;\n private int mNoButtonId = 0;\n private int mCancelButton = 0;\n private boolean mCancelable;\n\n /**\n * Constructor with default criteria.\n */\n public Config() {\n this(7, 10);\n }\n\n /**\n * Constructor.\n * @param criteriaInstallDays\n * @param criteriaLaunchTimes\n */\n public Config(int criteriaInstallDays, int criteriaLaunchTimes) {\n this.mCriteriaInstallDays = criteriaInstallDays;\n this.mCriteriaLaunchTimes = criteriaLaunchTimes;\n }\n\n /**\n * Set title string ID.\n * @param stringId\n */\n public void setTitle(@StringRes int stringId) {\n this.mTitleId = stringId;\n }\n\n /**\n * Set message string ID.\n * @param stringId\n */\n public void setMessage(@StringRes int stringId) {\n this.mMessageId = stringId;\n }\n \n /**\n * Set rate now string ID.\n * @param stringId\n */\n public void setYesButtonText(@StringRes int stringId) {\n this.mYesButtonId = stringId;\n }\n \n /**\n * Set no thanks string ID.\n * @param stringId\n */\n public void setNoButtonText(@StringRes int stringId) {\n this.mNoButtonId = stringId;\n }\n \n /**\n * Set cancel string ID.\n * @param stringId\n */\n public void setCancelButtonText(@StringRes int stringId) {\n this.mCancelButton = stringId;\n }\n\n /**\n * Set navigation url when user clicks rate button.\n * Typically, url will be https://play.google.com/store/apps/details?id=PACKAGE_NAME for Google Play.\n * @param url\n */\n public void setUrl(String url) {\n this.mUrl = url;\n }\n\n public void setCancelable(boolean cancelable) {\n this.mCancelable = cancelable;\n }\n }\n\n /**\n * Callback of dialog click event\n */\n public interface Callback {\n /**\n * \"Rate now\" event\n */\n void onYesClicked();\n\n /**\n * \"No, thanks\" event\n */\n void onNoClicked();\n\n /**\n * \"Later\" event\n */\n void onCancelClicked();\n }\n}\n"},"new_file":{"kind":"string","value":"ratethisapp/src/main/java/com/kobakei/ratethisapp/RateThisApp.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2013-2015 Keisuke Kobayashi\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.kobakei.ratethisapp;\n\nimport java.lang.ref.WeakReference;\nimport java.util.Date;\n\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.DialogInterface.OnCancelListener;\nimport android.content.DialogInterface.OnClickListener;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.SharedPreferences.Editor;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.support.annotation.StringRes;\nimport android.support.v7.app.AlertDialog;\nimport android.text.TextUtils;\nimport android.util.Log;\n\n/**\n * RateThisApp
    \n * A library to show the app rate dialog\n * @author Keisuke Kobayashi (k.kobayashi.122@gmail.com)\n *\n */\npublic class RateThisApp {\n\n private static final String TAG = RateThisApp.class.getSimpleName();\n\n private static final String PREF_NAME = \"RateThisApp\";\n private static final String KEY_INSTALL_DATE = \"rta_install_date\";\n private static final String KEY_LAUNCH_TIMES = \"rta_launch_times\";\n private static final String KEY_OPT_OUT = \"rta_opt_out\";\n private static final String KEY_ASK_LATER_DATE = \"rta_ask_later_date\";\n\n private static Date mInstallDate = new Date();\n private static int mLaunchTimes = 0;\n private static boolean mOptOut = false;\n private static Date mAskLaterDate = new Date();\n\n private static Config sConfig = new Config();\n private static Callback sCallback = null;\n // Weak ref to avoid leaking the context\n private static WeakReference sDialogRef = null;\n\n /**\n * If true, print LogCat\n */\n public static final boolean DEBUG = false;\n\n /**\n * Initialize RateThisApp configuration.\n * @param config Configuration object.\n */\n public static void init(Config config) {\n sConfig = config;\n }\n\n /**\n * Set callback instance.\n * The callback will receive yes/no/later events.\n * @param callback\n */\n public static void setCallback(Callback callback) {\n sCallback = callback;\n }\n\n /**\n * Call this API when the launcher activity is launched.
    \n * It is better to call this API in onStart() of the launcher activity.\n * @param context Context\n */\n public static void onStart(Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n // If it is the first launch, save the date in shared preference.\n if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) {\n storeInstallDate(context, editor);\n }\n // Increment launch times\n int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);\n launchTimes++;\n editor.putInt(KEY_LAUNCH_TIMES, launchTimes);\n log(\"Launch times; \" + launchTimes);\n\n editor.commit();\n\n mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0));\n mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);\n mOptOut = pref.getBoolean(KEY_OPT_OUT, false);\n mAskLaterDate = new Date(pref.getLong(KEY_ASK_LATER_DATE, 0));\n\n printStatus(context);\n }\n\n /**\n * Show the rate dialog if the criteria is satisfied.\n * @param context Context\n * @return true if shown, false otherwise.\n */\n public static boolean showRateDialogIfNeeded(final Context context) {\n if (shouldShowRateDialog()) {\n showRateDialog(context);\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Show the rate dialog if the criteria is satisfied.\n * @param context Context\n * @param themeId Theme ID\n * @return true if shown, false otherwise.\n */\n public static boolean showRateDialogIfNeeded(final Context context, int themeId) {\n if (shouldShowRateDialog()) {\n showRateDialog(context, themeId);\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Check whether the rate dialog should be shown or not.\n * Developers may call this method directly if they want to show their own view instead of\n * dialog provided by this library.\n * @return\n */\n public static boolean shouldShowRateDialog() {\n if (mOptOut) {\n return false;\n } else {\n if (mLaunchTimes >= sConfig.mCriteriaLaunchTimes) {\n return true;\n }\n long threshold = sConfig.mCriteriaInstallDays * 24 * 60 * 60 * 1000L;\t// msec\n if (new Date().getTime() - mInstallDate.getTime() >= threshold &&\n new Date().getTime() - mAskLaterDate.getTime() >= threshold) {\n return true;\n }\n return false;\n }\n }\n\n /**\n * Show the rate dialog\n * @param context\n */\n public static void showRateDialog(final Context context) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context);\n showRateDialog(context, builder);\n }\n\n /**\n * Show the rate dialog\n * @param context\n * @param themeId\n */\n public static void showRateDialog(final Context context, int themeId) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context, themeId);\n showRateDialog(context, builder);\n }\n\n /**\n * Stop showing the rate dialog\n * @param context\n */\n public static void stopRateDialog(final Context context){\n setOptOut(context, true);\n }\n\n private static void showRateDialog(final Context context, AlertDialog.Builder builder) {\n if (sDialogRef != null && sDialogRef.get() != null) {\n // Dialog is already present\n return;\n }\n\n int titleId = sConfig.mTitleId != 0 ? sConfig.mTitleId : R.string.rta_dialog_title;\n int messageId = sConfig.mMessageId != 0 ? sConfig.mMessageId : R.string.rta_dialog_message;\n int cancelButtonID = sConfig.mCancelButton != 0 ? sConfig.mCancelButton : R.string.rta_dialog_cancel;\n int thanksButtonID = sConfig.mNoButtonId != 0 ? sConfig.mNoButtonId : R.string.rta_dialog_no;\n int rateButtonID = sConfig.mYesButtonId != 0 ? sConfig.mYesButtonId : R.string.rta_dialog_ok;\n builder.setTitle(titleId);\n builder.setMessage(messageId);\n builder.setPositiveButton(rateButtonID, new OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (sCallback != null) {\n sCallback.onYesClicked();\n }\n String appPackage = context.getPackageName();\n String url = \"https://play.google.com/store/apps/details?id=\" + appPackage;\n if (!TextUtils.isEmpty(sConfig.mUrl)) {\n url = sConfig.mUrl;\n }\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));\n context.startActivity(intent);\n setOptOut(context, true);\n }\n });\n builder.setNeutralButton(cancelButtonID, new OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (sCallback != null) {\n sCallback.onCancelClicked();\n }\n clearSharedPreferences(context);\n storeAskLaterDate(context);\n }\n });\n builder.setNegativeButton(thanksButtonID, new OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (sCallback != null) {\n sCallback.onNoClicked();\n }\n setOptOut(context, true);\n }\n });\n builder.setOnCancelListener(new OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialog) {\n if (sCallback != null) {\n sCallback.onCancelClicked();\n }\n clearSharedPreferences(context);\n storeAskLaterDate(context);\n }\n });\n builder.setOnDismissListener(new DialogInterface.OnDismissListener() {\n @Override\n public void onDismiss(DialogInterface dialog) {\n sDialogRef.clear();\n }\n });\n sDialogRef = new WeakReference<>(builder.show());\n }\n\n /**\n * Clear data in shared preferences.
    \n * This API is called when the rate dialog is approved or canceled.\n * @param context\n */\n private static void clearSharedPreferences(Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n editor.remove(KEY_INSTALL_DATE);\n editor.remove(KEY_LAUNCH_TIMES);\n editor.commit();\n }\n\n /**\n * Set opt out flag. If it is true, the rate dialog will never shown unless app data is cleared.\n * @param context\n * @param optOut\n */\n private static void setOptOut(final Context context, boolean optOut) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n editor.putBoolean(KEY_OPT_OUT, optOut);\n editor.commit();\n mOptOut = optOut;\n }\n\n /**\n * Store install date.\n * Install date is retrieved from package manager if possible.\n * @param context\n * @param editor\n */\n private static void storeInstallDate(final Context context, SharedPreferences.Editor editor) {\n Date installDate = new Date();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {\n PackageManager packMan = context.getPackageManager();\n try {\n PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0);\n installDate = new Date(pkgInfo.firstInstallTime);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n }\n editor.putLong(KEY_INSTALL_DATE, installDate.getTime());\n log(\"First install: \" + installDate.toString());\n }\n\n /**\n * Store the date the user asked for being asked again later.\n * @param context\n */\n private static void storeAskLaterDate(final Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n Editor editor = pref.edit();\n editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis());\n editor.commit();\n }\n\n /**\n * Print values in SharedPreferences (used for debug)\n * @param context\n */\n private static void printStatus(final Context context) {\n SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n log(\"*** RateThisApp Status ***\");\n log(\"Install Date: \" + new Date(pref.getLong(KEY_INSTALL_DATE, 0)));\n log(\"Launch Times: \" + pref.getInt(KEY_LAUNCH_TIMES, 0));\n log(\"Opt out: \" + pref.getBoolean(KEY_OPT_OUT, false));\n }\n\n /**\n * Print log if enabled\n * @param message\n */\n private static void log(String message) {\n if (DEBUG) {\n Log.v(TAG, message);\n }\n }\n\n /**\n * RateThisApp configuration.\n */\n public static class Config {\n private String mUrl = null;\n private int mCriteriaInstallDays;\n private int mCriteriaLaunchTimes;\n private int mTitleId = 0;\n private int mMessageId = 0;\n private int mYesButtonId = 0;\n private int mNoButtonId = 0;\n private int mCancelButton = 0;\n\n /**\n * Constructor with default criteria.\n */\n public Config() {\n this(7, 10);\n }\n\n /**\n * Constructor.\n * @param criteriaInstallDays\n * @param criteriaLaunchTimes\n */\n public Config(int criteriaInstallDays, int criteriaLaunchTimes) {\n this.mCriteriaInstallDays = criteriaInstallDays;\n this.mCriteriaLaunchTimes = criteriaLaunchTimes;\n }\n\n /**\n * Set title string ID.\n * @param stringId\n */\n public void setTitle(@StringRes int stringId) {\n this.mTitleId = stringId;\n }\n\n /**\n * Set message string ID.\n * @param stringId\n */\n public void setMessage(@StringRes int stringId) {\n this.mMessageId = stringId;\n }\n \n /**\n * Set rate now string ID.\n * @param stringId\n */\n public void setYesButtonText(@StringRes int stringId) {\n this.mYesButtonId = stringId;\n }\n \n /**\n * Set no thanks string ID.\n * @param stringId\n */\n public void setNoButtonText(@StringRes int stringId) {\n this.mNoButtonId = stringId;\n }\n \n /**\n * Set cancel string ID.\n * @param stringId\n */\n public void setCancelButtonText(@StringRes int stringId) {\n this.mCancelButton = stringId;\n }\n\n /**\n * Set navigation url when user clicks rate button.\n * Typically, url will be https://play.google.com/store/apps/details?id=PACKAGE_NAME for Google Play.\n * @param url\n */\n public void setUrl(String url) {\n this.mUrl = url;\n }\n }\n\n /**\n * Callback of dialog click event\n */\n public interface Callback {\n /**\n * \"Rate now\" event\n */\n void onYesClicked();\n\n /**\n * \"No, thanks\" event\n */\n void onNoClicked();\n\n /**\n * \"Later\" event\n */\n void onCancelClicked();\n }\n}\n"},"message":{"kind":"string","value":"Add cancelable option to configuration\n"},"old_file":{"kind":"string","value":"ratethisapp/src/main/java/com/kobakei/ratethisapp/RateThisApp.java"},"subject":{"kind":"string","value":"Add cancelable option to configuration"}}},{"rowIdx":723,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ba76cf2a6e4d4e8c2b8c50fae79eb9f1ee9361fa"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"emqtt/mqtt-jmeter"},"new_contents":{"kind":"string","value":"package net.xmeter.gui;\n\nimport java.awt.BorderLayout;\n\nimport javax.swing.JPanel;\n\nimport org.apache.jmeter.gui.util.VerticalPanel;\nimport org.apache.jmeter.samplers.gui.AbstractSamplerGui;\nimport org.apache.jmeter.testelement.TestElement;\nimport org.apache.jorphan.logging.LoggingManager;\nimport org.apache.log.Logger;\n\nimport net.xmeter.Constants;\nimport net.xmeter.samplers.ConnectionSampler;\n\npublic class ConnectionSamplerUI extends AbstractSamplerGui implements Constants {\n\tprivate static final Logger logger = LoggingManager.getLoggerForClass();\n\tprivate CommonConnUI connUI = new CommonConnUI();\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1666890646673145131L;\n\n\tpublic ConnectionSamplerUI() {\n\t\tthis.init();\n\t}\n\n\tprivate void init() {\n\t\tlogger.info(\"Initializing the UI.\");\n\t\tsetLayout(new BorderLayout());\n\t\tsetBorder(makeBorder());\n\n\t\tadd(makeTitlePanel(), BorderLayout.NORTH);\n\t\tJPanel mainPanel = new VerticalPanel();\n\t\tadd(mainPanel, BorderLayout.CENTER);\n\n\t\tmainPanel.add(connUI.createConnPanel());\n\t\tmainPanel.add(connUI.createProtocolPanel()); \n\t\tmainPanel.add(connUI.createAuthentication());\n\t\tmainPanel.add(connUI.createConnOptions());\n\t}\n\n\t@Override\n\tpublic void configure(TestElement element) {\n\t\tsuper.configure(element);\n\t\tConnectionSampler sampler = (ConnectionSampler)element;\n\t\tconnUI.configure(sampler);\n\t}\n\n\t@Override\n\tpublic TestElement createTestElement() {\n\t\tConnectionSampler sampler = new ConnectionSampler();\n\t\tthis.configureTestElement(sampler);\n\t\tconnUI.setupSamplerProperties(sampler);\n\t\treturn sampler;\n\t}\n\n\t@Override\n\tpublic String getLabelResource() {\n\t\tthrow new RuntimeException();\n\t}\n\n\t@Override\n\tpublic String getStaticLabel() {\n\t\treturn \"MQTT Connection Sampler\";\n\t}\n\n\t@Override\n\tpublic void modifyTestElement(TestElement arg0) {\n\t\tConnectionSampler sampler = (ConnectionSampler)arg0;\n\t\tthis.configureTestElement(sampler);\n\t\tconnUI.setupSamplerProperties(sampler);\n\t}\n\n\t@Override\n\tpublic void clearGui() {\n\t\tsuper.clearGui();\n\t\tconnUI.clearUI();\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"mqtt_jmeter/src/main/java/net/xmeter/gui/ConnectionSamplerUI.java"},"old_contents":{"kind":"string","value":"package net.xmeter.gui;\n\nimport java.awt.BorderLayout;\n\nimport javax.swing.JPanel;\n\nimport org.apache.jmeter.gui.util.VerticalPanel;\nimport org.apache.jmeter.samplers.gui.AbstractSamplerGui;\nimport org.apache.jmeter.testelement.TestElement;\nimport org.apache.jorphan.logging.LoggingManager;\nimport org.apache.log.Logger;\n\nimport net.xmeter.Constants;\nimport net.xmeter.samplers.ConnectionSampler;\n\npublic class ConnectionSamplerUI extends AbstractSamplerGui implements Constants {\n\tprivate static final Logger logger = LoggingManager.getLoggerForClass();\n\tprivate CommonConnUI connUI = new CommonConnUI();\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1666890646673145131L;\n\n\tpublic ConnectionSamplerUI() {\n\t\tthis.init();\n\t}\n\n\tprivate void init() {\n\t\tlogger.info(\"Initializing the UI.\");\n\t\tsetLayout(new BorderLayout());\n\t\tsetBorder(makeBorder());\n\n\t\tadd(makeTitlePanel(), BorderLayout.NORTH);\n\t\tJPanel mainPanel = new VerticalPanel();\n\t\tadd(mainPanel, BorderLayout.CENTER);\n\n\t\tmainPanel.add(connUI.createConnPanel());\n\t\tmainPanel.add(connUI.createProtocolPanel()); \n\t\tmainPanel.add(connUI.createAuthentication());\n\t\tmainPanel.add(connUI.createConnOptions());\n\t}\n\n\t@Override\n\tpublic void configure(TestElement element) {\n\t\tsuper.configure(element);\n\t\tConnectionSampler sampler = (ConnectionSampler)element;\n\t\tconnUI.configure(sampler);\n\t}\n\n\t@Override\n\tpublic TestElement createTestElement() {\n\t\tConnectionSampler sampler = new ConnectionSampler();\n\t\tthis.configureTestElement(sampler);\n\t\tconnUI.setupSamplerProperties(sampler);\n\t\treturn sampler;\n\t}\n\n\t@Override\n\tpublic String getLabelResource() {\n\t\treturn \"\";\n\t}\n\n\t@Override\n\tpublic String getStaticLabel() {\n\t\treturn \"MQTT Connection Sampler\";\n\t}\n\n\t@Override\n\tpublic void modifyTestElement(TestElement arg0) {\n\t\tConnectionSampler sampler = (ConnectionSampler)arg0;\n\t\tthis.configureTestElement(sampler);\n\t\tconnUI.setupSamplerProperties(sampler);\n\t}\n\n\t@Override\n\tpublic void clearGui() {\n\t\tsuper.clearGui();\n\t\tconnUI.clearUI();\n\t}\n\n}\n"},"message":{"kind":"string","value":"add sampler label\n"},"old_file":{"kind":"string","value":"mqtt_jmeter/src/main/java/net/xmeter/gui/ConnectionSamplerUI.java"},"subject":{"kind":"string","value":"add sampler label"}}},{"rowIdx":724,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8147cba33019e8a26c34b671d92ab8c56e447aa2"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"4u7/couchbase-lite-java-core,Spotme/couchbase-lite-java-core,netsense-sas/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,couchbase/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,deleet/couchbase-lite-java-core,gotmyjobs/couchbase-lite-java-core"},"new_contents":{"kind":"string","value":"/**\n * Original iOS version by Jens Alfke\n * Ported to Android by Marty Schoch\n *\n * Copyright (c) 2012 Couchbase, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\npackage com.couchbase.lite.support;\n\nimport com.couchbase.lite.Database;\nimport com.couchbase.lite.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class FileDirUtils {\n\n public static boolean removeItemIfExists(String path) {\n File f = new File(path);\n return f.delete() || !f.exists();\n }\n\n public static boolean deleteRecursive(File fileOrDirectory) {\n if (fileOrDirectory.isDirectory()) {\n for (File child : fileOrDirectory.listFiles()) {\n deleteRecursive(child);\n }\n }\n\n boolean result = fileOrDirectory.delete() || !fileOrDirectory.exists();\n return result;\n }\n\n public static String getDatabaseNameFromPath(String path) {\n int lastSlashPos = path.lastIndexOf(\"/\");\n int extensionPos = path.lastIndexOf(\".\");\n if(lastSlashPos < 0 || extensionPos < 0 || extensionPos < lastSlashPos) {\n String message = \"Unable to determine database name from path: \" + path;\n Log.e(Database.TAG, message);\n throw new IllegalArgumentException(message);\n }\n return path.substring(lastSlashPos + 1, extensionPos);\n }\n\n public static void copyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileChannel source = null;\n FileChannel destination = null;\n\n try {\n source = new FileInputStream(sourceFile).getChannel();\n destination = new FileOutputStream(destFile).getChannel();\n destination.transferFrom(source, 0, source.size());\n }\n finally {\n if(source != null) {\n source.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }\n\n public static void copyFolder(File src, File dest)\n throws IOException{\n\n if(src.isDirectory()){\n\n //if directory not exists, create it\n if(!dest.exists()){\n dest.mkdir();\n }\n\n //list all the directory contents\n String files[] = src.list();\n\n for (String file : files) {\n //construct the src and dest file structure\n File srcFile = new File(src, file);\n File destFile = new File(dest, file);\n //recursive copy\n copyFolder(srcFile,destFile);\n }\n\n }else{\n copyFile(src, dest);\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/couchbase/lite/support/FileDirUtils.java"},"old_contents":{"kind":"string","value":"/**\n * Original iOS version by Jens Alfke\n * Ported to Android by Marty Schoch\n *\n * Copyright (c) 2012 Couchbase, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\npackage com.couchbase.lite.support;\n\nimport com.couchbase.lite.Database;\nimport com.couchbase.lite.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class FileDirUtils {\n\n public static boolean removeItemIfExists(String path) {\n File f = new File(path);\n return f.delete() || !f.exists();\n }\n\n public static boolean deleteRecursive(File fileOrDirectory) {\n if (fileOrDirectory.isDirectory()) {\n for (File child : fileOrDirectory.listFiles()) {\n deleteRecursive(child);\n }\n }\n\n boolean result = fileOrDirectory.delete() || !fileOrDirectory.exists();\n return result;\n }\n\n public static String getDatabaseNameFromPath(String path) {\n int lastSlashPos = path.lastIndexOf(\"/\");\n int extensionPos = path.lastIndexOf(\".\");\n if(lastSlashPos < 0 || extensionPos < 0 || extensionPos < lastSlashPos) {\n Log.e(Database.TAG, \"Unable to determine database name from path\");\n return null;\n }\n return path.substring(lastSlashPos + 1, extensionPos);\n }\n\n public static void copyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileChannel source = null;\n FileChannel destination = null;\n\n try {\n source = new FileInputStream(sourceFile).getChannel();\n destination = new FileOutputStream(destFile).getChannel();\n destination.transferFrom(source, 0, source.size());\n }\n finally {\n if(source != null) {\n source.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }\n\n public static void copyFolder(File src, File dest)\n throws IOException{\n\n if(src.isDirectory()){\n\n //if directory not exists, create it\n if(!dest.exists()){\n dest.mkdir();\n }\n\n //list all the directory contents\n String files[] = src.list();\n\n for (String file : files) {\n //construct the src and dest file structure\n File srcFile = new File(src, file);\n File destFile = new File(dest, file);\n //recursive copy\n copyFolder(srcFile,destFile);\n }\n\n }else{\n copyFile(src, dest);\n }\n }\n\n}\n"},"message":{"kind":"string","value":"Issue #111 - Fix: Why does Database ever let this.name be null?\n\nhttps://github.com/couchbase/couchbase-lite-java-core/issues/111\n"},"old_file":{"kind":"string","value":"src/main/java/com/couchbase/lite/support/FileDirUtils.java"},"subject":{"kind":"string","value":"Issue #111 - Fix: Why does Database ever let this.name be null?"}}},{"rowIdx":725,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ad61b68192a7a0b37a4346eddc2dd57c4d11a98b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jduberville/AndEngine,duchien85/AndEngine,luoxiaoshenghustedu/AndEngine,godghdai/AndEngine,zcwk/AndEngine,yudhir/AndEngine,yaye729125/gles,jduberville/AndEngine,shiguang1120/AndEngine,viacheslavokolitiy/AndEngine,pongo710/AndEngine,pongo710/AndEngine,borrom/AndEngine,ericlaro/AndEngineLibrary,ericlaro/AndEngineLibrary,zhidew/AndEngine,chautn/AndEngine,ericlaro/AndEngineLibrary,shiguang1120/AndEngine,nicolasgramlich/AndEngine,zcwk/AndEngine,yudhir/AndEngine,duchien85/AndEngine,borrom/AndEngine,chautn/AndEngine,borrom/AndEngine,godghdai/AndEngine,parthipanramesh/AndEngine,Munazza/AndEngine,parthipanramesh/AndEngine,luoxiaoshenghustedu/AndEngine,msdgwzhy6/AndEngine,chautn/AndEngine,zhidew/AndEngine,viacheslavokolitiy/AndEngine,msdgwzhy6/AndEngine,shiguang1120/AndEngine,jduberville/AndEngine,yudhir/AndEngine,chautn/AndEngine,pongo710/AndEngine,nicolasgramlich/AndEngine,godghdai/AndEngine,viacheslavokolitiy/AndEngine,jduberville/AndEngine,shiguang1120/AndEngine,nicolasgramlich/AndEngine,yaye729125/gles,msdgwzhy6/AndEngine,luoxiaoshenghustedu/AndEngine,zcwk/AndEngine,yaye729125/gles,Munazza/AndEngine,zhidew/AndEngine,zcwk/AndEngine,luoxiaoshenghustedu/AndEngine,nicolasgramlich/AndEngine,pongo710/AndEngine,ericlaro/AndEngineLibrary,yudhir/AndEngine,parthipanramesh/AndEngine,Munazza/AndEngine,msdgwzhy6/AndEngine,godghdai/AndEngine,yaye729125/gles,borrom/AndEngine,viacheslavokolitiy/AndEngine,Munazza/AndEngine,zhidew/AndEngine,parthipanramesh/AndEngine"},"new_contents":{"kind":"string","value":"package org.anddev.andengine.entity.sprite;\r\n\r\nimport java.util.Arrays;\r\n\r\nimport org.anddev.andengine.opengl.texture.region.TiledTextureRegion;\r\nimport org.anddev.andengine.opengl.vertex.RectangleVertexBuffer;\r\nimport org.anddev.andengine.util.MathUtils;\r\nimport org.anddev.andengine.util.constants.TimeConstants;\r\n\r\npublic class AnimatedSprite extends TiledSprite implements TimeConstants {\r\n\t// ===========================================================\r\n\t// Constants\r\n\t// ===========================================================\r\n\r\n\tprivate static final int LOOP_CONTINUOUS = -1;\r\n\r\n\t// ===========================================================\r\n\t// Fields\r\n\t// ===========================================================\r\n\r\n\tprivate boolean mAnimationRunning;\r\n\r\n\tprivate long mAnimationProgress;\r\n\tprivate long mAnimationDuration;\r\n\tprivate long[] mFrameEndsInNanoseconds;\r\n\r\n\tprivate int mFirstTileIndex;\r\n\tprivate int mInitialLoopCount;\r\n\tprivate int mLoopCount;\r\n\tprivate IAnimationListener mAnimationListener;\r\n\r\n\tprivate int mFrameCount;\r\n\tprivate int[] mFrames;\r\n\r\n\t// ===========================================================\r\n\t// Constructors\r\n\t// ===========================================================\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) {\r\n\t\tsuper(pX, pY, pTiledTextureRegion);\r\n\t}\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) {\r\n\t\tsuper(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion);\r\n\t}\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) {\r\n\t\tsuper(pX, pY, pTiledTextureRegion, pRectangleVertexBuffer);\r\n\t}\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) {\r\n\t\tsuper(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer);\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Getter & Setter\r\n\t// ===========================================================\r\n\r\n\tpublic boolean isAnimationRunning() {\r\n\t\treturn this.mAnimationRunning;\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Methods for/from SuperClass/Interfaces\r\n\t// ===========================================================\r\n\r\n\t@Override\r\n\tprotected void onManagedUpdate(final float pSecondsElapsed) {\r\n\t\tsuper.onManagedUpdate(pSecondsElapsed);\r\n\t\tif(this.mAnimationRunning) {\r\n\t\t\tfinal long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDSPERSECOND);\r\n\t\t\tthis.mAnimationProgress += nanoSecondsElapsed;\r\n\r\n\t\t\tif(this.mAnimationProgress > this.mAnimationDuration) {\r\n\t\t\t\tthis.mAnimationProgress %= this.mAnimationDuration;\r\n\t\t\t\tif(this.mInitialLoopCount != AnimatedSprite.LOOP_CONTINUOUS) {\r\n\t\t\t\t\tthis.mLoopCount--;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif(this.mInitialLoopCount == AnimatedSprite.LOOP_CONTINUOUS || this.mLoopCount >= 0) {\r\n\t\t\t\tfinal int currentFrameIndex = this.calculateCurrentFrameIndex();\r\n\t\t\t\t\r\n\t\t\t\tif(this.mFrames == null) {\r\n\t\t\t\t\tthis.setCurrentTileIndex(this.mFirstTileIndex + currentFrameIndex);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthis.setCurrentTileIndex(this.mFrames[currentFrameIndex]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tthis.mAnimationRunning = false;\r\n\t\t\t\tif(this.mAnimationListener != null) {\r\n\t\t\t\t\tthis.mAnimationListener.onAnimationEnd(this);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Methods\r\n\t// ===========================================================\r\n\r\n\tpublic void stopAnimation() {\r\n\t\tthis.mAnimationRunning = false;\r\n\t}\r\n\r\n\tpublic void stopAnimation(final int pTileIndex) {\r\n\t\tthis.mAnimationRunning = false;\r\n\t\tthis.setCurrentTileIndex(pTileIndex);\r\n\t}\r\n\r\n\tprivate int calculateCurrentFrameIndex() {\r\n\t\tfinal long animationProgress = this.mAnimationProgress;\r\n\t\tfinal long[] frameEnds = this.mFrameEndsInNanoseconds;\r\n\t\tfinal int frameCount = this.mFrameCount;\r\n\t\tfor(int i = 0; i < frameCount; i++) {\r\n\t\t\tif(frameEnds[i] > animationProgress) {\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn frameCount - 1;\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach) {\r\n\t\treturn this.animate(pFrameDurationEach, true);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop) {\r\n\t\treturn this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurationEach, pLoopCount, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop, final IAnimationListener pAnimationListener) {\r\n\t\treturn this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tfinal long[] frameDurations = new long[this.getTextureRegion().getTileCount()];\r\n\t\tArrays.fill(frameDurations, pFrameDurationEach);\r\n\t\treturn this.animate(frameDurations, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations) {\r\n\t\treturn this.animate(pFrameDurations, true);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop) {\r\n\t\treturn this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurations, pLoopCount, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop, final IAnimationListener pAnimationListener) {\r\n\t\treturn this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\treturn this.animate(pFrameDurations, 0, this.getTextureRegion().getTileCount() - 1, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final boolean pLoop) {\r\n\t\treturn this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, pLoopCount, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurations, pFrames, pLoopCount, null);\r\n\t}\r\n\r\n\t/**\r\n\t * Animate specifics frames\r\n\t * \r\n\t * @param pFrameDurations must have the same length as pFrames.\r\n\t * @param pFrames indices of the frames to animate.\r\n\t * @param pLoopCount\r\n\t * @param pAnimationListener\r\n\t */\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tfinal int frameCount = pFrames.length;\r\n\t\tif(pFrameDurations.length != frameCount) {\r\n\t\t\tthrow new IllegalArgumentException(\"pFrameDurations must have the same length as pFrames.\");\r\n\t\t}\r\n\r\n\t\treturn this.init(pFrameDurations, frameCount, pFrames, 0, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\t/**\r\n\t * @param pFrameDurations\r\n\t * must have the same length as pFirstTileIndex to\r\n\t * pLastTileIndex.\r\n\t * @param pFirstTileIndex\r\n\t * @param pLastTileIndex\r\n\t * @param pLoopCount\r\n\t * @param pAnimationListener\r\n\t */\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tif(pLastTileIndex - pFirstTileIndex < 1) {\r\n\t\t\tthrow new IllegalArgumentException(\"An animation needs at least two tiles to animate between.\");\r\n\t\t}\r\n\r\n\t\tfinal int frameCount = (pLastTileIndex - pFirstTileIndex) + 1;\r\n\t\tif(pFrameDurations.length != frameCount) {\r\n\t\t\tthrow new IllegalArgumentException(\"pFrameDurations must have the same length as pFirstTileIndex to pLastTileIndex.\");\r\n\t\t}\r\n\r\n\t\treturn this.init(pFrameDurations, frameCount, null, pFirstTileIndex, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\tprivate AnimatedSprite init(final long[] pFrameDurations, final int frameCount, final int[] pFrames, final int pFirstTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tthis.mFrameCount = frameCount;\r\n\t\tthis.mAnimationListener = pAnimationListener;\r\n\t\tthis.mInitialLoopCount = pLoopCount;\r\n\t\tthis.mLoopCount = pLoopCount;\r\n\t\tthis.mFrames = pFrames;\r\n\t\tthis.mFirstTileIndex = pFirstTileIndex;\r\n\r\n\t\tif(this.mFrameEndsInNanoseconds == null || this.mFrameCount > this.mFrameEndsInNanoseconds.length) {\r\n\t\t\tthis.mFrameEndsInNanoseconds = new long[this.mFrameCount];\r\n\t\t}\r\n\r\n\t\tfinal long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds;\r\n\t\tMathUtils.arraySumInto(pFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDSPERMILLISECOND);\r\n\r\n\t\tfinal long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1];\r\n\t\tthis.mAnimationDuration = lastFrameEnd;\r\n\r\n\t\tthis.mAnimationProgress = 0;\r\n\t\tthis.mAnimationRunning = true;\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Inner and Anonymous Classes\r\n\t// ===========================================================\r\n\r\n\tpublic static interface IAnimationListener {\r\n\t\t// ===========================================================\r\n\t\t// Constants\r\n\t\t// ===========================================================\r\n\r\n\t\t// ===========================================================\r\n\t\t// Fields\r\n\t\t// ===========================================================\r\n\r\n\t\tpublic void onAnimationEnd(final AnimatedSprite pAnimatedSprite);\r\n\t}\r\n}\r\n"},"new_file":{"kind":"string","value":"src/org/anddev/andengine/entity/sprite/AnimatedSprite.java"},"old_contents":{"kind":"string","value":"package org.anddev.andengine.entity.sprite;\r\n\r\nimport java.util.Arrays;\r\n\r\nimport org.anddev.andengine.opengl.texture.region.TiledTextureRegion;\r\nimport org.anddev.andengine.opengl.vertex.RectangleVertexBuffer;\r\nimport org.anddev.andengine.util.MathUtils;\r\nimport org.anddev.andengine.util.constants.TimeConstants;\r\n\r\npublic class AnimatedSprite extends TiledSprite implements TimeConstants {\r\n\t// ===========================================================\r\n\t// Constants\r\n\t// ===========================================================\r\n\r\n\tprivate static final int LOOP_CONTINUOUS = -1;\r\n\r\n\t// ===========================================================\r\n\t// Fields\r\n\t// ===========================================================\r\n\r\n\tprivate boolean mAnimationRunning;\r\n\r\n\tprivate long mAnimationProgress;\r\n\tprivate long mAnimationDuration;\r\n\tprivate long[] mFrameEndsInNanoseconds;\r\n\r\n\tprivate int mFirstTileIndex;\r\n\tprivate int mInitialLoopCount;\r\n\tprivate int mLoopCount;\r\n\tprivate IAnimationListener mAnimationListener;\r\n\r\n\tprivate int mFrameCount;\r\n\tprivate int[] mFrames;\r\n\r\n\t// ===========================================================\r\n\t// Constructors\r\n\t// ===========================================================\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) {\r\n\t\tsuper(pX, pY, pTiledTextureRegion);\r\n\t}\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) {\r\n\t\tsuper(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion);\r\n\t}\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) {\r\n\t\tsuper(pX, pY, pTiledTextureRegion, pRectangleVertexBuffer);\r\n\t}\r\n\r\n\tpublic AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) {\r\n\t\tsuper(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer);\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Getter & Setter\r\n\t// ===========================================================\r\n\r\n\tpublic boolean isAnimationRunning() {\r\n\t\treturn this.mAnimationRunning;\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Methods for/from SuperClass/Interfaces\r\n\t// ===========================================================\r\n\r\n\t@Override\r\n\tprotected void onManagedUpdate(final float pSecondsElapsed) {\r\n\t\tsuper.onManagedUpdate(pSecondsElapsed);\r\n\t\tif(this.mAnimationRunning) {\r\n\t\t\tfinal long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDSPERSECOND);\r\n\t\t\tthis.mAnimationProgress += nanoSecondsElapsed;\r\n\r\n\t\t\tif(this.mAnimationProgress > this.mAnimationDuration) {\r\n\t\t\t\tthis.mAnimationProgress %= this.mAnimationDuration;\r\n\t\t\t\tif(this.mInitialLoopCount != AnimatedSprite.LOOP_CONTINUOUS) {\r\n\t\t\t\t\tthis.mLoopCount--;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif(this.mInitialLoopCount == AnimatedSprite.LOOP_CONTINUOUS || this.mLoopCount >= 0) {\r\n\t\t\t\tfinal int currentFrameIndex = this.calculateCurrentFrameIndex();\r\n\t\t\t\t\r\n\t\t\t\tif(this.mFrames == null) {\r\n\t\t\t\t\tthis.setCurrentTileIndex(this.mFirstTileIndex + currentFrameIndex);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthis.setCurrentTileIndex(this.mFrames[currentFrameIndex]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tthis.mAnimationRunning = false;\r\n\t\t\t\tif(this.mAnimationListener != null) {\r\n\t\t\t\t\tthis.mAnimationListener.onAnimationEnd(this);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Methods\r\n\t// ===========================================================\r\n\r\n\tpublic void stopAnimation() {\r\n\t\tthis.mAnimationRunning = false;\r\n\t}\r\n\r\n\tpublic void stopAnimation(final int pTileIndex) {\r\n\t\tthis.mAnimationRunning = false;\r\n\t\tthis.setCurrentTileIndex(pTileIndex);\r\n\t}\r\n\r\n\tprivate int calculateCurrentFrameIndex() {\r\n\t\tfinal long animationProgress = this.mAnimationProgress;\r\n\t\tfinal long[] frameEnds = this.mFrameEndsInNanoseconds;\r\n\t\tfinal int frameCount = this.mFrameCount;\r\n\t\tfor(int i = 0; i < frameCount; i++) {\r\n\t\t\tif(frameEnds[i] > animationProgress) {\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn frameCount - 1;\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach) {\r\n\t\treturn this.animate(pFrameDurationEach, true);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop) {\r\n\t\treturn this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurationEach, pLoopCount, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop, final IAnimationListener pAnimationListener) {\r\n\t\treturn this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tfinal long[] frameDurations = new long[this.getTextureRegion().getTileCount()];\r\n\t\tArrays.fill(frameDurations, pFrameDurationEach);\r\n\t\treturn this.animate(frameDurations, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations) {\r\n\t\treturn this.animate(pFrameDurations, true);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop) {\r\n\t\treturn this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurations, pLoopCount, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop, final IAnimationListener pAnimationListener) {\r\n\t\treturn this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\treturn this.animate(pFrameDurations, 0, this.getTextureRegion().getTileCount() - 1, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final boolean pLoop) {\r\n\t\treturn this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, pLoopCount, null);\r\n\t}\r\n\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount) {\r\n\t\treturn this.animate(pFrameDurations, pFrames, pLoopCount, null);\r\n\t}\r\n\r\n\t/**\r\n\t * Animate specifics frames\r\n\t * \r\n\t * @param pFrameDurations must have the same length as pFrames.\r\n\t * @param pFrames indices of the frames to animate.\r\n\t * @param pLoopCount\r\n\t * @param pAnimationListener\r\n\t */\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\r\n\t\tfinal int frameCount = pFrames.length;\r\n\t\tif(pFrameDurations.length != frameCount) {\r\n\t\t\tthrow new IllegalArgumentException(\"pFrameDurations must have the same length as pFrames.\");\r\n\t\t}\r\n\r\n\t\treturn this.init(pFrameDurations, frameCount, pFrames, 0, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\t/**\r\n\t * @param pFrameDurations\r\n\t * must have the same length as pFirstTileIndex to\r\n\t * pLastTileIndex.\r\n\t * @param pFirstTileIndex\r\n\t * @param pLastTileIndex\r\n\t * @param pLoopCount\r\n\t * @param pAnimationListener\r\n\t */\r\n\tpublic AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tif(pLastTileIndex - pFirstTileIndex < 1) {\r\n\t\t\tthrow new IllegalArgumentException(\"An animation needs at least two tiles to animate between.\");\r\n\t\t}\r\n\r\n\t\tfinal int frameCount = (pLastTileIndex - pFirstTileIndex) + 1;\r\n\t\tif(pFrameDurations.length != frameCount) {\r\n\t\t\tthrow new IllegalArgumentException(\"pFrameDurations must have the same length as pFirstTileIndex to pLastTileIndex.\");\r\n\t\t}\r\n\r\n\t\treturn this.init(pFrameDurations, frameCount, null, pFirstTileIndex, pLoopCount, pAnimationListener);\r\n\t}\r\n\r\n\tprivate AnimatedSprite init(final long[] pFrameDurations, final int frameCount, final int[] pFrames, final int pFirstTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) {\r\n\t\tthis.mFrameCount = frameCount;\r\n\t\tthis.mAnimationListener = pAnimationListener;\r\n\t\tthis.mInitialLoopCount = pLoopCount;\r\n\t\tthis.mLoopCount = pLoopCount;\r\n\t\tthis.mFrames = pFrames;\r\n\t\tthis.mFirstTileIndex = pFirstTileIndex;\r\n\r\n\t\tif(this.mFrameEndsInNanoseconds == null || this.mFrameCount > this.mFrameEndsInNanoseconds.length) {\r\n\t\t\tthis.mFrameEndsInNanoseconds = new long[this.mFrameCount];\r\n\t\t}\r\n\r\n\t\tfinal long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds;\r\n\t\tMathUtils.arraySumInto(pFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDSPERMILLISECOND);\r\n\r\n\t\tfinal long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1];\r\n\t\tthis.mAnimationDuration = lastFrameEnd;\r\n\r\n\t\tthis.mAnimationProgress = 0;\r\n\t\tthis.mAnimationRunning = true;\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\t// ===========================================================\r\n\t// Inner and Anonymous Classes\r\n\t// ===========================================================\r\n\r\n\tpublic static interface IAnimationListener {\r\n\t\t// ===========================================================\r\n\t\t// Constants\r\n\t\t// ===========================================================\r\n\r\n\t\t// ===========================================================\r\n\t\t// Fields\r\n\t\t// ===========================================================\r\n\r\n\t\tpublic void onAnimationEnd(final AnimatedSprite pAnimatedSprite);\r\n\t}\r\n}\r\n"},"message":{"kind":"string","value":"Dummy commit.\n"},"old_file":{"kind":"string","value":"src/org/anddev/andengine/entity/sprite/AnimatedSprite.java"},"subject":{"kind":"string","value":"Dummy commit."}}},{"rowIdx":726,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"15eb9fe02047a41e9523ebc736be729ede6bbc4a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"otto-de/edison-microservice,otto-de/edison-microservice,otto-de/edison-microservice,otto-de/edison-microservice"},"new_contents":{"kind":"string","value":"package de.otto.edison.jobs.controller;\n\nimport de.otto.edison.jobs.domain.JobInfo;\nimport de.otto.edison.jobs.service.JobService;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.servlet.ModelAndView;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Optional;\n\nimport static de.otto.edison.jobs.controller.JobRepresentation.representationOf;\nimport static de.otto.edison.jobs.controller.UrlHelper.baseUriOf;\nimport static java.util.stream.Collectors.toList;\nimport static javax.servlet.http.HttpServletResponse.*;\nimport static org.springframework.web.bind.annotation.RequestMethod.*;\n\n@Controller\npublic class JobsController {\n\n private static final Logger LOG = LoggerFactory.getLogger(JobsController.class);\n\n @Autowired\n private JobService jobService;\n @Value(\"${server.context-path}\")\n private String serverContextPath;\n\n\n public JobsController() {\n }\n\n JobsController(final JobService jobService) {\n this.jobService = jobService;\n }\n\n @RequestMapping(value = \"/internal/jobs\", method = GET, produces = \"text/html\")\n public ModelAndView getJobsAsHtml(@RequestParam(value = \"type\", required = false) String type,\n @RequestParam(value = \"count\", defaultValue = \"100\") int count,\n @RequestParam(value = \"distinct\", defaultValue = \"true\", required = false) boolean distinct,\n HttpServletRequest request) {\n final List jobRepresentations = getJobInfos(type, count, distinct).stream()\n .map((j) -> representationOf(j, true, baseUriOf(request)))\n .collect(toList());\n\n final ModelAndView modelAndView = new ModelAndView(\"jobs\");\n modelAndView.addObject(\"jobs\", jobRepresentations);\n return modelAndView;\n }\n\n @RequestMapping(value = \"/internal/jobs\", method = GET, produces = \"application/json\")\n @ResponseBody\n public List getJobsAsJson(@RequestParam(value = \"type\", required = false) String type,\n @RequestParam(value = \"count\", defaultValue = \"100\") int count,\n @RequestParam(value = \"distinct\", defaultValue = \"true\", required = false) boolean distinct,\n HttpServletRequest request) {\n return getJobInfos(type, count, distinct)\n .stream()\n .map((j) -> representationOf(j, false, baseUriOf(request)))\n .collect(toList());\n }\n\n @RequestMapping(value = \"/internal/jobs\", method = DELETE)\n public void deleteJobs(@RequestParam(value = \"type\", required = false) String type) {\n jobService.deleteJobs(Optional.ofNullable(type));\n }\n\n /**\n * Starts a new job of the specified type, if no such job is currently running.\n *

    \n * The method will return immediately, without waiting for the job to complete.\n *

    \n * If a job with same type is running, the response will have HTTP status 409 CONFLICT,\n * otherwise HTTP 204 NO CONTENT is returned, together with the response header 'Location',\n * containing the full URL of the running job.\n *\n * @param jobType the type of the started job\n * @param request the HttpServletRequest used to determine the base URL\n * @param response the HttpServletResponse used to set the Location header\n * @throws IOException in case the job was not able to start properly (ie. conflict)\n */\n @RequestMapping(\n value = \"/internal/jobs/{jobType}\",\n method = POST)\n public void startJob(final @PathVariable String jobType,\n final HttpServletRequest request,\n final HttpServletResponse response) throws IOException {\n final Optional jobId = jobService.startAsyncJob(jobType);\n if (jobId.isPresent()) {\n response.setHeader(\"Location\", baseUriOf(request) + \"/internal/jobs/\" + jobId.get());\n response.setStatus(SC_NO_CONTENT);\n } else {\n response.sendError(SC_CONFLICT);\n }\n }\n\n @RequestMapping(\n value = \"/internal/jobs/{jobType}/disable\",\n method = POST\n )\n public String disableJobType(final @PathVariable String jobType) {\n jobService.disableJobType(jobType);\n return \"redirect:/internal/jobdefinitions\";\n }\n\n @RequestMapping(\n value = \"/internal/jobs/{jobType}/enable\",\n method = POST\n )\n public String enableJobType(final @PathVariable String jobType) {\n jobService.enableJobType(jobType);\n return \"redirect:/internal/jobdefinitions\";\n }\n\n @RequestMapping(value = \"/internal/jobs/{id}\", method = GET, produces = \"text/html\")\n public ModelAndView getJobAsHtml(final HttpServletRequest request,\n final HttpServletResponse response,\n @PathVariable(\"id\") final String jobId) throws IOException {\n\n setCorsHeaders(response);\n\n final Optional optionalJob = jobService.findJob(jobId);\n if (optionalJob.isPresent()) {\n final ModelAndView modelAndView = new ModelAndView(\"job\");\n modelAndView.addObject(\"job\", representationOf(optionalJob.get(), true, baseUriOf(request)));\n return modelAndView;\n } else {\n response.sendError(SC_NOT_FOUND, \"Job not found\");\n return null;\n }\n }\n\n @RequestMapping(value = \"/internal/jobs/{id}\", method = GET, produces = \"application/json\")\n @ResponseBody\n public JobRepresentation getJob(final HttpServletRequest request,\n final HttpServletResponse response,\n @PathVariable(\"id\") final String jobId) throws IOException {\n\n setCorsHeaders(response);\n\n final Optional optionalJob = jobService.findJob(jobId);\n if (optionalJob.isPresent()) {\n return representationOf(optionalJob.get(), false, baseUriOf(request));\n } else {\n response.sendError(SC_NOT_FOUND, \"Job not found\");\n return null;\n }\n }\n\n private void setCorsHeaders(final HttpServletResponse response) {\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET\");\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n }\n\n private List getJobInfos(String type, int count, boolean distinct) {\n final List jobInfos;\n if (distinct) {\n jobInfos = jobService.findJobsDistinct();\n } else {\n jobInfos = jobService.findJobs(Optional.ofNullable(type), count);\n }\n return jobInfos;\n }\n}\n"},"new_file":{"kind":"string","value":"edison-jobs/src/main/java/de/otto/edison/jobs/controller/JobsController.java"},"old_contents":{"kind":"string","value":"package de.otto.edison.jobs.controller;\n\nimport de.otto.edison.jobs.domain.JobInfo;\nimport de.otto.edison.jobs.service.JobService;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.servlet.ModelAndView;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Optional;\n\nimport static de.otto.edison.jobs.controller.JobRepresentation.representationOf;\nimport static de.otto.edison.jobs.controller.UrlHelper.baseUriOf;\nimport static java.util.stream.Collectors.toList;\nimport static javax.servlet.http.HttpServletResponse.*;\nimport static org.springframework.web.bind.annotation.RequestMethod.*;\n\n@Controller\npublic class JobsController {\n\n private static final Logger LOG = LoggerFactory.getLogger(JobsController.class);\n\n @Autowired\n private JobService jobService;\n @Value(\"${server.context-path}\")\n private String serverContextPath;\n\n\n public JobsController() {\n }\n\n JobsController(final JobService jobService) {\n this.jobService = jobService;\n }\n\n @RequestMapping(value = \"/internal/jobs\", method = GET, produces = \"text/html\")\n public ModelAndView getJobsAsHtml(@RequestParam(value = \"type\", required = false) String type,\n @RequestParam(value = \"count\", defaultValue = \"100\") int count,\n @RequestParam(value = \"distinct\", defaultValue = \"false\", required = false) boolean distinct,\n HttpServletRequest request) {\n final List jobRepresentations = getJobInfos(type, count, distinct).stream()\n .map((j) -> representationOf(j, true, baseUriOf(request)))\n .collect(toList());\n\n final ModelAndView modelAndView = new ModelAndView(\"jobs\");\n modelAndView.addObject(\"jobs\", jobRepresentations);\n return modelAndView;\n }\n\n @RequestMapping(value = \"/internal/jobs\", method = GET, produces = \"application/json\")\n @ResponseBody\n public List getJobsAsJson(@RequestParam(value = \"type\", required = false) String type,\n @RequestParam(value = \"count\", defaultValue = \"100\") int count,\n @RequestParam(value = \"distinct\", defaultValue = \"false\", required = false) boolean distinct,\n HttpServletRequest request) {\n return getJobInfos(type, count, distinct)\n .stream()\n .map((j) -> representationOf(j, false, baseUriOf(request)))\n .collect(toList());\n }\n\n @RequestMapping(value = \"/internal/jobs\", method = DELETE)\n public void deleteJobs(@RequestParam(value = \"type\", required = false) String type) {\n jobService.deleteJobs(Optional.ofNullable(type));\n }\n\n /**\n * Starts a new job of the specified type, if no such job is currently running.\n *

    \n * The method will return immediately, without waiting for the job to complete.\n *

    \n * If a job with same type is running, the response will have HTTP status 409 CONFLICT,\n * otherwise HTTP 204 NO CONTENT is returned, together with the response header 'Location',\n * containing the full URL of the running job.\n *\n * @param jobType the type of the started job\n * @param request the HttpServletRequest used to determine the base URL\n * @param response the HttpServletResponse used to set the Location header\n * @throws IOException in case the job was not able to start properly (ie. conflict)\n */\n @RequestMapping(\n value = \"/internal/jobs/{jobType}\",\n method = POST)\n public void startJob(final @PathVariable String jobType,\n final HttpServletRequest request,\n final HttpServletResponse response) throws IOException {\n final Optional jobId = jobService.startAsyncJob(jobType);\n if (jobId.isPresent()) {\n response.setHeader(\"Location\", baseUriOf(request) + \"/internal/jobs/\" + jobId.get());\n response.setStatus(SC_NO_CONTENT);\n } else {\n response.sendError(SC_CONFLICT);\n }\n }\n\n @RequestMapping(\n value = \"/internal/jobs/{jobType}/disable\",\n method = POST\n )\n public String disableJobType(final @PathVariable String jobType) {\n jobService.disableJobType(jobType);\n return \"redirect:/internal/jobdefinitions\";\n }\n\n @RequestMapping(\n value = \"/internal/jobs/{jobType}/enable\",\n method = POST\n )\n public String enableJobType(final @PathVariable String jobType) {\n jobService.enableJobType(jobType);\n return \"redirect:/internal/jobdefinitions\";\n }\n\n @RequestMapping(value = \"/internal/jobs/{id}\", method = GET, produces = \"text/html\")\n public ModelAndView getJobAsHtml(final HttpServletRequest request,\n final HttpServletResponse response,\n @PathVariable(\"id\") final String jobId) throws IOException {\n\n setCorsHeaders(response);\n\n final Optional optionalJob = jobService.findJob(jobId);\n if (optionalJob.isPresent()) {\n final ModelAndView modelAndView = new ModelAndView(\"job\");\n modelAndView.addObject(\"job\", representationOf(optionalJob.get(), true, baseUriOf(request)));\n return modelAndView;\n } else {\n response.sendError(SC_NOT_FOUND, \"Job not found\");\n return null;\n }\n }\n\n @RequestMapping(value = \"/internal/jobs/{id}\", method = GET, produces = \"application/json\")\n @ResponseBody\n public JobRepresentation getJob(final HttpServletRequest request,\n final HttpServletResponse response,\n @PathVariable(\"id\") final String jobId) throws IOException {\n\n setCorsHeaders(response);\n\n final Optional optionalJob = jobService.findJob(jobId);\n if (optionalJob.isPresent()) {\n return representationOf(optionalJob.get(), false, baseUriOf(request));\n } else {\n response.sendError(SC_NOT_FOUND, \"Job not found\");\n return null;\n }\n }\n\n private void setCorsHeaders(final HttpServletResponse response) {\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET\");\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n }\n\n private List getJobInfos(String type, int count, boolean distinct) {\n final List jobInfos;\n if (distinct) {\n jobInfos = jobService.findJobsDistinct();\n } else {\n jobInfos = jobService.findJobs(Optional.ofNullable(type), count);\n }\n return jobInfos;\n }\n}\n"},"message":{"kind":"string","value":"change default of joboverview to show distinct jobs\n"},"old_file":{"kind":"string","value":"edison-jobs/src/main/java/de/otto/edison/jobs/controller/JobsController.java"},"subject":{"kind":"string","value":"change default of joboverview to show distinct jobs"}}},{"rowIdx":727,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1ad1a4374e7b5a79d20c83d136cc79b688d33f56"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"henry-newbie/CalendarView"},"new_contents":{"kind":"string","value":"package com.henry.calendarview;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Paint.Align;\nimport android.graphics.Paint.Style;\nimport android.graphics.RectF;\nimport android.graphics.Typeface;\nimport android.text.format.DateUtils;\nimport android.text.format.Time;\nimport android.view.MotionEvent;\nimport android.view.View;\n\nimport java.security.InvalidParameterException;\nimport java.text.DateFormatSymbols;\nimport java.util.Calendar;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n * 每个月作为一个ItemView\n */\nclass SimpleMonthView extends View {\n\n public static final String VIEW_PARAMS_SELECTED_BEGIN_DATE = \"selected_begin_date\";\n public static final String VIEW_PARAMS_SELECTED_LAST_DATE = \"selected_last_date\";\n public static final String VIEW_PARAMS_NEAREST_DATE = \"mNearestDay\";\n\n// public static final String VIEW_PARAMS_HEIGHT = \"height\";\n public static final String VIEW_PARAMS_MONTH = \"month\";\n public static final String VIEW_PARAMS_YEAR = \"year\";\n public static final String VIEW_PARAMS_WEEK_START = \"week_start\";\n\n private static final int SELECTED_CIRCLE_ALPHA = 128;\n protected static int DEFAULT_HEIGHT = 32; // 默认一行的高度\n protected static final int DEFAULT_NUM_ROWS = 6;\n protected static int DAY_SELECTED_RECT_SIZE; // 选中圆角矩形半径\n protected static int ROW_SEPARATOR = 12; // 每行中间的间距\n protected static int MINI_DAY_NUMBER_TEXT_SIZE; // 日期字体的最小尺寸\n private static int TAG_TEXT_SIZE; // 标签字体大小\n protected static int MIN_HEIGHT = 10; // 最小高度\n// protected static int MONTH_DAY_LABEL_TEXT_SIZE; // 头部的星期几的字体大小\n protected static int MONTH_HEADER_SIZE; // 头部的高度(包括年份月份,星期几)\n protected static int YEAR_MONTH_TEXT_SIZE; // 头部年份月份的字体大小\n protected static int WEEK_TEXT_SIZE; // 头部年份月份的字体大小\n // private final int mSelectType; // 类型\n// private boolean mIsDisplayTag; // 是否显示标签\n\n private List mInvalidDays; // 禁用的日期\n private List mBusyDays; // 被占用的日期\n private SimpleMonthAdapter.CalendarDay mNearestDay; // 比离入住日期大且是最近的已被占用或者无效日期\n private List mCalendarTags; // 日期下面的标签\n private String mDefTag = \"标签\";\n\n protected int mPadding = 0;\n\n private String mDayOfWeekTypeface;\n private String mMonthTitleTypeface;\n\n protected Paint mWeekTextPaint; // 头部星期几的字体画笔\n protected Paint mDayTextPaint;\n protected Paint mTagTextPaint; // 日期底部的文字画笔\n// protected Paint mTitleBGPaint;\n protected Paint mYearMonthPaint; // 头部的画笔\n protected Paint mSelectedDayBgPaint;\n protected Paint mBusyDayBgPaint;\n protected Paint mInValidDayBgPaint;\n// protected Paint mSelectedDayTextPaint;\n protected int mCurrentDayTextColor; // 今天的字体颜色\n protected int mYearMonthTextColor; // 头部年份和月份字体颜色\n protected int mWeekTextColor; // 头部星期几字体颜色\n// protected int mDayTextColor;\n protected int mDayTextColor; // 日期字体颜色\n protected int mSelectedDayTextColor; // 被选中的日期字体颜色\n protected int mPreviousDayTextColor; // 过去的字体颜色\n protected int mSelectedDaysBgColor; // 选中的日期背景颜色\n protected int mBusyDaysBgColor; // 被占用的日期背景颜色\n protected int mInValidDaysBgColor; // 禁用的日期背景颜色\n protected int mBusyDaysTextColor; // 被占用的日期字体颜色\n protected int mInValidDaysTextColor; // 禁用的日期字体颜色\n\n private final StringBuilder mStringBuilder;\n\n protected boolean mHasToday = false;\n protected int mToday = -1;\n protected int mWeekStart = 1; // 一周的第一天(不同国家的一星期的第一天不同)\n protected int mNumDays = 7; // 一行几列\n protected int mNumCells; // 一个月有多少天\n private int mDayOfWeekStart = 0; // 日期对应星期几\n// protected Boolean mDrawRect; // 圆角还是圆形\n protected int mRowHeight = DEFAULT_HEIGHT; // 行高\n protected int mWidth; // simpleMonthView的宽度\n\n protected int mYear;\n protected int mMonth;\n final Time today;\n\n private final Calendar mCalendar;\n private final Calendar mDayLabelCalendar; // 用于显示星期几\n private final Boolean isPrevDayEnabled; // 今天以前的日期是否能被操作\n\n private int mNumRows;\n\n private DateFormatSymbols mDateFormatSymbols = new DateFormatSymbols();\n\n private OnDayClickListener mOnDayClickListener;\n\n SimpleMonthAdapter.CalendarDay mStartDate; // 入住日期\n SimpleMonthAdapter.CalendarDay mEndDate; // 退房日期\n\n SimpleMonthAdapter.CalendarDay cellCalendar; // cell的对应的日期\n\n /**\n * @param context\n * @param typedArray\n * @param dataModel\n */\n public SimpleMonthView(Context context, TypedArray typedArray, DayPickerView.DataModel dataModel) {\n super(context);\n\n Resources resources = context.getResources();\n mDayLabelCalendar = Calendar.getInstance();\n mCalendar = Calendar.getInstance();\n today = new Time(Time.getCurrentTimezone());\n today.setToNow();\n mDayOfWeekTypeface = resources.getString(R.string.sans_serif);\n mMonthTitleTypeface = resources.getString(R.string.sans_serif);\n mCurrentDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorCurrentDay, resources.getColor(R.color.normal_day));\n mYearMonthTextColor = typedArray.getColor(R.styleable.DayPickerView_colorYearMonthText, resources.getColor(R.color.normal_day));\n mWeekTextColor = typedArray.getColor(R.styleable.DayPickerView_colorWeekText, resources.getColor(R.color.normal_day));\n// mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorDayName, resources.getColor(R.color.normal_day));\n mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorNormalDayText, resources.getColor(R.color.normal_day));\n mPreviousDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorPreviousDayText, resources.getColor(R.color.normal_day));\n mSelectedDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayBackground, resources.getColor(R.color.selected_day_background));\n mSelectedDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayText, resources.getColor(R.color.selected_day_text));\n mBusyDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysBg, Color.GRAY);\n mInValidDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysBg, Color.GRAY);\n mBusyDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysText, resources.getColor(R.color.normal_day));\n mInValidDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysText, resources.getColor(R.color.normal_day));\n// mDrawRect = typedArray.getBoolean(R.styleable.DayPickerView_drawRoundRect, true);\n\n mStringBuilder = new StringBuilder(50);\n\n MINI_DAY_NUMBER_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeDay, resources.getDimensionPixelSize(R.dimen.text_size_day));\n TAG_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeTag, resources.getDimensionPixelSize(R.dimen.text_size_tag));\n YEAR_MONTH_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeYearMonth, resources.getDimensionPixelSize(R.dimen.text_size_month));\n WEEK_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeWeek, resources.getDimensionPixelSize(R.dimen.text_size_day_name));\n MONTH_HEADER_SIZE = typedArray.getDimensionPixelOffset(R.styleable.DayPickerView_headerMonthHeight, resources.getDimensionPixelOffset(R.dimen.header_month_height));\n DAY_SELECTED_RECT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_selectedDayRadius, resources.getDimensionPixelOffset(R.dimen.selected_day_radius));\n\n mRowHeight = ((typedArray.getDimensionPixelSize(R.styleable.DayPickerView_calendarHeight,\n resources.getDimensionPixelOffset(R.dimen.calendar_height)) - MONTH_HEADER_SIZE - ROW_SEPARATOR) / 6);\n\n isPrevDayEnabled = typedArray.getBoolean(R.styleable.DayPickerView_enablePreviousDay, false);\n mInvalidDays = dataModel.invalidDays;\n mBusyDays = dataModel.busyDays;\n mCalendarTags = dataModel.tags;\n mDefTag = dataModel.defTag;\n\n cellCalendar = new SimpleMonthAdapter.CalendarDay();\n\n initView();\n }\n\n /**\n * 计算每个月的日期占用的行数\n *\n * @return\n */\n private int calculateNumRows() {\n int offset = findDayOffset();\n int dividend = (offset + mNumCells) / mNumDays;\n int remainder = (offset + mNumCells) % mNumDays;\n return (dividend + (remainder > 0 ? 1 : 0));\n }\n\n /**\n * 绘制头部的一行星期几\n *\n * @param canvas\n */\n private void drawMonthDayLabels(Canvas canvas) {\n int y = MONTH_HEADER_SIZE - (WEEK_TEXT_SIZE / 2);\n // 一个cell的二分之宽度\n int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2);\n\n for (int i = 0; i < mNumDays; i++) {\n int calendarDay = (i + mWeekStart) % mNumDays;\n int x = (2 * i + 1) * dayWidthHalf + mPadding;\n mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay);\n canvas.drawText(mDateFormatSymbols.getShortWeekdays()[mDayLabelCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()),\n x, y, mWeekTextPaint);\n }\n }\n\n /**\n * 绘制头部(年份月份,星期几)\n *\n * @param canvas\n */\n private void drawMonthTitle(Canvas canvas) {\n int x = (mWidth + 2 * mPadding) / 2;\n int y = (MONTH_HEADER_SIZE - WEEK_TEXT_SIZE) / 2 + (YEAR_MONTH_TEXT_SIZE / 3);\n StringBuilder stringBuilder = new StringBuilder(getMonthAndYearString().toLowerCase());\n stringBuilder.setCharAt(0, Character.toUpperCase(stringBuilder.charAt(0)));\n canvas.drawText(stringBuilder.toString(), x, y, mYearMonthPaint);\n }\n\n /**\n * 每个月第一天是星期几\n *\n * @return\n */\n private int findDayOffset() {\n return (mDayOfWeekStart < mWeekStart ? (mDayOfWeekStart + mNumDays) : mDayOfWeekStart)\n - mWeekStart;\n }\n\n /**\n * 获取年份和月份\n *\n * @return\n */\n private String getMonthAndYearString() {\n int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY;\n mStringBuilder.setLength(0);\n long millis = mCalendar.getTimeInMillis();\n return DateUtils.formatDateRange(getContext(), millis, millis, flags);\n }\n\n private void onDayClick(SimpleMonthAdapter.CalendarDay calendarDay) {\n if (mOnDayClickListener != null && (isPrevDayEnabled || !prevDay(calendarDay.day, today))) {\n mOnDayClickListener.onDayClick(this, calendarDay);\n }\n }\n\n private boolean sameDay(int monthDay, Time time) {\n return (mYear == time.year) && (mMonth == time.month) && (monthDay == time.monthDay);\n }\n\n /**\n * 判断是否是已经过去的日期\n *\n * @param monthDay\n * @param time\n * @return\n */\n private boolean prevDay(int monthDay, Time time) {\n return ((mYear < time.year)) || (mYear == time.year && mMonth < time.month) ||\n (mYear == time.year && mMonth == time.month && monthDay < time.monthDay);\n }\n\n /**\n * 绘制所有的cell\n *\n * @param canvas\n */\n protected void drawMonthCell(Canvas canvas) {\n // ?\n int y = MONTH_HEADER_SIZE + ROW_SEPARATOR + mRowHeight / 2;\n int paddingDay = (mWidth - 2 * mPadding) / (2 * mNumDays);\n int dayOffset = findDayOffset();\n int day = 1;\n\n while (day <= mNumCells) {\n int x = paddingDay * (1 + dayOffset * 2) + mPadding;\n\n mDayTextPaint.setColor(mDayTextColor);\n mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));\n mTagTextPaint.setColor(mDayTextColor);\n\n cellCalendar.setDay(mYear, mMonth, day);\n\n // 当天\n boolean isToady = false;\n if (mHasToday && (mToday == day)) {\n isToady = true;\n canvas.drawText(\"今天\", x, getTextYCenter(mDayTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n // 已过去的日期\n boolean isPrevDay = false;\n if (!isPrevDayEnabled && prevDay(day, today)) {\n isPrevDay = true;\n mDayTextPaint.setColor(mPreviousDayTextColor);\n mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));\n canvas.drawText(String.format(\"%d\", day), x, y, mDayTextPaint);\n }\n\n boolean isBeginDay = false;\n // 绘制起始日期的方格\n if (mStartDate != null && cellCalendar.equals(mStartDate) && !mStartDate.equals(mEndDate)) {\n isBeginDay = true;\n drawDayBg(canvas, x, y, mSelectedDayBgPaint);\n mDayTextPaint.setColor(mSelectedDayTextColor);\n canvas.drawText(\"入住\", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n\n boolean isLastDay = false;\n // 绘制结束日期的方格\n if (mEndDate != null && cellCalendar.equals(mEndDate) && !mStartDate.equals(mEndDate)) {\n isLastDay = true;\n drawDayBg(canvas, x, y, mSelectedDayBgPaint);\n mDayTextPaint.setColor(mSelectedDayTextColor);\n canvas.drawText(\"退房\", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n\n // 在入住和退房之间的日期\n if (cellCalendar.after(mStartDate) && cellCalendar.before(mEndDate)) {\n mDayTextPaint.setColor(mSelectedDayTextColor);\n drawDayBg(canvas, x, y, mSelectedDayBgPaint);\n // 标签变为白色\n mTagTextPaint.setColor(Color.WHITE);\n// canvas.drawText(String.format(\"%d\", day), x, y - DAY_SELECTED_RECT_SIZE / 2, mDayTextPaint);\n }\n\n // 被占用的日期\n boolean isBusyDay = false;\n for (SimpleMonthAdapter.CalendarDay calendarDay : mBusyDays) {\n if (cellCalendar.equals(calendarDay) && !isPrevDay) {\n isBusyDay = true;\n// RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE,\n// (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE,\n// x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE);\n\n // 选择了入住和退房日期,退房日期等于mNearestDay的情况\n if (mStartDate != null && mEndDate != null && mNearestDay != null &&\n mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) {\n\n } else {\n // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色\n if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) {\n mDayTextPaint.setColor(mDayTextColor);\n } else {\n drawDayBg(canvas, x, y, mBusyDayBgPaint);\n// canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint);\n mDayTextPaint.setColor(mBusyDaysTextColor);\n }\n canvas.drawText(\"已租\", x, getTextYCenter(mBusyDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n canvas.drawText(String.format(\"%d\", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n }\n\n // 禁用的日期\n boolean isInvalidDays = false;\n for (SimpleMonthAdapter.CalendarDay calendarDay : mInvalidDays) {\n\n if (cellCalendar.equals(calendarDay) && !isPrevDay) {\n isBusyDay = true;\n// RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE,\n// (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE,\n// x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE);\n\n // 选择了入住和退房日期,退房日期等于mNearestDay的情况\n if (mStartDate != null && mEndDate != null && mNearestDay != null &&\n mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) {\n\n } else {\n // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色\n if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) {\n mDayTextPaint.setColor(mDayTextColor);\n } else {\n drawDayBg(canvas, x, y, mInValidDayBgPaint);\n// canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint);\n mDayTextPaint.setColor(mInValidDaysTextColor);\n }\n canvas.drawText(\"禁用\", x, getTextYCenter(mInValidDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n canvas.drawText(String.format(\"%d\", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n }\n\n // 把入住日期之前和不可用日期之后的日期全部灰掉(思路:\n // 1:入住日期和退房日期不能同一天\n // 2:只选择了入住日期且没有选择退房日期\n // 3:比入住日期小全部变灰且不可点击\n // 4:比入住日期大且离入住日期最近的被禁用或者被占用的日期\n if (mStartDate != null && mEndDate == null && !mStartDate.equals(mEndDate) && !isInvalidDays && !isBusyDay) {\n if (cellCalendar.before(mStartDate) || (mNearestDay != null && cellCalendar.after(mNearestDay))) {\n// RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE,\n// x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE);\n// canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint);\n drawDayBg(canvas, x, y, mBusyDayBgPaint);\n }\n }\n\n // 绘制标签\n if (!isPrevDay && !isInvalidDays && !isBusyDay && !isBeginDay && !isLastDay) {\n boolean isCalendarTag = false;\n for (SimpleMonthAdapter.CalendarDay calendarDay : mCalendarTags) {\n if (cellCalendar.equals(calendarDay)) {\n isCalendarTag = true;\n canvas.drawText(calendarDay.tag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint);\n }\n }\n if (!isCalendarTag) {\n canvas.drawText(mDefTag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint);\n }\n }\n\n // 绘制日期\n if (!isToady && !isPrevDay && !isInvalidDays && !isBusyDay) {\n canvas.drawText(String.format(\"%d\", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n\n dayOffset++;\n if (dayOffset == mNumDays) {\n dayOffset = 0;\n y += mRowHeight;\n }\n day++;\n }\n }\n\n /**\n * 根据坐标获取对应的日期\n * @param x\n * @param y\n * @return\n */\n public SimpleMonthAdapter.CalendarDay getDayFromLocation(float x, float y) {\n int padding = mPadding;\n if ((x < padding) || (x > mWidth - mPadding)) {\n return null;\n }\n\n int yDay = (int) (y - MONTH_HEADER_SIZE) / mRowHeight;\n int day = 1 + ((int) ((x - padding) * mNumDays / (mWidth - padding - mPadding)) - findDayOffset()) + yDay * mNumDays;\n\n if (mMonth > 11 || mMonth < 0 || CalendarUtils.getDaysInMonth(mMonth, mYear) < day || day < 1)\n return null;\n\n SimpleMonthAdapter.CalendarDay calendar = new SimpleMonthAdapter.CalendarDay(mYear, mMonth, day);\n\n // 获取日期下面的tag\n boolean flag = false;\n for (SimpleMonthAdapter.CalendarDay calendarTag : mCalendarTags) {\n if (calendarTag.compareTo(calendar) == 0) {\n flag = true;\n calendar = calendarTag;\n }\n }\n if (!flag) {\n calendar.tag = mDefTag;\n }\n return calendar;\n }\n\n /**\n * 初始化一些paint\n */\n protected void initView() {\n // 头部年份和月份的字体paint\n mYearMonthPaint = new Paint();\n mYearMonthPaint.setFakeBoldText(true);\n mYearMonthPaint.setAntiAlias(true);\n mYearMonthPaint.setTextSize(YEAR_MONTH_TEXT_SIZE);\n mYearMonthPaint.setTypeface(Typeface.create(mMonthTitleTypeface, Typeface.BOLD));\n mYearMonthPaint.setColor(mYearMonthTextColor);\n mYearMonthPaint.setTextAlign(Align.CENTER);\n mYearMonthPaint.setStyle(Style.FILL);\n\n // 头部星期几字体paint\n mWeekTextPaint = new Paint();\n mWeekTextPaint.setAntiAlias(true);\n mWeekTextPaint.setTextSize(WEEK_TEXT_SIZE);\n mWeekTextPaint.setColor(mWeekTextColor);\n mWeekTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL));\n mWeekTextPaint.setStyle(Style.FILL);\n mWeekTextPaint.setTextAlign(Align.CENTER);\n mWeekTextPaint.setFakeBoldText(true);\n\n// // 头部背景paint\n// mTitleBGPaint = new Paint();\n// mTitleBGPaint.setFakeBoldText(true);\n// mTitleBGPaint.setAntiAlias(true);\n// mTitleBGPaint.setColor(mSelectedDayTextColor);\n// mTitleBGPaint.setTextAlign(Align.CENTER);\n// mTitleBGPaint.setStyle(Style.FILL);\n\n // 被选中的日期背景paint\n mSelectedDayBgPaint = new Paint();\n mSelectedDayBgPaint.setFakeBoldText(true);\n mSelectedDayBgPaint.setAntiAlias(true);\n mSelectedDayBgPaint.setColor(mSelectedDaysBgColor);\n mSelectedDayBgPaint.setTextAlign(Align.CENTER);\n mSelectedDayBgPaint.setStyle(Style.FILL);\n mSelectedDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA);\n\n // 被占用的日期paint\n mBusyDayBgPaint = new Paint();\n mBusyDayBgPaint.setFakeBoldText(true);\n mBusyDayBgPaint.setAntiAlias(true);\n mBusyDayBgPaint.setColor(mBusyDaysBgColor);\n mBusyDayBgPaint.setTextSize(TAG_TEXT_SIZE);\n mBusyDayBgPaint.setTextAlign(Align.CENTER);\n mBusyDayBgPaint.setStyle(Style.FILL);\n mBusyDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA);\n\n // 禁用的日期paint\n mInValidDayBgPaint = new Paint();\n mInValidDayBgPaint.setFakeBoldText(true);\n mInValidDayBgPaint.setAntiAlias(true);\n mInValidDayBgPaint.setColor(mInValidDaysBgColor);\n mInValidDayBgPaint.setTextSize(TAG_TEXT_SIZE);\n mInValidDayBgPaint.setTextAlign(Align.CENTER);\n mInValidDayBgPaint.setStyle(Style.FILL);\n mInValidDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA);\n\n// // 被选中的日期字体paint\n// mSelectedDayTextPaint = new Paint();\n// mSelectedDayTextPaint.setAntiAlias(true);\n// mSelectedDayTextPaint.setTextSize(MONTH_DAY_LABEL_TEXT_SIZE);\n// mSelectedDayTextPaint.setColor(Color.WHITE);\n// mSelectedDayTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL));\n// mSelectedDayTextPaint.setStyle(Style.FILL);\n// mSelectedDayTextPaint.setTextAlign(Align.CENTER);\n// mSelectedDayTextPaint.setFakeBoldText(true);\n\n // 日期字体paint\n mDayTextPaint = new Paint();\n mDayTextPaint.setAntiAlias(true);\n mDayTextPaint.setColor(mDayTextColor);\n mDayTextPaint.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE);\n mDayTextPaint.setStyle(Style.FILL);\n mDayTextPaint.setTextAlign(Align.CENTER);\n mDayTextPaint.setFakeBoldText(false);\n\n // 标签字体paint\n mTagTextPaint = new Paint();\n mTagTextPaint.setAntiAlias(true);\n mTagTextPaint.setColor(mDayTextColor);\n mTagTextPaint.setTextSize(TAG_TEXT_SIZE);\n mTagTextPaint.setStyle(Style.FILL);\n mTagTextPaint.setTextAlign(Align.CENTER);\n mTagTextPaint.setFakeBoldText(false);\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n drawMonthTitle(canvas);\n drawMonthDayLabels(canvas);\n drawMonthCell(canvas);\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n // 设置simpleMonthView的宽度和高度\n setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mRowHeight * mNumRows + MONTH_HEADER_SIZE + ROW_SEPARATOR);\n }\n\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n mWidth = w;\n }\n\n public boolean onTouchEvent(MotionEvent event) {\n if (event.getAction() == MotionEvent.ACTION_UP) {\n SimpleMonthAdapter.CalendarDay calendarDay = getDayFromLocation(event.getX(), event.getY());\n// boolean isValidDay = false;\n if (calendarDay == null) {\n return true;\n }\n\n for (SimpleMonthAdapter.CalendarDay day : mInvalidDays) {\n // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选\n if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) {\n return true;\n }\n }\n\n for (SimpleMonthAdapter.CalendarDay day : mBusyDays) {\n // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选\n if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) {\n return true;\n }\n }\n onDayClick(calendarDay);\n }\n return true;\n }\n\n// public void reuse() {\n// mNumRows = DEFAULT_NUM_ROWS;\n// requestLayout();\n// }\n\n /**\n * 设置传递进来的参数\n *\n * @param params\n */\n public void setMonthParams(HashMap params) {\n if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {\n throw new InvalidParameterException(\"You must specify month and year for this view\");\n }\n setTag(params);\n\n// if (params.containsKey(VIEW_PARAMS_HEIGHT)) {\n// mRowHeight = (int) params.get(VIEW_PARAMS_HEIGHT);\n// if (mRowHeight < MIN_HEIGHT) {\n// mRowHeight = MIN_HEIGHT;\n// }\n// }\n\n if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_DATE)) {\n mStartDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_BEGIN_DATE);\n }\n if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_DATE)) {\n mEndDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_LAST_DATE);\n }\n\n if (params.containsKey(\"mNearestDay\")) {\n mNearestDay = (SimpleMonthAdapter.CalendarDay) params.get(\"mNearestDay\");\n }\n\n mMonth = (int) params.get(VIEW_PARAMS_MONTH);\n mYear = (int) params.get(VIEW_PARAMS_YEAR);\n\n mHasToday = false;\n mToday = -1;\n\n mCalendar.set(Calendar.MONTH, mMonth);\n mCalendar.set(Calendar.YEAR, mYear);\n mCalendar.set(Calendar.DAY_OF_MONTH, 1);\n mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);\n\n if (params.containsKey(VIEW_PARAMS_WEEK_START)) {\n mWeekStart = (int) params.get(VIEW_PARAMS_WEEK_START);\n } else {\n mWeekStart = mCalendar.getFirstDayOfWeek();\n }\n\n mNumCells = CalendarUtils.getDaysInMonth(mMonth, mYear);\n for (int i = 0; i < mNumCells; i++) {\n final int day = i + 1;\n if (sameDay(day, today)) {\n mHasToday = true;\n mToday = day;\n }\n }\n\n mNumRows = calculateNumRows();\n }\n\n public void setOnDayClickListener(OnDayClickListener onDayClickListener) {\n mOnDayClickListener = onDayClickListener;\n }\n\n public interface OnDayClickListener {\n void onDayClick(SimpleMonthView simpleMonthView, SimpleMonthAdapter.CalendarDay calendarDay);\n }\n\n /**\n * 绘制cell\n *\n * @param canvas\n * @param x\n * @param y\n */\n private void drawDayBg(Canvas canvas, int x, int y, Paint paint) {\n RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, y - DAY_SELECTED_RECT_SIZE,\n x + DAY_SELECTED_RECT_SIZE, y + DAY_SELECTED_RECT_SIZE);\n canvas.drawRoundRect(rectF, 10.0f, 10.0f, paint);\n }\n\n /**\n * 在使用drawText方法时文字不能根据y坐标居中,所以重新计算y坐标\n * @param paint\n * @param y\n * @return\n */\n private float getTextYCenter(Paint paint, int y) {\n Paint.FontMetrics fontMetrics = paint.getFontMetrics();\n float fontTotalHeight = fontMetrics.bottom - fontMetrics.top;\n float offY = fontTotalHeight / 2 - fontMetrics.bottom;\n return y + offY;\n }\n}"},"new_file":{"kind":"string","value":"library/src/main/java/com/henry/calendarview/SimpleMonthView.java"},"old_contents":{"kind":"string","value":"package com.henry.calendarview;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Paint.Align;\nimport android.graphics.Paint.Style;\nimport android.graphics.RectF;\nimport android.graphics.Typeface;\nimport android.text.format.DateUtils;\nimport android.text.format.Time;\nimport android.view.MotionEvent;\nimport android.view.View;\n\nimport java.security.InvalidParameterException;\nimport java.text.DateFormatSymbols;\nimport java.util.Calendar;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n * 每个月作为一个ItemView\n */\nclass SimpleMonthView extends View {\n\n public static final String VIEW_PARAMS_SELECTED_BEGIN_DATE = \"selected_begin_date\";\n public static final String VIEW_PARAMS_SELECTED_LAST_DATE = \"selected_last_date\";\n public static final String VIEW_PARAMS_NEAREST_DATE = \"mNearestDay\";\n\n// public static final String VIEW_PARAMS_HEIGHT = \"height\";\n public static final String VIEW_PARAMS_MONTH = \"month\";\n public static final String VIEW_PARAMS_YEAR = \"year\";\n public static final String VIEW_PARAMS_WEEK_START = \"week_start\";\n\n private static final int SELECTED_CIRCLE_ALPHA = 128;\n protected static int DEFAULT_HEIGHT = 32; // 默认一行的高度\n protected static final int DEFAULT_NUM_ROWS = 6;\n protected static int DAY_SELECTED_RECT_SIZE; // 选中圆角矩形半径\n protected static int ROW_SEPARATOR = 12; // 每行中间的间距\n protected static int MINI_DAY_NUMBER_TEXT_SIZE; // 日期字体的最小尺寸\n private static int TAG_TEXT_SIZE; // 标签字体大小\n protected static int MIN_HEIGHT = 10; // 最小高度\n// protected static int MONTH_DAY_LABEL_TEXT_SIZE; // 头部的星期几的字体大小\n protected static int MONTH_HEADER_SIZE; // 头部的高度(包括年份月份,星期几)\n protected static int YEAR_MONTH_TEXT_SIZE; // 头部年份月份的字体大小\n protected static int WEEK_TEXT_SIZE; // 头部年份月份的字体大小\n // private final int mSelectType; // 类型\n// private boolean mIsDisplayTag; // 是否显示标签\n\n private List mInvalidDays; // 禁用的日期\n private List mBusyDays; // 被占用的日期\n private SimpleMonthAdapter.CalendarDay mNearestDay; // 比离入住日期大且是最近的已被占用或者无效日期\n private List mCalendarTags; // 日期下面的标签\n private String mDefTag = \"标签\";\n\n protected int mPadding = 0;\n\n private String mDayOfWeekTypeface;\n private String mMonthTitleTypeface;\n\n protected Paint mWeekTextPaint; // 头部星期几的字体画笔\n protected Paint mDayTextPaint;\n protected Paint mTagTextPaint; // 日期底部的文字画笔\n// protected Paint mTitleBGPaint;\n protected Paint mYearMonthPaint; // 头部的画笔\n protected Paint mSelectedDayBgPaint;\n protected Paint mBusyDayBgPaint;\n protected Paint mInValidDayBgPaint;\n// protected Paint mSelectedDayTextPaint;\n protected int mCurrentDayTextColor; // 今天的字体颜色\n protected int mYearMonthTextColor; // 头部年份和月份字体颜色\n protected int mWeekTextColor; // 头部星期几字体颜色\n// protected int mDayTextColor;\n protected int mDayTextColor; // 日期字体颜色\n protected int mSelectedDayTextColor; // 被选中的日期字体颜色\n protected int mPreviousDayTextColor; // 过去的字体颜色\n protected int mSelectedDaysBgColor; // 选中的日期背景颜色\n protected int mBusyDaysBgColor; // 被占用的日期背景颜色\n protected int mInValidDaysBgColor; // 禁用的日期背景颜色\n protected int mBusyDaysTextColor; // 被占用的日期字体颜色\n protected int mInValidDaysTextColor; // 禁用的日期字体颜色\n\n private final StringBuilder mStringBuilder;\n\n protected boolean mHasToday = false;\n protected int mToday = -1;\n protected int mWeekStart = 1; // 一周的第一天(不同国家的一星期的第一天不同)\n protected int mNumDays = 7; // 一行几列\n protected int mNumCells; // 一个月有多少天\n private int mDayOfWeekStart = 0; // 日期对应星期几\n// protected Boolean mDrawRect; // 圆角还是圆形\n protected int mRowHeight = DEFAULT_HEIGHT; // 行高\n protected int mWidth; // simpleMonthView的宽度\n\n protected int mYear;\n protected int mMonth;\n final Time today;\n\n private final Calendar mCalendar;\n private final Calendar mDayLabelCalendar; // 用于显示星期几\n private final Boolean isPrevDayEnabled; // 今天以前的日期是否能被操作\n\n private int mNumRows;\n\n private DateFormatSymbols mDateFormatSymbols = new DateFormatSymbols();\n\n private OnDayClickListener mOnDayClickListener;\n\n SimpleMonthAdapter.CalendarDay mStartDate; // 入住日期\n SimpleMonthAdapter.CalendarDay mEndDate; // 退房日期\n\n SimpleMonthAdapter.CalendarDay cellCalendar; // cell的对应的日期\n\n /**\n * @param context\n * @param typedArray\n * @param dataModel\n */\n public SimpleMonthView(Context context, TypedArray typedArray, DayPickerView.DataModel dataModel) {\n super(context);\n\n Resources resources = context.getResources();\n mDayLabelCalendar = Calendar.getInstance();\n mCalendar = Calendar.getInstance();\n today = new Time(Time.getCurrentTimezone());\n today.setToNow();\n mDayOfWeekTypeface = resources.getString(R.string.sans_serif);\n mMonthTitleTypeface = resources.getString(R.string.sans_serif);\n mCurrentDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorCurrentDay, resources.getColor(R.color.normal_day));\n mYearMonthTextColor = typedArray.getColor(R.styleable.DayPickerView_colorYearMonthText, resources.getColor(R.color.normal_day));\n mWeekTextColor = typedArray.getColor(R.styleable.DayPickerView_colorWeekText, resources.getColor(R.color.normal_day));\n// mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorDayName, resources.getColor(R.color.normal_day));\n mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorNormalDayText, resources.getColor(R.color.normal_day));\n mPreviousDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorPreviousDayText, resources.getColor(R.color.normal_day));\n mSelectedDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayBackground, resources.getColor(R.color.selected_day_background));\n mSelectedDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayText, resources.getColor(R.color.selected_day_text));\n mBusyDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysBg, Color.GRAY);\n mInValidDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysBg, Color.GRAY);\n mBusyDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysText, resources.getColor(R.color.normal_day));\n mInValidDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysText, resources.getColor(R.color.normal_day));\n// mDrawRect = typedArray.getBoolean(R.styleable.DayPickerView_drawRoundRect, true);\n\n mStringBuilder = new StringBuilder(50);\n\n MINI_DAY_NUMBER_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeDay, resources.getDimensionPixelSize(R.dimen.text_size_day));\n TAG_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeTag, resources.getDimensionPixelSize(R.dimen.text_size_tag));\n YEAR_MONTH_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeYearMonth, resources.getDimensionPixelSize(R.dimen.text_size_month));\n WEEK_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeWeek, resources.getDimensionPixelSize(R.dimen.text_size_day_name));\n MONTH_HEADER_SIZE = typedArray.getDimensionPixelOffset(R.styleable.DayPickerView_headerMonthHeight, resources.getDimensionPixelOffset(R.dimen.header_month_height));\n DAY_SELECTED_RECT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_selectedDayRadius, resources.getDimensionPixelOffset(R.dimen.selected_day_radius));\n\n mRowHeight = ((typedArray.getDimensionPixelSize(R.styleable.DayPickerView_calendarHeight,\n resources.getDimensionPixelOffset(R.dimen.calendar_height)) - MONTH_HEADER_SIZE - ROW_SEPARATOR) / 6);\n\n isPrevDayEnabled = typedArray.getBoolean(R.styleable.DayPickerView_enablePreviousDay, false);\n mInvalidDays = dataModel.invalidDays;\n mBusyDays = dataModel.busyDays;\n mCalendarTags = dataModel.tags;\n mDefTag = dataModel.defTag;\n\n cellCalendar = new SimpleMonthAdapter.CalendarDay();\n\n initView();\n }\n\n /**\n * 计算每个月的日期占用的行数\n *\n * @return\n */\n private int calculateNumRows() {\n int offset = findDayOffset();\n int dividend = (offset + mNumCells) / mNumDays;\n int remainder = (offset + mNumCells) % mNumDays;\n return (dividend + (remainder > 0 ? 1 : 0));\n }\n\n /**\n * 绘制头部的一行星期几\n *\n * @param canvas\n */\n private void drawMonthDayLabels(Canvas canvas) {\n int y = MONTH_HEADER_SIZE - (WEEK_TEXT_SIZE / 2);\n // 一个cell的二分之宽度\n int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2);\n\n for (int i = 0; i < mNumDays; i++) {\n int calendarDay = (i + mWeekStart) % mNumDays;\n int x = (2 * i + 1) * dayWidthHalf + mPadding;\n mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay);\n canvas.drawText(mDateFormatSymbols.getShortWeekdays()[mDayLabelCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()),\n x, y, mWeekTextPaint);\n }\n }\n\n /**\n * 绘制头部(年份月份,星期几)\n *\n * @param canvas\n */\n private void drawMonthTitle(Canvas canvas) {\n int x = (mWidth + 2 * mPadding) / 2;\n int y = (MONTH_HEADER_SIZE - WEEK_TEXT_SIZE) / 2 + (YEAR_MONTH_TEXT_SIZE / 3);\n StringBuilder stringBuilder = new StringBuilder(getMonthAndYearString().toLowerCase());\n stringBuilder.setCharAt(0, Character.toUpperCase(stringBuilder.charAt(0)));\n canvas.drawText(stringBuilder.toString(), x, y, mYearMonthPaint);\n }\n\n /**\n * 每个月第一天是星期几\n *\n * @return\n */\n private int findDayOffset() {\n return (mDayOfWeekStart < mWeekStart ? (mDayOfWeekStart + mNumDays) : mDayOfWeekStart)\n - mWeekStart;\n }\n\n /**\n * 获取年份和月份\n *\n * @return\n */\n private String getMonthAndYearString() {\n int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY;\n mStringBuilder.setLength(0);\n long millis = mCalendar.getTimeInMillis();\n return DateUtils.formatDateRange(getContext(), millis, millis, flags);\n }\n\n private void onDayClick(SimpleMonthAdapter.CalendarDay calendarDay) {\n if (mOnDayClickListener != null && (isPrevDayEnabled || !prevDay(calendarDay.day, today))) {\n mOnDayClickListener.onDayClick(this, calendarDay);\n }\n }\n\n private boolean sameDay(int monthDay, Time time) {\n return (mYear == time.year) && (mMonth == time.month) && (monthDay == time.monthDay);\n }\n\n /**\n * 判断是否是已经过去的日期\n *\n * @param monthDay\n * @param time\n * @return\n */\n private boolean prevDay(int monthDay, Time time) {\n return ((mYear < time.year)) || (mYear == time.year && mMonth < time.month) ||\n (mYear == time.year && mMonth == time.month && monthDay < time.monthDay);\n }\n\n /**\n * 绘制所有的cell\n *\n * @param canvas\n */\n protected void drawMonthCell(Canvas canvas) {\n // ?\n int y = MONTH_HEADER_SIZE + ROW_SEPARATOR + mRowHeight / 2;\n int paddingDay = (mWidth - 2 * mPadding) / (2 * mNumDays);\n int dayOffset = findDayOffset();\n int day = 1;\n\n while (day <= mNumCells) {\n int x = paddingDay * (1 + dayOffset * 2) + mPadding;\n\n mDayTextPaint.setColor(mDayTextColor);\n mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));\n mTagTextPaint.setColor(mDayTextColor);\n\n cellCalendar.setDay(mYear, mMonth, day);\n\n // 当天\n boolean isToady = false;\n if (mHasToday && (mToday == day)) {\n isToady = true;\n canvas.drawText(\"今天\", x, getTextYCenter(mDayTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n // 已过去的日期\n boolean isPrevDay = false;\n if (!isPrevDayEnabled && prevDay(day, today)) {\n isPrevDay = true;\n mDayTextPaint.setColor(mPreviousDayTextColor);\n mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));\n canvas.drawText(String.format(\"%d\", day), x, y, mDayTextPaint);\n }\n\n boolean isBeginDay = false;\n // 绘制起始日期的方格\n if (mStartDate != null && cellCalendar.equals(mStartDate) && !mStartDate.equals(mEndDate)) {\n isBeginDay = true;\n drawDayBg(canvas, x, y, mSelectedDayBgPaint);\n mDayTextPaint.setColor(mSelectedDayTextColor);\n canvas.drawText(\"入住\", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n\n boolean isLastDay = false;\n // 绘制结束日期的方格\n if (mEndDate != null && cellCalendar.equals(mEndDate) && !mStartDate.equals(mEndDate)) {\n isLastDay = true;\n drawDayBg(canvas, x, y, mSelectedDayBgPaint);\n mDayTextPaint.setColor(mSelectedDayTextColor);\n canvas.drawText(\"退房\", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n\n // 在入住和退房之间的日期\n if (cellCalendar.after(mStartDate) && cellCalendar.before(mEndDate)) {\n mDayTextPaint.setColor(mSelectedDayTextColor);\n drawDayBg(canvas, x, y, mSelectedDayBgPaint);\n // 标签变为白色\n mTagTextPaint.setColor(Color.WHITE);\n// canvas.drawText(String.format(\"%d\", day), x, y - DAY_SELECTED_RECT_SIZE / 2, mDayTextPaint);\n }\n\n // 被占用的日期\n boolean isBusyDay = false;\n for (SimpleMonthAdapter.CalendarDay calendarDay : mBusyDays) {\n if (cellCalendar.equals(calendarDay) && !isPrevDay) {\n isBusyDay = true;\n// RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE,\n// (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE,\n// x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE);\n\n // 选择了入住和退房日期,退房日期等于mNearestDay的情况\n if (mStartDate != null && mEndDate != null && mNearestDay != null &&\n mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) {\n\n } else {\n // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色\n if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) {\n mDayTextPaint.setColor(mDayTextColor);\n } else {\n drawDayBg(canvas, x, y, mBusyDayBgPaint);\n// canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint);\n mDayTextPaint.setColor(mBusyDaysTextColor);\n }\n\n canvas.drawText(String.format(\"%d\", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n canvas.drawText(\"已租\", x, getTextYCenter(mBusyDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n }\n }\n\n // 禁用的日期\n boolean isInvalidDays = false;\n for (SimpleMonthAdapter.CalendarDay calendarDay : mInvalidDays) {\n\n if (cellCalendar.equals(calendarDay) && !isPrevDay) {\n isBusyDay = true;\n// RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE,\n// (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE,\n// x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE);\n\n // 选择了入住和退房日期,退房日期等于mNearestDay的情况\n if (mStartDate != null && mEndDate != null && mNearestDay != null &&\n mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) {\n\n } else {\n // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色\n if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) {\n mDayTextPaint.setColor(mDayTextColor);\n } else {\n drawDayBg(canvas, x, y, mInValidDayBgPaint);\n// canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint);\n mDayTextPaint.setColor(mInValidDaysTextColor);\n }\n\n canvas.drawText(String.format(\"%d\", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n canvas.drawText(\"禁用\", x, getTextYCenter(mInValidDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n }\n }\n\n // 把入住日期之前和不可用日期之后的日期全部灰掉(思路:\n // 1:入住日期和退房日期不能同一天\n // 2:只选择了入住日期且没有选择退房日期\n // 3:比入住日期小全部变灰且不可点击\n // 4:比入住日期大且离入住日期最近的被禁用或者被占用的日期\n if (mStartDate != null && mEndDate == null && !mStartDate.equals(mEndDate) && !isInvalidDays && !isBusyDay) {\n if (cellCalendar.before(mStartDate) || (mNearestDay != null && cellCalendar.after(mNearestDay))) {\n// RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE,\n// x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE);\n// canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint);\n drawDayBg(canvas, x, y, mBusyDayBgPaint);\n }\n }\n\n // 绘制标签\n if (!isPrevDay && !isInvalidDays && !isBusyDay && !isBeginDay && !isLastDay) {\n boolean isCalendarTag = false;\n for (SimpleMonthAdapter.CalendarDay calendarDay : mCalendarTags) {\n if (cellCalendar.equals(calendarDay)) {\n isCalendarTag = true;\n canvas.drawText(calendarDay.tag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint);\n }\n }\n if (!isCalendarTag) {\n canvas.drawText(mDefTag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint);\n }\n }\n\n // 绘制日期\n if (!isToady && !isPrevDay && !isInvalidDays && !isBusyDay) {\n canvas.drawText(String.format(\"%d\", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint);\n }\n\n dayOffset++;\n if (dayOffset == mNumDays) {\n dayOffset = 0;\n y += mRowHeight;\n }\n day++;\n }\n }\n\n /**\n * 根据坐标获取对应的日期\n * @param x\n * @param y\n * @return\n */\n public SimpleMonthAdapter.CalendarDay getDayFromLocation(float x, float y) {\n int padding = mPadding;\n if ((x < padding) || (x > mWidth - mPadding)) {\n return null;\n }\n\n int yDay = (int) (y - MONTH_HEADER_SIZE) / mRowHeight;\n int day = 1 + ((int) ((x - padding) * mNumDays / (mWidth - padding - mPadding)) - findDayOffset()) + yDay * mNumDays;\n\n if (mMonth > 11 || mMonth < 0 || CalendarUtils.getDaysInMonth(mMonth, mYear) < day || day < 1)\n return null;\n\n SimpleMonthAdapter.CalendarDay calendar = new SimpleMonthAdapter.CalendarDay(mYear, mMonth, day);\n\n // 获取日期下面的tag\n boolean flag = false;\n for (SimpleMonthAdapter.CalendarDay calendarTag : mCalendarTags) {\n if (calendarTag.compareTo(calendar) == 0) {\n flag = true;\n calendar = calendarTag;\n }\n }\n if (!flag) {\n calendar.tag = mDefTag;\n }\n return calendar;\n }\n\n /**\n * 初始化一些paint\n */\n protected void initView() {\n // 头部年份和月份的字体paint\n mYearMonthPaint = new Paint();\n mYearMonthPaint.setFakeBoldText(true);\n mYearMonthPaint.setAntiAlias(true);\n mYearMonthPaint.setTextSize(YEAR_MONTH_TEXT_SIZE);\n mYearMonthPaint.setTypeface(Typeface.create(mMonthTitleTypeface, Typeface.BOLD));\n mYearMonthPaint.setColor(mYearMonthTextColor);\n mYearMonthPaint.setTextAlign(Align.CENTER);\n mYearMonthPaint.setStyle(Style.FILL);\n\n // 头部星期几字体paint\n mWeekTextPaint = new Paint();\n mWeekTextPaint.setAntiAlias(true);\n mWeekTextPaint.setTextSize(WEEK_TEXT_SIZE);\n mWeekTextPaint.setColor(mWeekTextColor);\n mWeekTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL));\n mWeekTextPaint.setStyle(Style.FILL);\n mWeekTextPaint.setTextAlign(Align.CENTER);\n mWeekTextPaint.setFakeBoldText(true);\n\n// // 头部背景paint\n// mTitleBGPaint = new Paint();\n// mTitleBGPaint.setFakeBoldText(true);\n// mTitleBGPaint.setAntiAlias(true);\n// mTitleBGPaint.setColor(mSelectedDayTextColor);\n// mTitleBGPaint.setTextAlign(Align.CENTER);\n// mTitleBGPaint.setStyle(Style.FILL);\n\n // 被选中的日期背景paint\n mSelectedDayBgPaint = new Paint();\n mSelectedDayBgPaint.setFakeBoldText(true);\n mSelectedDayBgPaint.setAntiAlias(true);\n mSelectedDayBgPaint.setColor(mSelectedDaysBgColor);\n mSelectedDayBgPaint.setTextAlign(Align.CENTER);\n mSelectedDayBgPaint.setStyle(Style.FILL);\n mSelectedDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA);\n\n // 被占用的日期paint\n mBusyDayBgPaint = new Paint();\n mBusyDayBgPaint.setFakeBoldText(true);\n mBusyDayBgPaint.setAntiAlias(true);\n mBusyDayBgPaint.setColor(mBusyDaysBgColor);\n mBusyDayBgPaint.setTextSize(TAG_TEXT_SIZE);\n mBusyDayBgPaint.setTextAlign(Align.CENTER);\n mBusyDayBgPaint.setStyle(Style.FILL);\n mBusyDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA);\n\n // 禁用的日期paint\n mInValidDayBgPaint = new Paint();\n mInValidDayBgPaint.setFakeBoldText(true);\n mInValidDayBgPaint.setAntiAlias(true);\n mInValidDayBgPaint.setColor(mInValidDaysBgColor);\n mInValidDayBgPaint.setTextSize(TAG_TEXT_SIZE);\n mInValidDayBgPaint.setTextAlign(Align.CENTER);\n mInValidDayBgPaint.setStyle(Style.FILL);\n mInValidDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA);\n\n// // 被选中的日期字体paint\n// mSelectedDayTextPaint = new Paint();\n// mSelectedDayTextPaint.setAntiAlias(true);\n// mSelectedDayTextPaint.setTextSize(MONTH_DAY_LABEL_TEXT_SIZE);\n// mSelectedDayTextPaint.setColor(Color.WHITE);\n// mSelectedDayTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL));\n// mSelectedDayTextPaint.setStyle(Style.FILL);\n// mSelectedDayTextPaint.setTextAlign(Align.CENTER);\n// mSelectedDayTextPaint.setFakeBoldText(true);\n\n // 日期字体paint\n mDayTextPaint = new Paint();\n mDayTextPaint.setAntiAlias(true);\n mDayTextPaint.setColor(mDayTextColor);\n mDayTextPaint.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE);\n mDayTextPaint.setStyle(Style.FILL);\n mDayTextPaint.setTextAlign(Align.CENTER);\n mDayTextPaint.setFakeBoldText(false);\n\n // 标签字体paint\n mTagTextPaint = new Paint();\n mTagTextPaint.setAntiAlias(true);\n mTagTextPaint.setColor(mDayTextColor);\n mTagTextPaint.setTextSize(TAG_TEXT_SIZE);\n mTagTextPaint.setStyle(Style.FILL);\n mTagTextPaint.setTextAlign(Align.CENTER);\n mTagTextPaint.setFakeBoldText(false);\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n drawMonthTitle(canvas);\n drawMonthDayLabels(canvas);\n drawMonthCell(canvas);\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n // 设置simpleMonthView的宽度和高度\n setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mRowHeight * mNumRows + MONTH_HEADER_SIZE + ROW_SEPARATOR);\n }\n\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n mWidth = w;\n }\n\n public boolean onTouchEvent(MotionEvent event) {\n if (event.getAction() == MotionEvent.ACTION_UP) {\n SimpleMonthAdapter.CalendarDay calendarDay = getDayFromLocation(event.getX(), event.getY());\n// boolean isValidDay = false;\n if (calendarDay == null) {\n return true;\n }\n\n for (SimpleMonthAdapter.CalendarDay day : mInvalidDays) {\n // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选\n if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) {\n return true;\n }\n }\n\n for (SimpleMonthAdapter.CalendarDay day : mBusyDays) {\n // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选\n if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) {\n return true;\n }\n }\n onDayClick(calendarDay);\n }\n return true;\n }\n\n// public void reuse() {\n// mNumRows = DEFAULT_NUM_ROWS;\n// requestLayout();\n// }\n\n /**\n * 设置传递进来的参数\n *\n * @param params\n */\n public void setMonthParams(HashMap params) {\n if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {\n throw new InvalidParameterException(\"You must specify month and year for this view\");\n }\n setTag(params);\n\n// if (params.containsKey(VIEW_PARAMS_HEIGHT)) {\n// mRowHeight = (int) params.get(VIEW_PARAMS_HEIGHT);\n// if (mRowHeight < MIN_HEIGHT) {\n// mRowHeight = MIN_HEIGHT;\n// }\n// }\n\n if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_DATE)) {\n mStartDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_BEGIN_DATE);\n }\n if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_DATE)) {\n mEndDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_LAST_DATE);\n }\n\n if (params.containsKey(\"mNearestDay\")) {\n mNearestDay = (SimpleMonthAdapter.CalendarDay) params.get(\"mNearestDay\");\n }\n\n mMonth = (int) params.get(VIEW_PARAMS_MONTH);\n mYear = (int) params.get(VIEW_PARAMS_YEAR);\n\n mHasToday = false;\n mToday = -1;\n\n mCalendar.set(Calendar.MONTH, mMonth);\n mCalendar.set(Calendar.YEAR, mYear);\n mCalendar.set(Calendar.DAY_OF_MONTH, 1);\n mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);\n\n if (params.containsKey(VIEW_PARAMS_WEEK_START)) {\n mWeekStart = (int) params.get(VIEW_PARAMS_WEEK_START);\n } else {\n mWeekStart = mCalendar.getFirstDayOfWeek();\n }\n\n mNumCells = CalendarUtils.getDaysInMonth(mMonth, mYear);\n for (int i = 0; i < mNumCells; i++) {\n final int day = i + 1;\n if (sameDay(day, today)) {\n mHasToday = true;\n mToday = day;\n }\n }\n\n mNumRows = calculateNumRows();\n }\n\n public void setOnDayClickListener(OnDayClickListener onDayClickListener) {\n mOnDayClickListener = onDayClickListener;\n }\n\n public interface OnDayClickListener {\n void onDayClick(SimpleMonthView simpleMonthView, SimpleMonthAdapter.CalendarDay calendarDay);\n }\n\n /**\n * 绘制cell\n *\n * @param canvas\n * @param x\n * @param y\n */\n private void drawDayBg(Canvas canvas, int x, int y, Paint paint) {\n RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, y - DAY_SELECTED_RECT_SIZE,\n x + DAY_SELECTED_RECT_SIZE, y + DAY_SELECTED_RECT_SIZE);\n canvas.drawRoundRect(rectF, 10.0f, 10.0f, paint);\n }\n\n /**\n * 在使用drawText方法时文字不能根据y坐标居中,所以重新计算y坐标\n * @param paint\n * @param y\n * @return\n */\n private float getTextYCenter(Paint paint, int y) {\n Paint.FontMetrics fontMetrics = paint.getFontMetrics();\n float fontTotalHeight = fontMetrics.bottom - fontMetrics.top;\n float offY = fontTotalHeight / 2 - fontMetrics.bottom;\n return y + offY;\n }\n}"},"message":{"kind":"string","value":"fix bug\n"},"old_file":{"kind":"string","value":"library/src/main/java/com/henry/calendarview/SimpleMonthView.java"},"subject":{"kind":"string","value":"fix bug"}}},{"rowIdx":728,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e6a55250037e766d5f65fc2a1222d17996d2fbca"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"apache/rampart,apache/rampart"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2004,2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.rahas;\n\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.axiom.om.impl.dom.factory.OMDOMFactory;\nimport org.apache.axiom.om.util.Base64;\nimport org.apache.axis2.addressing.AddressingConstants;\nimport org.apache.axis2.context.MessageContext;\nimport org.apache.ws.security.WSConstants;\nimport org.apache.ws.security.WSSecurityEngineResult;\nimport org.apache.ws.security.WSSecurityException;\nimport org.apache.ws.security.handler.WSHandlerConstants;\nimport org.apache.ws.security.handler.WSHandlerResult;\nimport org.apache.ws.security.message.token.SecurityTokenReference;\nimport org.opensaml.SAMLAssertion;\nimport org.w3c.dom.Element;\n\nimport javax.xml.namespace.QName;\n\nimport java.security.Principal;\nimport java.security.cert.X509Certificate;\nimport java.util.Vector;\n\n/**\n * Common data items on WS-Trust request messages\n */\npublic class RahasData {\n\n private MessageContext inMessageContext;\n\n private OMElement rstElement;\n\n private int version = -1;\n\n private String wstNs;\n\n private String requestType;\n\n private String tokenType;\n \n private String tokenId;\n\n private int keysize = -1;\n\n private String computedKeyAlgo;\n\n private String keyType;\n\n private String appliesToAddress;\n \n private OMElement appliesToEpr;\n\n private Principal principal;\n\n private X509Certificate clientCert;\n\n private byte[] ephmeralKey;\n\n private byte[] requestEntropy;\n\n private byte[] responseEntropy;\n\n private String addressingNs;\n\n private String soapNs;\n \n private OMElement claimElem;\n \n private String claimDialect;\n \n private SAMLAssertion assertion;\n /**\n * Create a new RahasData instance and populate it with the information from\n * the request.\n *\n * @throws TrustException RequestSecurityToken element is invalid.\n */\n public RahasData(MessageContext inMessageContext) throws TrustException {\n\n this.inMessageContext = inMessageContext;\n\n //Check for an authenticated Principal\n this.processWSS4JSecurityResults();\n\n // Find out the incoming addressing version\n this.addressingNs = (String) this.inMessageContext\n .getProperty(AddressingConstants.WS_ADDRESSING_VERSION);\n\n this.rstElement = this.inMessageContext.getEnvelope().getBody()\n .getFirstElement();\n\n this.soapNs = this.inMessageContext.getEnvelope().getNamespace()\n .getNamespaceURI();\n\n this.wstNs = this.rstElement.getNamespace().getNamespaceURI();\n\n int ver = TrustUtil.getWSTVersion(this.wstNs);\n\n if (ver == -1) {\n throw new TrustException(TrustException.INVALID_REQUEST);\n } else {\n this.version = ver;\n }\n\n this.processRequestType();\n\n this.processTokenType();\n\n this.processKeyType();\n\n this.processKeySize();\n\n this.processAppliesTo();\n\n this.processEntropy();\n \n this.processClaims();\n \n this.processValidateTarget();\n \n this.processRenewTarget();\n\n }\n\n /**\n * Processes the authenticated user information from the WSS4J security\n * results.\n *\n * @throws TrustException\n */\n private void processWSS4JSecurityResults() throws TrustException {\n\n /*\n * User can be identifier using a UsernameToken or a certificate - If a\n * certificate is found then we use that to - identify the user and -\n * encrypt the response (if required) - If a UsernameToken is found then\n * we will not be encrypting the response\n */\n\n Vector results;\n if ((results = (Vector) this.inMessageContext\n .getProperty(WSHandlerConstants.RECV_RESULTS)) == null) {\n throw new TrustException(TrustException.REQUEST_FAILED);\n } else {\n\n for (int i = 0; i < results.size(); i++) {\n WSHandlerResult rResult = (WSHandlerResult) results.get(i);\n Vector wsSecEngineResults = rResult.getResults();\n\n for (int j = 0; j < wsSecEngineResults.size(); j++) {\n WSSecurityEngineResult wser = (WSSecurityEngineResult) wsSecEngineResults\n .get(j);\n Object principalObject = wser.get(WSSecurityEngineResult.TAG_PRINCIPAL);\n int act = ((Integer)wser.get(WSSecurityEngineResult.TAG_ACTION)).\n intValue();\n if (act == WSConstants.SIGN && principalObject != null) {\n this.clientCert = (X509Certificate) wser\n .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);\n this.principal = (Principal)principalObject;\n } else if (act == WSConstants.UT && principalObject != null) {\n this.principal = (Principal)principalObject;\n } else if (act == WSConstants.BST) {\n final X509Certificate[] certificates = \n (X509Certificate[]) wser\n .get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);\n this.clientCert = certificates[0];\n this.principal = this.clientCert.getSubjectDN();\n } else if (act == WSConstants.ST_UNSIGNED) {\n this.assertion = (SAMLAssertion) wser\n .get(WSSecurityEngineResult.TAG_SAML_ASSERTION);\n \n }\n }\n }\n // If the principal or a SAML assertion is missing\n if (this.principal == null && this.assertion == null) {\n throw new TrustException(TrustException.REQUEST_FAILED);\n }\n }\n }\n\n private void processAppliesTo() throws TrustException {\n\n OMElement appliesToElem = this.rstElement\n .getFirstChildWithName(new QName(RahasConstants.WSP_NS,\n RahasConstants.IssuanceBindingLocalNames.\n APPLIES_TO));\n\n if (appliesToElem != null) {\n OMElement eprElem = appliesToElem.getFirstElement();\n this.appliesToEpr = eprElem;\n \n // If there were no addressing headers\n // The find the addressing version using the EPR element\n if (this.addressingNs == null) {\n this.addressingNs = eprElem.getNamespace()\n .getNamespaceURI();\n }\n\n if (eprElem != null) {\n \n //Of the epr is a web service then try to get the addr\n \n OMElement addrElem = eprElem\n .getFirstChildWithName(new QName(\n this.addressingNs,\n AddressingConstants.EPR_ADDRESS));\n if (addrElem != null && addrElem.getText() != null\n && !\"\".equals(addrElem.getText().trim())) {\n this.appliesToAddress = addrElem.getText().trim();\n } \n } else {\n throw new TrustException(\"invalidAppliesToElem\");\n }\n }\n }\n\n private void processRequestType() throws TrustException {\n OMElement reqTypeElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.REQUEST_TYPE));\n\n if (reqTypeElem == null ||\n reqTypeElem.getText() == null ||\n reqTypeElem.getText().trim().length() == 0) {\n throw new TrustException(TrustException.INVALID_REQUEST);\n } else {\n this.requestType = reqTypeElem.getText().trim();\n }\n }\n\n private void processTokenType() {\n OMElement tokTypeElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.TOKEN_TYPE));\n\n if (tokTypeElem != null && tokTypeElem.getText() != null\n && !\"\".equals(tokTypeElem.getText().trim())) {\n this.tokenType = tokTypeElem.getText().trim();\n }\n }\n\n /**\n * Find the value of the KeyType element of the RST\n */\n private void processKeyType() {\n OMElement keyTypeElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.IssuanceBindingLocalNames.KEY_TYPE));\n if (keyTypeElem != null) {\n String text = keyTypeElem.getText();\n if (text != null && !\"\".equals(text.trim())) {\n this.keyType = text.trim();\n }\n }\n }\n\n /**\n * Finds the KeySize and creates an empty ephmeral key.\n *\n * @throws TrustException\n */\n private void processKeySize() throws TrustException {\n OMElement keySizeElem =\n this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.IssuanceBindingLocalNames.\n KEY_SIZE));\n if (keySizeElem != null) {\n String text = keySizeElem.getText();\n if (text != null && !\"\".equals(text.trim())) {\n try {\n //Set key size\n this.keysize = Integer.parseInt(text.trim());\n\n //Create an empty array to hold the key\n this.ephmeralKey = new byte[this.keysize/8];\n } catch (NumberFormatException e) {\n throw new TrustException(TrustException.INVALID_REQUEST,\n new String[]{\"invalid wst:Keysize value\"}, e);\n }\n }\n }\n this.keysize = -1;\n }\n \n /**\n * Processes a claims.\n *\n */\n private void processClaims() throws TrustException{\n \tclaimElem = this.rstElement\n \t\t\t.getFirstChildWithName(new QName(this.wstNs,\n \t\t\t\t\tRahasConstants.IssuanceBindingLocalNames.CLAIMS));\n \t\n \tif(claimElem != null){\n \t\tclaimDialect = claimElem.getAttributeValue(new QName(this.wstNs,\n \t\t\t\t\tRahasConstants.ATTR_CLAIMS_DIALECT));\n \t}\n \t\n }\n \n private void processValidateTarget()throws TrustException{\n \n OMElement validateTargetElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.VALIDATE_TARGET));\n \n if (validateTargetElem != null) {\n \n OMElement strElem = validateTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS,\n \"SecurityTokenReference\"));\n \n Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), \n strElem.getXMLStreamReader()).getDocumentElement());\n \n try {\n SecurityTokenReference str = new SecurityTokenReference((Element)elem);\n if (str.containsReference()) {\n tokenId = str.getReference().getURI();\n } else if(str.containsKeyIdentifier()){\n \ttokenId = str.getKeyIdentifierValue();\n }\n } catch (WSSecurityException e) {\n throw new TrustException(\"errorExtractingTokenId\",e);\n } \n }\n }\n \n private void processRenewTarget()throws TrustException{\n \n OMElement renewTargetElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.RENEW_TARGET));\n if (renewTargetElem != null) {\n \n OMElement strElem = renewTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS,\n \"SecurityTokenReference\"));\n \n Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), \n strElem.getXMLStreamReader()).getDocumentElement());\n \n try {\n SecurityTokenReference str = new SecurityTokenReference((Element)elem);\n if (str.containsReference()) {\n tokenId = str.getReference().getURI();\n } else if(str.containsKeyIdentifier()){\n \ttokenId = str.getKeyIdentifierValue();\n }\n if(tokenId == null){\n if(str.containsKeyIdentifier()){\n tokenId = str.getKeyIdentifierValue();\n }\n }\n } catch (WSSecurityException e) {\n throw new TrustException(\"errorExtractingTokenId\",e);\n } \n }\n }\n\n /**\n * Process wst:Entropy element in the request.\n */\n private void processEntropy() throws TrustException {\n OMElement entropyElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.IssuanceBindingLocalNames.ENTROPY));\n\n if (entropyElem != null) {\n OMElement binSecElem = entropyElem.getFirstElement();\n if (binSecElem != null && binSecElem.getText() != null\n && !\"\".equals(binSecElem.getText())) {\n this.requestEntropy = Base64.decode(binSecElem.getText());\n } else {\n throw new TrustException(\"malformedEntropyElement\",\n new String[]{entropyElem.toString()});\n }\n\n }\n }\n\n /**\n * @return Returns the appliesToAddress.\n */\n public String getAppliesToAddress() {\n return appliesToAddress;\n }\n\n /**\n * @return Returns the clientCert.\n */\n public X509Certificate getClientCert() {\n return clientCert;\n }\n\n /**\n * @return Returns the computedKeyAlgo.\n */\n public String getComputedKeyAlgo() {\n return computedKeyAlgo;\n }\n\n /**\n * @return Returns the ephmeralKey.\n */\n public byte[] getEphmeralKey() {\n return ephmeralKey;\n }\n\n /**\n * @return Returns the inMessageContext.\n */\n public MessageContext getInMessageContext() {\n return inMessageContext;\n }\n\n /**\n * @return Returns the keysize.\n */\n public int getKeysize() {\n return keysize;\n }\n\n /**\n * @return Returns the keyType.\n */\n public String getKeyType() {\n return keyType;\n }\n\n /**\n * @return Returns the principal.\n */\n public Principal getPrincipal() {\n return principal;\n }\n\n /**\n * @return Returns the requestEntropy.\n */\n public byte[] getRequestEntropy() {\n return requestEntropy;\n }\n\n /**\n * @return Returns the requestType.\n */\n public String getRequestType() {\n return requestType;\n }\n\n /**\n * @return Returns the responseEntropy.\n */\n public byte[] getResponseEntropy() {\n return responseEntropy;\n }\n\n /**\n * @return Returns the rstElement.\n */\n public OMElement getRstElement() {\n return rstElement;\n }\n\n /**\n * @return Returns the tokenType.\n */\n public String getTokenType() {\n return tokenType;\n }\n\n /**\n * @return Returns the version.\n */\n public int getVersion() {\n return version;\n }\n\n /**\n * @return Returns the addressingNs.\n */\n public String getAddressingNs() {\n return addressingNs;\n }\n\n /**\n * @return Returns the wstNs.\n */\n public String getWstNs() {\n return wstNs;\n }\n\n /**\n * @return Returns the soapNs.\n */\n public String getSoapNs() {\n return soapNs;\n }\n\n /**\n * @return Returns the tokenId.\n */\n public String getTokenId() {\n return tokenId;\n }\n\n /**\n * @param responseEntropy The responseEntropy to set.\n */\n public void setResponseEntropy(byte[] responseEntropy) {\n this.responseEntropy = responseEntropy;\n }\n\n /**\n * @param ephmeralKey The ephmeralKey to set.\n */\n public void setEphmeralKey(byte[] ephmeralKey) {\n this.ephmeralKey = ephmeralKey;\n }\n\n\tpublic String getClaimDialect() {\n\t\treturn claimDialect;\n\t}\n\n\tpublic OMElement getClaimElem() {\n\t\treturn claimElem;\n\t}\n\n public OMElement getAppliesToEpr() {\n return appliesToEpr;\n }\n\n\n}\n"},"new_file":{"kind":"string","value":"modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2004,2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.rahas;\n\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.axiom.om.impl.dom.factory.OMDOMFactory;\nimport org.apache.axiom.om.util.Base64;\nimport org.apache.axis2.addressing.AddressingConstants;\nimport org.apache.axis2.context.MessageContext;\nimport org.apache.ws.security.WSConstants;\nimport org.apache.ws.security.WSSecurityEngineResult;\nimport org.apache.ws.security.WSSecurityException;\nimport org.apache.ws.security.handler.WSHandlerConstants;\nimport org.apache.ws.security.handler.WSHandlerResult;\nimport org.apache.ws.security.message.token.SecurityTokenReference;\nimport org.opensaml.SAMLAssertion;\nimport org.w3c.dom.Element;\n\nimport javax.xml.namespace.QName;\n\nimport java.security.Principal;\nimport java.security.cert.X509Certificate;\nimport java.util.Vector;\n\n/**\n * Common data items on WS-Trust request messages\n */\npublic class RahasData {\n\n private MessageContext inMessageContext;\n\n private OMElement rstElement;\n\n private int version = -1;\n\n private String wstNs;\n\n private String requestType;\n\n private String tokenType;\n \n private String tokenId;\n\n private int keysize = -1;\n\n private String computedKeyAlgo;\n\n private String keyType;\n\n private String appliesToAddress;\n \n private OMElement appliesToEpr;\n\n private Principal principal;\n\n private X509Certificate clientCert;\n\n private byte[] ephmeralKey;\n\n private byte[] requestEntropy;\n\n private byte[] responseEntropy;\n\n private String addressingNs;\n\n private String soapNs;\n \n private OMElement claimElem;\n \n private String claimDialect;\n \n private SAMLAssertion assertion;\n /**\n * Create a new RahasData instance and populate it with the information from\n * the request.\n *\n * @throws TrustException RequestSecurityToken element is invalid.\n */\n public RahasData(MessageContext inMessageContext) throws TrustException {\n\n this.inMessageContext = inMessageContext;\n\n //Check for an authenticated Principal\n this.processWSS4JSecurityResults();\n\n // Find out the incoming addressing version\n this.addressingNs = (String) this.inMessageContext\n .getProperty(AddressingConstants.WS_ADDRESSING_VERSION);\n\n this.rstElement = this.inMessageContext.getEnvelope().getBody()\n .getFirstElement();\n\n this.soapNs = this.inMessageContext.getEnvelope().getNamespace()\n .getNamespaceURI();\n\n this.wstNs = this.rstElement.getNamespace().getNamespaceURI();\n\n int ver = TrustUtil.getWSTVersion(this.wstNs);\n\n if (ver == -1) {\n throw new TrustException(TrustException.INVALID_REQUEST);\n } else {\n this.version = ver;\n }\n\n this.processRequestType();\n\n this.processTokenType();\n\n this.processKeyType();\n\n this.processKeySize();\n\n this.processAppliesTo();\n\n this.processEntropy();\n \n this.processClaims();\n \n this.processValidateTarget();\n \n this.processRenewTarget();\n\n }\n\n /**\n * Processes the authenticated user information from the WSS4J security\n * results.\n *\n * @throws TrustException\n */\n private void processWSS4JSecurityResults() throws TrustException {\n\n /*\n * User can be identifier using a UsernameToken or a certificate - If a\n * certificate is found then we use that to - identify the user and -\n * encrypt the response (if required) - If a UsernameToken is found then\n * we will not be encrypting the response\n */\n\n Vector results;\n if ((results = (Vector) this.inMessageContext\n .getProperty(WSHandlerConstants.RECV_RESULTS)) == null) {\n throw new TrustException(TrustException.REQUEST_FAILED);\n } else {\n\n for (int i = 0; i < results.size(); i++) {\n WSHandlerResult rResult = (WSHandlerResult) results.get(i);\n Vector wsSecEngineResults = rResult.getResults();\n\n for (int j = 0; j < wsSecEngineResults.size(); j++) {\n WSSecurityEngineResult wser = (WSSecurityEngineResult) wsSecEngineResults\n .get(j);\n Object principalObject = wser.get(WSSecurityEngineResult.TAG_PRINCIPAL);\n int act = ((Integer)wser.get(WSSecurityEngineResult.TAG_ACTION)).\n intValue();\n if (act == WSConstants.SIGN && principalObject != null) {\n this.clientCert = (X509Certificate) wser\n .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);\n this.principal = (Principal)principalObject;\n } else if (act == WSConstants.UT && principalObject != null) {\n this.principal = (Principal)principalObject;\n } else if (act == WSConstants.BST) {\n final X509Certificate[] certificates = \n (X509Certificate[]) wser\n .get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);\n this.clientCert = certificates[0];\n this.principal = this.clientCert.getSubjectDN();\n } else if (act == WSConstants.ST_UNSIGNED) {\n this.assertion = (SAMLAssertion) wser\n .get(WSSecurityEngineResult.TAG_SAML_ASSERTION);\n \n }\n }\n }\n // If the principal or a SAML assertion is missing\n if (this.principal == null && this.assertion == null) {\n throw new TrustException(TrustException.REQUEST_FAILED);\n }\n }\n }\n\n private void processAppliesTo() throws TrustException {\n\n OMElement appliesToElem = this.rstElement\n .getFirstChildWithName(new QName(RahasConstants.WSP_NS,\n RahasConstants.IssuanceBindingLocalNames.\n APPLIES_TO));\n\n if (appliesToElem != null) {\n OMElement eprElem = appliesToElem.getFirstElement();\n this.appliesToEpr = eprElem;\n \n // If there were no addressing headers\n // The find the addressing version using the EPR element\n if (this.addressingNs == null) {\n this.addressingNs = eprElem.getNamespace()\n .getNamespaceURI();\n }\n\n if (eprElem != null) {\n \n //Of the epr is a web service then try to get the addr\n \n OMElement addrElem = eprElem\n .getFirstChildWithName(new QName(\n this.addressingNs,\n AddressingConstants.EPR_ADDRESS));\n if (addrElem != null && addrElem.getText() != null\n && !\"\".equals(addrElem.getText().trim())) {\n this.appliesToAddress = addrElem.getText().trim();\n } \n } else {\n throw new TrustException(\"invalidAppliesToElem\");\n }\n }\n }\n\n private void processRequestType() throws TrustException {\n OMElement reqTypeElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.REQUEST_TYPE));\n\n if (reqTypeElem == null ||\n reqTypeElem.getText() == null ||\n reqTypeElem.getText().trim().length() == 0) {\n throw new TrustException(TrustException.INVALID_REQUEST);\n } else {\n this.requestType = reqTypeElem.getText().trim();\n }\n }\n\n private void processTokenType() {\n OMElement tokTypeElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.TOKEN_TYPE));\n\n if (tokTypeElem != null && tokTypeElem.getText() != null\n && !\"\".equals(tokTypeElem.getText().trim())) {\n this.tokenType = tokTypeElem.getText().trim();\n }\n }\n\n /**\n * Find the value of the KeyType element of the RST\n */\n private void processKeyType() {\n OMElement keyTypeElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.IssuanceBindingLocalNames.KEY_TYPE));\n if (keyTypeElem != null) {\n String text = keyTypeElem.getText();\n if (text != null && !\"\".equals(text.trim())) {\n this.keyType = text.trim();\n }\n }\n }\n\n /**\n * Finds the KeySize and creates an empty ephmeral key.\n *\n * @throws TrustException\n */\n private void processKeySize() throws TrustException {\n OMElement keySizeElem =\n this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.IssuanceBindingLocalNames.\n KEY_SIZE));\n if (keySizeElem != null) {\n String text = keySizeElem.getText();\n if (text != null && !\"\".equals(text.trim())) {\n try {\n //Set key size\n this.keysize = Integer.parseInt(text.trim());\n\n //Create an empty array to hold the key\n this.ephmeralKey = new byte[this.keysize/8];\n } catch (NumberFormatException e) {\n throw new TrustException(TrustException.INVALID_REQUEST,\n new String[]{\"invalid wst:Keysize value\"}, e);\n }\n }\n }\n this.keysize = -1;\n }\n \n /**\n * Processes a claims.\n *\n */\n private void processClaims() throws TrustException{\n \tclaimElem = this.rstElement\n \t\t\t.getFirstChildWithName(new QName(this.wstNs,\n \t\t\t\t\tRahasConstants.IssuanceBindingLocalNames.CLAIMS));\n \t\n \tif(claimElem != null){\n \t\tclaimDialect = claimElem.getAttributeValue(new QName(this.wstNs,\n \t\t\t\t\tRahasConstants.ATTR_CLAIMS_DIALECT));\n \t}\n \t\n }\n \n private void processValidateTarget()throws TrustException{\n \n OMElement validateTargetElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.VALIDATE_TARGET));\n \n if (validateTargetElem != null) {\n \n OMElement strElem = validateTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS,\n \"SecurityTokenReference\"));\n \n Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), \n strElem.getXMLStreamReader()).getDocumentElement());\n \n try {\n SecurityTokenReference str = new SecurityTokenReference((Element)elem);\n if (str.containsReference()) {\n tokenId = str.getReference().getURI();\n }\n } catch (WSSecurityException e) {\n throw new TrustException(\"errorExtractingTokenId\",e);\n } \n }\n }\n \n private void processRenewTarget()throws TrustException{\n \n OMElement renewTargetElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.LocalNames.RENEW_TARGET));\n if (renewTargetElem != null) {\n \n OMElement strElem = renewTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS,\n \"SecurityTokenReference\"));\n \n Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), \n strElem.getXMLStreamReader()).getDocumentElement());\n \n try {\n SecurityTokenReference str = new SecurityTokenReference((Element)elem);\n if (str.containsReference()) {\n tokenId = str.getReference().getURI();\n }\n if(tokenId == null){\n if(str.containsKeyIdentifier()){\n tokenId = str.getKeyIdentifierValue();\n }\n }\n } catch (WSSecurityException e) {\n throw new TrustException(\"errorExtractingTokenId\",e);\n } \n }\n }\n\n /**\n * Process wst:Entropy element in the request.\n */\n private void processEntropy() throws TrustException {\n OMElement entropyElem = this.rstElement\n .getFirstChildWithName(new QName(this.wstNs,\n RahasConstants.IssuanceBindingLocalNames.ENTROPY));\n\n if (entropyElem != null) {\n OMElement binSecElem = entropyElem.getFirstElement();\n if (binSecElem != null && binSecElem.getText() != null\n && !\"\".equals(binSecElem.getText())) {\n this.requestEntropy = Base64.decode(binSecElem.getText());\n } else {\n throw new TrustException(\"malformedEntropyElement\",\n new String[]{entropyElem.toString()});\n }\n\n }\n }\n\n /**\n * @return Returns the appliesToAddress.\n */\n public String getAppliesToAddress() {\n return appliesToAddress;\n }\n\n /**\n * @return Returns the clientCert.\n */\n public X509Certificate getClientCert() {\n return clientCert;\n }\n\n /**\n * @return Returns the computedKeyAlgo.\n */\n public String getComputedKeyAlgo() {\n return computedKeyAlgo;\n }\n\n /**\n * @return Returns the ephmeralKey.\n */\n public byte[] getEphmeralKey() {\n return ephmeralKey;\n }\n\n /**\n * @return Returns the inMessageContext.\n */\n public MessageContext getInMessageContext() {\n return inMessageContext;\n }\n\n /**\n * @return Returns the keysize.\n */\n public int getKeysize() {\n return keysize;\n }\n\n /**\n * @return Returns the keyType.\n */\n public String getKeyType() {\n return keyType;\n }\n\n /**\n * @return Returns the principal.\n */\n public Principal getPrincipal() {\n return principal;\n }\n\n /**\n * @return Returns the requestEntropy.\n */\n public byte[] getRequestEntropy() {\n return requestEntropy;\n }\n\n /**\n * @return Returns the requestType.\n */\n public String getRequestType() {\n return requestType;\n }\n\n /**\n * @return Returns the responseEntropy.\n */\n public byte[] getResponseEntropy() {\n return responseEntropy;\n }\n\n /**\n * @return Returns the rstElement.\n */\n public OMElement getRstElement() {\n return rstElement;\n }\n\n /**\n * @return Returns the tokenType.\n */\n public String getTokenType() {\n return tokenType;\n }\n\n /**\n * @return Returns the version.\n */\n public int getVersion() {\n return version;\n }\n\n /**\n * @return Returns the addressingNs.\n */\n public String getAddressingNs() {\n return addressingNs;\n }\n\n /**\n * @return Returns the wstNs.\n */\n public String getWstNs() {\n return wstNs;\n }\n\n /**\n * @return Returns the soapNs.\n */\n public String getSoapNs() {\n return soapNs;\n }\n\n /**\n * @return Returns the tokenId.\n */\n public String getTokenId() {\n return tokenId;\n }\n\n /**\n * @param responseEntropy The responseEntropy to set.\n */\n public void setResponseEntropy(byte[] responseEntropy) {\n this.responseEntropy = responseEntropy;\n }\n\n /**\n * @param ephmeralKey The ephmeralKey to set.\n */\n public void setEphmeralKey(byte[] ephmeralKey) {\n this.ephmeralKey = ephmeralKey;\n }\n\n\tpublic String getClaimDialect() {\n\t\treturn claimDialect;\n\t}\n\n\tpublic OMElement getClaimElem() {\n\t\treturn claimElem;\n\t}\n\n public OMElement getAppliesToEpr() {\n return appliesToEpr;\n }\n\n\n}\n"},"message":{"kind":"string","value":"Fixed the problem of renewing a STS token not working - RAMPART-274\n\ngit-svn-id: 3a0daac14c5e6bfdff62a55945ca5e1dd585acf7@1051532 13f79535-47bb-0310-9956-ffa450edef68\n"},"old_file":{"kind":"string","value":"modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java"},"subject":{"kind":"string","value":"Fixed the problem of renewing a STS token not working - RAMPART-274"}}},{"rowIdx":729,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-2-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"59f4df1d2d39e1dee5278626bd2efb16d4a56847"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"mwilliamson/java-mammoth"},"new_contents":{"kind":"string","value":"package org.zwobble.mammoth.tests.docx;\n\nimport org.hamcrest.Matcher;\nimport org.hamcrest.Matchers;\nimport org.junit.jupiter.api.DynamicTest;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.TestFactory;\nimport org.zwobble.mammoth.internal.archives.Archive;\nimport org.zwobble.mammoth.internal.archives.InMemoryArchive;\nimport org.zwobble.mammoth.internal.documents.*;\nimport org.zwobble.mammoth.internal.docx.*;\nimport org.zwobble.mammoth.internal.results.InternalResult;\nimport org.zwobble.mammoth.internal.xml.XmlElement;\nimport org.zwobble.mammoth.internal.xml.XmlNode;\nimport org.zwobble.mammoth.internal.xml.XmlNodes;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\nimport static java.util.Arrays.asList;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\nimport static org.zwobble.mammoth.internal.documents.NoteReference.endnoteReference;\nimport static org.zwobble.mammoth.internal.documents.NoteReference.footnoteReference;\nimport static org.zwobble.mammoth.internal.util.Lists.eagerMap;\nimport static org.zwobble.mammoth.internal.util.Lists.list;\nimport static org.zwobble.mammoth.internal.util.Maps.map;\nimport static org.zwobble.mammoth.internal.util.Streams.toByteArray;\nimport static org.zwobble.mammoth.internal.xml.XmlNodes.element;\nimport static org.zwobble.mammoth.tests.DeepReflectionMatcher.deepEquals;\nimport static org.zwobble.mammoth.tests.ResultMatchers.*;\nimport static org.zwobble.mammoth.tests.documents.DocumentElementMakers.*;\nimport static org.zwobble.mammoth.tests.docx.BodyXmlReaderMakers.bodyReader;\nimport static org.zwobble.mammoth.tests.docx.DocumentMatchers.*;\nimport static org.zwobble.mammoth.tests.docx.OfficeXmlBuilders.*;\n\npublic class BodyXmlTests {\n @Test\n public void textFromTextElementIsRead() {\n XmlElement element = textXml(\"Hello!\");\n assertThat(readSuccess(bodyReader(), element), isTextElement(\"Hello!\"));\n }\n\n @Test\n public void canReadTextWithinRun() {\n XmlElement element = runXml(list(textXml(\"Hello!\")));\n assertThat(\n readSuccess(bodyReader(), element),\n isRun(run(withChildren(text(\"Hello!\")))));\n }\n\n @Test\n public void canReadTextWithinParagraph() {\n XmlElement element = paragraphXml(list(runXml(list(textXml(\"Hello!\")))));\n assertThat(\n readSuccess(bodyReader(), element),\n isParagraph(paragraph(withChildren(run(withChildren(text(\"Hello!\")))))));\n }\n\n @Test\n public void paragraphHasNoStyleIfItHasNoProperties() {\n XmlElement element = paragraphXml();\n assertThat(\n readSuccess(bodyReader(), element),\n hasStyle(Optional.empty()));\n }\n\n @Test\n public void whenParagraphHasStyleIdInStylesThenStyleNameIsReadFromStyles() {\n XmlElement element = paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:pStyle\", map(\"w:val\", \"Heading1\"))))));\n\n Style style = new Style(\"Heading1\", Optional.of(\"Heading 1\"));\n Styles styles = new Styles(\n map(\"Heading1\", style),\n map(),\n map(),\n map()\n );\n assertThat(\n readSuccess(bodyReader(styles), element),\n hasStyle(Optional.of(style)));\n }\n\n @Test\n public void warningIsEmittedWhenParagraphStyleCannotBeFound() {\n XmlElement element = paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:pStyle\", map(\"w:val\", \"Heading1\"))))));\n assertThat(\n read(bodyReader(), element),\n isInternalResult(\n hasStyle(Optional.of(new Style(\"Heading1\", Optional.empty()))),\n list(\"Paragraph style with ID Heading1 was referenced but not defined in the document\")));\n }\n\n @Nested\n public class ParagraphIndentTests {\n @Test\n public void whenWStartIsSetThenStartIndentIsReadFromWStart() {\n XmlElement paragraphXml = paragraphWithIndent(map(\"w:start\", \"720\", \"w:left\", \"40\"));\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(hasIndentStart(Optional.of(\"720\")))\n );\n }\n\n @Test\n public void whenWStartIsNotSetThenStartIndentIsReadFromWLeft() {\n XmlElement paragraphXml = paragraphWithIndent(map(\"w:left\", \"720\"));\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(hasIndentStart(Optional.of(\"720\")))\n );\n }\n\n @Test\n public void whenWEndIsSetThenEndIndentIsReadFromWEnd() {\n XmlElement paragraphXml = paragraphWithIndent(map(\"w:end\", \"720\", \"w:right\", \"40\"));\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(hasIndentEnd(Optional.of(\"720\")))\n );\n }\n\n @Test\n public void whenWEndIsNotSetThenEndIndentIsReadFromWRight() {\n XmlElement paragraphXml = paragraphWithIndent(map(\"w:right\", \"720\"));\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(hasIndentEnd(Optional.of(\"720\")))\n );\n }\n\n @Test\n public void paragraphHasIndentFirstLineReadFromParagraphPropertiesIfPresent() {\n XmlElement paragraphXml = paragraphWithIndent(map(\"w:firstLine\", \"720\"));\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(hasIndentFirstLine(Optional.of(\"720\")))\n );\n }\n\n @Test\n public void paragraphHasIndentHangingReadFromParagraphPropertiesIfPresent() {\n XmlElement paragraphXml = paragraphWithIndent(map(\"w:hanging\", \"720\"));\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(hasIndentHanging(Optional.of(\"720\")))\n );\n }\n\n @Test\n public void whenIndentAttributesArentSetThenIndentsAreNotSet() {\n XmlElement paragraphXml = paragraphWithIndent(map());\n assertThat(\n readSuccess(bodyReader(), paragraphXml),\n hasIndent(allOf(\n hasIndentStart(Optional.empty()),\n hasIndentEnd(Optional.empty()),\n hasIndentFirstLine(Optional.empty()),\n hasIndentHanging(Optional.empty())\n ))\n );\n }\n\n private XmlElement paragraphWithIndent(Map attributes) {\n return paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:ind\", attributes)\n ))\n ));\n }\n }\n\n @Test\n public void paragraphHasNoNumberingIfItHasNoNumberingProperties() {\n XmlElement element = paragraphXml();\n assertThat(\n readSuccess(bodyReader(), element),\n hasNumbering(Optional.empty()));\n }\n\n @Test\n public void paragraphHasNumberingPropertiesFromParagraphPropertiesIfPresent() {\n XmlElement element = paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:numPr\", map(), list(\n element(\"w:ilvl\", map(\"w:val\", \"1\")),\n element(\"w:numId\", map(\"w:val\", \"42\"))))))));\n\n Numbering numbering = numberingMap(map(\"42\", map(\"1\", Numbering.AbstractNumLevel.ordered(\"1\"))));\n\n assertThat(\n readSuccess(bodyReader(numbering), element),\n hasNumbering(NumberingLevel.ordered(\"1\")));\n }\n\n @Test\n public void numberingOnParagraphStyleTakesPrecedenceOverNumPr() {\n XmlElement element = paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:pStyle\", map(\"w:val\", \"List\")),\n element(\"w:numPr\", map(), list(\n element(\"w:ilvl\", map(\"w:val\", \"1\")),\n element(\"w:numId\", map(\"w:val\", \"42\"))\n ))\n ))\n ));\n\n Numbering numbering = numberingMap(map(\n \"42\", map(\"1\", new Numbering.AbstractNumLevel(\"1\", false, Optional.empty())),\n \"43\", map(\"1\", new Numbering.AbstractNumLevel(\"1\", true, Optional.of(\"List\")))\n ));\n Styles styles = new Styles(\n map(\"List\", new Style(\"List\", Optional.empty())),\n map(),\n map(),\n map()\n );\n\n assertThat(\n readSuccess(bodyReader(numbering, styles), element),\n hasNumbering(NumberingLevel.ordered(\"1\"))\n );\n }\n\n @Test\n public void numberingPropertiesAreIgnoredIfLevelIsMissing() {\n // TODO: emit warning\n XmlElement element = paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:numPr\", map(), list(\n element(\"w:numId\", map(\"w:val\", \"42\"))))))));\n\n Numbering numbering = numberingMap(map(\"42\", map(\"1\", Numbering.AbstractNumLevel.ordered(\"1\"))));\n\n assertThat(\n readSuccess(bodyReader(numbering), element),\n hasNumbering(Optional.empty()));\n }\n\n @Test\n public void numberingPropertiesAreIgnoredIfNumIdIsMissing() {\n // TODO: emit warning\n XmlElement element = paragraphXml(list(\n element(\"w:pPr\", list(\n element(\"w:numPr\", map(), list(\n element(\"w:ilvl\", map(\"w:val\", \"1\"))))))));\n\n Numbering numbering = numberingMap(map(\"42\", map(\"1\", Numbering.AbstractNumLevel.ordered(\"1\"))));\n\n assertThat(\n readSuccess(bodyReader(numbering), element),\n hasNumbering(Optional.empty()));\n }\n\n @Nested\n public class ComplexFieldsTests {\n private final String URI = \"http://example.com\";\n private final XmlElement BEGIN_COMPLEX_FIELD = element(\"w:r\", list(\n element(\"w:fldChar\", map(\"w:fldCharType\", \"begin\"))\n ));\n private final XmlElement SEPARATE_COMPLEX_FIELD = element(\"w:r\", list(\n element(\"w:fldChar\", map(\"w:fldCharType\", \"separate\"))\n ));\n private final XmlElement END_COMPLEX_FIELD = element(\"w:r\", list(\n element(\"w:fldChar\", map(\"w:fldCharType\", \"end\"))\n ));\n private final XmlElement HYPERLINK_INSTRTEXT = element(\"w:instrText\", list(\n XmlNodes.text(\" HYPERLINK \\\"\" + URI + '\"')\n ));\n private Matcher isEmptyHyperlinkedRun() {\n return isHyperlinkedRun(hasChildren());\n }\n\n @SafeVarargs\n private final Matcher isHyperlinkedRun(Matcher... matchers) {\n return isRun(hasChildren(\n isHyperlink(matchers)\n ));\n }\n\n @Test\n public void runsInAComplexFieldForHyperlinksAreReadAsHyperlinks() {\n XmlElement hyperlinkRunXml = runXml(\"this is a hyperlink\");\n XmlElement element = paragraphXml(list(\n BEGIN_COMPLEX_FIELD,\n HYPERLINK_INSTRTEXT,\n SEPARATE_COMPLEX_FIELD,\n hyperlinkRunXml,\n END_COMPLEX_FIELD\n ));\n DocumentElement paragraph = readSuccess(bodyReader(), element);\n\n assertThat(paragraph, isParagraph(hasChildren(\n isEmptyRun(),\n isEmptyHyperlinkedRun(),\n isHyperlinkedRun(\n hasHref(URI),\n hasChildren(\n isTextElement(\"this is a hyperlink\")\n )\n ),\n isEmptyRun()\n )));\n }\n\n @Test\n public void runsAfterAComplexFieldForHyperlinksAreNotReadAsHyperlinks() {\n XmlElement afterEndXml = runXml(\"this will not be a hyperlink\");\n XmlElement element = paragraphXml(list(\n BEGIN_COMPLEX_FIELD,\n HYPERLINK_INSTRTEXT,\n SEPARATE_COMPLEX_FIELD,\n END_COMPLEX_FIELD,\n afterEndXml\n ));\n DocumentElement paragraph = readSuccess(bodyReader(), element);\n\n assertThat(paragraph, isParagraph(hasChildren(\n isEmptyRun(),\n isEmptyHyperlinkedRun(),\n isEmptyRun(),\n isRun(hasChildren(\n isTextElement(\"this will not be a hyperlink\")\n ))\n )));\n }\n\n @Test\n public void canHandleSplitInstrTextElements() {\n XmlElement hyperlinkRunXml = runXml(\"this is a hyperlink\");\n XmlElement element = paragraphXml(list(\n BEGIN_COMPLEX_FIELD,\n element(\"w:instrText\", list(\n XmlNodes.text(\" HYPE\")\n )),\n element(\"w:instrText\", list(\n XmlNodes.text(\"RLINK \\\"\" + URI + '\"')\n )),\n SEPARATE_COMPLEX_FIELD,\n hyperlinkRunXml,\n END_COMPLEX_FIELD\n ));\n DocumentElement paragraph = readSuccess(bodyReader(), element);\n\n assertThat(paragraph, isParagraph(hasChildren(\n isEmptyRun(),\n isEmptyHyperlinkedRun(),\n isHyperlinkedRun(\n hasHref(URI),\n hasChildren(\n isTextElement(\"this is a hyperlink\")\n )\n ),\n isEmptyRun()\n )));\n }\n\n @Test\n public void hyperlinkIsNotEndedByEndOfNestedComplexField() {\n XmlElement authorInstrText = element(\"w:instrText\", list(\n XmlNodes.text(\" AUTHOR \\\"John Doe\\\"\")\n ));\n XmlElement hyperlinkRunXml = runXml(\"this is a hyperlink\");\n XmlElement element = paragraphXml(list(\n BEGIN_COMPLEX_FIELD,\n HYPERLINK_INSTRTEXT,\n SEPARATE_COMPLEX_FIELD,\n BEGIN_COMPLEX_FIELD,\n authorInstrText,\n SEPARATE_COMPLEX_FIELD,\n END_COMPLEX_FIELD,\n hyperlinkRunXml,\n END_COMPLEX_FIELD\n ));\n DocumentElement paragraph = readSuccess(bodyReader(), element);\n\n assertThat(paragraph, isParagraph(hasChildren(\n isEmptyRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isHyperlinkedRun(\n hasHref(URI),\n hasChildren(\n isTextElement(\"this is a hyperlink\")\n )\n ),\n isEmptyRun()\n )));\n }\n\n @Test\n public void complexFieldNestedWithinAHyperlinkComplexFieldIsWrappedWithTheHyperlink() {\n XmlElement authorInstrText = element(\"w:instrText\", list(\n XmlNodes.text(\" AUTHOR \\\"John Doe\\\"\")\n ));\n XmlElement element = paragraphXml(list(\n BEGIN_COMPLEX_FIELD,\n HYPERLINK_INSTRTEXT,\n SEPARATE_COMPLEX_FIELD,\n BEGIN_COMPLEX_FIELD,\n authorInstrText,\n SEPARATE_COMPLEX_FIELD,\n runXml(\"John Doe\"),\n END_COMPLEX_FIELD,\n END_COMPLEX_FIELD\n ));\n DocumentElement paragraph = readSuccess(bodyReader(), element);\n\n assertThat(paragraph, isParagraph(hasChildren(\n isEmptyRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isHyperlinkedRun(\n hasHref(URI),\n hasChildren(\n isTextElement(\"John Doe\")\n )\n ),\n isEmptyHyperlinkedRun(),\n isEmptyRun()\n )));\n }\n\n @Test\n public void fieldWithoutSeparateFldCharIsIgnored() {\n XmlElement hyperlinkRunXml = runXml(\"this is a hyperlink\");\n XmlElement element = paragraphXml(list(\n BEGIN_COMPLEX_FIELD,\n HYPERLINK_INSTRTEXT,\n SEPARATE_COMPLEX_FIELD,\n BEGIN_COMPLEX_FIELD,\n END_COMPLEX_FIELD,\n hyperlinkRunXml,\n END_COMPLEX_FIELD\n ));\n DocumentElement paragraph = readSuccess(bodyReader(), element);\n\n assertThat(paragraph, isParagraph(hasChildren(\n isEmptyRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isEmptyHyperlinkedRun(),\n isHyperlinkedRun(\n hasHref(URI),\n hasChildren(\n isTextElement(\"this is a hyperlink\")\n )\n ),\n isEmptyRun()\n )));\n }\n }\n\n @Test\n public void runHasNoStyleIfItHasNoProperties() {\n XmlElement element = runXml(list());\n assertThat(\n readSuccess(bodyReader(), element),\n hasStyle(Optional.empty()));\n }\n\n @Test\n public void whenRunHasStyleIdInStylesThenStyleNameIsReadFromStyles() {\n XmlElement element = runXml(list(\n element(\"w:rPr\", list(\n element(\"w:rStyle\", map(\"w:val\", \"Heading1Char\"))))));\n\n Style style = new Style(\"Heading1Char\", Optional.of(\"Heading 1 Char\"));\n Styles styles = new Styles(\n map(),\n map(\"Heading1Char\", style),\n map(),\n map()\n );\n assertThat(\n readSuccess(bodyReader(styles), element),\n hasStyle(Optional.of(style)));\n }\n\n @Test\n public void warningIsEmittedWhenRunStyleCannotBeFound() {\n XmlElement element = runXml(list(\n element(\"w:rPr\", list(\n element(\"w:rStyle\", map(\"w:val\", \"Heading1Char\"))))));\n\n assertThat(\n read(bodyReader(), element),\n isInternalResult(\n hasStyle(Optional.of(new Style(\"Heading1Char\", Optional.empty()))),\n list(\"Run style with ID Heading1Char was referenced but not defined in the document\")));\n }\n\n @Test\n public void runIsNotBoldIfBoldElementIsNotPresent() {\n XmlElement element = runXmlWithProperties();\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"bold\", equalTo(false)));\n }\n\n @Test\n public void runIsBoldIfBoldElementIsPresent() {\n XmlElement element = runXmlWithProperties(element(\"w:b\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"bold\", equalTo(true)));\n }\n\n @Test\n public void runIsNotItalicIfItalicElementIsNotPresent() {\n XmlElement element = runXmlWithProperties();\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"italic\", equalTo(false)));\n }\n\n @Test\n public void runIsItalicIfItalicElementIsPresent() {\n XmlElement element = runXmlWithProperties(element(\"w:i\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"italic\", equalTo(true)));\n }\n\n @Test\n public void runIsNotUnderlinedIfUnderlineElementIsNotPresent() {\n XmlElement element = runXmlWithProperties();\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"underline\", equalTo(false))\n );\n }\n\n @Test\n public void runIsUnderlinedIfUnderlineElementIsPresentWithoutValAttribute() {\n XmlElement element = runXmlWithProperties(element(\"w:u\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"underline\", equalTo(true))\n );\n }\n\n @Test\n public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIsFalse() {\n XmlElement element = runXmlWithProperties(element(\"w:u\", map(\"w:val\", \"false\")));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"underline\", equalTo(false))\n );\n }\n\n @Test\n public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIs0() {\n XmlElement element = runXmlWithProperties(element(\"w:u\", map(\"w:val\", \"0\")));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"underline\", equalTo(false))\n );\n }\n\n @Test\n public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIsNone() {\n XmlElement element = runXmlWithProperties(element(\"w:u\", map(\"w:val\", \"none\")));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"underline\", equalTo(false))\n );\n }\n\n @Test\n public void runIsUnderlinedIfUnderlineElementIsPresentAndValIsNotNoneNorFalsy() {\n XmlElement element = runXmlWithProperties(element(\"w:u\", map(\"w:val\", \"single\")));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"underline\", equalTo(true))\n );\n }\n\n @Test\n public void runIsNotStruckthroughIfStrikethroughElementIsNotPresent() {\n XmlElement element = runXmlWithProperties();\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"strikethrough\", equalTo(false)));\n }\n\n @Test\n public void runIsStruckthroughIfStrikethroughElementIsPresent() {\n XmlElement element = runXmlWithProperties(element(\"w:strike\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"strikethrough\", equalTo(true)));\n }\n\n @Test\n public void runIsNotSmallCapsIfSmallCapsElementIsNotPresent() {\n XmlElement element = runXmlWithProperties();\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"smallCaps\", equalTo(false)));\n }\n\n @Test\n public void runIsSmallCapsIfSmallCapsElementIsPresent() {\n XmlElement element = runXmlWithProperties(element(\"w:smallCaps\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"smallCaps\", equalTo(true)));\n }\n\n @Nested\n public class RunBooleanPropertyTests {\n private class TestCase {\n final String propertyName;\n final String tagName;\n\n TestCase(String propertyName, String tagName) {\n this.propertyName = propertyName;\n this.tagName = tagName;\n }\n }\n\n private final List TEST_CASES = list(\n new TestCase(\"bold\", \"w:b\"),\n new TestCase(\"underline\", \"w:u\"),\n new TestCase(\"italic\", \"w:i\"),\n new TestCase(\"strikethrough\", \"w:strike\"),\n new TestCase(\"allCaps\", \"w:caps\"),\n new TestCase(\"smallCaps\", \"w:smallCaps\")\n );\n\n @TestFactory\n public List runBooleanPropertyIsFalseIfElementIsPresentAndValIsFalse() {\n return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest(\n testCase.propertyName + \" property is false if \" + testCase.tagName + \" element is present and val is false\",\n () -> {\n XmlElement element = runXmlWithProperties(\n element(testCase.tagName, map(\"w:val\", \"false\"))\n );\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(testCase.propertyName, equalTo(false)));\n })\n );\n }\n\n @TestFactory\n public List runBooleanPropertyIsFalseIfElementIsPresentAndValIs0() {\n return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest(\n testCase.propertyName + \" property is false if \" + testCase.tagName + \" element is present and val is 0\",\n () -> {\n XmlElement element = runXmlWithProperties(\n element(testCase.tagName, map(\"w:val\", \"0\"))\n );\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(testCase.propertyName, equalTo(false)));\n })\n );\n }\n\n @TestFactory\n public List runBooleanPropertyIsFalseIfElementIsPresentAndValIsTrue() {\n return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest(\n testCase.propertyName + \" property is true if \" + testCase.tagName + \" element is present and val is true\",\n () -> {\n XmlElement element = runXmlWithProperties(\n element(testCase.tagName, map(\"w:val\", \"true\"))\n );\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(testCase.propertyName, equalTo(true)));\n })\n );\n }\n\n @TestFactory\n public List runBooleanPropertyIsFalseIfElementIsPresentAndValIs1() {\n return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest(\n testCase.propertyName + \" property is false if \" + testCase.tagName + \" element is present and val is 1\",\n () -> {\n XmlElement element = runXmlWithProperties(\n element(testCase.tagName, map(\"w:val\", \"1\"))\n );\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(testCase.propertyName, equalTo(true)));\n })\n );\n }\n }\n\n @Test\n public void runHasBaselineVerticalAlignmentIfVerticalAlignmentElementIsNotPresent() {\n XmlElement element = runXmlWithProperties();\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"verticalAlignment\", equalTo(VerticalAlignment.BASELINE)));\n }\n\n @Test\n public void runIsSuperscriptIfVerticalAlignmentPropertyIsSetToSuperscript() {\n XmlElement element = runXmlWithProperties(\n element(\"w:vertAlign\", map(\"w:val\", \"superscript\")));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"verticalAlignment\", equalTo(VerticalAlignment.SUPERSCRIPT)));\n }\n\n @Test\n public void runIsSubscriptIfVerticalAlignmentPropertyIsSetToSubscript() {\n XmlElement element = runXmlWithProperties(\n element(\"w:vertAlign\", map(\"w:val\", \"subscript\")));\n\n assertThat(\n readSuccess(bodyReader(), element),\n hasProperty(\"verticalAlignment\", equalTo(VerticalAlignment.SUBSCRIPT)));\n }\n\n @Test\n public void canReadTabElement() {\n XmlElement element = element(\"w:tab\");\n\n assertThat(\n readSuccess(bodyReader(), element),\n equalTo(Tab.TAB));\n }\n\n @Test\n public void noBreakHyphenElementIsReadAsNonBreakingHyphenCharacter() {\n XmlElement element = element(\"w:noBreakHyphen\");\n\n assertThat(\n readSuccess(bodyReader(), element),\n isTextElement(\"\\u2011\")\n );\n }\n\n @Test\n public void softHyphenElementIsReadAsSoftHyphenCharacter() {\n XmlElement element = element(\"w:softHyphen\");\n\n assertThat(\n readSuccess(bodyReader(), element),\n isTextElement(\"\\u00ad\")\n );\n }\n\n @Test\n public void symWithSupportedFontAndSupportedCodePointInAsciiRangeIsConvertedToText() {\n XmlElement element = element(\"w:sym\", map(\"w:font\", \"Wingdings\", \"w:char\", \"28\"));\n\n DocumentElement result = readSuccess(bodyReader(), element);\n\n assertThat(\n result,\n isTextElement(\"\\uD83D\\uDD7F\")\n );\n }\n\n @Test\n public void symWithSupportedFontAndSupportedCodePointInPrivateUseAreaIsConvertedToText() {\n XmlElement element = element(\"w:sym\", map(\"w:font\", \"Wingdings\", \"w:char\", \"F028\"));\n\n DocumentElement result = readSuccess(bodyReader(), element);\n\n assertThat(\n result,\n isTextElement(\"\\uD83D\\uDD7F\")\n );\n }\n\n @Test\n public void symWithUnsupportedFontAndCodePointProducesEmptyResultWithWarning() {\n XmlElement element = element(\"w:sym\", map(\"w:font\", \"Dingwings\", \"w:char\", \"28\"));\n\n InternalResult> result = readAll(bodyReader(), element);\n\n assertThat(result, isInternalResult(\n equalTo(list()),\n list(\"A w:sym element with an unsupported character was ignored: char 28 in font Dingwings\")\n ));\n }\n\n @Test\n public void brWithoutExplicitTypeIsReadAsLineBreak() {\n XmlElement element = element(\"w:br\");\n\n assertThat(\n readSuccess(bodyReader(), element),\n equalTo(Break.LINE_BREAK));\n }\n\n @Test\n public void brWithTextWrappingTypeIsReadAsLineBreak() {\n XmlElement element = element(\"w:br\", map(\"w:type\", \"textWrapping\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n equalTo(Break.LINE_BREAK)\n );\n }\n\n @Test\n public void brWithPageTypeIsReadAsPageBreak() {\n XmlElement element = element(\"w:br\", map(\"w:type\", \"page\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n equalTo(Break.PAGE_BREAK)\n );\n }\n\n @Test\n public void brWithColumnTypeIsReadAsColumnBreak() {\n XmlElement element = element(\"w:br\", map(\"w:type\", \"column\"));\n\n assertThat(\n readSuccess(bodyReader(), element),\n equalTo(Break.COLUMN_BREAK)\n );\n }\n\n @Test\n public void warningOnBreaksThatArentRecognised() {\n XmlElement element = element(\"w:br\", map(\"w:type\", \"unknownBreakType\"));\n\n assertThat(\n readAll(bodyReader(), element),\n isInternalResult(equalTo(list()), list(\"Unsupported break type: unknownBreakType\")));\n }\n\n @Test\n public void canReadTableElements() {\n XmlElement element = element(\"w:tbl\", list(\n element(\"w:tr\", list(\n element(\"w:tc\", list(\n element(\"w:p\")))))));\n\n assertThat(\n readSuccess(bodyReader(), element),\n isTable(hasChildren(\n deepEquals(tableRow(list(\n new TableCell(1, 1, list(\n paragraph()\n ))\n )))\n ))\n );\n }\n\n @Test\n public void tableHasNoStyleIfItHasNoProperties() {\n XmlElement element = element(\"w:tbl\");\n assertThat(\n readSuccess(bodyReader(), element),\n hasStyle(Optional.empty())\n );\n }\n\n @Test\n public void whenTableHasStyleIdInStylesThenStyleNameIsReadFromStyles() {\n XmlElement element = element(\"w:tbl\", list(\n element(\"w:tblPr\", list(\n element(\"w:tblStyle\", map(\"w:val\", \"TableNormal\"))\n ))\n ));\n\n Style style = new Style(\"TableNormal\", Optional.of(\"Normal Table\"));\n Styles styles = new Styles(\n map(),\n map(),\n map(\"TableNormal\", style),\n map()\n );\n assertThat(\n readSuccess(bodyReader(styles), element),\n hasStyle(Optional.of(style))\n );\n }\n\n @Test\n public void warningIsEmittedWhenTableStyleCannotBeFound() {\n XmlElement element = element(\"w:tbl\", list(\n element(\"w:tblPr\", list(\n element(\"w:tblStyle\", map(\"w:val\", \"TableNormal\"))\n ))\n ));\n\n assertThat(\n read(bodyReader(), element),\n isInternalResult(\n hasStyle(Optional.of(new Style(\"TableNormal\", Optional.empty()))),\n list(\"Table style with ID TableNormal was referenced but not defined in the document\")\n )\n );\n }\n\n @Test\n public void tblHeaderMarksTableRowAsHeader() {\n XmlElement element = element(\"w:tbl\", list(\n element(\"w:tr\", list(\n element(\"w:trPr\", list(\n element(\"w:tblHeader\")\n ))\n )),\n element(\"w:tr\")\n ));\n\n assertThat(\n readSuccess(bodyReader(), element),\n isTable(hasChildren(\n isRow(isHeader(true)),\n isRow(isHeader(false))\n ))\n );\n }\n\n @Test\n public void gridspanIsReadAsColspanForTableCell() {\n XmlElement element = element(\"w:tbl\", list(\n element(\"w:tr\", list(\n element(\"w:tc\", list(\n element(\"w:tcPr\", list(\n element(\"w:gridSpan\", map(\"w:val\", \"2\"))\n )),\n element(\"w:p\")))))));\n\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(table(list(\n tableRow(list(\n new TableCell(1, 2, list(\n paragraph()\n ))\n ))\n )))\n );\n }\n\n @Test\n public void vmergeIsReadAsRowspanForTableCell() {\n XmlElement element = element(\"w:tbl\", list(\n wTr(wTc()),\n wTr(wTc(wTcPr(wVmerge(\"restart\")))),\n wTr(wTc(wTcPr(wVmerge(\"continue\")))),\n wTr(wTc(wTcPr(wVmerge(\"continue\")))),\n wTr(wTc())\n ));\n\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(table(list(\n tableRow(list(new TableCell(1, 1, list()))),\n tableRow(list(new TableCell(3, 1, list()))),\n tableRow(list()),\n tableRow(list()),\n tableRow(list(new TableCell(1, 1, list())))\n )))\n );\n }\n\n @Test\n public void vmergeWithoutValIsTreatedAsContinue() {\n XmlElement element = element(\"w:tbl\", list(\n wTr(wTc(wTcPr(wVmerge(\"restart\")))),\n wTr(wTc(wTcPr(element(\"w:vMerge\"))))\n ));\n\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(table(list(\n tableRow(list(new TableCell(2, 1, list()))),\n tableRow(list())\n )))\n );\n }\n\n @Test\n public void vmergeAccountsForCellsSpanningColumns() {\n XmlElement element = element(\"w:tbl\", list(\n wTr(wTc(), wTc(), wTc(wTcPr(wVmerge(\"restart\")))),\n wTr(wTc(wTcPr(wGridspan(\"2\"))), wTc(wTcPr(wVmerge(\"continue\")))),\n wTr(wTc(), wTc(), wTc(wTcPr(wVmerge(\"continue\")))),\n wTr(wTc(), wTc(), wTc())\n ));\n\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(table(list(\n tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()), new TableCell(3, 1, list()))),\n tableRow(list(new TableCell(1, 2, list()))),\n tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()))),\n tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()), new TableCell(1, 1, list())))\n )))\n );\n }\n\n @Test\n public void noVerticalCellMergingIfMergedCellsDoNotLineUp() {\n XmlElement element = element(\"w:tbl\", list(\n wTr(wTc(wTcPr(wGridspan(\"2\"))), wTc(wTcPr(wVmerge(\"restart\")))),\n wTr(wTc(), wTc(wTcPr(wVmerge(\"continue\"))))\n ));\n\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(table(list(\n tableRow(list(new TableCell(1, 2, list()), new TableCell(1, 1, list()))),\n tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list())))\n )))\n );\n }\n\n @Test\n public void warningIfNonRowInTable() {\n XmlElement element = element(\"w:tbl\", list(\n element(\"w:p\")\n ));\n\n assertThat(\n read(bodyReader(), element),\n isInternalResult(\n deepEquals(table(list(paragraph()))),\n list(\"unexpected non-row element in table, cell merging may be incorrect\")\n )\n );\n }\n\n @Test\n public void warningIfNonCellInTableRow() {\n XmlElement element = element(\"w:tbl\", list(\n wTr(element(\"w:p\"))\n ));\n\n assertThat(\n read(bodyReader(), element),\n isInternalResult(\n deepEquals(table(list(tableRow(list(paragraph()))))),\n list(\"unexpected non-cell element in table row, cell merging may be incorrect\")\n )\n );\n }\n\n @Test\n public void hyperlinkIsReadAsExternalHyperlinkIfItHasARelationshipId() {\n Relationships relationships = new Relationships(list(\n hyperlinkRelationship(\"r42\", \"http://example.com\")\n ));\n XmlElement element = element(\"w:hyperlink\", map(\"r:id\", \"r42\"), list(runXml(list())));\n assertThat(\n readSuccess(bodyReader(relationships), element),\n isHyperlink(\n hasHref(\"http://example.com\"),\n hasNoAnchor(),\n hasChildren(isRun(hasChildren()))\n )\n );\n }\n\n @Test\n public void hyperlinkIsReadAsExternalHyperlinkIfItHasARelationshipIdAndAnAnchor() {\n Relationships relationships = new Relationships(list(\n hyperlinkRelationship(\"r42\", \"http://example.com/\")\n ));\n XmlElement element = element(\"w:hyperlink\", map(\"r:id\", \"r42\", \"w:anchor\", \"fragment\"), list(runXml(list())));\n assertThat(\n readSuccess(bodyReader(relationships), element),\n isHyperlink(hasHref(\"http://example.com/#fragment\"))\n );\n }\n\n @Test\n public void hyperlinkExistingFragmentIsReplacedWhenAnchorIsSetOnExternalLink() {\n Relationships relationships = new Relationships(list(\n hyperlinkRelationship(\"r42\", \"http://example.com/#previous\")\n ));\n XmlElement element = element(\"w:hyperlink\", map(\"r:id\", \"r42\", \"w:anchor\", \"fragment\"), list(runXml(list())));\n assertThat(\n readSuccess(bodyReader(relationships), element),\n isHyperlink(hasHref(\"http://example.com/#fragment\"))\n );\n }\n\n @Test\n public void hyperlinkIsReadAsInternalHyperlinkIfItHasAnAnchorAttribute() {\n XmlElement element = element(\"w:hyperlink\", map(\"w:anchor\", \"start\"), list(runXml(list())));\n assertThat(\n readSuccess(bodyReader(), element),\n isHyperlink(\n hasAnchor(\"start\"),\n hasNoHref()\n )\n );\n }\n\n @Test\n public void hyperlinkIsIgnoredIfItDoesNotHaveARelationshipIdNorAnchor() {\n XmlElement element = element(\"w:hyperlink\", list(runXml(list())));\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(run(withChildren())));\n }\n\n @Test\n public void hyperlinkTargetFrameIsRead() {\n XmlElement element = element(\"w:hyperlink\", map(\n \"w:anchor\", \"start\",\n \"w:tgtFrame\", \"_blank\"\n ));\n assertThat(\n readSuccess(bodyReader(), element),\n isHyperlink(hasTargetFrame(\"_blank\"))\n );\n }\n\n @Test\n public void hyperlinkEmptyTargetFrameIsIgnored() {\n XmlElement element = element(\"w:hyperlink\", map(\n \"w:anchor\", \"start\",\n \"w:tgtFrame\", \"\"\n ));\n assertThat(\n readSuccess(bodyReader(), element),\n isHyperlink(hasNoTargetFrame())\n );\n }\n\n @Test\n public void goBackBookmarkIsIgnored() {\n XmlElement element = element(\"w:bookmarkStart\", map(\"w:name\", \"_GoBack\"));\n assertThat(\n readAll(bodyReader(), element),\n isInternalResult(equalTo(list()), list()));\n }\n\n @Test\n public void bookmarkStartIsReadIfNameIsNotGoBack() {\n XmlElement element = element(\"w:bookmarkStart\", map(\"w:name\", \"start\"));\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(new Bookmark(\"start\")));\n }\n\n @Test\n public void footnoteReferenceHasIdRead() {\n XmlElement element = element(\"w:footnoteReference\", map(\"w:id\", \"4\"));\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(footnoteReference(\"4\")));\n }\n\n @Test\n public void endnoteReferenceHasIdRead() {\n XmlElement element = element(\"w:endnoteReference\", map(\"w:id\", \"4\"));\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(endnoteReference(\"4\")));\n }\n\n @Test\n public void commentReferenceHasIdRead() {\n XmlElement element = element(\"w:commentReference\", map(\"w:id\", \"4\"));\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(new CommentReference(\"4\")));\n }\n\n @Test\n public void textBoxesHaveContentAppendedAfterContainingParagraph() {\n XmlElement textBox = element(\"w:pict\", list(\n element(\"v:shape\", list(\n element(\"v:textbox\", list(\n element(\"w:txbxContent\", list(\n paragraphXml(list(\n runXml(list(textXml(\"[textbox-content]\")))))))))))));\n XmlElement paragraph = paragraphXml(list(\n runXml(list(textXml(\"[paragragh start]\"))),\n runXml(list(textBox, textXml(\"[paragragh end]\")))));\n\n List expected = list(\n paragraph(withChildren(\n run(withChildren(\n new Text(\"[paragragh start]\"))),\n run(withChildren(\n new Text(\"[paragragh end]\"))))),\n paragraph(withChildren(\n run(withChildren(\n new Text(\"[textbox-content]\"))))));\n\n assertThat(\n readAll(bodyReader(), paragraph),\n isInternalResult(deepEquals(expected), list()));\n }\n\n\n private static final String IMAGE_BYTES = \"Not an image at all!\";\n private static final String IMAGE_RELATIONSHIP_ID = \"rId5\";\n\n\n @Test\n public void canReadImagedataElementsWithIdAttribute() throws IOException {\n assertCanReadEmbeddedImage(image ->\n element(\"v:imagedata\", map(\"r:id\", image.relationshipId, \"o:title\", image.altText)));\n }\n\n @Test\n public void whenImagedataElementHasNoRelationshipIdThenItIsIgnoredWithWarning() throws IOException {\n XmlElement element = element(\"v:imagedata\");\n\n assertThat(\n readAll(bodyReader(), element),\n isInternalResult(equalTo(list()), list(\"A v:imagedata element without a relationship ID was ignored\")));\n }\n\n @Test\n public void canReadInlinePictures() throws IOException {\n assertCanReadEmbeddedImage(image ->\n inlineImageXml(embeddedBlipXml(image.relationshipId), image.altText));\n }\n\n @Test\n public void altTextTitleIsUsedIfAltTextDescriptionIsBlank() throws IOException {\n XmlElement element = inlineImageXml(\n embeddedBlipXml(IMAGE_RELATIONSHIP_ID),\n Optional.of(\" \"),\n Optional.of(\"It's a hat\")\n );\n\n Image image = readEmbeddedImage(element);\n\n assertThat(image, hasProperty(\"altText\", deepEquals(Optional.of(\"It's a hat\"))));\n }\n\n @Test\n public void altTextTitleIsUsedIfAltTextDescriptionIsMissing() throws IOException {\n XmlElement element = inlineImageXml(\n embeddedBlipXml(IMAGE_RELATIONSHIP_ID),\n Optional.empty(),\n Optional.of(\"It's a hat\")\n );\n\n Image image = readEmbeddedImage(element);\n\n assertThat(image, hasProperty(\"altText\", deepEquals(Optional.of(\"It's a hat\"))));\n }\n\n @Test\n public void altTextDescriptionIsPreferredToAltTextTitle() throws IOException {\n XmlElement element = inlineImageXml(\n embeddedBlipXml(IMAGE_RELATIONSHIP_ID),\n Optional.of(\"It's a hat\"),\n Optional.of(\"hat\")\n );\n\n Image image = readEmbeddedImage(element);\n\n assertThat(image, hasProperty(\"altText\", deepEquals(Optional.of(\"It's a hat\"))));\n }\n\n @Test\n public void canReadAnchoredPictures() throws IOException {\n assertCanReadEmbeddedImage(image ->\n anchoredImageXml(embeddedBlipXml(image.relationshipId), image.altText));\n }\n\n private void assertCanReadEmbeddedImage(Function generateXml) throws IOException {\n XmlElement element = generateXml.apply(new EmbeddedImage(IMAGE_RELATIONSHIP_ID, \"It's a hat\"));\n Image image = readEmbeddedImage(element);\n assertThat(image, allOf(\n hasProperty(\"altText\", deepEquals(Optional.of(\"It's a hat\"))),\n hasProperty(\"contentType\", deepEquals(Optional.of(\"image/png\")))));\n assertThat(\n toString(image.open()),\n equalTo(IMAGE_BYTES));\n }\n\n private Image readEmbeddedImage(XmlElement element) {\n Relationships relationships = new Relationships(list(\n imageRelationship(IMAGE_RELATIONSHIP_ID, \"media/hat.png\")\n ));\n Archive file = InMemoryArchive.fromStrings(map(\"word/media/hat.png\", IMAGE_BYTES));\n\n return (Image) readSuccess(\n BodyXmlReaderMakers.bodyReader(relationships, file),\n element);\n }\n\n private static String toString(InputStream stream) throws IOException {\n return new String(toByteArray(stream), StandardCharsets.UTF_8);\n }\n\n private class EmbeddedImage {\n private final String relationshipId;\n private final String altText;\n\n public EmbeddedImage(String relationshipId, String altText) {\n this.relationshipId = relationshipId;\n this.altText = altText;\n }\n }\n\n @Test\n public void warningIfImageTypeIsUnsupportedByWebBrowsers() {\n XmlElement element = inlineImageXml(embeddedBlipXml(IMAGE_RELATIONSHIP_ID), \"\");\n Relationships relationships = new Relationships(list(\n imageRelationship(IMAGE_RELATIONSHIP_ID, \"media/hat.emf\")\n ));\n Archive file = InMemoryArchive.fromStrings(map(\"word/media/hat.emf\", IMAGE_BYTES));\n ContentTypes contentTypes = new ContentTypes(map(\"emf\", \"image/x-emf\"), map());\n\n InternalResult result = read(\n bodyReader(relationships, file, contentTypes),\n element);\n\n assertThat(\n result,\n hasWarnings(list(\"Image of type image/x-emf is unlikely to display in web browsers\")));\n }\n\n @Test\n public void canReadLinkedPictures() throws IOException {\n XmlElement element = inlineImageXml(linkedBlipXml(IMAGE_RELATIONSHIP_ID), \"\");\n Relationships relationships = new Relationships(list(\n imageRelationship(IMAGE_RELATIONSHIP_ID, \"file:///media/hat.png\")\n ));\n\n Image image = (Image) readSuccess(\n bodyReader(relationships, new InMemoryFileReader(map(\"file:///media/hat.png\", IMAGE_BYTES))),\n element);\n\n assertThat(\n toString(image.open()),\n equalTo(IMAGE_BYTES));\n }\n\n private XmlElement inlineImageXml(XmlElement blip, String description) {\n return inlineImageXml(blip, Optional.of(description), Optional.empty());\n }\n\n private XmlElement inlineImageXml(XmlElement blip, Optional description, Optional title) {\n return element(\"w:drawing\", list(\n element(\"wp:inline\", imageXml(blip, description, title))));\n }\n\n private XmlElement anchoredImageXml(XmlElement blip, String description) {\n return element(\"w:drawing\", list(\n element(\"wp:anchor\", imageXml(blip, Optional.of(description), Optional.empty()))));\n }\n\n private List imageXml(XmlElement blip, Optional description, Optional title) {\n Map properties = new HashMap<>();\n description.ifPresent(value -> properties.put(\"descr\", value));\n title.ifPresent(value -> properties.put(\"title\", value));\n\n return list(\n element(\"wp:docPr\", properties),\n element(\"a:graphic\", list(\n element(\"a:graphicData\", list(\n element(\"pic:pic\", list(\n element(\"pic:blipFill\", list(blip)))))))));\n }\n\n private XmlElement embeddedBlipXml(String relationshipId) {\n return blipXml(map(\"r:embed\", relationshipId));\n }\n\n private XmlElement linkedBlipXml(String relationshipId) {\n return blipXml(map(\"r:link\", relationshipId));\n }\n\n private XmlElement blipXml(Map attributes) {\n return element(\"a:blip\", attributes);\n }\n\n @Test\n public void sdtIsReadUsingSdtContent() throws IOException {\n XmlElement element = element(\"w:sdt\", list(element(\"w:sdtContent\", list(textXml(\"Blackdown\")))));\n\n assertThat(\n readAll(bodyReader(), element),\n isInternalSuccess(deepEquals(list(text(\"Blackdown\")))));\n }\n\n @Test\n public void appropriateElementsHaveTheirChildrenReadNormally() {\n assertChildrenAreReadNormally(\"w:ins\");\n assertChildrenAreReadNormally(\"w:object\");\n assertChildrenAreReadNormally(\"w:smartTag\");\n assertChildrenAreReadNormally(\"w:drawing\");\n assertChildrenAreReadNormally(\"v:group\");\n assertChildrenAreReadNormally(\"v:rect\");\n assertChildrenAreReadNormally(\"v:roundrect\");\n assertChildrenAreReadNormally(\"v:shape\");\n assertChildrenAreReadNormally(\"v:textbox\");\n assertChildrenAreReadNormally(\"w:txbxContent\");\n }\n\n private void assertChildrenAreReadNormally(String name) {\n XmlElement element = element(name, list(paragraphXml()));\n\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(paragraph()));\n }\n\n @Test\n public void ignoredElementsAreIgnoredWithoutWarning() {\n assertIsIgnored(\"office-word:wrap\");\n assertIsIgnored(\"v:shadow\");\n assertIsIgnored(\"v:shapetype\");\n assertIsIgnored(\"w:bookmarkEnd\");\n assertIsIgnored(\"w:sectPr\");\n assertIsIgnored(\"w:proofErr\");\n assertIsIgnored(\"w:lastRenderedPageBreak\");\n assertIsIgnored(\"w:commentRangeStart\");\n assertIsIgnored(\"w:commentRangeEnd\");\n assertIsIgnored(\"w:del\");\n assertIsIgnored(\"w:footnoteRef\");\n assertIsIgnored(\"w:endnoteRef\");\n assertIsIgnored(\"w:annotationRef\");\n assertIsIgnored(\"w:pPr\");\n assertIsIgnored(\"w:rPr\");\n assertIsIgnored(\"w:tblPr\");\n assertIsIgnored(\"w:tblGrid\");\n assertIsIgnored(\"w:tcPr\");\n }\n\n private void assertIsIgnored(String name) {\n XmlElement element = element(name, list(paragraphXml()));\n\n assertThat(\n readAll(bodyReader(), element),\n isInternalResult(equalTo(list()), list()));\n }\n\n @Test\n public void unrecognisedElementsAreIgnoredWithWarning() {\n XmlElement element = element(\"w:huh\");\n assertThat(\n readAll(bodyReader(), element),\n isInternalResult(equalTo(list()), list(\"An unrecognised element was ignored: w:huh\")));\n }\n\n @Test\n public void textNodesAreIgnoredWhenReadingChildren() {\n XmlElement element = runXml(list(XmlNodes.text(\"[text]\")));\n assertThat(\n readSuccess(bodyReader(), element),\n deepEquals(run(withChildren())));\n }\n\n private static DocumentElement readSuccess(BodyXmlReader reader, XmlElement element) {\n InternalResult result = read(reader, element);\n assertThat(result.getWarnings(), emptyIterable());\n return result.getValue();\n }\n\n private static InternalResult read(BodyXmlReader reader, XmlElement element) {\n InternalResult> result = readAll(reader, element);\n assertThat(result.getValue(), Matchers.hasSize(1));\n return result.map(elements -> elements.get(0));\n }\n\n private static InternalResult> readAll(BodyXmlReader reader, XmlElement element) {\n return reader.readElement(element).toResult();\n }\n\n private XmlElement paragraphXml() {\n return paragraphXml(list());\n }\n\n private static XmlElement paragraphXml(List children) {\n return element(\"w:p\", children);\n }\n\n private static XmlElement runXml(String text) {\n return runXml(list(textXml(text)));\n }\n\n private static XmlElement runXml(List children) {\n return element(\"w:r\", children);\n }\n\n private static XmlElement runXmlWithProperties(XmlNode... children) {\n return element(\"w:r\", list(element(\"w:rPr\", asList(children))));\n }\n\n private static XmlElement textXml(String value) {\n return element(\"w:t\", list(XmlNodes.text(value)));\n }\n\n private Matcher hasStyle(Optional