answer
stringlengths
17
10.2M
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.AnnotationREST; import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.common.store.TemporarySolrDataStore; import java.time.LocalDate; import java.time.ZoneId; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.ac.ebi.quickgo.annotation.AnnotationParameters.*; import static uk.ac.ebi.quickgo.annotation.IdGeneratorUtil.createGPId; import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker.EXTENSIONS; import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*; import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.ResponseItem.responseItem; import static uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl.DEFAULT_ENTRIES_PER_PAGE; import static uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl.MAX_PAGE_NUMBER; import static uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl.MAX_PAGE_RESULTS; import static uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery.SELECT_ALL_WHERE_FIELD_IS_NOT_EMPTY; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {AnnotationREST.class}) @WebAppConfiguration public class AnnotationControllerIT { // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); public static final String DATE_STRING_FORMAT = "%04d%02d%02d"; public static final String EXACT = "exact"; public static final String DESCENDANTS = "descendants"; //Test Data private static final String MISSING_ASSIGNED_BY = "ZZZZZ"; private static final String RESOURCE_URL = "/annotation"; private static final String MISSING_GO_ID = "GO:0009871"; private static final String INVALID_GO_ID = "GO:1"; private static final String ECO_ID2 = "ECO:0000323"; private static final String MISSING_ECO_ID = "ECO:0000888"; private static final String WITH_FROM_PATH = "withFrom.*.connectedXrefs"; //Configuration private static final int NUMBER_OF_GENERIC_DOCS = 3; public static final String EXACT_USAGE = "exact"; private MockMvc mockMvc; private List<AnnotationDocument> genericDocs; @Autowired private WebApplicationContext webApplicationContext; @Autowired private AnnotationRepository repository; @Before public void setup() { repository.deleteAll(); mockMvc = MockMvcBuilders. webAppContextSetup(webApplicationContext) .build(); genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS); repository.save(genericDocs); } // CONSISTENT ORDER @Test public void annotationsAlwaysReturnedInOrderWrittenToRepository() throws Exception { repository.deleteAll(); String geneProductId1 = "A0A000"; String geneProductId2 = "CPX-102"; String geneProductId3 = "URS00000064B1_559292"; //Create sequence number as B,Z,A AnnotationDocMocker.rowNumberGenerator = new AtomicLong(100); final AnnotationDocument annotationDoc1 = AnnotationDocMocker.createAnnotationDoc(geneProductId1); AnnotationDocMocker.rowNumberGenerator = new AtomicLong(10); final AnnotationDocument annotationDoc2 = AnnotationDocMocker.createAnnotationDoc(geneProductId2); AnnotationDocMocker.rowNumberGenerator = new AtomicLong(50); final AnnotationDocument annotationDoc3 = AnnotationDocMocker.createAnnotationDoc(geneProductId3); //save in order A, B, Z repository.save(annotationDoc1); repository.save(annotationDoc2); repository.save(annotationDoc3); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search")); //Results should arrive in sequence number response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(3)) .andExpect(fieldInRowHasValue(GENEPRODUCT_ID_FIELD, 0, geneProductId2)) .andExpect(fieldInRowHasValue(GENEPRODUCT_ID_FIELD, 1, geneProductId3)) .andExpect(fieldInRowHasValue(GENEPRODUCT_ID_FIELD, 2, geneProductId1)); } // ASSIGNED BY @Test public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), assignedBy)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), assignedBy1 + "," + assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId2, geneProductId1)); } @Test public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(ASSIGNED_BY_PARAM.getName(), assignedBy1) .param(ASSIGNED_BY_PARAM.getName(), assignedBy2)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId2, geneProductId1)); } @Test public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), MISSING_ASSIGNED_BY)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), MISSING_ASSIGNED_BY + "," + assignedBy)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void invalidAssignedByThrowsAnError() throws Exception { String invalidAssignedBy = "_ASPGD"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), invalidAssignedBy)); response.andDo(print()) .andExpect(status().isBadRequest()); } // TAXON ID @Test public void lookupAnnotationFilterByTaxonIdSuccessfully() throws Exception { String geneProductId = "P99999"; int taxonId = 2; AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), Integer.toString(taxonId)) .param(TAXON_USAGE_PARAM.getName(), EXACT)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccursInField(TAXON_ID_FIELD, taxonId)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleTaxonIdsSuccessfully() throws Exception { String geneProductId1 = "P99999"; int taxonId1 = 2; AnnotationDocument document1 = createDocWithTaxonId(geneProductId1, taxonId1); repository.save(document1); String geneProductId2 = "P99998"; int taxonId2 = 3; AnnotationDocument document2 = createDocWithTaxonId(geneProductId2, taxonId2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), Integer.toString(taxonId1)) .param(TAXON_ID_PARAM.getName(), Integer.toString(taxonId2)) .param(TAXON_USAGE_PARAM.getName(), EXACT)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccursInField(TAXON_ID_FIELD, taxonId2, taxonId1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId2, geneProductId1)); } @Test public void lookupWhereTaxonIdIsZeroWillNotShowTaxonIdBecauseThisMeansInvalid() throws Exception { String geneProductId = "P99999"; int taxonId = 0; AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldDoesNotExist(TAXON_ID_FIELD)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void filterByMissingTaxonIdFindsNothingSuccessfully() throws Exception { int desiredTaxonId = 999999; String geneProductId = "P99999"; int taxonId = 2; AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), Integer.toString(desiredTaxonId)) .param(TAXON_USAGE_PARAM.getName(), EXACT)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void invalidTaxIdThrowsError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), "-2") .param(TAXON_USAGE_PARAM.getName(), EXACT)); response.andDo(print()) .andExpect(status().isBadRequest()); } // -- taxon descendant filtering @Test public void filterByTaxonAncestorSuccessfully() throws Exception { int taxonId = 3; int parentTaxonId = 4; int grandParentTaxonId = 5; List<AnnotationDocument> documents = createDocsWithTaxonAncestors(asList(taxonId, parentTaxonId, grandParentTaxonId)); repository.save(documents); String[] expectedGPIds = asArray(transformDocs(documents, d -> d.geneProductId)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), Integer.toString(grandParentTaxonId)) .param(TAXON_USAGE_PARAM.getName(), DESCENDANTS)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(3)) .andExpect(fieldsInAllResultsExist(3)) .andExpect(valuesOccursInField(TAXON_ID_FIELD, taxonId, parentTaxonId, grandParentTaxonId)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, expectedGPIds)); } @Test public void filterByTaxonAncestorsSuccessfully() throws Exception { int taxonId1 = 3; int parentTaxonId1 = 4; int grandParentTaxonId1 = 5; int taxonId2 = 8; int parentTaxonId2 = 9; int grandParentTaxonId2 = 10; List<AnnotationDocument> documents = createDocsWithTaxonAncestors(asList(taxonId1, parentTaxonId1, grandParentTaxonId1)); documents.addAll(createDocsWithTaxonAncestors(asList(taxonId2, parentTaxonId2, grandParentTaxonId2))); repository.save(documents); Integer[] expectedTaxonIds = {taxonId1, parentTaxonId1, grandParentTaxonId1, taxonId2, parentTaxonId2}; String[] expectedGPIds = asArray( transformDocs( filterDocuments( documents, expectedTaxonIds, doc -> doc.taxonId), doc -> doc.geneProductId)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), Integer.toString(grandParentTaxonId1), Integer.toString(parentTaxonId2)) .param(TAXON_USAGE_PARAM.getName(), DESCENDANTS)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(5)) .andExpect(fieldsInAllResultsExist(5)) .andExpect(valuesOccursInField(TAXON_ID_FIELD, expectedTaxonIds)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, expectedGPIds)); } @Test public void filterByMissingTaxonAncestorFindsNothingSuccessfully() throws Exception { int desiredTaxonId = 99999999; int taxonId = 3; int parentTaxonId = 4; int grandParentTaxonId = 5; List<AnnotationDocument> documents = createDocsWithTaxonAncestors(asList(taxonId, parentTaxonId, grandParentTaxonId)); repository.save(documents); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), Integer.toString(desiredTaxonId)) .param(TAXON_USAGE_PARAM.getName(), DESCENDANTS)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void invalidTaxIdWithDescendantsThrowsError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(TAXON_ID_PARAM.getName(), "-2") .param(TAXON_USAGE_PARAM.getName(), DESCENDANTS)); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void filterAnnotationsByGoEvidenceCodeSuccessfully() throws Exception { String goEvidenceCode = "IEA"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), goEvidenceCode)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode)); } @Test public void filterAnnotationsByLowercaseGoEvidenceCodeSuccessfully() throws Exception { String goEvidenceCode = "iea"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), goEvidenceCode)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode.toUpperCase())); } @Test public void filterAnnotationsByNonExistentGoEvidenceCodeReturnsNothing() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), "ZZZ")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterAnnotationsUsingMultipleGoEvidenceCodesSuccessfully() throws Exception { String goEvidenceCode = "IEA"; String goEvidenceCode1 = "BSS"; AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createGPId(999)); annoDoc1.goEvidence = goEvidenceCode1; repository.save(annoDoc1); String goEvidenceCode2 = "AWE"; AnnotationDocument annoDoc2 = AnnotationDocMocker.createAnnotationDoc(createGPId(998)); annoDoc2.goEvidence = goEvidenceCode2; repository.save(annoDoc2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), "IEA,BSS,AWE,PEG")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode1, 1)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode2, 1)) .andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode, NUMBER_OF_GENERIC_DOCS)); } @Test public void invalidGoEvidenceThrowsException() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), "BlahBlah")); response.andExpect(status().isBadRequest()) .andExpect(contentTypeToBeJson()); } @Test public void successfullyLookupAnnotationsByQualifier() throws Exception { String qualifier = "enables"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM.getName(), qualifier)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(valueOccursInField(QUALIFIER_FIELD, qualifier)); } @Test public void successfullyLookupAnnotationsByNegatedQualifier() throws Exception { String qualifier = "not|enables"; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.qualifier = qualifier; repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM.getName(), qualifier)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valueOccursInField(QUALIFIER_FIELD, qualifier)); } @Test public void failToFindAnnotationsWhenQualifierDoesntExist() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM.getName(), "peeled")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterByGeneProductIDSuccessfully() throws Exception { String geneProductId = "A1E959"; String fullGeneProductId = "UniProtKB:" + geneProductId; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(fullGeneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, fullGeneProductId, 1)); } @Test public void filterByFullyQualifiedUniProtGeneProductIDSuccessfully() throws Exception { String geneProductId = "UniProtKB:A1E959"; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } @Test public void filterByPartiallyQualifiedGeneProductIDSuccessfully() throws Exception { String db = "UniProtKB"; String id = "A1E959"; String geneProductId = db + ":" + id; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), id)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } // -- filter gene product ids of the form UniProtKB:P12345:VAR_12345 or UniProtKB:P12345:PRO_12345, etc @Test public void findGeneProductVarById() throws Exception { String db = "UniProtKB"; String id = "P05067"; String var = "VAR_000023"; String geneProductId = db + ":" + id + ":" + var; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), id)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } @Test public void findTwoGeneProductsIncludingOneWithVarById() throws Exception { String db = "UniProtKB"; String id = "P05067"; String var = "VAR_000023"; String geneProductId = db + ":" + id + ":" + var; AnnotationDocument doc1 = AnnotationDocMocker.createAnnotationDoc(db + ":" + id); AnnotationDocument doc2 = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc1); repository.save(doc2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), id)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, doc1.geneProductId, 1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, doc2.geneProductId, 1)); } @Test public void findGeneProductVarByDbAndId() throws Exception { String db = "UniProtKB"; String id = "P05067"; String var = "VAR_000023"; String geneProductId = db + ":" + id + ":" + var; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), db + ":" + id)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } @Test public void findGeneProductVarByDbIdAndVar() throws Exception { String db = "UniProtKB"; String id = "P05068"; String var = "VAR_000023"; String geneProductId = db + ":" + id + ":" + var; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } @Test public void findGeneProductVarByIdAndVar() throws Exception { String db = "UniProtKB"; String id = "P05067"; String var = "VAR_000023"; String idWithVar = id + ":" + var; String geneProductId = db + ":" + idWithVar; AnnotationDocument doc1 = AnnotationDocMocker.createAnnotationDoc(db + ":" + id); AnnotationDocument doc2 = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc1); repository.save(doc2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), idWithVar)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } // -- filter gene product ids of the form UniProtKB:P12345-2 @Test public void findGeneProductIsoformById() throws Exception { String db = "UniProtKB"; String id = "P05067"; String iso = "-2"; String geneProductId = db + ":" + id + iso; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), id)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } @Test public void findGeneProductIsoformByDbAndId() throws Exception { String db = "UniProtKB"; String id = "P05067"; String iso = "-2"; String dbWithId = db + ":" + id; String geneProductId = db + ":" + id + iso; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), dbWithId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } @Test public void findGeneProductIsoformByIdAndIsoform() throws Exception { String db = "UniProtKB"; String id = "P05067"; String iso = "-2"; String idWithIso = id + iso; String geneProductIdWithIsoform = db + ":" + idWithIso; AnnotationDocument docWithIsoform = AnnotationDocMocker.createAnnotationDoc(geneProductIdWithIsoform); AnnotationDocument docWithoutIsoform = AnnotationDocMocker.createAnnotationDoc(db + ":" + id); repository.save(docWithIsoform); repository.save(docWithoutIsoform); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), idWithIso)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductIdWithIsoform, 1)); } @Test public void findGeneProductIsoformByDbIdAndIsoform() throws Exception { String db = "UniProtKB"; String id = "P05068"; String iso = "-2"; String geneProductId = db + ":" + id + iso; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1)); } // -- filter gene product ids of the form UniProtKB:P12345-2:VAR_12345 -- not a valid UniProt identifier @Test public void filteringUsingInvalidGeneProductIdCausesBadRequest() throws Exception { String geneProductId = "UniProtKB:P05068-2:VAR_000023"; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void findIsoformEntryAndNonIsoformEntryById() throws Exception { String id = "P05067"; String geneProductIdWithIso = "UniProtKB:P05067-2"; String geneProductIdWithVar = "UniProtKB:P05067:PRO_0000005211"; AnnotationDocument doc1 = AnnotationDocMocker.createAnnotationDoc(geneProductIdWithIso); AnnotationDocument doc2 = AnnotationDocMocker.createAnnotationDoc(geneProductIdWithVar); repository.save(doc1); repository.save(doc2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), id)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductIdWithIso, 1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductIdWithVar, 1)); } @Test public void filterByUniProtKBAndIntactAndRNACentralAndComplexPortalWithCaseInsensitivity() throws Exception { repository.deleteAll(); String uniprotGp = "A0A000"; String rnaGp = "URS00000064B1_559292"; String complexPortalGp = "CPX-101"; repository.save(AnnotationDocMocker.createAnnotationDoc(uniprotGp)); repository.save(AnnotationDocMocker.createAnnotationDoc(rnaGp)); repository.save(AnnotationDocMocker.createAnnotationDoc(complexPortalGp)); StringJoiner sj = new StringJoiner(","); sj.add(uniprotGp).add(complexPortalGp).add(rnaGp); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), sj.toString())); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()).andExpect(totalNumOfResults(3)).andExpect(fieldsInAllResultsExist(3)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, uniprotGp, 1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, rnaGp, 1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, complexPortalGp, 1)); } @Test public void filterByGeneProductUsingInvalidIDFailsValidation() throws Exception { String invalidGeneProductID = "99999"; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(invalidGeneProductID); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), invalidGeneProductID)); response.andExpect(status().isBadRequest()); } @Test public void filterByValidIdThatDoesNotExistExpectZeroResultsButNoError() throws Exception { String geneProductId = "Z0Z000"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterByThreeGeneProductIdsTwoOfWhichExistToEnsureTheyAreReturned() throws Exception { String geneProductId = "Z0Z000"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId) .param(GENE_PRODUCT_ID_PARAM.getName(), genericDocs.get(0).geneProductId) .param(GENE_PRODUCT_ID_PARAM.getName(), genericDocs.get(1).geneProductId)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, genericDocs.get(0).geneProductId, 1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, genericDocs.get(1).geneProductId, 1)); } @Test public void filterByGeneProductIDAndAssignedBySuccessfully() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(GENE_PRODUCT_ID_PARAM.getName(), genericDocs.get(0).geneProductId) .param(ASSIGNED_BY_PARAM.getName(), genericDocs.get(0).assignedBy)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, genericDocs.get(0).geneProductId, 1)) .andExpect(itemExistsExpectedTimes(ASSIGNED_BY_FIELD, genericDocs.get(1).assignedBy, 1)); } @Test public void idValidationTestWorksCorrectlyForGeneProductIDWithFeature() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(GENE_PRODUCT_ID_PARAM.getName(), "P19712:PRO_0000038050")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void successfullyLookupAnnotationsByGoId() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(GO_ID_PARAM.getName(), AnnotationDocMocker.GO_ID) .param(GO_USAGE_PARAM.getName(), EXACT_USAGE)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(GO_ID_FIELD, AnnotationDocMocker.GO_ID, NUMBER_OF_GENERIC_DOCS)); } @Test public void successfullyLookupAnnotationsByGoIdCaseInsensitive() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(GO_ID_PARAM.getName(), AnnotationDocMocker.GO_ID.toLowerCase()) .param(GO_USAGE_PARAM.getName(), EXACT_USAGE)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(GO_ID_FIELD, AnnotationDocMocker.GO_ID, NUMBER_OF_GENERIC_DOCS)); } @Test public void failToFindAnnotationsWhenGoIdDoesntExist() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(GO_ID_PARAM.getName(), MISSING_GO_ID) .param(GO_USAGE_PARAM.getName(), EXACT_USAGE)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void incorrectFormattedGoIdCausesError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_ID_PARAM.getName(), INVALID_GO_ID)); response.andExpect(status().isBadRequest()) .andExpect(contentTypeToBeJson()); } @Test public void filterAnnotationsUsingSingleEvidenceCodeReturnsResults() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID) .param(EVIDENCE_CODE_USAGE_PARAM.getName(), EXACT_USAGE)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(atLeastOneResultHasItem(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID)); } @Test public void filterAnnotationsUsingMultipleEvidenceCodesInSingleParameterProducesMixedResults() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("B0A000"); doc.evidenceCode = ECO_ID2; repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID + "," + doc.evidenceCode + "," + MISSING_ECO_ID) .param(EVIDENCE_CODE_USAGE_PARAM.getName(), EXACT_USAGE)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 1)) .andExpect(fieldsInAllResultsExist(4)) .andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID, NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), doc.evidenceCode, 1)) .andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID, 0)); } @Test public void filterAnnotationsUsingMultipleEvidenceCodesAsIndependentParametersProducesMixedResults() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("B0A000"); doc.evidenceCode = ECO_ID2; repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID) .param(EVIDENCE_CODE_PARAM.getName(), doc.evidenceCode) .param(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID) .param(EVIDENCE_CODE_USAGE_PARAM.getName(), EXACT_USAGE)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 1)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 1)) .andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID, NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), doc.evidenceCode, 1)) .andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID, 0)); } @Test public void filterByNonExistentEvidenceCodeReturnsZeroResults() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID) .param(EVIDENCE_CODE_USAGE_PARAM.getName(), EXACT_USAGE)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void retrievesSecondPageOfAllEntriesRequest() throws Exception { int totalEntries = 60; repository.deleteAll(); repository.save(createGenericDocs(totalEntries)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM.getName(), "2")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(totalEntries)) .andExpect(resultsInPage(DEFAULT_ENTRIES_PER_PAGE)) .andExpect( pageInfoMatches( 2, totalPages(totalEntries, DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestEqualToAvailablePagesReturns200() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM.getName(), "1")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect( pageInfoMatches( 1, totalPages(NUMBER_OF_GENERIC_DOCS, DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM.getName(), "0")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void pageRequestHigherThanAvailablePagesReturns400() throws Exception { repository.deleteAll(); int existingPages = 4; int resultsPerPage = 10; repository.save(createGenericDocs(resultsPerPage * existingPages)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM.getName(), String.valueOf(resultsPerPage)) .param(PAGE_PARAM.getName(), String.valueOf(existingPages + 1))); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void requestingMoreResultsPerPageThanPermittedReturns400() throws Exception { repository.deleteAll(); int docsNecessaryToForcePagination = MAX_PAGE_RESULTS + 1; repository.save(createGenericDocs(docsNecessaryToForcePagination)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM.getName(), String.valueOf(MAX_PAGE_RESULTS + 1)) .param(PAGE_PARAM.getName(), String.valueOf(1))); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void pageRequestHigherThanPaginationLimitReturns400() throws Exception { int totalEntries = MAX_PAGE_NUMBER + 1; int pageSize = 1; int pageNumWhichIsTooHigh = totalEntries; repository.deleteAll(); repository.save(createGenericDocs(totalEntries)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM.getName(), String.valueOf(pageSize)) .param(PAGE_PARAM.getName(), String.valueOf(pageNumWhichIsTooHigh))); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void successfulLookupWithFromForSingleId() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "InterPro:IPR015421")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem() .withAttribute("db", "InterPro") .withAttribute("id", "IPR015421").build())); } @Test public void successfulLookupWithFromForMultipleValues() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "InterPro:IPR015421,InterPro:IPR015422")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem() .withAttribute("db", "InterPro") .withAttribute("id", "IPR015421").build())) .andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem() .withAttribute("db", "InterPro") .withAttribute("id", "IPR015422").build())); } @Test public void searchingForUnknownWithFromCreatesError() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "XXX:54321")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void successfulLookupWithFromUsingDatabaseNameOnly() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "InterPro")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem() .withAttribute("db", "InterPro") .withAttribute("id", "IPR015421").build())) .andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem() .withAttribute("db", "InterPro") .withAttribute("id", "IPR015422").build())); } @Test public void successfulLookupWithFromUsingDatabaseIdOnly() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "IPR015421")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem() .withAttribute("db", "InterPro") .withAttribute("id", "IPR015421").build())); } @Test public void limitForPageExceedsMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM.getName(), "101")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageWithinMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(LIMIT_PARAM.getName(), "100")); response.andExpect(status().isOk()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(pageInfoMatches(1, 1, 100)); } @Test public void limitForPageThrowsErrorWhenNegative() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search") .param(LIMIT_PARAM.getName(), "-20")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void filterBySingleReferenceReturnsDocumentsThatContainTheReference() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), AnnotationDocMocker.REFERENCE)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS)); } @Test public void filterBySingleReferenceReturnsOnlyDocumentsThatContainTheReferenceWhenOthersExists() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.reference = "PMID:0000002"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), doc.reference)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, doc.reference, 1)); } @Test public void filterByThreeReferencesReturnsDocumentsThatContainThoseReferences() throws Exception { AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123"); docA.reference = "PMID:0000002"; repository.save(docA); AnnotationDocument docB = AnnotationDocMocker.createAnnotationDoc("A0A124"); docB.reference = "PMID:0000003"; repository.save(docB); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), AnnotationDocMocker.REFERENCE + "," + docA.reference + "," + docB.reference)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect( itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docB.reference, 1)); } @Test public void filterByThreeIndependentReferencesReturnsDocumentsThatContainThoseReferences() throws Exception { AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123"); docA.reference = "PMID:0000002"; repository.save(docA); AnnotationDocument docB = AnnotationDocMocker.createAnnotationDoc("A0A124"); docB.reference = "PMID:0000003"; repository.save(docB); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), AnnotationDocMocker.REFERENCE).param(REF_PARAM.getName(), docA.reference) .param(REF_PARAM.getName(), docB.reference)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect( itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docB.reference, 1)); } @Test public void filterByReferenceDbOnlyReturnsDocumentsWithReferencesThatStartWithThatDb() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "GO_REF")); //This one shouldn't be found AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123"); docA.reference = "PMID:0000002"; repository.save(docA); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterByReferenceDbNotAvailableInDocumentsReturnsZeroResults() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "GO_LEFT")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterBySingleReferenceIdReturnsDocumentsThatContainTheReferenceId() throws Exception { AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123"); docA.reference = "PMID:0000002"; repository.save(docA); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "0000002")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 1)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 1)) .andExpect( itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1)); } @Test public void filterByMultipleReferenceIdReturnsDocumentsThatContainTheReferenceId() throws Exception { AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123"); docA.reference = "PMID:0000002"; repository.save(docA); AnnotationDocument docB = AnnotationDocMocker.createAnnotationDoc("A0A124"); docB.reference = "PMID:0000003"; repository.save(docB); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "0000002") .param(REF_PARAM.getName(), "0000003")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2)) .andExpect( itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1)) .andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docB.reference, 1)); } @Test public void filterByUnknownReferenceIdIsUnsuccessful() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "999999")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterByGeneProductTypeReturnsMatchingDocuments() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "protein")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterBySingleGeneProductTypeOfRnaReturnsMatchingDocument() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.geneProductType = "miRNA"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "miRNA")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterAnnotationsByTwoGeneProductTypesAsOneParameterReturnsMatchingDocuments() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.geneProductType = "complex"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "protein,complex")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(4)) .andExpect(fieldsInAllResultsExist(4)); } @Test public void filterAnnotationsByTwoGeneProductTypesAsTwoParametersReturnsMatchingDocuments() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.geneProductType = "complex"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "protein").param(GENE_PRODUCT_TYPE_PARAM.getName(), "complex")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(4)) .andExpect(fieldsInAllResultsExist(4)); } @Test public void filterByNonExistentGeneProductTypeReturnsNothing() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.geneProductType = "complex"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "miRNA")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterByTargetSetReturnsMatchingDocuments() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "KRUK")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterByTwoTargetSetValuesReturnsMatchingDocuments() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "KRUK,BHF-UCL")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterByNewTargetSetValueReturnsMatchingDocuments() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.targetSets = Collections.singletonList("Parkinsons"); repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "Parkinsons")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterByTargetSetCaseInsensitiveReturnsMatchingDocuments() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.targetSets = Collections.singletonList("parkinsons"); repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "PARKINSONS")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterByNonExistentTargetSetReturnsNoDocuments() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "CLAP")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void filterAnnotationsByGoAspectSuccessfully() throws Exception { String goAspect = AnnotationDocMocker.GO_ASPECT; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), goAspect)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterAnnotationsByInvertedCaseGoAspectSuccessfully() throws Exception { String goAspect = StringUtils.swapCase(AnnotationDocMocker.GO_ASPECT); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), goAspect)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterAnnotationsByInvalidGoAspectReturnsError() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), "ZZZ")); response.andExpect(status().isBadRequest()); } @Test public void filterWithAspectMolecularFunctionReturnsAnnotationsWithMolecularFunction() throws Exception { String goAspect = "molecular_function"; AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createGPId(999)); annoDoc1.goAspect = goAspect; repository.save(annoDoc1); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), goAspect)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterByExtensionFull() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(EXTENSION_PARAM.getName(), EXTENSIONS)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS)) .andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS)); } @Test public void filterByUniqueExtensionTarget() throws Exception { String extension = "results_in_development_of(UBERON:1234567)"; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.extensions = extension; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search") .param(EXTENSION_PARAM.getName(), extension)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void retrieveWhereAnnotationExtensionIsNotEmpty() throws Exception { int numberOfDocsWithExtensions = 3; int numberOfDocsWithoutExtensions = 2; repository.deleteAll(); List<AnnotationDocument> docsWithExtensions = createGenericDocs(numberOfDocsWithExtensions); List<AnnotationDocument> docsWithoutExtensions = createGenericDocs(numberOfDocsWithoutExtensions); for (AnnotationDocument doc : docsWithoutExtensions) { doc.extensions = null; } repository.save(docsWithExtensions); repository.save(docsWithoutExtensions); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(EXTENSION_PARAM.getName(), SELECT_ALL_WHERE_FIELD_IS_NOT_EMPTY)); List<String> geneProductsThatAppearInDocumentsThatHaveExtensions = docsWithExtensions.stream() .map(d -> d.geneProductId).collect(toList()); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(numberOfDocsWithExtensions)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductsThatAppearInDocumentsThatHaveExtensions)); } @Test public void usingInvalidWildCardFieldResultsInError() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), SELECT_ALL_WHERE_FIELD_IS_NOT_EMPTY)); response.andDo(print()) .andExpect(status().isBadRequest()); } // Holds values TrEMBL, Swiss-Prot and maybe more @Test public void filterByGeneProductSubset() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A842"); String geneProductSubset = "Swiss-Prot"; doc.geneProductSubset = geneProductSubset; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GP_SUBSET_PARAM.getName(), geneProductSubset)); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterByGeneProductSubsetMixedCaseSearchValue() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A849"); doc.geneProductSubset = "Swiss-Prot"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GP_SUBSET_PARAM.getName(), "swisS-proT")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterByProteome() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123"); doc.proteome = "gcrpCan"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(PROTEOME_PARAM.getName(), "gcrpCan")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void filterByProteomeMixedCaseSearchValue() throws Exception { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A772"); doc.proteome = "gcrpCan"; repository.save(doc); ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(PROTEOME_PARAM.getName(), "GcrPcan")); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)); } @Test public void checkDateFormatIsCorrect() throws Exception { String geneProductId = "P99999"; AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); int year = 1900; int month = 1; int date = 31; doc.date = Date.from( LocalDate.of(year, month, date).atStartOfDay(ZoneId.systemDefault()).toInstant()); repository.save(doc); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)); String expectedResponseDate = getRequiredDateString(year, month, date); response.andDo(print()) .andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)) .andExpect(valuesOccurInField(DATE_FIELD, expectedResponseDate)); } @Test public void about() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/about")); response.andDo(print()) .andExpect(jsonPath("$.annotation.timestamp").value("2017-03-01 18:00")); } private <T> List<T> transformDocs(List<AnnotationDocument> docs, Function<AnnotationDocument, T> transformation) { return docs.stream().map(transformation).collect(toList()); } private <T> List<AnnotationDocument> filterDocuments( List<AnnotationDocument> documents, T[] expectedValues, Function<AnnotationDocument, T> docTransformer) { return documents.stream() .filter(doc -> Stream .of(expectedValues) .anyMatch(e -> e == docTransformer.apply(doc))) .collect(toList()); } private String[] asArray(List<String> list) { return list.toArray(new String[list.size()]); } private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.assignedBy = assignedBy; return doc; } private AnnotationDocument createDocWithTaxonId(String geneProductId, int taxonId) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.taxonId = taxonId; return doc; } private List<AnnotationDocument> createDocsWithTaxonAncestors(List<Integer> lineage) { List<AnnotationDocument> documents = new ArrayList<>(); for (int i = 0; i < lineage.size(); i++) { documents.add(createDocWithTaxonAncestors(createGPId(i), lineage.subList(i, lineage.size()))); } return documents; } private AnnotationDocument createDocWithTaxonAncestors( String geneProductId, List<Integer> lineage) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.taxonId = lineage.get(0); doc.taxonAncestors = lineage; return doc; } private String getRequiredDateString(int year, int month, int date) { return String.format(DATE_STRING_FORMAT, year, month, date); } private List<AnnotationDocument> createGenericDocs(int n) { return IntStream.range(0, n) .mapToObj(i -> AnnotationDocMocker.createAnnotationDoc("UniProtKB:"+ createGPId(i))).collect (toList()); } private int totalPages(int totalEntries, int resultsPerPage) { return (int) Math.ceil(totalEntries / resultsPerPage) + 1; } }
package uk.ac.ebi.quickgo.annotation.controller; import uk.ac.ebi.quickgo.annotation.AnnotationREST; import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*; import static uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {AnnotationREST.class}) @WebAppConfiguration public class AnnotationControllerIT { // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); private static final int NUMBER_OF_GENERIC_DOCS = 3; private static final String ASSIGNED_BY_PARAM = "assignedBy"; private static final String PAGE_PARAM = "page"; private static final String LIMIT_PARAM = "limit"; private static final String UNAVAILABLE_ASSIGNED_BY = "ZZZZZ"; private static final String GOEVIDENCE_PARM="goEvidence"; private MockMvc mockMvc; private List<AnnotationDocument> genericDocs; private static final String RESOURCE_URL = "/QuickGO/services/annotation"; @Autowired private WebApplicationContext webApplicationContext; @Autowired private AnnotationRepository repository; @Before public void setup() { repository.deleteAll(); mockMvc = MockMvcBuilders. webAppContextSetup(webApplicationContext) .build(); genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS); repository.save(genericDocs); } //ASSIGNED BY @Test public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, assignedBy1 + "," + assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception { String geneProductId1 = "P99999"; String assignedBy1 = "ASPGD"; AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1); repository.save(document1); String geneProductId2 = "P99998"; String assignedBy2 = "BHF-UCL"; AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2); repository.save(document2); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(ASSIGNED_BY_PARAM, assignedBy1) .param(ASSIGNED_BY_PARAM, assignedBy2)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(2)) .andExpect(fieldsInAllResultsExist(2)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId1, geneProductId2)); } @Test public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception { String geneProductId = "P99999"; String assignedBy = "ASPGD"; AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy); repository.save(document); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY + "," + assignedBy)); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(1)) .andExpect(fieldsInAllResultsExist(1)) .andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId)); } @Test public void invalidAssignedByThrowsAnError() throws Exception { String invalidAssignedBy = "_ASPGD"; ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, invalidAssignedBy)); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void lookupAnnotationFilterByGoEvidenceCodeBySuccessfully() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GOEVIDENCE_PARM, "IEA")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(fieldsInAllResultsExist(1)); } @Test public void lookupAnnotationFilterByNonExistentGoEvidenceCodeReturnsNothing() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GOEVIDENCE_PARM, "ZZZ")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(0)); } @Test public void invalidGoEvidenceThrowsException() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(GOEVIDENCE_PARM, "BlahBlah")); response.andExpect(status().isBadRequest()) .andExpect(contentTypeToBeJson()); } @Test public void retrievesSecondPageOfAllEntriesRequest() throws Exception { int totalEntries = 60; repository.deleteAll(); repository.save(createGenericDocs(totalEntries)); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, "2")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(totalEntries)) .andExpect(resultsInPage(DEFAULT_ENTRIES_PER_PAGE)) .andExpect( pageInfoMatches( 2, totalPages(totalEntries, DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestEqualToAvailablePagesReturns200() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "1")); response.andExpect(status().isOk()) .andExpect(contentTypeToBeJson()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect( pageInfoMatches( 1, totalPages(genericDocs.size(), DEFAULT_ENTRIES_PER_PAGE), DEFAULT_ENTRIES_PER_PAGE) ); } @Test public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(PAGE_PARAM, "0")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void pageRequestHigherThanAvailablePagesReturns400() throws Exception { repository.deleteAll(); int existingPages = 4; createGenericDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages); ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(PAGE_PARAM, String.valueOf(existingPages + 1))); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageExceedsMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "101")); response.andDo(print()) .andExpect(status().isBadRequest()); } @Test public void limitForPageWithinMaximumAllowed() throws Exception { ResultActions response = mockMvc.perform( get(RESOURCE_URL + "/search").param(LIMIT_PARAM, "100")); response.andExpect(status().isOk()) .andExpect(totalNumOfResults(genericDocs.size())) .andExpect(pageInfoMatches(1, 1, 100)); } @Test public void limitForPageThrowsErrorWhenNegative() throws Exception { ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search") .param(LIMIT_PARAM, "-20")); response.andDo(print()) .andExpect(status().isBadRequest()); } private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) { AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId); doc.assignedBy = assignedBy; return doc; } private List<AnnotationDocument> createGenericDocs(int n) { return IntStream.range(0, n) .mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createId(i))).collect (Collectors.toList()); } private String createId(int idNum) { return String.format("A0A%03d", idNum); } private int totalPages(int totalEntries, int resultsPerPage) { return (int) Math.ceil(totalEntries / resultsPerPage) + 1; } }
package openfoodfacts.github.scrachx.openfood.fragments; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import openfoodfacts.github.scrachx.openfood.R; import openfoodfacts.github.scrachx.openfood.models.State; public class IngredientsProductFragment extends Fragment { TextView ingredientProduct, substanceProduct, traceProduct, additiveProduct, palmOilProduct, mayBeFromPalmOilProduct; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_ingredients_product,container,false); ingredientProduct = (TextView) rootView.findViewById(R.id.textIngredientProduct); substanceProduct = (TextView) rootView.findViewById(R.id.textSubstanceProduct); traceProduct = (TextView) rootView.findViewById(R.id.textTraceProduct); additiveProduct = (TextView) rootView.findViewById(R.id.textAdditiveProduct); palmOilProduct = (TextView) rootView.findViewById(R.id.textPalmOilProduct); mayBeFromPalmOilProduct = (TextView) rootView.findViewById(R.id.textMayBeFromPalmOilProduct); Intent intent = getActivity().getIntent(); State state = (State) intent.getExtras().getSerializable("state"); ingredientProduct.setText(getString(R.string.txtIngredients) + ' ' + state.getProduct().getIngredientsText()); substanceProduct.setText(getString(R.string.txtSubstances) + ' ' + state.getProduct().getAllergens()); traceProduct.setText(getString(R.string.txtTraces) + ' ' + state.getProduct().getTraces()); additiveProduct.setText(getString(R.string.txtAdditives) + ' ' + state.getProduct().getAdditivesTags().toString()); palmOilProduct.setText(getString(R.string.txtPalmOilProduct) + ' ' + state.getProduct().getIngredientsFromPalmOilTags().toString()); mayBeFromPalmOilProduct.setText(getString(R.string.txtMayBeFromPalmOilProduct) + ' ' + state.getProduct().getIngredientsThatMayBeFromPalmOilTags().toString()); return rootView; } }
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.ovirt.engine.core.bll.provider.ProviderProxyFactory; import org.ovirt.engine.core.bll.provider.storage.OpenStackImageProviderProxy; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.businessentities.Provider; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.storage.ImageFileType; import org.ovirt.engine.core.common.businessentities.storage.RepoImage; import org.ovirt.engine.core.common.businessentities.storage.StorageType; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.common.errors.VdcBllErrors; import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.vdscommands.GetFileStatsParameters; import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.dao.RepoFileMetaDataDAO; import org.ovirt.engine.core.dao.StorageDomainDAO; import org.ovirt.engine.core.dao.StoragePoolDAO; import org.ovirt.engine.core.dao.provider.ProviderDao; import org.ovirt.engine.core.di.Injector; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation; import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class manages the Iso domain cache mechanism, <BR/> * which reflects upon support for Iso tool validation, activation of Iso domain, and fetching the Iso list by query.<BR/> * The cache is being refreshed with quartz scheduler which run by configuration value AutoRepoDomainRefreshTime. The * cache procedure using VDSM to fetch the Iso files from all the Data Centers and update the DB cache table with the * appropriate file data.<BR/> */ @SuppressWarnings("synthetic-access") public class IsoDomainListSyncronizer { private static final Logger log = LoggerFactory.getLogger(IsoDomainListSyncronizer.class); private static final AuditLogDirector auditLogDirector = new AuditLogDirector(); private List<RepoImage> problematicRepoFileList = new ArrayList<>(); private static final int MIN_TO_MILLISECONDS = 60 * 1000; private static volatile IsoDomainListSyncronizer isoDomainListSyncronizer; private static final ConcurrentMap<Object, Lock> syncDomainForFileTypeMap = new ConcurrentHashMap<>(); private int isoDomainRefreshRate; RepoFileMetaDataDAO repoStorageDom; ProviderDao providerDao; public static final String TOOL_CLUSTER_LEVEL = "clusterLevel"; public static final String TOOL_VERSION = "toolVersion"; public static final String REGEX_TOOL_PATTERN = String.format("%1$s(?<%2$s>[0-9]{1,}.[0-9])_{1}(?<%3$s>[0-9]{1,}).[i|I][s|S][o|O]$", getGuestToolsSetupIsoPrefix(), TOOL_CLUSTER_LEVEL, TOOL_VERSION); public static final String ISO_FILE_PATTERN = "*.iso"; public static final String FLOPPY_FILE_PATTERN = "*.vfd"; // Not kept as static member to enable reloading the config value public static String getGuestToolsSetupIsoPrefix() { return Config.getValue(ConfigValues.GuestToolsSetupIsoPrefix); } /** * private constructor to initialize the quartz scheduler */ protected IsoDomainListSyncronizer() { init(); } protected void init() { log.info("Start initializing {}", getClass().getSimpleName()); repoStorageDom = DbFacade.getInstance().getRepoFileMetaDataDao(); providerDao = DbFacade.getInstance().getProviderDao(); isoDomainRefreshRate = Config.<Integer> getValue(ConfigValues.AutoRepoDomainRefreshTime) * MIN_TO_MILLISECONDS; Injector.get(SchedulerUtilQuartzImpl.class).scheduleAFixedDelayJob(this, "fetchIsoDomains", new Class[] {}, new Object[] {}, 300000, isoDomainRefreshRate, TimeUnit.MILLISECONDS); log.info("Finished initializing {}", getClass().getSimpleName()); } /** * Returns the singleton instance. * @return Singleton instance of IsoDomainManager */ public static IsoDomainListSyncronizer getInstance() { if (isoDomainListSyncronizer == null) { synchronized (IsoDomainListSyncronizer.class) { if (isoDomainListSyncronizer == null) { isoDomainListSyncronizer = new IsoDomainListSyncronizer(); } } } return isoDomainListSyncronizer; } /** * Check and update if needed each Iso domain in each Data Center in the system. */ @OnTimerMethodAnnotation("fetchIsoDomains") public void fetchIsoDomains() { // Gets all the active Iso storage domains. List<RepoImage> repofileList = DbFacade.getInstance() .getRepoFileMetaDataDao() .getAllRepoFilesForAllStoragePools(StorageDomainType.ISO, StoragePoolStatus.Up, StorageDomainStatus.Active, VDSStatus.Up); resetProblematicList(); // Iterate for each storage domain. List<Callable<Void>> tasks = new ArrayList<>(); for (final RepoImage repoImage : repofileList) { // If the list should be refreshed and the refresh from the VDSM was succeeded, fetch the file list again // from the DB. if (shouldRefreshIsoDomain(repoImage.getLastRefreshed())) { tasks.add(new Callable<Void>() { @Override public Void call() { updateCachedIsoFileListFromVdsm(repoImage); return null; } }); } else { log.debug("Automatic refresh process for '{}' file type in storage domain id '{}' was not performed" + " since refresh time out did not passed yet.", repoImage.getFileType(), repoImage.getRepoDomainId()); } } ThreadPoolUtil.invokeAll(tasks); // After refresh for all Iso domains finished, handle the log. handleErrorLog(new ArrayList<>(problematicRepoFileList)); } /** * Returns a RepoFilesMetaData list with Iso file names for storage domain Id and with file type extension.<BR> * If user choose to refresh the cache, and a problem occurs, then throws VdcBLLException. * * @param storageDomainId * - The storage domain Id, which we fetch the Iso list from. * @param imageType * - The imageType we want to fetch the files from the cache. * @param forceRefresh * - Indicates if the domain should be refreshed from VDSM. * @throws VdcBLLException - if a problem occurs when refreshing the image repo cache. * @return List of RepoFilesMetaData files. */ public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } // At any case, if refreshed or not, get Iso list from the cache. return getCachedIsoListByDomainId(storageDomainId, imageType); } private boolean refreshRepos(Guid storageDomainId, ImageFileType imageType) { boolean refreshResult; List<RepoImage> tempProblematicRepoFileList = new ArrayList<>(); StorageDomain storageDomain = DbFacade.getInstance().getStorageDomainDao().get(storageDomainId); if (storageDomain.getStorageDomainType() == StorageDomainType.ISO) { refreshResult = refreshIsoDomain(storageDomainId, tempProblematicRepoFileList, imageType); } else if (storageDomain.getStorageDomainType() == StorageDomainType.Image && storageDomain.getStorageType() == StorageType.GLANCE) { refreshResult = refreshImageDomain(storageDomain, imageType); } else { log.error("Unable to refresh the storage domain '{}', Storage Domain Type '{}' not supported", storageDomainId, storageDomain.getStorageDomainType()); return false; } handleErrorLog(tempProblematicRepoFileList); // If refresh succeeded update the audit log if (refreshResult) { addToAuditLogSuccessMessage(storageDomain.getStorageName(), imageType.name()); } return refreshResult; } private boolean refreshImageDomain(final StorageDomain storageDomain, final ImageFileType imageType) { final RepoFileMetaDataDAO repoFileMetaDataDao = repoStorageDom; Provider provider = providerDao.get(new Guid(storageDomain.getStorage())); final OpenStackImageProviderProxy client = ProviderProxyFactory.getInstance().create(provider); Lock syncObject = getSyncObject(storageDomain.getId(), imageType); try { syncObject.lock(); return (Boolean) TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { repoFileMetaDataDao.removeRepoDomainFileList(storageDomain.getId(), imageType); Integer totalListSize = Config.<Integer> getValue(ConfigValues.GlanceImageTotalListSize); List<RepoImage> repoImages = client.getAllImagesAsRepoImages( Config.<Integer> getValue(ConfigValues.GlanceImageListSize), totalListSize); if (repoImages.size() >= totalListSize) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("imageDomain", storageDomain.getName()); logable.addCustomValue("imageListSize", String.valueOf(repoImages.size())); auditLogDirector.log(logable, AuditLogType.REFRESH_REPOSITORY_IMAGE_LIST_INCOMPLETE); } for (RepoImage repoImage : repoImages) { repoImage.setRepoDomainId(storageDomain.getId()); repoFileMetaDataDao.addRepoFileMap(repoImage); } return true; } }); } finally { syncObject.unlock(); } } /** * The procedure Try to refresh the repository files of the storage domain id, with storage pool Id. If succeeded * will return True, otherwise return false and update the list, of the problematic repository files with the * storage pool and storage domain id, that could not complete the cache update transaction. * * @param storageDomainId * - The Repository domain Id, we want to refresh. * @param storagePoolId * - The Storage pool Id, we use to fetch the Iso files from.. * @param imageType * - The imageType we want to fetch the files from the cache. * @return Boolean value indicating if the refresh succeeded or not. */ private boolean refreshIsoDomainFileForStoragePool(Guid storageDomainId, Guid storagePoolId, ImageFileType imageType) { boolean refreshSucceeded = false; // Setting the indication to the indication whether the storage pool is valid. boolean updateFromVDSMSucceeded = true; // If the SPM and the storage pool are valid, try to refresh the Iso list by fetching it from the SPM. if (imageType == ImageFileType.ISO || imageType == ImageFileType.All) { updateFromVDSMSucceeded = updateIsoListFromVDSM(storagePoolId, storageDomainId); } if (imageType == ImageFileType.Floppy || imageType == ImageFileType.All) { updateFromVDSMSucceeded = updateFloppyListFromVDSM(storagePoolId, storageDomainId) && updateFromVDSMSucceeded; } // Log if the refresh succeeded or add the storage domain to the problematic list. if (updateFromVDSMSucceeded) { refreshSucceeded = true; log.debug("Refresh succeeded for file type '{}' at storage domain id '{}' in storage pool id '{}'.", imageType.name(), storageDomainId, storagePoolId); } return refreshSucceeded; } /** * The procedure Try to refresh the repository files of the storage domain id, By iterate over the storage pools of * this domain, and try to choose a valid storage pool, to fetch the repository files from the VDSM, and refresh the * cached table. <BR/> * If succeeded, will return True. Otherwise return false with updated list of problematic repository files with the * storage pool, storage domain, and file type, that could not complete the cache update transaction. * * @param storageDomainId * - The Repository domain Id, we want to refresh. * @param problematicRepoFileList * - List of business entities, each one indicating the problematic entity. * @param imageType * - The imageType we want to fetch the files from the cache. * @return Boolean value indicating if the refresh succeeded or not. */ private boolean refreshIsoDomain(Guid storageDomainId, List<RepoImage> problematicRepoFileList, ImageFileType imageType) { List<StoragePoolIsoMap> isoMapList = fetchAllStoragePoolsForIsoDomain(storageDomainId, imageType); for (StoragePoolIsoMap storagePoolIsoMap : isoMapList) { Guid storagePoolId = storagePoolIsoMap.getstorage_pool_id(); StorageDomainStatus status = storagePoolIsoMap.getStatus(); if (StorageDomainStatus.Active != status) { handleInactiveStorageDomain(storageDomainId, imageType, status); } else { // Try to refresh the domain of the storage pool id because its status is active. boolean refreshOk = refreshIsoDomainFileForStoragePool(storageDomainId, storagePoolId, imageType); if (!refreshOk) { log.debug("Failed refreshing Storage domain id '{}', for '{}' file type in storage pool id '{}'.", storageDomainId, imageType, storagePoolId); // Add the repository file to the list of problematic Iso domains. RepoImage repoImage = createMockRepositoryFileMetaData(storageDomainId, imageType, storagePoolId); problematicRepoFileList.add(repoImage); return false; } } } return true; } // Fetch all the Storage pools for this Iso domain Id. private List<StoragePoolIsoMap> fetchAllStoragePoolsForIsoDomain(Guid storageDomainId, ImageFileType imageType) { List<StoragePoolIsoMap> isoMapList = DbFacade.getInstance() .getStoragePoolIsoMapDao() .getAllForStorage(storageDomainId); log.debug("Fetched {} storage pools for '{}' file type, in Iso domain '{}'.", isoMapList.size(), imageType, storageDomainId); return isoMapList; } // set a mock repository file meta data with storage domain id and storage pool id. private static RepoImage createMockRepositoryFileMetaData(Guid storageDomainId, ImageFileType imageType, Guid storagePoolId) { RepoImage repoImage = new RepoImage(); repoImage.setStoragePoolId(storagePoolId); repoImage.setRepoDomainId(storageDomainId); repoImage.setFileType(imageType); return repoImage; } private void handleInactiveStorageDomain(Guid storageDomainId, ImageFileType imageType, StorageDomainStatus status) { log.debug("Storage domain id '{}', is not active, and therefore could not be refreshed for '{}'" + " file type (Iso domain status is '{}').", storageDomainId, imageType, status); } /** * Refresh the Iso domain when activating the domain, * with executing a new Thread to prevent long lock status for the domain. * * @param isoStorageDomainId * - The storage domain Id we want to get the file list from. * @param storagePoolId * - The storage pool Id we get an Iso active domain, we want to get the file list from (used mainly for log issues). */ public void refresheIsoDomainWhenActivateDomain(final Guid isoStorageDomainId, final Guid storagePoolId) { if (storagePoolId != null && (isoStorageDomainId != null)) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { refreshActivatedStorageDomainFromVdsm(storagePoolId, isoStorageDomainId); } }); } } /** * Returns the cached Iso file meta data list, for storage domain. * * @param isoStorageDomainId * - The storage domain Id we want to get the file list from. * @return List of Iso files fetched from DB, if parameter is invalid returns an empty list. */ public List<RepoImage> getCachedIsoListByDomainId(Guid isoStorageDomainId, ImageFileType imageType) { List<RepoImage> fileListMD = new ArrayList<>(); if (isoStorageDomainId != null) { fileListMD = repoStorageDom.getRepoListForStorageDomain(isoStorageDomainId, imageType); } return fileListMD; } /** * Handling the list of problematic repository files, to maintain multi thread caching. * @see #resetProblematicList() */ private synchronized void addRepoFileToProblematicList(List<RepoImage> repoImageList) { problematicRepoFileList.addAll(repoImageList); } /** * Reset the list of problematic repository files, before starting the refresh procedure. * uses for multy thread caching. * @see #addRepoFileToProblematicList(List<RepoImage>) */ private synchronized void resetProblematicList() { problematicRepoFileList.clear(); } /** * Print information on the problematic storage domain. Mainly transfer the business entity to list, for handling * the error uniformly. * Create a mock RepoImage object in a list, to use the functionality of the handleErrorLog with list. * * @param storagePoolId * - The storage domain Id. * @param storagePoolId * - The storage pool Id. * @param imageType * - The file type extension (ISO or Floppy). * @see #handleErrorLog(List) */ private static void handleErrorLog(Guid storagePoolId, Guid storageDomainId, ImageFileType imageType) { List<RepoImage> tempProblematicRepoFileList = new ArrayList<>(); RepoImage repoImage = createMockRepositoryFileMetaData( storageDomainId, imageType, storagePoolId); // Add the repository file to the list, and use handleError. tempProblematicRepoFileList.add(repoImage); handleErrorLog(tempProblematicRepoFileList); } /** * Print information on the problematic storage domains and print an audit log.<BR/> * If the problematicFileListForHandleError list retrieved empty or null,<BR/> * then don't do nothing and return false flag. * * @param problematicFileListForHandleError * - List of repository file meta data, each one indicating a problematic repository domain. * @return true, if has problematic storage domains, false otherwise (List is empty). */ private static boolean handleErrorLog(List<RepoImage> problematicFileListForHandleError) { boolean hasProblematic = false; if (problematicFileListForHandleError != null && !problematicFileListForHandleError.isEmpty()) { StringBuilder problematicStorages = new StringBuilder(); StringBuilder problematicIsoDomainsForAuditLog = new StringBuilder(); Set<String> storageDomainNames = new HashSet<>(); for (RepoImage repoMap : problematicFileListForHandleError) { problematicStorages.append(buildDetailedProblematicMapMsg(repoMap)); storageDomainNames.add(buildDetailedAuditLogMessage(repoMap)); } // Build Audit log message with problematic domains. for (String domainName : storageDomainNames) { problematicIsoDomainsForAuditLog.append(" ").append(domainName); } hasProblematic = true; log.error("The following storage domains had a problem retrieving data from VDSM: {}", problematicStorages); addToAuditLogErrorMessage(problematicIsoDomainsForAuditLog.toString()); } return hasProblematic; } /** * Returns a string builder contains problematic repoImage details. * * @param repoImage * - The problematic storage domain. */ private static StringBuilder buildDetailedProblematicMapMsg(RepoImage repoImage) { StringBuilder problematicStorageMsg = new StringBuilder(); if (repoImage != null) { problematicStorageMsg.append(" ("); if (repoImage.getStoragePoolId() != null) { problematicStorageMsg.append(" Storage Pool Id: ").append(repoImage.getStoragePoolId()); } if (repoImage.getRepoDomainId() != null) { problematicStorageMsg.append(" Storage domain Id: ").append(repoImage.getRepoDomainId()); } problematicStorageMsg.append(" File type: ").append(repoImage.getFileType()).append(") "); } else { problematicStorageMsg.append("(A repository file meta data business entity, has null value) "); } return problematicStorageMsg; } /** * Returns String contains problematic iso domain name for audit log message. * @param repoImage * - The problematic storage domain. * @return */ private static String buildDetailedAuditLogMessage(RepoImage repoImage) { String storageDomainName = "Repository not found"; if (repoImage != null && repoImage.getRepoDomainId() != null) { StorageDomain storageDomain = DbFacade.getInstance().getStorageDomainDao().get(repoImage.getRepoDomainId()); if (storageDomain != null) { storageDomainName = String.format("%s (%s file type)", storageDomain.getStorageName(), repoImage.getFileType().name()); } } else { log.error("Repository file meta data not found for logging"); } return storageDomainName; } /** * Updates the DB cache table with files fetched from VDSM. * The method is dedicated for multiple threads refresh. * If refresh from VDSM has encounter problems, we update the problematic domain list. * @param repoImage */ private void updateCachedIsoFileListFromVdsm(RepoImage repoImage) { boolean isRefreshed = false; try { List<RepoImage> problematicRepoFileList = new ArrayList<>(); isRefreshed = refreshIsoDomain(repoImage.getRepoDomainId(), problematicRepoFileList, repoImage.getFileType()); addRepoFileToProblematicList(problematicRepoFileList); } finally { log.info("Finished automatic refresh process for '{}' file type with {}, for storage domain id '{}'.", repoImage.getFileType(), isRefreshed ? "success" : "failure", repoImage.getRepoDomainId()); } } private static boolean refreshIsoFileListMetaData(final Guid repoStorageDomainId, final RepoFileMetaDataDAO repoFileMetaDataDao, final Map<String, Map<String, Object>> fileStats, final ImageFileType imageType) { Lock syncObject = getSyncObject(repoStorageDomainId, imageType); try { syncObject.lock(); return (Boolean) TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { long currentTime = System.currentTimeMillis(); repoFileMetaDataDao.removeRepoDomainFileList(repoStorageDomainId, imageType); for (Map.Entry<String, Map<String, Object>> entry : fileStats.entrySet()) { repoFileMetaDataDao.addRepoFileMap(newRepoImage(currentTime, entry)); } return true; } public RepoImage newRepoImage(long currentTime, Map.Entry<String, Map<String, Object>> entry) { RepoImage repo_md = new RepoImage(); repo_md.setLastRefreshed(currentTime); repo_md.setSize(retrieveIsoFileSize(entry)); repo_md.setRepoDomainId(repoStorageDomainId); repo_md.setDateCreated(null); repo_md.setRepoImageId(entry.getKey()); repo_md.setRepoImageName(null); repo_md.setFileType(imageType); return repo_md; } }); } catch (Exception e) { log.warn("Updating repository content to DB failed for repoStorageDomainId={}, imageType={}: {}", repoStorageDomainId, imageType, e.getMessage()); log.debug("Exception", e); return false; } finally { syncObject.unlock(); } } private static Long retrieveIsoFileSize(Map.Entry<String, Map<String, Object>> fileStats) { try { Object fileSize = fileStats.getValue().get(VdsProperties.size); if (fileSize == null) { return null; } return Long.valueOf((String) fileStats.getValue().get(VdsProperties.size)); } catch (RuntimeException e) { // handling exception in UI will be much more complicated. log.error("File's '{}' size is illegal number: {}", fileStats.getKey(), e.getMessage()); log.debug("Exception", e); return null; } } /** * Try to update the cached table from the VDSM, if succeeded fetch the file list again from the DB. if not ,handle * the log message. * * @param storagePoolId * - The storage pool id we want to get the file list from. * @param storageDomainId * - The storage domain id we want to get the file list from. */ private synchronized void refreshActivatedStorageDomainFromVdsm(Guid storagePoolId, Guid storageDomainId) { if (!updateIsoListFromVDSM(storagePoolId, storageDomainId)) { // Add an audit log that refresh was failed for Iso files. handleErrorLog(storagePoolId, storageDomainId, ImageFileType.ISO); } if (!updateFloppyListFromVDSM(storagePoolId, storageDomainId)) { // Add an audit log that refresh was failed for Floppy files. handleErrorLog(storagePoolId, storageDomainId, ImageFileType.Floppy); } } /** * Check if last refreshed time has exceeded the time limit configured in isoDomainRefreshRate. * * @param lastRefreshed * - Time when repository file was last refreshed. * @return True if time exceeded, and should refresh the domain, false otherwise. */ private boolean shouldRefreshIsoDomain(long lastRefreshed) { return ((System.currentTimeMillis() - lastRefreshed) > isoDomainRefreshRate); } /** * Gets the Iso file list from VDSM, and if the fetch is valid refresh the Iso list in the DB. * * @param repoStoragePoolId - The repository storage pool id, we want to update the file list. * @param repoStorageDomainId - The repository storage domain id, for activate storage domain id. * * @return True, if the fetch from VDSM has succeeded. False otherwise. */ private boolean updateIsoListFromVDSM(Guid repoStoragePoolId, Guid repoStorageDomainId) { VDSReturnValue fileStats = getFileStats(repoStoragePoolId, repoStorageDomainId, ISO_FILE_PATTERN, VDSCommandType.GetIsoList); FileListRefreshed fileListRefreshed = new FileListRefreshed() { @Override public void onFileListRefreshed(Guid poolId, Set<String> isoList) { VmHandler.refreshVmsToolsVersion(poolId, isoList); } }; return refreshVdsmFileList(repoStoragePoolId, repoStorageDomainId, fileListRefreshed, ImageFileType.ISO, fileStatsFromVDSReturnValue(fileStats)); } private boolean refreshVdsmFileList(Guid repoStoragePoolId, Guid repoStorageDomainId, FileListRefreshed fileListRefreshed, ImageFileType imageFileType, Map<String, Map<String, Object>> fileStats) { if (repoStorageDomainId == null) { return false; } boolean vdsmRefreshOk = fileStats != null; log.debug("The refresh process from VDSM, for {}, {}.", imageFileType, succeededOrFailed(vdsmRefreshOk)); if (!vdsmRefreshOk) { return false; } boolean refreshSucceeded = refreshIsoFileListMetaData(repoStorageDomainId, repoStorageDom, fileStats, imageFileType); if (refreshSucceeded && fileListRefreshed != null) { fileListRefreshed.onFileListRefreshed(repoStoragePoolId, fileStats.keySet()); } return refreshSucceeded; } private Map<String, Map<String, Object>> fileStatsFromVDSReturnValue(VDSReturnValue fileStats) { if (fileStats == null || !fileStats.getSucceeded()) { return null; } @SuppressWarnings("unchecked") Map<String, Map<String, Object>> result = (Map<String, Map<String, Object>>) fileStats.getReturnValue(); return result; } public interface FileListRefreshed { void onFileListRefreshed(Guid poolId, Set<String> isoList); } /** * Gets the Iso floppy file list from VDSM, and if the fetch is valid refresh the Iso floppy list in the DB. * * @param repoStoragePoolId * - The repository storage pool id, we want to update the file list. * @param repoStorageDomainId * - The repository storage domain id, for activate storage domain id. * @return True, if the fetch from VDSM has succeeded. False otherwise. */ private boolean updateFloppyListFromVDSM(Guid repoStoragePoolId, Guid repoStorageDomainId) { VDSReturnValue fileStats = getFileStats(repoStoragePoolId, repoStorageDomainId, FLOPPY_FILE_PATTERN, VDSCommandType.GetFloppyList); return refreshVdsmFileList(repoStoragePoolId, repoStorageDomainId, null, ImageFileType.Floppy, fileStatsFromVDSReturnValue(fileStats)); } private String succeededOrFailed(boolean status) { return status ? " succeeded" : "failed"; } private VDSReturnValue getFileStats(Guid repoStoragePoolId, Guid repoStorageDomainId, String filePattern, VDSCommandType alternateGetFileStatsCommand) { try { StoragePool dc = getStoragePoolDAO().get(repoStoragePoolId); VDSBrokerFrontend resourceManager = Backend.getInstance().getResourceManager(); if (FeatureSupported.getFileStats(dc.getCompatibilityVersion())) { return resourceManager.RunVdsCommand(VDSCommandType.GetFileStats, new GetFileStatsParameters(repoStoragePoolId, repoStorageDomainId, filePattern, false)); } else { return resourceManager.RunVdsCommand(alternateGetFileStatsCommand, new IrsBaseVDSCommandParameters(repoStoragePoolId)); } } catch (Exception e) { log.warn("The refresh process for pattern {} failed: {}", filePattern, e.getMessage()); log.debug("Exception", e); return null; } } /** * Maintain a <code>ConcurrentMap</code> which contains <code>Lock</code> object.<BR/> * The key Object is a <code>Pair</code> object, which will represent the domain and the file type.<BR/> * If no synchronized object found, the <code>Lock</code> will be add to the <code>ConcurrentMap</code>. * * @param domainId * - The domain Id that supposed to be refreshed. * @param imageType * - The file type supposed to be refreshed. * @return - The Lock object, which represent the domain and the file type, to lock. */ private static Lock getSyncObject(Guid domainId, ImageFileType imageType) { Pair<Guid, ImageFileType> domainPerFileType = new Pair<>(domainId, imageType); syncDomainForFileTypeMap.putIfAbsent(domainPerFileType, new ReentrantLock()); return syncDomainForFileTypeMap.get(domainPerFileType); } /** * Add audit log message when fetch encounter problems. * * @param problematicRepoFilesList * - List of Iso domain names, which encounter problem fetching from VDSM. */ private static void addToAuditLogErrorMessage(String problematicRepoFilesList) { AuditLogableBase logable = new AuditLogableBase(); // Get translated error by error code ,if no translation found (should not happened) , // will set the error code instead. logable.addCustomValue("imageDomains", problematicRepoFilesList); auditLogDirector.log(logable, AuditLogType.REFRESH_REPOSITORY_IMAGE_LIST_FAILED); } /** * Add audit log message when fetch encounter problems. */ private static void addToAuditLogSuccessMessage(String IsoDomain, String imageType) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("imageDomains", String.format("%s (%s file type)", IsoDomain, imageType)); auditLogDirector.log(logable, AuditLogType.REFRESH_REPOSITORY_IMAGE_LIST_SUCCEEDED); } private boolean isStorageDomainValid(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { // Check storage domain Id validity. if (storageDomainId == null) { log.error("Storage domain ID received from command query is null."); return false; } if (forceRefresh) { return refreshRepos(storageDomainId, imageType); } return true; } /** * Checks if there is an active ISO domain in the storage pool. If so returns the Iso Guid, otherwise returns null. * @param storagePoolId * The storage pool id. * @return Iso Guid of active Iso, and null if not. */ public Guid findActiveISODomain(Guid storagePoolId) { List<StorageDomain> domains = getStorageDomainDAO().getAllForStoragePool( storagePoolId); for (StorageDomain domain : domains) { if (domain.getStorageDomainType() == StorageDomainType.ISO && domain.getStatus() == StorageDomainStatus.Active) { return domain.getId(); } } return null; } private StorageDomainDAO getStorageDomainDAO() { return DbFacade.getInstance().getStorageDomainDao(); } private StoragePoolDAO getStoragePoolDAO() { return DbFacade.getInstance().getStoragePoolDao(); } }
package org.ovirt.engine.core.bll.validator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.bll.ImagesHandler; import org.ovirt.engine.core.bll.ValidationResult; import org.ovirt.engine.core.bll.interfaces.BackendInternal; import org.ovirt.engine.core.bll.scheduling.SchedulingManager; import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator; import org.ovirt.engine.core.bll.validator.storage.DiskImagesValidator; import org.ovirt.engine.core.bll.validator.storage.MultipleStorageDomainsValidator; import org.ovirt.engine.core.bll.validator.storage.StoragePoolValidator; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcActionUtils; import org.ovirt.engine.core.common.action.RunVmParams; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.BootSequence; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VdsDynamic; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.storage.Disk; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.ImageFileType; import org.ovirt.engine.core.common.businessentities.storage.RepoImage; import org.ovirt.engine.core.common.businessentities.storage.VolumeType; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.queries.GetImagesListParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.SimpleDependecyInjector; import org.ovirt.engine.core.common.utils.customprop.VmPropertiesUtils; import org.ovirt.engine.core.common.vdscommands.IsVmDuringInitiatingVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dao.DiskDao; import org.ovirt.engine.core.dao.StorageDomainDao; import org.ovirt.engine.core.dao.VdsDynamicDao; import org.ovirt.engine.core.dao.network.NetworkDao; import org.ovirt.engine.core.dao.network.VmNicDao; import org.ovirt.engine.core.di.Injector; import org.ovirt.engine.core.utils.NetworkUtils; public class RunVmValidator { private VM vm; private RunVmParams runVmParam; private boolean isInternalExecution; private Guid activeIsoDomainId; private OsRepository osRepository; private List<Disk> cachedVmDisks; private List<DiskImage> cachedVmImageDisks; private Set<String> cachedInterfaceNetworkNames; private List<Network> cachedClusterNetworks; private Set<String> cachedClusterNetworksNames; public RunVmValidator(VM vm, RunVmParams rumVmParam, boolean isInternalExecution, Guid activeIsoDomainId) { this.vm = vm; this.runVmParam = rumVmParam; this.isInternalExecution = isInternalExecution; this.activeIsoDomainId = activeIsoDomainId; this.osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class); } /** * Used for testings */ protected RunVmValidator() { } /** * A general method for run vm validations. used in runVmCommand and in VmPoolCommandBase * * @param messages * @param storagePool * @param vdsBlackList * - hosts that we already tried to run on * @param vdsWhiteList * - initial host list, mainly runOnSpecificHost (runOnce/migrateToHost) * @param destVdsList * @param vdsGroup * @return */ public boolean canRunVm(List<String> messages, StoragePool storagePool, List<Guid> vdsBlackList, List<Guid> vdsWhiteList, List<Guid> destVdsList, VDSGroup vdsGroup) { if (vm.getStatus() == VMStatus.Paused) { // if the VM is paused, we should only check the VDS status // as the rest of the checks were already checked before return validate(validateVdsStatus(vm), messages); } else if (vm.getStatus() == VMStatus.Suspended) { return validate(new VmValidator(vm).vmNotLocked(), messages) && validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId()), messages) && validate(validateVmStatusUsingMatrix(vm), messages) && validate(validateStoragePoolUp(vm, storagePool, getVmImageDisks()), messages) && validate(vmDuringInitialization(vm), messages) && validate(validateStorageDomains(vm, isInternalExecution, filterReadOnlyAndPreallocatedDisks(getVmImageDisks())), messages) && validate(validateImagesForRunVm(vm, getVmImageDisks()), messages) && getSchedulingManager().canSchedule( vdsGroup, vm, vdsBlackList, vdsWhiteList, destVdsList, messages); } return validateVmProperties(vm, runVmParam.getCustomProperties(), messages) && validate(validateBootSequence(vm, runVmParam.getBootSequence(), getVmDisks(), activeIsoDomainId), messages) && validate(validateDisplayType(), messages) && validate(new VmValidator(vm).vmNotLocked(), messages) && validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId()), messages) && validate(validateVmStatusUsingMatrix(vm), messages) && validate(validateStoragePoolUp(vm, storagePool, getVmImageDisks()), messages) && validate(validateIsoPath(vm, runVmParam.getDiskPath(), runVmParam.getFloppyPath(), activeIsoDomainId), messages) && validate(vmDuringInitialization(vm), messages) && validate(validateStatelessVm(vm, runVmParam.getRunAsStateless()), messages) && validate(validateFloppy(), messages) && validate(validateStorageDomains(vm, isInternalExecution, filterReadOnlyAndPreallocatedDisks(getVmImageDisks())), messages) && validate(validateImagesForRunVm(vm, getVmImageDisks()), messages) && validate(validateMemorySize(vm), messages) && getSchedulingManager().canSchedule( vdsGroup, vm, vdsBlackList, vdsWhiteList, destVdsList, messages); } private List<DiskImage> filterReadOnlyAndPreallocatedDisks(List<DiskImage> vmImageDisks) { List<DiskImage> retVal = new ArrayList<>(); for (DiskImage disk : vmImageDisks) { if (!(disk.getVolumeType() == VolumeType.Preallocated || disk.getReadOnly())) { retVal.add(disk); } } return retVal; } private SchedulingManager getSchedulingManager() { return Injector.get(SchedulingManager.class); } protected ValidationResult validateMemorySize(VM vm) { int maxSize; if (getOsRepository().get64bitOss().contains(vm.getOs())) { maxSize = Config.getValue(ConfigValues.VM64BitMaxMemorySizeInMB, vm.getVdsGroupCompatibilityVersion().getValue()); } else { maxSize = Config.getValue(ConfigValues.VM32BitMaxMemorySizeInMB); } if (vm.getMemSizeMb() > maxSize) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_MEMORY_EXCEEDS_SUPPORTED_LIMIT); } return ValidationResult.VALID; } public ValidationResult validateFloppy() { if (StringUtils.isNotEmpty(runVmParam.getFloppyPath()) && !VmValidationUtils.isFloppySupported(vm.getOs(), vm.getVdsGroupCompatibilityVersion())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_FLOPPY_IS_NOT_SUPPORTED_BY_OS); } return ValidationResult.VALID; } /** * @return true if all VM network interfaces are valid */ public ValidationResult validateNetworkInterfaces() { ValidationResult validationResult = validateInterfacesConfigured(vm); if (!validationResult.isValid()) { return validationResult; } validationResult = validateInterfacesAttachedToClusterNetworks(vm, getClusterNetworksNames(), getInterfaceNetworkNames()); if (!validationResult.isValid()) { return validationResult; } validationResult = validateInterfacesAttachedToVmNetworks(getClusterNetworks(), getInterfaceNetworkNames()); if (!validationResult.isValid()) { return validationResult; } return ValidationResult.VALID; } protected ValidationResult validateDisplayType() { if (!VmValidationUtils.isGraphicsAndDisplaySupported(vm.getOs(), vm.getVdsGroupCompatibilityVersion(), getVmActiveGraphics(), vm.getDefaultDisplayType())) { return new ValidationResult( EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_VM_DISPLAY_TYPE_IS_NOT_SUPPORTED_BY_OS); } return ValidationResult.VALID; } private Set<GraphicsType> getVmActiveGraphics() { if (vm.getGraphicsInfos() != null && !vm.getGraphicsInfos().isEmpty()) { // graphics overriden in runonce return vm.getGraphicsInfos().keySet(); } else { List<VmDevice> graphicDevices = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.GRAPHICS); Set<GraphicsType> graphicsTypes = new HashSet<>(); for (VmDevice graphicDevice : graphicDevices) { GraphicsType type = GraphicsType.fromString(graphicDevice.getDevice()); graphicsTypes.add(type); } return graphicsTypes; } } protected boolean validateVmProperties(VM vm, String runOnceCustomProperties, List<String> messages) { String customProperties = runOnceCustomProperties != null ? runOnceCustomProperties : vm.getCustomProperties(); return getVmPropertiesUtils().validateVmProperties( vm.getVdsGroupCompatibilityVersion(), customProperties, messages); } protected ValidationResult validateBootSequence(VM vm, BootSequence runOnceBootSequence, List<Disk> vmDisks, Guid activeIsoDomainId) { BootSequence bootSequence = runOnceBootSequence != null ? runOnceBootSequence : vm.getDefaultBootSequence(); // Block from running a VM with no HDD when its first boot device is // HD and no other boot devices are configured if (bootSequence == BootSequence.C && vmDisks.isEmpty()) { return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_DISK_WITHOUT_DISK); } // If CD appears as first and there is no ISO in storage // pool/ISO inactive - you cannot run this VM if (bootSequence == BootSequence.CD && activeIsoDomainId == null) { return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO); } // if there is network in the boot sequence, check that the // vm has network, otherwise the vm cannot be run in vdsm if (bootSequence == BootSequence.N && getVmNicDao().getAllForVm(vm.getId()).isEmpty()) { return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_NETWORK_WITHOUT_NETWORK); } return ValidationResult.VALID; } /** * Check storage domains. Storage domain status and disk space are checked only for non-HA VMs. * * @param vm * The VM to run * @param isInternalExecution * Command is internal? * @param vmImages * The VM's image disks * @return <code>true</code> if the VM can be run, <code>false</code> if not */ protected ValidationResult validateStorageDomains(VM vm, boolean isInternalExecution, List<DiskImage> vmImages) { if (vmImages.isEmpty()) { return ValidationResult.VALID; } if (!vm.isAutoStartup() || !isInternalExecution) { Set<Guid> storageDomainIds = ImagesHandler.getAllStorageIdsForImageIds(vmImages); MultipleStorageDomainsValidator storageDomainValidator = new MultipleStorageDomainsValidator(vm.getStoragePoolId(), storageDomainIds); ValidationResult result = storageDomainValidator.allDomainsExistAndActive(); if (!result.isValid()) { return result; } result = !vm.isAutoStartup() ? storageDomainValidator.allDomainsWithinThresholds() : ValidationResult.VALID; if (!result.isValid()) { return result; } } return ValidationResult.VALID; } /** * Check isValid only if VM is not HA VM */ protected ValidationResult validateImagesForRunVm(VM vm, List<DiskImage> vmDisks) { if (vmDisks.isEmpty()) { return ValidationResult.VALID; } return !vm.isAutoStartup() ? new DiskImagesValidator(vmDisks).diskImagesNotLocked() : ValidationResult.VALID; } protected ValidationResult validateIsoPath(VM vm, String diskPath, String floppyPath, Guid activeIsoDomainId) { if (vm.isAutoStartup()) { return ValidationResult.VALID; } if (StringUtils.isEmpty(vm.getIsoPath()) && StringUtils.isEmpty(diskPath) && StringUtils.isEmpty(floppyPath)) { return ValidationResult.VALID; } if (activeIsoDomainId == null) { return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO); } if (!StringUtils.isEmpty(diskPath) && !isRepoImageExists(diskPath, activeIsoDomainId, ImageFileType.ISO)) { return new ValidationResult(EngineMessage.ERROR_CANNOT_FIND_ISO_IMAGE_PATH); } if (!StringUtils.isEmpty(floppyPath) && !isRepoImageExists(floppyPath, activeIsoDomainId, ImageFileType.Floppy)) { return new ValidationResult(EngineMessage.ERROR_CANNOT_FIND_FLOPPY_IMAGE_PATH); } return ValidationResult.VALID; } protected ValidationResult vmDuringInitialization(VM vm) { if (vm.isRunning() || vm.getStatus() == VMStatus.NotResponding || isVmDuringInitiating(vm)) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_IS_RUNNING); } return ValidationResult.VALID; } protected ValidationResult validateVdsStatus(VM vm) { if (vm.getStatus() == VMStatus.Paused && vm.getRunOnVds() != null && getVdsDynamic(vm.getRunOnVds()).getStatus() != VDSStatus.Up) { return new ValidationResult( EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, EngineMessage.VAR__HOST_STATUS__UP.toString()); } return ValidationResult.VALID; } protected ValidationResult validateStatelessVm(VM vm, Boolean stateless) { // if the VM is not stateless, there is nothing to check if (stateless != null ? !stateless : !vm.isStateless()) { return ValidationResult.VALID; } ValidationResult previewValidation = getSnapshotValidator().vmNotInPreview(vm.getId()); if (!previewValidation.isValid()) { return previewValidation; } // if the VM itself is stateless or run once as stateless if (vm.isAutoStartup()) { return new ValidationResult(EngineMessage.VM_CANNOT_RUN_STATELESS_HA); } ValidationResult hasSpaceValidation = hasSpaceForSnapshots(); if (!hasSpaceValidation.isValid()) { return hasSpaceValidation; } return ValidationResult.VALID; } protected ValidationResult validateVmStatusUsingMatrix(VM vm) { if (!VdcActionUtils.canExecute(Arrays.asList(vm), VM.class, VdcActionType.RunVm)) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(vm.getStatus())); } return ValidationResult.VALID; } /** * check that we can create snapshots for all disks * return true if all storage domains have enough space to create snapshots for this VM plugged disks */ protected ValidationResult hasSpaceForSnapshots() { List<Disk> disks = DbFacade.getInstance().getDiskDao().getAllForVm(vm.getId()); List<DiskImage> allDisks = ImagesHandler.filterImageDisks(disks, false, true, false); Set<Guid> sdIds = ImagesHandler.getAllStorageIdsForImageIds(allDisks); MultipleStorageDomainsValidator msdValidator = getStorageDomainsValidator(sdIds); ValidationResult retVal = msdValidator.allDomainsWithinThresholds(); if (retVal == ValidationResult.VALID) { return msdValidator.allDomainsHaveSpaceForNewDisks(allDisks); } return retVal; } protected MultipleStorageDomainsValidator getStorageDomainsValidator(Collection<Guid> sdIds) { Guid spId = vm.getStoragePoolId(); return new MultipleStorageDomainsValidator(spId, sdIds); } protected ValidationResult validateStoragePoolUp(VM vm, StoragePool storagePool, List<DiskImage> vmImages) { if (vmImages.isEmpty() || vm.isAutoStartup()) { return ValidationResult.VALID; } return new StoragePoolValidator(storagePool).isUp(); } /** * Checking that the interfaces are all configured, interfaces with no network are allowed only if network linking * is supported. * * @return true if all VM network interfaces are attached to existing cluster networks, or to no network (when * network linking is supported). */ protected ValidationResult validateInterfacesConfigured(VM vm) { for (VmNetworkInterface nic : vm.getInterfaces()) { if (nic.getVnicProfileId() == null) { return FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ? ValidationResult.VALID: new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED); } } return ValidationResult.VALID; } /** * @param vm The VM to be run * @param clusterNetworkNames cluster logical networks names * @param interfaceNetworkNames VM interface network names * @return true if all VM network interfaces are attached to existing cluster networks */ protected ValidationResult validateInterfacesAttachedToClusterNetworks(VM vm, final Set<String> clusterNetworkNames, final Set<String> interfaceNetworkNames) { Set<String> result = new HashSet<>(interfaceNetworkNames); result.removeAll(clusterNetworkNames); if (FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion())) { result.remove(null); } // If after removing the cluster network names we still have objects, then we have interface on networks that // aren't attached to the cluster return result.isEmpty() ? ValidationResult.VALID : new ValidationResult( EngineMessage.ACTION_TYPE_FAILED_NETWORK_NOT_IN_CLUSTER, String.format("$networks %1$s", StringUtils.join(result, ","))); } /** * @param clusterNetworks * cluster logical networks * @param interfaceNetworkNames * VM interface network names * @return true if all VM network interfaces are attached to VM networks */ protected ValidationResult validateInterfacesAttachedToVmNetworks(final List<Network> clusterNetworks, Set<String> interfaceNetworkNames) { List<String> nonVmNetworkNames = NetworkUtils.filterNonVmNetworkNames(clusterNetworks, interfaceNetworkNames); return nonVmNetworkNames.isEmpty() ? ValidationResult.VALID : new ValidationResult( EngineMessage.ACTION_TYPE_FAILED_NOT_A_VM_NETWORK, String.format("$networks %1$s", StringUtils.join(nonVmNetworkNames, ","))); } /// Utility methods /// protected boolean validate(ValidationResult validationResult, List<String> message) { if (!validationResult.isValid()) { message.add(validationResult.getMessage().name()); for (String variableReplacement : validationResult.getVariableReplacements()) { message.add(variableReplacement); } } return validationResult.isValid(); } protected NetworkDao getNetworkDao() { return DbFacade.getInstance().getNetworkDao(); } protected VdsDynamicDao getVdsDynamicDao() { return DbFacade.getInstance().getVdsDynamicDao(); } protected BackendInternal getBackend() { return Backend.getInstance(); } protected VmNicDao getVmNicDao() { return DbFacade.getInstance().getVmNicDao(); } protected StorageDomainDao getStorageDomainDao() { return DbFacade.getInstance().getStorageDomainDao(); } protected VmPropertiesUtils getVmPropertiesUtils() { return VmPropertiesUtils.getInstance(); } protected DiskDao getDiskDao() { return DbFacade.getInstance().getDiskDao(); } private boolean isRepoImageExists(String repoImagePath, Guid storageDomainId, ImageFileType imageFileType) { VdcQueryReturnValue ret = getBackend().runInternalQuery( VdcQueryType.GetImagesList, new GetImagesListParameters(storageDomainId, imageFileType)); if (ret != null && ret.getReturnValue() != null && ret.getSucceeded()) { for (RepoImage isoFileMetaData : ret.<List<RepoImage>>getReturnValue()) { if (repoImagePath.equals(isoFileMetaData.getRepoImageId())) { return true; } } } return false; } protected boolean isVmDuringInitiating(VM vm) { return (Boolean) getBackend() .getResourceManager() .RunVdsCommand(VDSCommandType.IsVmDuringInitiating, new IsVmDuringInitiatingVDSCommandParameters(vm.getId())) .getReturnValue(); } protected SnapshotsValidator getSnapshotValidator() { return new SnapshotsValidator(); } private VdsDynamic getVdsDynamic(Guid vdsId) { return getVdsDynamicDao().get(vdsId); } private List<Disk> getVmDisks() { if (cachedVmDisks == null) { cachedVmDisks = getDiskDao().getAllForVm(vm.getId(), true); } return cachedVmDisks; } private List<DiskImage> getVmImageDisks() { if (cachedVmImageDisks == null) { cachedVmImageDisks = ImagesHandler.filterImageDisks(getVmDisks(), true, false, false); cachedVmImageDisks.addAll(ImagesHandler.filterDisksBasedOnCinder(getVmDisks(), true)); } return cachedVmImageDisks; } private Set<String> getInterfaceNetworkNames() { if (cachedInterfaceNetworkNames == null) { cachedInterfaceNetworkNames = Entities.vmInterfacesByNetworkName(vm.getInterfaces()).keySet(); } return cachedInterfaceNetworkNames; } private List<Network> getClusterNetworks() { if (cachedClusterNetworks == null) { cachedClusterNetworks = getNetworkDao().getAllForCluster(vm.getVdsGroupId()); } return cachedClusterNetworks; } private Set<String> getClusterNetworksNames() { if (cachedClusterNetworksNames == null) { cachedClusterNetworksNames = Entities.objectNames(getClusterNetworks()); } return cachedClusterNetworksNames; } public OsRepository getOsRepository() { return osRepository; } }
package org.bridgedb.bio; import java.util.regex.Pattern; import org.bridgedb.DataSource; import org.bridgedb.DataSourcePatterns; import org.bridgedb.DataSource.PrefixUrlMaker; import org.bridgedb.DataSource.UrlMaker; public class BioDataSource { public static final DataSource TAIR = DataSource.register ( "A", "TAIR", null, "http: "AT1G35255", true, false, Organism.ArabidopsisThaliana); public static final DataSource AGILENT = DataSource.register ( "Ag", "Agilent", null, null, "A_24_P98555", false, false, null); public static final DataSource BIOGRID = DataSource.register ( "Bg", "BioGrid", null, "http: null, false, false, null); public static final DataSource CINT = DataSource.register ( "C", "Cint", null, null, null, false, false, null); public static final DataSource CCDS = DataSource.register ( "Cc", "CCDS", new PrefixUrlMaker ("http: "CCDS43989", false, false, null); public static final DataSource CAS = DataSource.register ( "Ca", "CAS", new PrefixUrlMaker ("http://chem.sis.nlm.nih.gov/chemidplus/direct.jsp?regno="), null, null, true, true, null); public static final DataSource CHEBI = DataSource.register ( "Ce", "ChEBI", new PrefixUrlMaker ("http: null, null, true, true, null); public static final DataSource HMDB = DataSource.register ( "Ch", "HMDB", new PrefixUrlMaker ("http: "http: public static final DataSource KEGG_COMPOUND = DataSource.register ( "Ck", "Kegg Compound", new PrefixUrlMaker ("http: null, null, true, true, null); public static final DataSource PUBCHEM = DataSource.register ( "Cp", "PubChem", new PrefixUrlMaker ("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="), "http://pubchem.ncbi.nlm.nih.gov/", null, true, true, null); public static final DataSource CHEMSPIDER = DataSource.register ( "Cs", "Chemspider", new UrlMaker () { @Override public String getUrl(String id) { return "http: } }, "http: public static final DataSource SGD = DataSource.register ( "D", "SGD", new PrefixUrlMaker ("http://db.yeastgenome.org/cgi-bin/locus.pl?locus="), "http: public static final DataSource ENZYME_CODE = DataSource.register ( "E", "EC Number", new PrefixUrlMaker ("http: "http: , "2.7.1.71", true, false, null); public static final DataSource ECOLI = DataSource.register ( "Ec", "Ecoli", null, null, null, true, false, Organism.EscherichiaColi); public static final DataSource EMBL = DataSource.register ( "Em", "EMBL", new PrefixUrlMaker ("http: "http: /** @deprecated use one of the organism-specific system codes instead */ public static final DataSource ENSEMBL = DataSource.register ( "En", "Ensembl", new PrefixUrlMaker("http: "http: "ENSG00000139618", false, false, null); public static final DataSource ENSEMBL_MOSQUITO = DataSource.register ( "EnAg", "Ensembl Mosquito", new PrefixUrlMaker("http: "http: "AGAP006864", true, false, Organism.AnophelesGambiae); public static final DataSource GRAMENE_ARABIDOPSIS = DataSource.register ( "EnAt", "Gramene Arabidopsis", new PrefixUrlMaker("http: "http: "ATMG01360-TAIR-G", true, false, Organism.ArabidopsisThaliana); public static final DataSource ENSEMBL_BSUBTILIS = DataSource.register ( "EnBs", "Ensembl B. subtilis", new PrefixUrlMaker("http://bacteria.ensembl.org/Bacillus/B_subtilis/Gene/Summary?g="), "http: "EBBACG00000000013", true, false, Organism.BacillusSubtilis); public static final DataSource ENSEMBL_COW = DataSource.register ( "EnBt", "Ensembl Cow", new PrefixUrlMaker("http: "http: "ENSBTAG00000043548", true, false, Organism.BosTaurus); public static final DataSource ENSEMBL_CELEGANS = DataSource.register ( "EnCe", "Ensembl C. elegans", new PrefixUrlMaker("http: "http: "Y42H9B.1", true, false, Organism.CaenorhabditisElegans); public static final DataSource ENSEMBL_DOG = DataSource.register ( "EnCf", "Ensembl Dog", new PrefixUrlMaker("http: "http: "ENSCAFG00000025860", true, false, Organism.CanisFamiliaris); public static final DataSource ENSEMBL_FRUITFLY = DataSource.register ( "EnDm", "Ensembl Fruitfly", new PrefixUrlMaker("http: "http: "FBgn0032956", true, false, Organism.DrosophilaMelanogaster); public static final DataSource ENSEMBL_ZEBRAFISH = DataSource.register ( "EnDr", "Ensembl Zebrafish", new PrefixUrlMaker("http: "http: "ENSDARG00000024771", true, false, Organism.DanioRerio); public static final DataSource ENSEMBL_ECOLI = DataSource.register ( "EnEc", "Ensembl E. coli", new PrefixUrlMaker("http://bacteria.ensembl.org/Escherichia_Shigella/E_coli_K12/Gene/Summary?g="), "http: "EBESCG00000000010", true, false, Organism.EscherichiaColi); public static final DataSource ENSEMBL_CHICKEN = DataSource.register ( "EnGg", "Ensembl Chicken", new PrefixUrlMaker("http: "http: "ENSGALG00000021736", true, false, Organism.GallusGallus); public static final DataSource ENSEMBL_HUMAN = DataSource.register ( "EnHs", "Ensembl Human", new PrefixUrlMaker("http: "http: "ENSG00000139618", true, false, Organism.HomoSapiens); public static final DataSource ENSEMBL_MOUSE = DataSource.register ( "EnMm", "Ensembl Mouse", new PrefixUrlMaker("http: "http: "ENSMUSG00000017167", true, false, Organism.MusMusculus); public static final DataSource GRAMENE_RICE = DataSource.register ( "EnOj", "Gramene Rice", new PrefixUrlMaker("http: "http: "osa-MIR171a", true, false, Organism.OryzaSativa); public static final DataSource ENSEMBL_CHIMP = DataSource.register ( "EnPt", "Ensembl Chimp", new PrefixUrlMaker("http: "http: "ENSPTRG00000036034", true, false, Organism.PanTroglodytes); public static final DataSource ENSEMBL_HORSE = DataSource.register ( "EnQc", "Ensembl Horse", new PrefixUrlMaker("http: "http: "ENSECAG00000026160", true, false, Organism.EquusCaballus); public static final DataSource ENSEMBL_RAT = DataSource.register ( "EnRn", "Ensembl Rat", new PrefixUrlMaker("http: "http: "ENSRNOG00000016648", true, false, Organism.RattusNorvegicus); public static final DataSource ENSEMBL_SCEREVISIAE = DataSource.register ( "EnSc", "Ensembl Yeast", new PrefixUrlMaker("http: "http: "YGR147C", true, false, Organism.SaccharomycesCerevisiae); public static final DataSource ENSEMBL_XENOPUS = DataSource.register ( "EnXt", "Ensembl Xenopus", new PrefixUrlMaker("http: "http: "ENSXETG00000029448", true, false, Organism.XenopusTropicalis); public static final DataSource FLYBASE = DataSource.register ( "F", "FlyBase", new PrefixUrlMaker("http://flybase.bio.indiana.edu/.bin/fbidq.html?"), null, "FBgn0031208", true, false, Organism.DrosophilaMelanogaster); public static final DataSource GENBANK = DataSource.register ( "G", "GenBank", null, null, null, false, false, null); public static final DataSource CODELINK = DataSource.register ( "Ge", "CodeLink", null, null, "GE86325", false, false, null); public static final DataSource GRAMENE_GENES_DB = DataSource.register ( "Gg", "Gramene Genes DB", new PrefixUrlMaker ("http: "http: "GR:0060184", true, false, null); public static final DataSource GRAMENE_LITERATURE = DataSource.register ( "Gl", "Gramene Literature", new PrefixUrlMaker ("http: "http: "6200", false, false, null); public static final DataSource GRAMENE_PATHWAY = DataSource.register ( "Gp", "Gramene Pathway", null, "http: "PROTEIN-KINASE-RXN", false, false, null); public static final DataSource GEN_PEPT = DataSource.register ( "Gp", "GenPept", null, null, "AAH72400", false, false, null); public static final DataSource HUGO = DataSource.register ( "H", "HUGO", new PrefixUrlMaker ("http: "http: "25068", true, false, Organism.HomoSapiens); public static final DataSource HSGENE = DataSource.register ( "Hs", "HsGene", null, null, null, true, false, Organism.HomoSapiens); public static final DataSource INTERPRO = DataSource.register ( "I", "InterPro", new PrefixUrlMaker ("http: "http: public static final DataSource ILLUMINA = DataSource.register ( "Il", "Illumina", null, null, "ILMN_5668", false, false, null); public static final DataSource IPI = DataSource.register ( "Ip", "IPI", new UrlMaker () { @Override public String getUrl(String id) { return "http://srs.ebi.ac.uk/srsbin/cgi-bin/wgetz?-e+[IPI-acc:" + id + "]"; } }, null, "IPI00020529", false, false, null); public static final DataSource IRGSP_GENE = DataSource.register ( "Ir", "IRGSP Gene", null, "http://rgp.dna.affrc.go.jp/IRGSP/", "Os12g0561000", true, false, null); public static final DataSource ENTREZ_GENE = DataSource.register ( "L", "Entrez Gene", new PrefixUrlMaker ("http: "http: public static final DataSource MGI = DataSource.register ( "M", "MGI", new PrefixUrlMaker ("http: "http: "MGI:2687328", true, false, Organism.MusMusculus); public static final DataSource MIRBASE = DataSource.register ( "Mb", "miRBase", new PrefixUrlMaker ("http://microrna.sanger.ac.uk/cgi-bin/sequences/mirna_entry.pl?acc="), null, "MI0000808", true, false, null); public static final DataSource MAIZE_GDB = DataSource.register ( "Mg", "MaizeGDB", new PrefixUrlMaker ("http: null, "acc1", true, false, Organism.ZeaMays); public static final DataSource NASC_GENE = DataSource.register ( "N", "NASC Gene", null, null, "ATMG00960-TAIR-G", true, false, Organism.ArabidopsisThaliana); public static final DataSource NUGOWIKI = DataSource.register ( "Nw", "NuGO wiki", new PrefixUrlMaker ("http://nugowiki.org/index.php/"), null, "HMDB00001", false, true, null); public static final DataSource OTHER = DataSource.register ( "O", "Other", null, null, null, true, false, null); public static final DataSource ORYZA_BASE = DataSource.register ( "Ob", "Oryzabase", new PrefixUrlMaker ("http: "http: public static final DataSource OMIM = DataSource.register ( "Om", "OMIM", new PrefixUrlMaker ("http: "http: false, false, null); public static final DataSource RICE_ENSEMBL_GENE = DataSource.register ( "Os", "Rice Ensembl Gene", new PrefixUrlMaker ("http: "http: public static final DataSource PDB = DataSource.register ( "Pd", "PDB", new PrefixUrlMaker ("http://bip.weizmann.ac.il/oca-bin/ocashort?id="), "http: "2Z17", true, false, null); public static final DataSource PFAM = DataSource.register ( "Pf", "Pfam", new PrefixUrlMaker ("http: "http: null, true, false, null); public static final DataSource PLANTGDB = DataSource.register ( "Pl", "PlantGDB", null, "http: "PUT-157a-Vitis_vinifera-37378", true, false, null); public static final DataSource REFSEQ = DataSource.register ( "Q", "RefSeq", new UrlMaker() { private static final String PRE = "http: public String getUrl (String id) { if(id.startsWith("NM")) { return PRE + "db=Nucleotide&cmd=Search&term=" + id; } else { return PRE + "db=Protein&cmd=search&term=" + id; } } } , "http: public static final DataSource RGD = DataSource.register ( "R", "RGD", new PrefixUrlMaker ("http://rgd.mcw.edu/generalSearch/RgdSearch.jsp?quickSearch=1&searchKeyword="), "http://rgd.mcw.edu/", "1587276", true, false, Organism.RattusNorvegicus); public static final DataSource RFAM = DataSource.register ( "Rf", "Rfam", new PrefixUrlMaker ("http: "RF00066", true, false, null); public static final DataSource UNIPROT = DataSource.register ( "S", "Uniprot/TrEMBL", new PrefixUrlMaker ("http: "http: public static final DataSource SNP = DataSource.register ( "Sn", "dbSNP", null, null, null, true, false, null); public static final DataSource GENE_ONTOLOGY = DataSource.register ( "T", "GeneOntology", new PrefixUrlMaker ("http://godatabase.org/cgi-bin/go.cgi?view=details&search_constraint=terms&depth=0&query="), "http: public static final DataSource TIGR = DataSource.register ( "Ti", "J. Craig Venter Institute (formerly TIGR)", null, "http: public static final DataSource UNIGENE = DataSource.register ( "U", "UniGene", new PrefixUrlMaker ("http: "http: "Hs.553708", true, false, null); public static final DataSource UCSC = DataSource.register ( "Uc", "UCSC Genome Browser", new PrefixUrlMaker ("http://genome.ucsc.edu/cgi-bin/hgTracks?position="), "http://genome.ucsc.edu/", "uc001tyh.1", true, false, null); public static final DataSource WORMBASE = DataSource.register ( "W", "WormBase", new PrefixUrlMaker ("http: "http: true, false, Organism.CaenorhabditisElegans); public static final DataSource WIKIPEDIA = DataSource.register ( "Wi", "Wikipedia", new PrefixUrlMaker ("http: public static final DataSource WHEAT_GENE_CATALOG = DataSource.register ( "Wc", "Wheat gene catalog (Grain Genes)", new PrefixUrlMaker ("http://wheat.pw.usda.gov/sql?sql=select+distinct+genewgcreference.number+as+WGC,+reference.name+as+Reference,+reference.title+as+Title,+journal.name+as+Journal,+reference.volume+as+Volume,+reference.pages+as+Page+from+reference+inner+join+genewgcreference+on+genewgcreference.referenceid=reference.id+inner+join+journal+on+reference.journalid=journal.id+where+genewgcreference.number="), "http://wheat.pw.usda.gov/", "341", true, false, Organism.TriticumAestivum); public static final DataSource WHEAT_GENE_NAMES = DataSource.register ( "Wn", "Wheat gene names (Grain Genes)", new PrefixUrlMaker ("http://wheat.pw.usda.gov/report?class=gene;name="), "http://wheat.pw.usda.gov/", "5S-Rrna-D1_(Triticum)", true, false, Organism.TriticumAestivum); public static final DataSource WHEAT_GENE_REFERENCES= DataSource.register ( "Wr", "Wheat gene references (Grain Genes)", new PrefixUrlMaker ("http://wheat.pw.usda.gov/cgi-bin/graingenes/report.cgi?class=reference&name="), "http://wheat.pw.usda.gov/", "WGS-95-1333", false, false, Organism.TriticumAestivum); public static final DataSource AFFY = DataSource.register ( "X", "Affy", new PrefixUrlMaker ("http: "http: public static final DataSource ZFIN = DataSource.register ( "Z", "ZFIN", new PrefixUrlMaker ("http://zfin.org/cgi-bin/webdriver?MIval=aa-markerview.apg&OID="), "http://zfin.org", "ZDB-GENE-041118-11", true, false, Organism.DanioRerio); static { DataSourcePatterns.registerPattern( BioDataSource.SGD, Pattern.compile("S\\d{9}")); DataSourcePatterns.registerPattern( BioDataSource.FLYBASE, Pattern.compile("(C[RG]\\d{4,5}|FBgn\\d{7})") ); DataSourcePatterns.registerPattern( BioDataSource.GENBANK, Pattern.compile("(\\w\\d{5})|(\\w{2}\\d{6})|(\\w{3}\\d{5})") ); //interpro DataSourcePatterns.registerPattern( BioDataSource.INTERPRO, Pattern.compile("IPR\\d{6}") ); //entrez gene DataSourcePatterns.registerPattern( BioDataSource.ENTREZ_GENE, Pattern.compile("\\d+") ); //MGI DataSourcePatterns.registerPattern( BioDataSource.MGI, Pattern.compile("MGI:\\d+") ); DataSourcePatterns.registerPattern ( BioDataSource.RFAM, Pattern.compile ("RF\\d+") ); DataSourcePatterns.registerPattern ( BioDataSource.IPI, Pattern.compile ("IPI\\d+") ); DataSourcePatterns.registerPattern ( BioDataSource.UCSC, Pattern.compile ("uc\\d{3}[a-z]{3}\\.\\d") ); DataSourcePatterns.registerPattern ( BioDataSource.ILLUMINA, Pattern.compile ("ILMN_\\d+") ); DataSourcePatterns.registerPattern ( BioDataSource.MIRBASE, Pattern.compile ("MI\\d+") ); //refseq DataSourcePatterns.registerPattern( BioDataSource.REFSEQ, Pattern.compile("\\w{2}_\\d+") ); //RGD DataSourcePatterns.registerPattern( BioDataSource.RGD, Pattern.compile("RGD:\\d+") ); //Swiss Prot (http://expasy.org/sprot/userman.html#AC_line) DataSourcePatterns.registerPattern( BioDataSource.UNIPROT, Pattern.compile("([A-N,R-][0-9][A-Z][A-Z,0-9][A-Z,0-9][0-9])|([O,P,Q][0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][0-9])") ); //gene ontology DataSourcePatterns.registerPattern( BioDataSource.GENE_ONTOLOGY, Pattern.compile("GO:\\d+") ); //unigene DataSourcePatterns.registerPattern( BioDataSource.UNIGENE, Pattern.compile("[A-Z][a-z][a-z]?\\.\\d+") ); //Wormbase DataSourcePatterns.registerPattern( BioDataSource.WORMBASE, Pattern.compile("WBGene\\d{8}") ); //affymetrix DataSourcePatterns.registerPattern( BioDataSource.AFFY, Pattern.compile(".+_at") ); //Ensemble DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_HUMAN, Pattern.compile("ENSG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_MOUSE, Pattern.compile("ENSMUSG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_RAT, Pattern.compile("ENSRNOG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_MOSQUITO, Pattern.compile("AGAP\\d{6}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_BSUBTILIS, Pattern.compile("EBBACG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_ECOLI, Pattern.compile("EBESCG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_CHICKEN, Pattern.compile("ENSGALG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_HORSE, Pattern.compile("ENSECAG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_XENOPUS, Pattern.compile("ENSXETG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_CHIMP, Pattern.compile("ENSPTRG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_COW, Pattern.compile("ENSBTAG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_DOG, Pattern.compile("ENSCAFG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_ZEBRAFISH, Pattern.compile("ENSDARG\\d{11}") ); DataSourcePatterns.registerPattern( BioDataSource.ENSEMBL_FRUITFLY, Pattern.compile("FBgn\\d{7}") ); DataSourcePatterns.registerPattern( BioDataSource.TAIR, Pattern.compile("AT[\\dCM]G\\d{5}") ); DataSourcePatterns.registerPattern( BioDataSource.GRAMENE_ARABIDOPSIS, Pattern.compile("AT[\\dCM]G\\d{5}\\-TAIR\\-G") ); DataSourcePatterns.registerPattern( BioDataSource.IRGSP_GENE, Pattern.compile("Os\\d{2}g\\d+") ); DataSourcePatterns.registerPattern( BioDataSource.GRAMENE_GENES_DB, Pattern.compile("GR:\\d+") ); DataSourcePatterns.registerPattern( BioDataSource.BIOGRID, Pattern.compile("\\d+") ); DataSourcePatterns.registerPattern( BioDataSource.NASC_GENE, Pattern.compile("AT[\\dCM]G\\d{5}\\-TAIR\\-G") ); DataSourcePatterns.registerPattern( BioDataSource.PLANTGDB, Pattern.compile("PUT-[\\w\\d-]+") ); //EMBL DataSourcePatterns.registerPattern( BioDataSource.EMBL, Pattern.compile("\\w{2}\\d{6}") ); //HUGO DataSourcePatterns.registerPattern( BioDataSource.HUGO, Pattern.compile("\\d+") ); //OMIM (http://www.ncbi.nlm.nih.gov/Omim/omimfaq.html#numbering_system) DataSourcePatterns.registerPattern( BioDataSource.OMIM, Pattern.compile("\\d{6}(\\.\\d{4})?") ); //PDB ( http://www.rcsb.org/robohelp_f/#search_database/query_results.htm ) DataSourcePatterns.registerPattern( BioDataSource.PDB, Pattern.compile("\\d[A-Z\\d]{3}") ); DataSourcePatterns.registerPattern( BioDataSource.PFAM, Pattern.compile("(PF\\d{5})|(PB\\d{6})") ); DataSourcePatterns.registerPattern( BioDataSource.ZFIN, Pattern.compile("ZDB.+") ); DataSourcePatterns.registerPattern( BioDataSource.AGILENT, Pattern.compile("A_\\d+_.+") ); DataSourcePatterns.registerPattern( BioDataSource.HMDB, Pattern.compile("HMDB\\d{5}") ); DataSourcePatterns.registerPattern( BioDataSource.CAS, Pattern.compile("\\d+-\\d+-\\d+") ); DataSourcePatterns.registerPattern( BioDataSource.ENZYME_CODE, Pattern.compile("(\\d+\\.){3}\\d+") ); DataSourcePatterns.registerPattern( BioDataSource.CHEBI, Pattern.compile("CHEBI\\:\\d+") ); DataSourcePatterns.registerPattern( BioDataSource.KEGG_COMPOUND, Pattern.compile("C\\d+") ); } /** Call this to initialize the BioDataSource.XXX constants. * You should call this before using any of these constants, * or they may be undefined. */ // Currently this method is emtpy, but you should still call // it to make sure the static initializer is run. public static void init() {} }
package org.intermine.bio.dataconversion; import java.util.HashMap; import java.util.Map; import org.intermine.bio.io.gff3.GFF3Record; import org.intermine.metadata.Model; import org.intermine.xml.full.Item; public class TiffinGFF3RecordHandler extends GFF3RecordHandler { private Map<String, Item> motifs = new HashMap<String, Item>(); /** * Create a new TiffinGFF3RecordHandler for the given target model. * @param tgtModel the model for which items will be created */ public TiffinGFF3RecordHandler (Model tgtModel) { super(tgtModel); } /** * {@inheritDoc} */ @Override public void process(GFF3Record record) { Item bindingSite = getFeature(); String name = record.getNames().get(0); Item motif = getMotif(name); bindingSite.setReference("motif", motif); } private Item getMotif(String name) { Item motif = motifs.get(name); if (motif == null) { motif = createItem("Motif"); motif.setAttribute("primaryIdentifier", name); motif.setAttribute("curated", "false"); motifs.put(name, motif); addEarlyItem(motif); Item synonym = createItem("Synonym"); synonym.setAttribute("value", name); synonym.setAttribute("type", "identifier"); synonym.setAttribute("isPrimary", "true"); synonym.setReference("subject", motif); addItem(synonym); } return motif; } }
package io.jenkins.blueocean.service.embedded.rest; import hudson.model.Action; import hudson.model.FreeStyleBuild; import hudson.model.Run; import hudson.plugins.git.util.BuildData; import io.jenkins.blueocean.commons.ServiceException; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.BlueActionProxy; import io.jenkins.blueocean.rest.model.BluePipelineNodeContainer; import io.jenkins.blueocean.rest.model.BluePipelineStep; import io.jenkins.blueocean.rest.model.BlueRun; import io.jenkins.blueocean.rest.model.Container; import io.jenkins.blueocean.rest.model.Containers; import io.jenkins.blueocean.rest.model.GenericResource; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Basic {@link BlueRun} implementation. * * @author Vivek Pandey */ public class AbstractRunImpl<T extends Run> extends BlueRun { protected final T run; private final Link parent; public AbstractRunImpl(T run, Link parent) { this.run = run; this.parent = parent; } //TODO: It serializes jenkins Run model children, enable this code after fixing it // /** // * Allow properties reachable through {@link Run} to be exposed upon request (via the tree parameter). // */ // @Exported // public T getRun() { // return run; /** * Subtype should return */ public Container<?> getChangeSet() { return null; } @Override public String getOrganization() { return OrganizationImpl.INSTANCE.getName(); } @Override public String getId() { return run.getId(); } @Override public String getPipeline() { return run.getParent().getName(); } @Override public Date getStartTime() { return new Date(run.getStartTimeInMillis()); } @Override public Date getEnQueueTime() { return new Date(run.getTimeInMillis()); } @Override public BlueRunState getStateObj() { if(!run.hasntStartedYet() && run.isLogUpdated()) { return BlueRunState.RUNNING; } else if(!run.isLogUpdated()){ return BlueRunState.FINISHED; } else { return BlueRunState.QUEUED; } } @Override public BlueRunResult getResult() { return run.getResult() != null ? BlueRunResult.valueOf(run.getResult().toString()) : BlueRunResult.UNKNOWN; } @Override public Date getEndTime() { if (!run.isBuilding()) { return new Date(run.getStartTimeInMillis() + run.getDuration()); } return null; } @Override public Long getDurationInMillis() { return run.getDuration(); } @Override public Long getEstimatedDurtionInMillis() { return run.getEstimatedDuration(); } @Override public String getRunSummary() { return run.getBuildStatusSummary().message; } @Override public String getType() { return run.getClass().getSimpleName(); } @Override public Object getLog() { return new LogResource(run.getLogText()); } @Override public Container<BlueArtifact> getArtifacts() { Map<String, BlueArtifact> m = new HashMap<String, BlueArtifact>(); List<Run.Artifact> artifacts = run.getArtifacts(); for (final Run.Artifact artifact: artifacts) { m.put(artifact.getFileName(), new BlueArtifact() { @Override public String getName() { return artifact.getFileName(); } @Override public String getUrl() { return Stapler.getCurrentRequest().getContextPath() + "/" + run.getUrl()+"artifact/"+ artifact.getHref(); } @Override public long getSize() { try { return artifact.getFileSize(); } catch (NumberFormatException e) { return 0; } } @Override public Link getLink() { return new Link(getUrl()); } }); } return Containers.fromResourceMap(getLink(),m); } @Override public BluePipelineNodeContainer getNodes() { return null; // default } @Override public Container<?> getSteps() { return null; } public Collection<?> getActions() { List<BlueActionProxy> actionProxies = new ArrayList<>(); for(Action action:run.getAllActions()){ if(action == null || !action.getClass().isAnnotationPresent(ExportedBean.class)){ continue; } actionProxies.add(new ActionProxiesImpl(action, this)); } return actionProxies; } protected static BlueRun getBlueRun(Run r, Link parent){ //TODO: We need to take care several other job types if (r instanceof FreeStyleBuild) { return new FreeStyleRunImpl((FreeStyleBuild)r, parent); }else if(r instanceof WorkflowRun){ return new PipelineRunImpl((WorkflowRun)r, parent); }else{ return new AbstractRunImpl<>(r, parent); } } @Exported(name = "commitId") public String getCommitId(){ BuildData data = run.getAction(BuildData.class); if(data == null || data.getLastBuiltRevision() == null || data.getLastBuiltRevision().getSha1String() == null) { return null; } else { return data.getLastBuiltRevision().getSha1String(); } } @Override public BlueRunStopResponse stop() { throw new ServiceException.NotImplementedException("Stop should be implemented on a subclass"); } /** * Handles HTTP path handled by actions or other extensions * * @param token path token that an action or extension can handle * * @return action or extension that handles this path. */ public Object getDynamic(String token) { for (Action a : run.getAllActions()) { if (token.equals(a.getUrlName())) return new GenericResource<>(a); } return null; } @Override public Link getLink() { if(parent == null){ return OrganizationImpl.INSTANCE.getLink().rel(String.format("pipelines/%s/runs/%s", run.getParent().getName(), getId())); } return parent.rel("runs/"+getId()); } }
package com.dianping.cat.consumer.transaction; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Map; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.unidal.dal.jdbc.DalException; import org.unidal.dal.jdbc.DalNotFoundException; import org.unidal.lookup.annotation.Inject; import org.xml.sax.SAXException; import com.dianping.cat.Cat; import com.dianping.cat.config.content.ContentFetcher; import com.dianping.cat.consumer.transaction.config.entity.AllTransactionConfig; import com.dianping.cat.consumer.transaction.config.entity.Name; import com.dianping.cat.consumer.transaction.config.entity.Type; import com.dianping.cat.consumer.transaction.config.transform.DefaultSaxParser; import com.dianping.cat.core.config.Config; import com.dianping.cat.core.config.ConfigDao; import com.dianping.cat.core.config.ConfigEntity; public class AllTransactionConfigManager implements Initializable, LogEnabled { @Inject private ConfigDao m_configDao; @Inject private ContentFetcher m_fetcher; private int m_configId; private AllTransactionConfig m_config; private Logger m_logger; private long m_modifyTime; private static final String CONFIG_NAME = "all-transaction-config"; @Override public void enableLogging(Logger logger) { m_logger = logger; } public AllTransactionConfig getConfig() { return m_config; } @Override public void initialize() throws InitializationException { try { Config config = m_configDao.findByName(CONFIG_NAME, ConfigEntity.READSET_FULL); String content = config.getContent(); m_configId = config.getId(); m_config = DefaultSaxParser.parse(content); m_modifyTime = config.getModifyDate().getTime(); } catch (DalNotFoundException e) { try { String content = m_fetcher.getConfigContent(CONFIG_NAME); Config config = m_configDao.createLocal(); Date now = new Date(); config.setName(CONFIG_NAME); config.setContent(content); config.setModifyDate(now); m_configDao.insert(config); m_configId = config.getId(); m_config = DefaultSaxParser.parse(content); m_modifyTime = now.getTime(); } catch (Exception ex) { Cat.logError(ex); } } catch (Exception e) { Cat.logError(e); } if (m_config == null) { m_config = new AllTransactionConfig(); } } public boolean insert(String xml) { try { m_config = DefaultSaxParser.parse(xml); boolean result = storeConfig(); return result; } catch (Exception e) { Cat.logError(e); m_logger.error(e.getMessage(), e); return false; } } public void refreshConfig() throws DalException, SAXException, IOException { Config config = m_configDao.findByName(CONFIG_NAME, ConfigEntity.READSET_FULL); long modifyTime = config.getModifyDate().getTime(); synchronized (this) { if (modifyTime > m_modifyTime) { String content = config.getContent(); AllTransactionConfig blackList = DefaultSaxParser.parse(content); m_config = blackList; m_modifyTime = modifyTime; } } } private boolean storeConfig() { synchronized (this) { try { Config config = m_configDao.createLocal(); config.setId(m_configId); config.setKeyId(m_configId); config.setName(CONFIG_NAME); config.setContent(m_config.toString()); m_configDao.updateByPK(config, ConfigEntity.UPDATESET_FULL); } catch (Exception e) { Cat.logError(e); return false; } } return true; } public boolean validate(String type) { Map<String, Type> types = m_config.getTypes(); return types.containsKey(type) || types.containsKey("*"); } public boolean validate(String type, String name) { Map<String, Type> types = m_config.getTypes(); Type typeConfig = types.get(type); if (typeConfig != null) { List<Name> list = typeConfig.getNameList(); for (Name nameConfig : list) { String configId = nameConfig.getId(); if (configId.equals(name) || "*".equals(configId)) { return true; } } } return false; } }
package edu.kit.iks.Cryptographics.DiffieHellman.Demonstration; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import javax.swing.JLabel; import javax.swing.Timer; import edu.kit.iks.CryptographicsLib.VisualizationView; public class ExplainAimView extends VisualizationView { private JLabel aimExplain; private int x1, y1, x2, y2; private static final long serialVersionUID = 5986978581223106407L; public ExplainAimView() { super(); this.setLayout(new GridBagLayout()); this.setBackground(Color.WHITE); this.aimExplain = new JLabel(); this.aimExplain.setText("<html><div style=\"width:200px\">Our aim is to exchange a secret on a public channel, " + "without Eve getting the secret too. Therefore we can't simply send the secret, as shown" + "in the figure above as Eve would get the secret too. Thus we need" + "to exchange the secret in a different way</div></html>"); this.add(aimExplain); this.x1 = 460; this.y1 = 155; this.x2 = 600; this.y2 = 155; Timer timer = new Timer(50, new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if(x1 < 750) { x1 += 3; if (x1 > 600 && y2 > 63) { y2 -= 3; } } repaint(); } }); timer.start(); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawLine(450, 180, 800, 180); g2.drawLine(625, 60, 625, 180); g2.drawString("Alice", 400, 180); g2.drawString("Bob", 810, 180); g2.drawString("Eve", 610, 50); Ellipse2D.Double ellip = new Ellipse2D.Double(x1, y1, 50, 50); g2.setPaint(Color.BLUE); g2.fill(ellip); if(x1 > 600) { Ellipse2D.Double ellip2 = new Ellipse2D.Double(x2, y2, 50, 50); g2.fill(ellip2); } } }
/* * (e-mail:zhongxunking@163.com) */ /* * : * @author 2017-09-14 16:11 */ package org.antframework.configcenter.web.controller; import org.antframework.boot.bekit.AntBekitException; import org.antframework.common.util.facade.Status; import org.antframework.configcenter.facade.api.ConfigService; import org.antframework.configcenter.facade.order.FindAppOrder; import org.antframework.configcenter.facade.order.QueryPropertiesOrder; import org.antframework.configcenter.facade.result.FindAppResult; import org.antframework.configcenter.facade.result.QueryPropertiesResult; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * controller */ @RestController @RequestMapping("/config") public class ConfigController { @Autowired private ConfigService configService; /** * * * @param appCode * @param queriedAppCode * @param profileCode */ @RequestMapping("/queryProperties") public QueryPropertiesResult queryProperties(String appCode, String queriedAppCode, String profileCode) { FindAppResult findAppResult = configService.findApp(buildFindAppOrder(appCode)); if (!findAppResult.isSuccess() || findAppResult.getAppInfo() == null) { throw new AntBekitException(Status.FAIL, findAppResult.getCode(), findAppResult.getMessage()); } QueryPropertiesResult queryPropertiesResult = configService.queryProperties(buildQueryPropertiesOrder(queriedAppCode, profileCode, appCode)); return queryPropertiesResult; } // FindAppOrder private FindAppOrder buildFindAppOrder(String appCode) { FindAppOrder order = new FindAppOrder(); order.setAppCode(appCode); return order; } // QueryPropertiesOrder private QueryPropertiesOrder buildQueryPropertiesOrder(String queriedAppCode, String profileCode, String appCode) { QueryPropertiesOrder order = new QueryPropertiesOrder(); order.setAppCode(queriedAppCode); order.setProfileCode(profileCode); order.setOnlyOutward(!StringUtils.equals(queriedAppCode, appCode)); return order; } }
package com.jrestless.core.filter.cors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import javax.ws.rs.DELETE; import javax.ws.rs.HttpMethod; import javax.ws.rs.OPTIONS; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class CorsFilterIntTest extends JerseyTest { private static final String DEFAULT_ORIGIN = "http://example.com"; private static final String SAME_ORGIN = "http://localhost:9998"; @BeforeEach @Override // JerseyTest#setUp is annotated with @Before and as such not invoked by JUnit 5 => invoke public void setUp() throws Exception { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); super.setUp(); System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); } @AfterEach @Override // JerseyTest#tearDown is annotated with @After and as such not invoked by JUnit 5 => invoke public void tearDown() throws Exception { super.tearDown(); } @Override protected Application configure() { CorsFilter corsFilter = new CorsFilter.Builder() .allowMethod(HttpMethod.DELETE) .allowMethod(HttpMethod.OPTIONS) .allowHeader("ah0") .allowHeader("ah1") .allowOrigin(DEFAULT_ORIGIN) .allowOrigin("http://test.com") .exposeHeader("eh0") .exposeHeader("eh1") .build(); ResourceConfig application = new ResourceConfig(); application.register(corsFilter); application.register(TestResource.class); return application; } @Test public void testNoCorsRequest() { Response response = target() .path("delete") .request() .delete(); assertEquals(200, response.getStatus()); assertNoCorsHeaders(response.getHeaders()); } @Test public void testValidCorsPreflightRequest() { Response response = target() .path("delete") .request() .header(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE) .header(CorsHeaders.ORIGIN, DEFAULT_ORIGIN) .options(); assertEquals(200, response.getStatus()); MultivaluedMap<String, Object> headers = response.getHeaders(); assertEquals(DEFAULT_ORIGIN, headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals(HttpMethod.DELETE, headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS)); assertEquals("true", headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals("3600", headers.getFirst(CorsHeaders.ACCESS_CONTROL_MAX_AGE)); assertEquals(CorsHeaders.ORIGIN, headers.getFirst(HttpHeaders.VARY)); } @Test public void testInvalidCorsPreflightRequestByMethod() { Response response = target() .path("delete") .request() .header(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.GET) .header(CorsHeaders.ORIGIN, DEFAULT_ORIGIN) .options(); assertEquals(403, response.getStatus()); assertNoCorsHeaders(response.getHeaders()); } @Test public void testInvalidCorsPreflightRequestByOrigin() { Response response = target() .path("delete") .request() .header(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE) .header(CorsHeaders.ORIGIN, "http://bad.com") .options(); assertEquals(403, response.getStatus()); assertNoCorsHeaders(response.getHeaders()); } @Test public void testInvalidCorsPreflightRequestByHeader() { Response response = target() .path("delete") .request() .header(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE) .header(CorsHeaders.ORIGIN, DEFAULT_ORIGIN) .header(CorsHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "blub") .options(); assertEquals(403, response.getStatus()); assertNoCorsHeaders(response.getHeaders()); } @Test public void testActualCorsRequest() { Response response = target() .path("delete") .request() .header(CorsHeaders.ORIGIN, DEFAULT_ORIGIN) .delete(); assertEquals(200, response.getStatus()); assertEquals(DEFAULT_ORIGIN, response.getHeaderString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals("true", response.getHeaderString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals(CorsHeaders.ORIGIN, response.getHeaderString(HttpHeaders.VARY)); assertEquals("eh0,eh1", response.getHeaderString(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); } @Test public void testActualOptionsCorsRequest() { Response response = target() .path("options") .request() .header(CorsHeaders.ORIGIN, DEFAULT_ORIGIN) .options(); assertEquals(200, response.getStatus()); assertEquals(DEFAULT_ORIGIN, response.getHeaderString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals("true", response.getHeaderString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertEquals(CorsHeaders.ORIGIN, response.getHeaderString(HttpHeaders.VARY)); assertEquals("eh0,eh1", response.getHeaderString(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); assertNull(response.getHeaderString(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS)); assertNull(response.getHeaderString(CorsHeaders.ACCESS_CONTROL_MAX_AGE)); } @Test public void testSameOriginPreflight() { Response response = target() .path("delete") .request() .header(CorsHeaders.ORIGIN, SAME_ORGIN) .header(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE) .options(); assertEquals(200, response.getStatus()); assertNoCorsHeaders(response.getHeaders()); } @Test public void testSameOriginActual() { Response response = target() .path("delete") .request() .header(CorsHeaders.ORIGIN, SAME_ORGIN) .delete(); assertEquals(200, response.getStatus()); assertNoCorsHeaders(response.getHeaders()); } @Path("/") public static class TestResource { @Path("/delete") @DELETE public Response delete() { return Response.ok().build(); } @Path("/options") @OPTIONS public Response options() { return Response.ok().build(); } } private static void assertNoCorsHeaders(MultivaluedMap<String, Object> headers) { assertFalse(headers.keySet().stream().anyMatch(h -> !h.equals(HttpHeaders.CONTENT_LENGTH) && !h.equals(HttpHeaders.DATE) && !h.equals(HttpHeaders.CONTENT_TYPE) && !h.equals(HttpHeaders.ALLOW))); } }
package org.collectionspace.chain.csp.persistence.services; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.HashMap; import java.util.Map; import org.collectionspace.chain.csp.persistence.services.connection.ConnectionException; import org.collectionspace.chain.csp.persistence.services.connection.RequestMethod; import org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL; import org.collectionspace.csp.api.core.CSPDependencyException; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.dom4j.Document; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestDummyData extends ServicesBaseClass { private static final Logger log=LoggerFactory.getLogger(TestDummyData.class); @Before public void checkServicesRunning() throws ConnectionException { setup(); } @Test public void testDataCreation() { Storage ss; try { ss = makeServicesStorage(); //create objects/procedures/ String objectUrl = create("collectionobjects/", "collectionobjects_common", "dummydata-object1.xml","collection-object"); String acquisitionUrl = create("acquisitions/", "acquisitions_common", "dummydata-acquisition.xml","acquisition"); String intakeUrl = create("intakes/", "intakes_common", "dummydata-intake.xml","intake"); String loaninUrl = create("loansin/", "loansin_common", "dummydata-loanin.xml","loanin"); String loanoutUrl = create("loansout/", "loansout_common", "dummydata-loanout.xml","loanout"); String objectexitUrl = create("objectexit/", "objectexit_common", "dummydata-objectexit.xml","objectexit"); // String groupUrl = create("group/", "group_common", "dummydata-group.xml","group"); //make relationships relate2way(ss,objectUrl,acquisitionUrl); relate2way(ss,objectUrl,intakeUrl); relate2way(ss,objectUrl,loaninUrl); relate2way(ss,objectUrl,loanoutUrl); relate2way(ss,objectUrl,objectexitUrl); testRelations(ss,objectUrl,acquisitionUrl,"affects"); testRelations(ss,objectUrl,intakeUrl,"affects"); testRelations(ss,objectUrl,loaninUrl,"affects"); testRelations(ss,objectUrl,loanoutUrl,"affects"); testRelations(ss,objectUrl,objectexitUrl,"affects"); // testRelations(ss,objectUrl,groupUrl,"affects"); } catch (CSPDependencyException e) { fail(e.getMessage()); } catch (Exception e) { fail(e.getMessage()); } } private Boolean testRelations(Storage ss, String src, String dst, String type) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException{ JSONObject searchRestriction = new JSONObject(); searchRestriction.put("src",src); searchRestriction.put("dst",dst); searchRestriction.put("type","affects"); ///relations?sbj=f3b18013-154d-4e1d-ac5e&obj=c5a79acc-55c6-4046-8f4b JSONObject datalist = ss.getPathsJSON("relations/main",searchRestriction); String[] listitems = (String[])datalist.get("listItems"); assertEquals(listitems.length,1); return false; } private String relate2way(Storage ss,String obj1,String obj2) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException{ String path3=relate(ss,obj1,obj2); String path3a=relate(ss,obj2,obj1); assertNotNull("relate one way", path3); assertNotNull("relate second way", path3a); return path3; } private String relate(Storage ss,String obj1,String obj2) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { String[] path1=obj1.split("/"); String[] path2=obj2.split("/"); JSONObject data = createRelation(path2[1],path2[2],"affects",path1[1],path1[2],false); // create return ss.autocreateJSON("relations/main/",data); } private String createMini(String type,String id) throws JSONException { return type+"/"+id; } private JSONObject createRelation(String src_type,String src,String type,String dst_type,String dst,boolean one_way) throws JSONException { JSONObject out=new JSONObject(); out.put("src",createMini(src_type,src)); out.put("dst",createMini(dst_type,dst)); out.put("type",type); return out; } private String create(String serviceurl, String partname, String Createfilename, String mungeurl) throws Exception { ReturnedURL url; log.info("Testing " + serviceurl + " with " + Createfilename + " and partname=" + partname); // TODO add document parsing for PUT, and for POSTs that require uniqueness (to maintain self-contained tests that don't destroy existing data) // POST (Create) if(partname != null) { Map<String,Document> parts=new HashMap<String,Document>(); parts.put(partname,getDocument(Createfilename)); url=conn.getMultipartURL(RequestMethod.POST,serviceurl,parts,creds,cache); } else { url=conn.getURL(RequestMethod.POST,serviceurl,getDocument(Createfilename),creds,cache); } assertEquals(201,url.getStatus()); String[] path1=url.getURL().split("/"); return "/"+mungeurl+"/"+path1[2]; } }
package de.vogella.rcp.intro.dialogs.custom.dialogs; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class MyDialog extends TitleAreaDialog { private Text firstNameText; private Text lastNameText; private String firstName; private String lastName; public MyDialog(Shell parentShell) { super(parentShell); } @Override public void create() { super.create(); // Set the title setTitle("This is my first own dialog"); // Set the message setMessage("This is a TitleAreaDialog", IMessageProvider.INFORMATION); } @Override protected Control createDialogArea(Composite parent) { GridLayout layout = new GridLayout(); layout.numColumns = 2; // layout.horizontalAlignment = GridData.FILL; parent.setLayout(layout); // The text fields will grow with the size of the dialog GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = GridData.FILL; Label label1 = new Label(parent, SWT.NONE); label1.setText("First Name"); firstNameText = new Text(parent, SWT.BORDER); firstNameText.setLayoutData(gridData); Label label2 = new Label(parent, SWT.NONE); label2.setText("Last Name"); // You should not re-use GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = GridData.FILL; lastNameText = new Text(parent, SWT.BORDER); lastNameText.setLayoutData(gridData); return parent; } @Override protected void createButtonsForButtonBar(Composite parent) { GridData gridData = new GridData(); gridData.verticalAlignment = GridData.FILL; gridData.horizontalSpan = 3; gridData.grabExcessHorizontalSpace = true; gridData.grabExcessVerticalSpace = true; gridData.horizontalAlignment = SWT.CENTER; parent.setLayoutData(gridData); // Create Add button // Own method as we need to overview the SelectionAdapter createOkButton(parent, OK, "Add", true); // Add a SelectionListener // Create Cancel button Button cancelButton = createButton(parent, CANCEL, "Cancel", false); // Add a SelectionListener cancelButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setReturnCode(CANCEL); close(); } }); } protected Button createOkButton(Composite parent, int id, String label, boolean defaultButton) { // increment the number of columns in the button bar ((GridLayout) parent.getLayout()).numColumns++; Button button = new Button(parent, SWT.PUSH); button.setText(label); button.setFont(JFaceResources.getDialogFont()); button.setData(new Integer(id)); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (isValidInput()) { okPressed(); } } }); if (defaultButton) { Shell shell = parent.getShell(); if (shell != null) { shell.setDefaultButton(button); } } setButtonLayoutData(button); return button; } private boolean isValidInput() { boolean valid = true; if (firstNameText.getText().length() == 0) { setErrorMessage("Please maintain the first name"); valid = false; } if (lastNameText.getText().length() == 0) { setErrorMessage("Please maintain the last name"); valid = false; } return valid; } @Override protected boolean isResizable() { return true; } // We need to have the textFields into Strings because the UI gets disposed // and the Text Fields are not accessible any more. private void saveInput() { firstName = firstNameText.getText(); lastName = lastNameText.getText(); } @Override protected void okPressed() { saveInput(); super.okPressed(); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
package org.owasp.dependencycheck.analyzer; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Identifier; import org.owasp.dependencycheck.dependency.VulnerableSoftware; /** * This analyzer attempts to remove some well known false positives - * specifically regarding the java runtime. * * @author Jeremy Long (jeremy.long@owasp.org) */ public class FalsePositiveAnalyzer extends AbstractAnalyzer { //<editor-fold defaultstate="collapsed" desc="All standard implmentation details of Analyzer"> /** * The set of file extensions supported by this analyzer. */ private static final Set<String> EXTENSIONS = null; /** * The name of the analyzer. */ private static final String ANALYZER_NAME = "False Positive Analyzer"; /** * The phase that this analyzer is intended to run in. */ private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.POST_IDENTIFIER_ANALYSIS; /** * Returns a list of file EXTENSIONS supported by this analyzer. * * @return a list of file EXTENSIONS supported by this analyzer. */ public Set<String> getSupportedExtensions() { return EXTENSIONS; } /** * Returns the name of the analyzer. * * @return the name of the analyzer. */ public String getName() { return ANALYZER_NAME; } /** * Returns whether or not this analyzer can process the given extension. * * @param extension the file extension to test for support * @return whether or not the specified file extension is supported by this * analyzer. */ public boolean supportsExtension(String extension) { return true; } /** * Returns the phase that the analyzer is intended to run in. * * @return the phase that the analyzer is intended to run in. */ public AnalysisPhase getAnalysisPhase() { return ANALYSIS_PHASE; } //</editor-fold> /** * Analyzes the dependencies and removes bad/incorrect CPE associations * based on various heuristics. * * @param dependency the dependency to analyze. * @param engine the engine that is scanning the dependencies * @throws AnalysisException is thrown if there is an error reading the JAR * file. */ @Override public void analyze(Dependency dependency, Engine engine) throws AnalysisException { removeJreEntries(dependency); removeBadMatches(dependency); removeSpuriousCPE(dependency); addFalseNegativeCPEs(dependency); } /** * <p>Intended to remove spurious CPE entries. By spurious we mean * duplicate, less specific CPE entries.</p> * <p>Example:</p> * <code> * cpe:/a:some-vendor:some-product * cpe:/a:some-vendor:some-product:1.5 * cpe:/a:some-vendor:some-product:1.5.2 * </code> * <p>Should be trimmed to:</p> * <code> * cpe:/a:some-vendor:some-product:1.5.2 * </code> * * @param dependency the dependency being analyzed */ private void removeSpuriousCPE(Dependency dependency) { final List<Identifier> ids = new ArrayList<Identifier>(); ids.addAll(dependency.getIdentifiers()); Collections.sort(ids); final ListIterator<Identifier> mainItr = ids.listIterator(); while (mainItr.hasNext()) { final Identifier currentId = mainItr.next(); final VulnerableSoftware currentCpe = parseCpe(currentId.getType(), currentId.getValue()); if (currentCpe == null) { continue; } final ListIterator<Identifier> subItr = ids.listIterator(mainItr.nextIndex()); while (subItr.hasNext()) { final Identifier nextId = subItr.next(); final VulnerableSoftware nextCpe = parseCpe(nextId.getType(), nextId.getValue()); if (nextCpe == null) { continue; } //TODO fix the version problem below if (currentCpe.getVendor().equals(nextCpe.getVendor())) { if (currentCpe.getProduct().equals(nextCpe.getProduct())) { // see if one is contained in the other.. remove the contained one from dependency.getIdentifier final String currentVersion = currentCpe.getVersion(); final String nextVersion = nextCpe.getVersion(); if (currentVersion == null && nextVersion == null) { //how did we get here? Logger.getLogger(FalsePositiveAnalyzer.class .getName()).log(Level.FINE, "currentVersion and nextVersion are both null?"); } else if (currentVersion == null && nextVersion != null) { dependency.getIdentifiers().remove(currentId); } else if (nextVersion == null && currentVersion != null) { dependency.getIdentifiers().remove(nextId); } else if (currentVersion.length() < nextVersion.length()) { if (nextVersion.startsWith(currentVersion) || "-".equals(currentVersion)) { dependency.getIdentifiers().remove(currentId); } } else { if (currentVersion.startsWith(nextVersion) || "-".equals(nextVersion)) { dependency.getIdentifiers().remove(nextId); } } } } } } } /** * Regex to identify core java libraries and a few other commonly * misidentified ones. */ public static final Pattern CORE_JAVA = Pattern.compile("^cpe:/a:(sun|oracle|ibm):(j2[ems]e|" + "java(_platfrom_micro_edition|_runtime_environment|_se|virtual_machine|se_development_kit|fx)?|" + "jdk|jre|jsf|jsse)($|:.*)"); /** * Regex to identify core java library files. This is currently incomplete. */ public static final Pattern CORE_FILES = Pattern.compile("^((alt[-])?rt|jsf[-].*|jsse|jfxrt|jfr|jce|javaws|deploy|charsets)\\.jar$"); /** * Removes any CPE entries for the JDK/JRE unless the filename ends with * rt.jar * * @param dependency the dependency to remove JRE CPEs from */ private void removeJreEntries(Dependency dependency) { final Set<Identifier> identifiers = dependency.getIdentifiers(); final Iterator<Identifier> itr = identifiers.iterator(); while (itr.hasNext()) { final Identifier i = itr.next(); final Matcher coreCPE = CORE_JAVA.matcher(i.getValue()); final Matcher coreFiles = CORE_FILES.matcher(dependency.getFileName()); if (coreCPE.matches() && !coreFiles.matches()) { itr.remove(); } //replacecd with the regex above. // if (("cpe:/a:sun:java".equals(i.getValue()) // || "cpe:/a:oracle:java".equals(i.getValue()) // || "cpe:/a:ibm:java".equals(i.getValue()) // || "cpe:/a:sun:j2se".equals(i.getValue()) // || "cpe:/a:oracle:j2se".equals(i.getValue()) // || i.getValue().startsWith("cpe:/a:sun:java:") // || i.getValue().startsWith("cpe:/a:sun:j2se:") // || i.getValue().startsWith("cpe:/a:sun:java:jre") // || i.getValue().startsWith("cpe:/a:sun:java:jdk") // || i.getValue().startsWith("cpe:/a:sun:java_se") // || i.getValue().startsWith("cpe:/a:oracle:java_se") // || i.getValue().startsWith("cpe:/a:oracle:java:") // || i.getValue().startsWith("cpe:/a:oracle:j2se:") // || i.getValue().startsWith("cpe:/a:oracle:jre") // || i.getValue().startsWith("cpe:/a:oracle:jdk") // || i.getValue().startsWith("cpe:/a:ibm:java:")) // && !dependency.getFileName().toLowerCase().endsWith("rt.jar")) { // itr.remove(); } } /** * Parses a CPE string into an IndexEntry. * * @param type the type of identifier * @param value the cpe identifier to parse * @return an VulnerableSoftware object constructed from the identifier */ private VulnerableSoftware parseCpe(String type, String value) { if (!"cpe".equals(type)) { return null; } final VulnerableSoftware cpe = new VulnerableSoftware(); try { cpe.parseName(value); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FalsePositiveAnalyzer.class.getName()).log(Level.FINEST, null, ex); return null; } return cpe; } /** * Removes bad CPE matches for a dependency. Unfortunately, right now these * are hard-coded patches for specific problems identified when testing this * on a LARGE volume of jar files. * * @param dependency the dependency to analyze */ private void removeBadMatches(Dependency dependency) { final Set<Identifier> identifiers = dependency.getIdentifiers(); final Iterator<Identifier> itr = identifiers.iterator(); /* TODO - can we utilize the pom's groupid and artifactId to filter??? most of * these are due to low quality data. Other idea would be to say any CPE * found based on LOW confidence evidence should have a different CPE type? (this * might be a better solution then just removing the URL for "best-guess" matches). */ //Set<Evidence> groupId = dependency.getVendorEvidence().getEvidence("pom", "groupid"); //Set<Evidence> artifactId = dependency.getVendorEvidence().getEvidence("pom", "artifactid"); while (itr.hasNext()) { final Identifier i = itr.next(); //TODO move this startswith expression to a configuration file? if ("cpe".equals(i.getType())) { if ((i.getValue().matches(".*c\\+\\+.*") || i.getValue().startsWith("cpe:/a:jquery:jquery") || i.getValue().startsWith("cpe:/a:prototypejs:prototype") || i.getValue().startsWith("cpe:/a:yahoo:yui") || i.getValue().startsWith("cpe:/a:file:file") || i.getValue().startsWith("cpe:/a:mozilla:mozilla") || i.getValue().startsWith("cpe:/a:cvs:cvs") || i.getValue().startsWith("cpe:/a:ftp:ftp") || i.getValue().startsWith("cpe:/a:ssh:ssh")) && dependency.getFileName().toLowerCase().endsWith(".jar")) { itr.remove(); } else if (i.getValue().startsWith("cpe:/a:apache:maven") && !dependency.getFileName().toLowerCase().matches("maven-core-[\\d\\.]+\\.jar")) { itr.remove(); } } } } /** * There are some known CPE entries, specifically regarding sun and oracle * products due to the acquisition and changes in product names, that based * on given evidence we can add the related CPE entries to ensure a complete * list of CVE entries. * * @param dependency the dependency being analyzed */ private void addFalseNegativeCPEs(Dependency dependency) { final Iterator<Identifier> itr = dependency.getIdentifiers().iterator(); while (itr.hasNext()) { final Identifier i = itr.next(); if ("cpe".equals(i.getType()) && i.getValue() != null && (i.getValue().startsWith("cpe:/a:oracle:opensso:") || i.getValue().startsWith("cpe:/a:oracle:opensso_enterprise:") || i.getValue().startsWith("cpe:/a:sun:opensso_enterprise:") || i.getValue().startsWith("cpe:/a:sun:opensso:"))) { final String newCpe = String.format("cpe:/a:sun:opensso_enterprise:%s", i.getValue().substring(22)); final String newCpe2 = String.format("cpe:/a:oracle:opensso_enterprise:%s", i.getValue().substring(22)); final String newCpe3 = String.format("cpe:/a:sun:opensso:%s", i.getValue().substring(22)); final String newCpe4 = String.format("cpe:/a:oracle:opensso:%s", i.getValue().substring(22)); try { dependency.addIdentifier("cpe", newCpe, String.format("http://web.nvd.nist.gov/view/vuln/search?cpe=%s", URLEncoder.encode(newCpe, "UTF-8"))); dependency.addIdentifier("cpe", newCpe2, String.format("http://web.nvd.nist.gov/view/vuln/search?cpe=%s", URLEncoder.encode(newCpe2, "UTF-8"))); dependency.addIdentifier("cpe", newCpe3, String.format("http://web.nvd.nist.gov/view/vuln/search?cpe=%s", URLEncoder.encode(newCpe3, "UTF-8"))); dependency.addIdentifier("cpe", newCpe4, String.format("http://web.nvd.nist.gov/view/vuln/search?cpe=%s", URLEncoder.encode(newCpe4, "UTF-8"))); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FalsePositiveAnalyzer.class .getName()).log(Level.FINE, null, ex); } } } } }
package eu.earthobservatory.org.StrabonEndpoint.client; import org.openrdf.query.resultio.stSPARQLQueryResultFormat; /** * Every SPARQL endpoint that supports storing and querying of * spatial RDF data should extend the {@link SpatialEndpoint} * abstract class. * * @author Charalampos Nikolaou <charnik@di.uoa.gr> */ public abstract class SpatialEndpoint extends HTTPClient implements Endpoint<stSPARQLQueryResultFormat> { public SpatialEndpoint(String host, int port) { super(host, port); } public SpatialEndpoint(String host, int port, String endpointName) { super(host, port, endpointName); } }
package org.fcrepo.generator.dublincore; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.InputStream; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JcrPropertiesGeneratorTest { Session mockSession; Node mockNode; @Before public void setUp(){ mockSession = mock(Session.class); mockNode = mock(Node.class); try{ when(mockNode.getName()).thenReturn("id"); when(mockNode.getSession()).thenReturn(mockSession); } catch(RepositoryException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testGetStreamNoProperties() throws Exception { PropertyIterator mockIterator = mock(PropertyIterator.class); when(mockIterator.hasNext()).thenReturn(false); when(mockNode.getProperties(JcrPropertiesGenerator.SALIENT_DC_PROPERTY_NAMESPACES)).thenReturn(mockIterator); final InputStream inputStream = new JcrPropertiesGenerator().getStream(mockNode); final String actual = IOUtils.toString(inputStream); final String expected = "<oai_dc:dc xmlns:oai_dc=\"http: assertEquals(expected, actual); } @Test public void testGetStreamSingleValuedProperties() throws Exception { // Modeshape PropertyIterator is private to modeshape. // Too lazy to build out our own implementation for testing, so here's // a bunch of mocks PropertyIterator mockIterator = mock(PropertyIterator.class); when(mockIterator.hasNext()).thenReturn(true, true, false); Property mockProperty1 = mock(Property.class); when(mockProperty1.isMultiple()).thenReturn(false); when(mockProperty1.getName()).thenReturn("dc:title"); Value mockValue1 = mock(Value.class); when(mockValue1.getString()).thenReturn("title"); when(mockProperty1.getValue()).thenReturn(mockValue1); Property mockProperty2 = mock(Property.class); when(mockProperty2.getName()).thenReturn("dc:identifier"); Value mockValue2 = mock(Value.class); when(mockValue2.getString()).thenReturn("identifier"); when(mockProperty2.getValue()).thenReturn(mockValue2); when(mockIterator.nextProperty()).thenReturn(mockProperty1, mockProperty2); when(mockNode.getProperties(JcrPropertiesGenerator.SALIENT_DC_PROPERTY_NAMESPACES)).thenReturn(mockIterator); final InputStream inputStream = new JcrPropertiesGenerator().getStream(mockNode); final String actual = IOUtils.toString(inputStream); final String expected = "<oai_dc:dc xmlns:oai_dc=\"http: "\t<dc:title>title</dc:title>\n" + "\t<dc:identifier>identifier</dc:identifier>\n" + "</oai_dc:dc>"; assertEquals(expected, actual); } @Test public void testGetStreamMultivaluedProperties() throws Exception { // Modeshape PropertyIterator is private to modeshape. // Too lazy to build out our own implementation for testing, so here's // a bunch of mocks PropertyIterator mockIterator = mock(PropertyIterator.class); when(mockIterator.hasNext()).thenReturn(true, false); Property mockProperty1 = mock(Property.class); when(mockProperty1.isMultiple()).thenReturn(true); when(mockProperty1.getName()).thenReturn("dc:title"); Value mockValue1 = mock(Value.class); when(mockValue1.getString()).thenReturn("title"); Value mockValue2 = mock(Value.class); when(mockValue2.getString()).thenReturn("title2"); Value[] values = new Value[] { mockValue1, mockValue2 }; when(mockProperty1.getValues()).thenReturn(values); when(mockIterator.nextProperty()).thenReturn(mockProperty1); when(mockNode.getProperties(JcrPropertiesGenerator.SALIENT_DC_PROPERTY_NAMESPACES)).thenReturn(mockIterator); final InputStream inputStream = new JcrPropertiesGenerator().getStream(mockNode); final String actual = IOUtils.toString(inputStream); final String expected = "<oai_dc:dc xmlns:oai_dc=\"http: "\t<dc:title>title</dc:title>\n" + "\t<dc:title>title2</dc:title>\n" + "</oai_dc:dc>"; assertEquals(expected, actual); } }
package ch.sourcepond.io.fileobserver.impl.directory; import ch.sourcepond.io.fileobserver.api.FileKey; import ch.sourcepond.io.fileobserver.api.FileObserver; import ch.sourcepond.io.fileobserver.impl.observer.CompoundObserverHandler; import ch.sourcepond.io.fileobserver.impl.registrar.Registrar; import ch.sourcepond.io.fileobserver.impl.registrar.RegistrarFactory; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Path; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.spi.FileSystemProvider; import java.util.List; import static ch.sourcepond.io.fileobserver.impl.TestKey.TEST_KEY; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class DirectoriesTest { private final FsDirectoriesFactory fsDirectoriesFactory = mock(FsDirectoriesFactory.class); private final FsDirectories fsDirectories = mock(FsDirectories.class); private final FsDirectory fsDirectory = mock(FsDirectory.class); private final FileObserver observer = mock(FileObserver.class); private final WatchService watchService = mock(WatchService.class); private final FileSystem fs = mock(FileSystem.class); private final Path rootDirectory = mock(Path.class); private final BasicFileAttributes rootDirectoryAttrs = mock(BasicFileAttributes.class); private final BasicFileAttributes attrs = mock(BasicFileAttributes.class); private final Path testPath = mock(Path.class); private final FileSystemProvider provider = mock(FileSystemProvider.class); private final FileKey fileKey = mock(FileKey.class); private final RegistrarFactory registrarFactory = mock(RegistrarFactory.class); private final Registrar registrar = mock(Registrar.class); private final CompoundObserverHandler compoundObserverHandler = mock(CompoundObserverHandler.class); private final List<FsDirectories> roots = mock(List.class); private Directories directories = new Directories(registrarFactory, compoundObserverHandler, fsDirectoriesFactory, roots); @Before public void setup() throws IOException { when(rootDirectory.getFileSystem()).thenReturn(fs); when(testPath.getFileSystem()).thenReturn(fs); when(fs.newWatchService()).thenReturn(watchService); when(fsDirectoriesFactory.newDirectories(registrar)).thenReturn(fsDirectories); when(fs.provider()).thenReturn(provider); when(provider.readAttributes(rootDirectory, BasicFileAttributes.class)).thenReturn(rootDirectoryAttrs); when(rootDirectoryAttrs.isDirectory()).thenReturn(true); when(provider.readAttributes(testPath, BasicFileAttributes.class)).thenReturn(attrs); when(registrarFactory.newRegistrar(fs)).thenReturn(registrar); when(fsDirectory.newKey(testPath)).thenReturn(fileKey); directories.addRoot(TEST_KEY, rootDirectory); } @Test public void addRoot() throws IOException { verify(fsDirectories).rootAdded(TEST_KEY, rootDirectory, compoundObserverHandler); } @Test public void addRootIOExceptionOccurred() throws IOException { directories = new Directories(registrarFactory, compoundObserverHandler, fsDirectoriesFactory, roots); final IOException expected = new IOException(); doThrow(expected).when(registrarFactory).newRegistrar(fs); try { directories.addRoot(TEST_KEY, rootDirectory); fail("Exception expected"); } catch (final IOException e) { assertSame(expected, e.getCause().getCause()); } } @Test public void removeRoot() throws IOException { when(fsDirectories.directoryDeleted(rootDirectory)).thenReturn(true); directories.removeRoot(rootDirectory); directories.addRoot(TEST_KEY,rootDirectory); verify(registrarFactory, times(2)).newRegistrar(fs); } @Test public void addObserver() { when(fsDirectories.getDirectory(testPath)).thenReturn(fsDirectory); directories.addObserver(observer); // verify(compoundObserverHandler).putIfAbsent(observer, ); } @Test public void removeObserver() { directories.removeObserver(observer); verify(compoundObserverHandler).remove(observer); } @Test public void pathCreatedPathIsADirectory() throws Exception { when(attrs.isDirectory()).thenReturn(true); directories.addObserver(observer); directories.pathModified(testPath); verify(fsDirectories).directoryCreated(testPath, compoundObserverHandler); } @Test public void pathDeleted() throws Exception { when(fsDirectories.getDirectory(testPath)).thenReturn(fsDirectory); when(fsDirectories.directoryDeleted(testPath)).thenReturn(true); directories.addObserver(observer); directories.pathDeleted(testPath); verify(compoundObserverHandler).deleted(fileKey); // Root should still be the same directories.addRoot(TEST_KEY, rootDirectory); // Should have been called twice verify(registrarFactory, times(2)).newRegistrar(fs); } @Test public void close() throws Exception { directories.close(); verify(fsDirectories).close(); directories.addRoot(TEST_KEY, rootDirectory); // Should have been called twice verify(registrarFactory, times(2)).newRegistrar(fs); } @Test public void closeFsDirectoriesIsNull() throws Exception { // Should not cause an exception directories.close(null); directories.addRoot(TEST_KEY, rootDirectory); // Should have been called exactly once verify(registrarFactory).newRegistrar(fs); } @Test public void closeFsDirectories() throws Exception { directories.close(fsDirectories); verify(fsDirectories).close(); verify(roots).remove(fsDirectories); directories.addRoot(TEST_KEY, rootDirectory); // Should have been called twice verify(registrarFactory, times(2)).newRegistrar(fs); } @Test(expected = IllegalStateException.class) public void noAppropriateRootDirFound() { when(fsDirectories.directoryDeleted(rootDirectory)).thenReturn(true); directories.removeRoot(rootDirectory); directories.pathModified(rootDirectory); } @Test public void fileModified() { when(fsDirectories.getDirectory(testPath)).thenReturn(fsDirectory); directories.pathModified(testPath); verify(fsDirectory).informIfChanged(compoundObserverHandler, testPath); } }
package org.fedorahosted.flies.maven; import java.io.File; import java.net.URL; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.fedorahosted.flies.client.commands.ConfigurableCommand; import com.pyx4j.log4j.MavenLogAppender; /** * Base class for Flies mojos which support configuration by the user's * flies.ini * * @author Sean Flanigan <sflaniga@redhat.com> * */ public abstract class ConfigurableMojo<C extends ConfigurableCommand> extends AbstractMojo { private final C command; // @formatter:off // @formatter:on /** * Client configuration file for Flies. * * @parameter expression="${flies.client.config}" * default-value="${user.home}/.config/flies.ini" */ /* * NB the annotation 'default-value' overrides ConfigurableCommand (even * though the values are virtually identical) because Mojos aren't meant to * use System properties directly (since they may be sharing a VM and its * System properties) */ @SuppressWarnings("unused") private File userConfig; /** * Base URL for the Flies server. Defaults to the value in flies.xml (if * present), or else to flies.ini. * * @parameter expression="${flies.url}" */ @SuppressWarnings("unused") private URL url; /** * Username for accessing the Flies REST API. Defaults to the value in * flies.ini. * * @parameter expression="${flies.username}" */ @SuppressWarnings("unused") private String username; /** * API key for accessing the Flies REST API. Defaults to the value in * flies.ini. * * @parameter expression="${flies.key}" */ @SuppressWarnings("unused") private String key; /** * Whether to enable debug mode. Defaults to the value in flies.ini. * * @parameter expression="${flies.debug}" */ @SuppressWarnings("unused") private boolean debug; /** * Whether to display full information about errors (ie exception stack * traces). Defaults to the value in flies.ini. * * @parameter expression="${flies.errors}" */ @SuppressWarnings("unused") private boolean errors; public ConfigurableMojo(C command) { this.command = command; } @Override public void execute() throws MojoExecutionException, MojoFailureException { // @formatter:off // @formatter:on MavenLogAppender.startPluginLog(this); try { getCommand().initConfig(); getCommand().run(); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("error loading Flies user config", e); } finally { MavenLogAppender.endPluginLog(this); } } public C getCommand() { return command; } public void setDebug(boolean debug) { command.setDebug(debug); } public void setErrors(boolean errors) { command.setErrors(errors); } public void setKey(String key) { command.setKey(key); } public void setUrl(URL url) { command.setUrl(url); } public void setUserConfig(File userConfig) { command.setUserConfig(userConfig); } public void setUsername(String username) { command.setUsername(username); } }
package org.eclipse.hawkbit.ui.distributions.event; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; /** * Class which contains the Event when selecting all entries of a table */ public class SoftwareModuleTableEvent extends BaseEntityEvent<SoftwareModule> { /** * SoftwareModule table components events. * */ public enum SoftwareModuleComponentEvent { SELECT_ALL } private SoftwareModuleComponentEvent softwareModuleComponentEvent; /** * Constructor. * * @param eventType * the event type. * @param entity * the entity */ public SoftwareModuleTableEvent(final BaseEntityEventType eventType, final SoftwareModule entity) { super(eventType, entity); } /** * The component event. * * @param softwareModuleComponentEvent * the softwareModule component event. */ public SoftwareModuleTableEvent(final SoftwareModuleComponentEvent softwareModuleComponentEvent) { super(null, null); this.softwareModuleComponentEvent = softwareModuleComponentEvent; } public SoftwareModuleComponentEvent getSoftwareModuleComponentEvent() { return softwareModuleComponentEvent; } }
package com.ctrip.hermes.metaserver.consumer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.unidal.tuple.Pair; import com.alibaba.fastjson.TypeReference; import com.ctrip.hermes.core.bo.Tpg; import com.ctrip.hermes.core.lease.Lease; import com.ctrip.hermes.core.lease.LeaseAcquireResponse; import com.ctrip.hermes.core.service.SystemClockService; import com.ctrip.hermes.metaserver.ZKSuppportTestCase; import com.ctrip.hermes.metaserver.commons.ClientLeaseInfo; import com.ctrip.hermes.metaserver.commons.LeaseOperationCallback; import com.ctrip.hermes.metaservice.service.ZookeeperService; import com.ctrip.hermes.metaservice.zk.ZKClient; import com.ctrip.hermes.metaservice.zk.ZKPathUtils; import com.ctrip.hermes.metaservice.zk.ZKSerializeUtils; /** * @author Leo Liang(jhliang@ctrip.com) * */ @RunWith(MockitoJUnitRunner.class) public class ConsumerLeaseHolderTest extends ZKSuppportTestCase { private ConsumerLeaseHolder m_leaseHolder; public static class TestConsumerLeaaseHolder extends ConsumerLeaseHolder { @Override protected void startHouseKeeper() { } } private void addLeasesToZk(Tpg tpg, List<Pair<String, ClientLeaseInfo>> data) throws Exception { String path = ZKPathUtils.getConsumerLeaseZkPath(tpg.getTopic(), tpg.getPartition(), tpg.getGroupId()); String parentPath = ZKPathUtils.getConsumerLeaseTopicParentZkPath(tpg.getTopic()); byte[] bytes = null; if (data != null && !data.isEmpty()) { Map<String, ClientLeaseInfo> leases = new HashMap<>(); for (Pair<String, ClientLeaseInfo> pair : data) { leases.put(pair.getKey(), pair.getValue()); } bytes = ZKSerializeUtils.serialize(leases); } else { bytes = new byte[0]; } ensurePath(parentPath); ensurePath(parentPath + "/" + tpg.getPartition()); ensurePath(path); m_curator.setData().forPath(path, bytes); m_curator.setData().forPath(parentPath, ZKSerializeUtils.serialize(System.currentTimeMillis())); } private void assertLeases(Map<Tpg, Map<String, ClientLeaseInfo>> allValidLeases, Tpg tpg, List<Pair<String, ClientLeaseInfo>> expectedLeaseInfos) { Map<String, ClientLeaseInfo> actualLeaseInfos = allValidLeases.get(tpg); assertEquals(expectedLeaseInfos.size(), actualLeaseInfos.size()); for (Pair<String, ClientLeaseInfo> expectedLeaseInfo : expectedLeaseInfos) { ClientLeaseInfo actualClientLeaseInfo = actualLeaseInfos.get(expectedLeaseInfo.getKey()); ClientLeaseInfo expectedClientLeaseInfo = expectedLeaseInfo.getValue(); assertEquals(expectedClientLeaseInfo.getIp(), actualClientLeaseInfo.getIp()); assertEquals(expectedClientLeaseInfo.getPort(), actualClientLeaseInfo.getPort()); Lease actualLease = actualClientLeaseInfo.getLease(); Lease expectedLease = expectedClientLeaseInfo.getLease(); assertEquals(expectedLease.getId(), actualLease.getId()); assertEquals(expectedLease.getExpireTime(), actualLease.getExpireTime()); } } private void configureConsumerLeaseHolder() throws Exception { defineComponent(ConsumerLeaseHolder.class, TestConsumerLeaaseHolder.class) .req(ZKClient.class) .req(ZookeeperService.class) .req(SystemClockService.class); m_leaseHolder = lookup(ConsumerLeaseHolder.class); } @Override protected void initZkData() throws Exception { ensurePath(ZKPathUtils.getConsumerLeaseRootZkPath()); } private void leaseHolderReload() throws Exception { m_leaseHolder.updateContexts(m_leaseHolder.loadExistingLeases()); } @Override protected void doSetUp() throws Exception { configureConsumerLeaseHolder(); } @Test public void testExecuteLeaseOperation() throws Exception { final long fakeNowTimestamp = System.currentTimeMillis() + 500 * 1000L; final Tpg tpg = new Tpg("t1", 0, "g1"); addLeasesToZk(tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 500), "0.0.0.0", 1234)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, 30), "0.0.0.1", 1233)) )); leaseHolderReload(); m_leaseHolder.executeLeaseOperation(tpg, new LeaseOperationCallback() { @Override public LeaseAcquireResponse execute(Map<String, ClientLeaseInfo> existingValidLeases) throws Exception { assertEquals(1, existingValidLeases.size()); ClientLeaseInfo c0ClientLeaseInfo = existingValidLeases.get("c0"); ClientLeaseInfo c1ClientLeaseInfo = existingValidLeases.get("c1"); assertNotNull(c0ClientLeaseInfo); assertNull(c1ClientLeaseInfo); Map<Tpg, Map<String, ClientLeaseInfo>> leases = new HashMap<>(); leases.put(tpg, existingValidLeases); assertLeases( leases, tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 500), "0.0.0.0", 1234)))); return null; } }); } @Test public void testInit() throws Exception { long fakeNowTimestamp = System.currentTimeMillis() + 500 * 1000L; Tpg t1p0g1 = new Tpg("t1", 0, "g1"); Tpg t1p0g2 = new Tpg("t1", 0, "g2"); Tpg t1p1g1 = new Tpg("t1", 1, "g1"); Tpg t1p2g1 = new Tpg("t1", 2, "g1"); Tpg t2p0g1 = new Tpg("t2", 0, "g1"); Tpg t3p0g1 = new Tpg("t3", 0, "g1"); addLeasesToZk(t1p0g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 50), "0.0.0.0", 1234)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, fakeNowTimestamp + 30), "0.0.0.1", 1233)) )); addLeasesToZk(t1p0g2, Arrays.asList( new Pair<String, ClientLeaseInfo>("c2", new ClientLeaseInfo(new Lease(3, fakeNowTimestamp + 150), "0.0.0.2", 2222)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, fakeNowTimestamp + 30), "0.0.0.1", 1233)) )); addLeasesToZk( t1p1g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c2", new ClientLeaseInfo(new Lease(3, fakeNowTimestamp + 150), "0.0.0.2", 2222)) )); addLeasesToZk(t1p2g1, null); addLeasesToZk( t2p0g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 50), "0.0.0.0", 1234)) )); addLeasesToZk(t3p0g1, null); leaseHolderReload(); Map<Tpg, Map<String, ClientLeaseInfo>> allValidLeases = m_leaseHolder.getAllValidLeases(); assertEquals(4, allValidLeases.size()); assertLeases(allValidLeases, t1p0g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 50), "0.0.0.0", 1234)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, fakeNowTimestamp + 30), "0.0.0.1", 1233)) )); assertLeases(allValidLeases, t1p0g2, Arrays.asList( new Pair<String, ClientLeaseInfo>("c2", new ClientLeaseInfo(new Lease(3, fakeNowTimestamp + 150), "0.0.0.2", 2222)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, fakeNowTimestamp + 30), "0.0.0.1", 1233)) )); assertLeases( allValidLeases, t1p1g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c2", new ClientLeaseInfo(new Lease(3, fakeNowTimestamp + 150), "0.0.0.2", 2222)) )); assertLeases( allValidLeases, t2p0g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 50), "0.0.0.0", 1234)) )); assertTrue(m_leaseHolder.topicWatched("t1")); assertTrue(m_leaseHolder.topicWatched("t2")); assertTrue(m_leaseHolder.topicWatched("t3")); assertFalse(m_leaseHolder.topicWatched("t4")); } @Test public void testInitWithoutData() throws Exception { assertTrue(m_leaseHolder.getAllValidLeases().isEmpty()); } @Test public void testLeaseAddedInZk() throws Exception { leaseHolderReload(); long fakeNowTimestamp = System.currentTimeMillis(); Tpg tpg = new Tpg("t1", 0, "g1"); String consumerName = "c0"; String ip = "0.0.0.1"; int port = 1234; long expireTime = fakeNowTimestamp + 50000L; addLeasesToZk(tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>(consumerName, new ClientLeaseInfo(new Lease(1, expireTime), ip, port)) )); Map<Tpg, Map<String, ClientLeaseInfo>> allValidLeases = m_leaseHolder.getAllValidLeases(); int retries = 50; int i = 0; while (i++ < retries && allValidLeases.isEmpty()) { TimeUnit.MILLISECONDS.sleep(100); allValidLeases = m_leaseHolder.getAllValidLeases(); } assertEquals(1, allValidLeases.size()); assertTrue(m_leaseHolder.topicWatched(tpg.getTopic())); assertLeases(allValidLeases, tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>(consumerName, new ClientLeaseInfo(new Lease(1, expireTime), ip, port)))); } @Test public void testLeaseChangedInZk() throws Exception { long fakeNowTimestamp = System.currentTimeMillis(); Tpg tpg = new Tpg("t1", 0, "g1"); String consumerName = "c0"; String ip = "0.0.0.1"; int port = 1234; long expireTime = fakeNowTimestamp + 50000L; int retries = 50; addLeasesToZk( tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>(consumerName + "a", new ClientLeaseInfo(new Lease(2, System .currentTimeMillis() + 500L), ip + "2", port + 1)) )); Map<Tpg, Map<String, ClientLeaseInfo>> allValidLeases = m_leaseHolder.getAllValidLeases(); for (int i = 0; i < retries && allValidLeases.isEmpty(); i++) { TimeUnit.MILLISECONDS.sleep(100); allValidLeases = m_leaseHolder.getAllValidLeases(); } allValidLeases.clear(); addLeasesToZk(tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>(consumerName, new ClientLeaseInfo(new Lease(1, expireTime), ip, port)) )); for (int i = 0; i < retries; i++) { TimeUnit.MILLISECONDS.sleep(100); allValidLeases = m_leaseHolder.getAllValidLeases(); if (!allValidLeases.isEmpty() && allValidLeases.get(tpg).containsKey(consumerName)) { break; } } assertEquals(1, allValidLeases.size()); assertLeases(allValidLeases, tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>(consumerName, new ClientLeaseInfo(new Lease(1, expireTime), ip, port)))); } @Test public void testLeaseRemovedInZk() throws Exception { long fakeNowTimestamp = System.currentTimeMillis(); Tpg tpg = new Tpg("t1", 0, "g1"); String consumerName = "c0"; String ip = "0.0.0.1"; int port = 1234; long expireTime = fakeNowTimestamp + 1000L; int retries = 50; addLeasesToZk(tpg, Arrays.asList( new Pair<String, ClientLeaseInfo>(consumerName, new ClientLeaseInfo(new Lease(1, expireTime), ip, port)) )); Map<Tpg, Map<String, ClientLeaseInfo>> allValidLeases = m_leaseHolder.getAllValidLeases(); for (int i = 0; i < retries && allValidLeases.isEmpty(); i++) { TimeUnit.MILLISECONDS.sleep(100); allValidLeases = m_leaseHolder.getAllValidLeases(); } assertEquals(1, allValidLeases.size()); allValidLeases.clear(); deleteChildren(ZKPathUtils.getConsumerLeaseTopicParentZkPath(tpg.getTopic()), true); for (int i = 0; i < retries; i++) { TimeUnit.MILLISECONDS.sleep(100); allValidLeases = m_leaseHolder.getAllValidLeases(); if (allValidLeases.isEmpty()) { break; } } assertFalse(m_leaseHolder.topicWatched(tpg.getTopic())); assertTrue(allValidLeases.isEmpty()); } @Test public void testNewLease() throws Exception { Tpg tpg = new Tpg("t1", 0, "g1"); String consumerName = "c0"; final String ip = "1.1.1.2"; final int port = 1111; leaseHolderReload(); Map<String, ClientLeaseInfo> existingValidLeases = new HashMap<>(); m_leaseHolder.newLease(tpg, consumerName, existingValidLeases, 1000 * 1000L, ip, port); assertEquals(1, existingValidLeases.size()); ClientLeaseInfo clientLeaseInfo = existingValidLeases.get(consumerName); assertNotNull(clientLeaseInfo); assertEquals(ip, clientLeaseInfo.getIp()); assertEquals(port, clientLeaseInfo.getPort()); assertFalse(clientLeaseInfo.getLease().isExpired()); Map<String, ClientLeaseInfo> zkLeases = ZKSerializeUtils.deserialize( m_curator.getData().forPath( ZKPathUtils.getConsumerLeaseZkPath(tpg.getTopic(), tpg.getPartition(), tpg.getGroupId())), new TypeReference<Map<String, ClientLeaseInfo>>() { }.getType()); assertEquals(1, zkLeases.size()); clientLeaseInfo = zkLeases.get(consumerName); assertNotNull(clientLeaseInfo); assertEquals(ip, clientLeaseInfo.getIp()); assertEquals(port, clientLeaseInfo.getPort()); assertFalse(clientLeaseInfo.getLease().isExpired()); } @Test public void testRemoveExpiredLeasesAndGetAllValidLeases() throws Exception { long fakeNowTimestamp = System.currentTimeMillis() + 500 * 1000L; Tpg t1p0g1 = new Tpg("t1", 0, "g1"); Tpg t1p1g1 = new Tpg("t1", 1, "g1"); Tpg t1p0g2 = new Tpg("t1", 0, "g2"); addLeasesToZk(t1p0g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 50), "0.0.0.0", 1234)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, fakeNowTimestamp + 30), "0.0.0.1", 1233)) )); addLeasesToZk(t1p1g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c2", new ClientLeaseInfo(new Lease(3, 0), "0.0.0.2", 2222)) )); addLeasesToZk(t1p0g2, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, 0), "0.0.0.0", 1234)) )); leaseHolderReload(); int retries = 50; int i = 0; Map<Tpg, Map<String, ClientLeaseInfo>> allValidLeases = null; while (i++ < retries) { allValidLeases = m_leaseHolder.getAllValidLeases(); if (allValidLeases.size() == 1) { break; } else { TimeUnit.MILLISECONDS.sleep(100); } } assertEquals(1, allValidLeases.size()); assertLeases(allValidLeases, t1p0g1, Arrays.asList( new Pair<String, ClientLeaseInfo>("c0", new ClientLeaseInfo(new Lease(1, fakeNowTimestamp + 50), "0.0.0.0", 1234)), new Pair<String, ClientLeaseInfo>("c1", new ClientLeaseInfo(new Lease(2, fakeNowTimestamp + 30), "0.0.0.1", 1233)) )); } @Test public void testRenewLease() throws Exception { Tpg tpg = new Tpg("t1", 1, "g1"); final String ip = "1.1.1.2"; final int port = 1111; String consumerName = "c0"; leaseHolderReload(); long now = System.currentTimeMillis(); Map<String, ClientLeaseInfo> existingValidLeases = new HashMap<>(); ClientLeaseInfo existingLeaseInfo = new ClientLeaseInfo(new Lease(1, now + 1000L), ip, port); m_leaseHolder.renewLease(tpg, consumerName, existingValidLeases, existingLeaseInfo, 1000 * 1000L, ip, port); assertEquals(1, existingValidLeases.size()); ClientLeaseInfo clientLeaseInfo = existingValidLeases.get(consumerName); assertNotNull(clientLeaseInfo); assertEquals(ip, clientLeaseInfo.getIp()); assertEquals(port, clientLeaseInfo.getPort()); assertFalse(clientLeaseInfo.getLease().isExpired()); assertEquals(1, clientLeaseInfo.getLease().getId()); assertEquals(now + 1000L + 1000 * 1000L, clientLeaseInfo.getLease().getExpireTime()); Map<String, ClientLeaseInfo> zkLeases = ZKSerializeUtils.deserialize( m_curator.getData().forPath( ZKPathUtils.getConsumerLeaseZkPath(tpg.getTopic(), tpg.getPartition(), tpg.getGroupId())), new TypeReference<Map<String, ClientLeaseInfo>>() { }.getType()); assertEquals(1, zkLeases.size()); clientLeaseInfo = zkLeases.get(consumerName); assertNotNull(clientLeaseInfo); assertEquals(ip, clientLeaseInfo.getIp()); assertEquals(port, clientLeaseInfo.getPort()); assertFalse(clientLeaseInfo.getLease().isExpired()); assertEquals(1, clientLeaseInfo.getLease().getId()); assertEquals(now + 1000L + 1000 * 1000L, clientLeaseInfo.getLease().getExpireTime()); } }
package org.hudsonci.model.project.property; import hudson.util.DescribableList; import org.apache.commons.collections.CollectionUtils; import org.hudsonci.api.model.IJob; public class DescribableListProjectProperty extends BaseProjectProperty<DescribableList> { public DescribableListProjectProperty(IJob job) { super(job); } @Override public DescribableList getDefaultValue() { return new DescribableList(getJob()); } @Override public boolean allowOverrideValue(DescribableList cascadingValue, DescribableList candidateValue) { return (null != candidateValue || null != cascadingValue) && ((null == cascadingValue || null == candidateValue) || !CollectionUtils.isEqualCollection(cascadingValue.toList(), candidateValue.toList())); } @Override protected boolean returnOriginalValue() { return isOverridden() || (null != getOriginalValue() && !getOriginalValue().isEmpty()); } @Override public DescribableList getOriginalValue() { DescribableList result = super.getOriginalValue(); return null != result ? result : getDefaultValue(); } }
package org.hudsonci.servlets.internal; import org.hudsonci.servlets.ServletRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import static com.google.common.base.Preconditions.checkNotNull; /** * Wraps a {@link Servlet} as a {@link Filter} for installation via {@link hudson.util.PluginServletFilter}. * * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> * @since 2.1.0 */ public class ServletRegistrationFilterAdapter implements Filter { private static final Logger log = LoggerFactory.getLogger(ServletRegistrationFilterAdapter.class); private final ServletRegistration registration; private final Servlet servlet; private final String uriPrefix; private boolean enabled; public ServletRegistrationFilterAdapter(final ServletRegistration registration) throws Exception { this.registration = checkNotNull(registration); this.servlet = createServlet(); if (registration.getName() == null) { registration.setName(servlet.getClass().getName()); } uriPrefix = registration.getUriPrefix(); if (uriPrefix == null) { throw new IllegalArgumentException("Registration missing uriPrefix"); } } public boolean isEnabled() { return enabled; } public void setEnabled(final boolean enabled) { this.enabled = enabled; } private Servlet createServlet() throws Exception { Servlet servlet = registration.getServlet(); if (servlet != null) { return servlet; } Class<? extends Servlet> type = registration.getServletType(); if (type != null) { return type.newInstance(); } throw new IllegalArgumentException("Registration missing servlet or servlet type"); } public void init(final FilterConfig config) throws ServletException { checkNotNull(config); servlet.init(new ServletConfig() { public String getServletName() { return registration.getName(); } public ServletContext getServletContext() { return config.getServletContext(); } public Enumeration getInitParameterNames() { final Iterator<String> iter = registration.getParameters().keySet().iterator(); return new Enumeration() { public boolean hasMoreElements() { return iter.hasNext(); } public Object nextElement() { return iter.next(); } }; } public String getInitParameter(final String name) { return registration.getParameters().get(name); } }); } public void destroy() { servlet.destroy(); } public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { assert chain != null; if (isEnabled() && request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } else { chain.doFilter(request, response); } } private void doFilter(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException { assert request != null; assert response != null; assert chain != null; String uri = request.getRequestURI(); // Get the requestUri without the context uriPrefix and the leading slash uri = uri.substring(request.getContextPath().length()); if (uri.startsWith(uriPrefix)) { // Wrap the request to augment the servlet uriPrefix HttpServletRequestWrapper req = new HttpServletRequestWrapper(request) { @Override public String getServletPath() { return String.format("/%s", uriPrefix); } }; servlet.service(req, response); } else { chain.doFilter(request, response); } } }
package persistence; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import com.google.gson.JsonObject; import model.entity.AssignOrderToUser; import model.entity.AssignProductToOrder; import model.entity.AssignProductToOwner; public class FileWrite { public void fileWriteReportOwner(ArrayList<AssignProductToOwner> ownerList) throws IOException{ File fileFolder = new File(System.getProperty("user.dir")+"\\"+"Report"); File file=new File(fileFolder.getAbsolutePath()+"\\"+"owner.json"); fileFolder.mkdirs(); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); JsonObject restaurantObject = new JsonObject(); JsonObject ownerObject = new JsonObject(); restaurantObject.add(ConstantPersistence.RESTAURANT_LISIT, ownerObject); for (AssignProductToOwner owner : ownerList) { ownerObject.addProperty(ConstantPersistence.RESTAURANT_NAME, owner.getOwner().getName()); ownerObject.addProperty(ConstantPersistence.PASSWORD, owner.getOwner().getPassword()); ownerObject.addProperty(ConstantPersistence.RESTAURANT_IMAGE, owner.getOwner().getUrl()); JsonObject productsObjetc = new JsonObject(); ownerObject.add(ConstantPersistence.PRODUCT_LIST, productsObjetc); productsObjetc.addProperty(ConstantPersistence.PRODUCT_NAME, owner.getProduct().getName()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_DESCRIPTION, owner.getProduct().getDescription()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_PRICE, owner.getProduct().getPrice()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_IMAGE, owner.getProduct().getImg()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_STATE, String.valueOf(owner.getProduct().getState())); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(restaurantObject.toString()); bufferedWriter.close(); } public void fileWriteReportOrder(ArrayList<AssignProductToOrder> assignProductToOrderList) throws IOException{ File fileFolder = new File(System.getProperty("user.dir")+"\\"+"Report"); File file=new File(fileFolder.getAbsolutePath()+"\\"+"order.json"); fileFolder.mkdirs(); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); JsonObject restaurantObject = new JsonObject(); JsonObject orderObject = new JsonObject(); restaurantObject.add(ConstantPersistence.ORDER_LIST, orderObject); for (AssignProductToOrder assignProductToOrder : assignProductToOrderList) { orderObject.addProperty(ConstantPersistence.ORDER_STATE, String.valueOf(assignProductToOrder.getOrder().getState())); orderObject.addProperty(ConstantPersistence.ORDER_DIRECTION, assignProductToOrder.getOrder().getDirection()); JsonObject productsObjetc = new JsonObject(); orderObject.add(ConstantPersistence.PRODUCT_LIST, productsObjetc); productsObjetc.addProperty(ConstantPersistence.PRODUCT_NAME, assignProductToOrder.getProduct().getName()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_DESCRIPTION, assignProductToOrder.getProduct().getDescription()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_PRICE, assignProductToOrder.getProduct().getPrice()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_IMAGE, assignProductToOrder.getProduct().getImg()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_STATE, String.valueOf(assignProductToOrder.getProduct().getState())); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(restaurantObject.toString()); bufferedWriter.close(); } public void fileWriteReportUser(ArrayList<AssignOrderToUser> assignOrderToUserList) throws IOException{ File fileFolder = new File(System.getProperty("user.dir")+"\\"+"Report"); File file=new File(fileFolder.getAbsolutePath()+"\\"+"user.json"); fileFolder.mkdirs(); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); JsonObject restaurantObject = new JsonObject(); JsonObject userObject = new JsonObject(); restaurantObject.add(ConstantPersistence.USER, userObject); for (AssignOrderToUser assignOrderToUser : assignOrderToUserList) { userObject.addProperty(ConstantPersistence.USER_NAME, assignOrderToUser.getUser().getName()); userObject.addProperty(ConstantPersistence.PASSWORD, assignOrderToUser.getUser().getPassword()); userObject.addProperty(ConstantPersistence.USER_STATE, assignOrderToUser.getUser().isState()); JsonObject orderObjetc = new JsonObject(); userObject.add(ConstantPersistence.ORDER_LIST, orderObjetc); orderObjetc.addProperty(ConstantPersistence.ORDER_STATE, String.valueOf(assignOrderToUser.getOrder().getState())); orderObjetc.addProperty(ConstantPersistence.ORDER_DIRECTION, assignOrderToUser.getOrder().getDirection()); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(restaurantObject.toString()); bufferedWriter.close(); } }
package ru.nsu.ccfit.bogush; import ru.nsu.ccfit.bogush.view.FactoryView; import java.io.IOException; public class Main { private static final String CONFIG_FILE = "config.properties"; private static CarFactoryModel model; private static void prepare(String configFilePath) throws IOException { Config config = new ConfigSerializer().load(configFilePath); model = new CarFactoryModel(config); } public static void main(String[] args) { try { prepare(CONFIG_FILE); new FactoryView(model); } catch (Exception e) { e.printStackTrace(); } } }
package com.facebook.imagepipeline.animated.factory; import javax.annotation.concurrent.NotThreadSafe; import android.content.Context; @NotThreadSafe public interface AnimatedFactory { AnimatedDrawableFactory getAnimatedDrawableFactory(Context context); AnimatedImageFactory getAnimatedImageFactory(); }
package org.intermine.webservice.client.benchmark; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.PathQuery; import org.intermine.webservice.client.core.ServiceFactory; import org.intermine.webservice.client.services.QueryService; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; public class ResultFormats { private static final String baseUrl = "http: private static final QueryService flymine = new ServiceFactory(baseUrl).getQueryService(); private PathQuery query; private int expectedSize = -1; static int runs = 20; @Before public void setup() { query = new PathQuery(flymine.getFactory().getModel()); query.addViews("Gene.symbol", "Gene.length"); query.addConstraint(Constraints.eq("Gene.symbol", "c*")); query.addConstraint(Constraints.isNotNull("Gene.length")); expectedSize = flymine.getCount(query); } private static interface RowCounter { public int count(PathQuery query) throws Exception; public String getName(); } private void doBenchmark(RowCounter counter) throws Exception { long start = System.currentTimeMillis(); for (int i = 0; i < runs; i++) { int c = counter.count(query); assertEquals(expectedSize, c); } long end = System.currentTimeMillis(); System.out.printf("%s: %.2f seconds per run of %d\n", counter.getName(), Float.valueOf(end - start) / 1000 / runs, expectedSize); } @Test public void benchmarkJsonRows() throws Exception { RowCounter counter = new RowCounter() { @Override public int count(PathQuery query) { int c = 0, cells = query.getView().size(); Iterator<List<Object>> it = flymine.getRowListIterator(query); while (it.hasNext()) { List<Object> row = it.next(); assertEquals(cells, row.size()); c++; } return c; } @Override public String getName() { return "JSON-ROWS"; } }; doBenchmark(counter); } @Test public void benchmarkJsonObj() throws Exception { RowCounter counter = new RowCounter() { @Override public int count(PathQuery query) throws JSONException { int c = 0; List<String> paths = query.getView(); List<String> fields = new ArrayList<String>(); for (String path: paths) { fields.add(path.replaceAll("[^.]*\\.", "")); } Iterator<JSONObject> it = flymine.getAllJSONResults(query).iterator(); while (it.hasNext()) { JSONObject res = it.next(); for (String field: fields) { assertNotNull(field + " is not null", res.get(field)); } c++; } return c; } @Override public String getName() { return "JSON-OBJ"; } }; doBenchmark(counter); } @Test public void benchmarkJsonXML() throws Exception { RowCounter counter = new RowCounter() { @Override public int count(PathQuery query) throws JSONException { int c = 0, cells = query.getView().size(); Iterator<List<String>> it = flymine.getAllResults(query).iterator(); while (it.hasNext()) { List<String> res = it.next(); assertEquals(cells, res.size()); c++; } return c; } @Override public String getName() { return "XML"; } }; doBenchmark(counter); } }
// modification, are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. package br.com.carlosrafaelgn.fplay; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.Build; import android.text.InputType; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import br.com.carlosrafaelgn.fplay.activity.ActivityHost; import br.com.carlosrafaelgn.fplay.activity.ClientActivity; import br.com.carlosrafaelgn.fplay.activity.MainHandler; import br.com.carlosrafaelgn.fplay.list.Song; import br.com.carlosrafaelgn.fplay.playback.Player; import br.com.carlosrafaelgn.fplay.ui.BackgroundActivityMonitor; import br.com.carlosrafaelgn.fplay.ui.BgButton; import br.com.carlosrafaelgn.fplay.ui.BgListView; import br.com.carlosrafaelgn.fplay.ui.ColorPickerView; import br.com.carlosrafaelgn.fplay.ui.CustomContextMenu; import br.com.carlosrafaelgn.fplay.ui.ObservableScrollView; import br.com.carlosrafaelgn.fplay.ui.SettingView; import br.com.carlosrafaelgn.fplay.ui.UI; import br.com.carlosrafaelgn.fplay.ui.drawable.ColorDrawable; import br.com.carlosrafaelgn.fplay.ui.drawable.TextIconDrawable; import br.com.carlosrafaelgn.fplay.util.BluetoothConnectionManager; import br.com.carlosrafaelgn.fplay.util.ColorUtils; import br.com.carlosrafaelgn.fplay.visualizer.BluetoothVisualizerControllerJni; public final class ActivitySettings extends ClientActivity implements Player.PlayerTurnOffTimerObserver, View.OnClickListener, DialogInterface.OnClickListener, ColorPickerView.OnColorPickerViewListener, ObservableScrollView.OnScrollListener, Runnable { private static final double MIN_THRESHOLD = 1.5; //waaaaaaaaaayyyyyyyy below W3C recommendations, so no one should complain about the app being "boring" private final boolean colorMode, bluetoothMode; private boolean changed, checkingReturn, configsChanged, lblTitleOk, startTransmissionOnConnection; private BgButton btnGoBack, btnBluetooth, btnAbout; private EditText txtCustomMinutes; private ObservableScrollView list; private TextView lblTitle; private RelativeLayout panelControls; private LinearLayout panelSettings; private SettingView firstViewAdded, lastViewAdded, optLoadCurrentTheme, optUseAlternateTypeface, optAutoTurnOff, optAutoIdleTurnOff, optAutoTurnOffPlaylist, optKeepScreenOn, optTheme, optFlat, optBorders, optPlayWithLongPress, optExpandSeekBar, optVolumeControlType, optDoNotAttenuateVolume, opt3D, optIsDividerVisible, optIsVerticalMarginLarge, optExtraSpacing, optPlaceTitleAtTheBottom, optForcedLocale, optPlacePlaylistToTheRight, optScrollBarToTheLeft, optScrollBarSongList, optScrollBarBrowser, optWidgetTransparentBg, optWidgetTextColor, optWidgetIconColor, optHandleCallKey, optHeadsetHook1, optHeadsetHook2, optHeadsetHook3, optPlayWhenHeadsetPlugged, optBlockBackKey, optBackKeyAlwaysReturnsToPlayerWhenBrowsing, optWrapAroundList, optDoubleClickMode, optMarqueeTitle, optPrepareNext, optClearListWhenPlayingFolders, optGoBackWhenPlayingFolders, optExtraInfoMode, optForceOrientation, optTransition, optAnimations, optNotFullscreen, optFadeInFocus, optFadeInPause, optFadeInOther, optBtMessage, optBtConnect, optBtStart, optBtFramesToSkip, optBtSize, optBtVUMeter, optBtSpeed, optAnnounceCurrentSong, optFollowCurrentSong, optBytesBeforeDecoding, optSecondsBeforePlayback, lastMenuView; private SettingView[] colorViews; private int lastColorView, currentHeader, btMessageText, btErrorMessage, btConnectText, btStartText; private TextView[] headers; public ActivitySettings(boolean colorMode, boolean bluetoothMode) { this.colorMode = colorMode; this.bluetoothMode = bluetoothMode; } @Override public CharSequence getTitle() { return (bluetoothMode ? "Bluetooth + Arduino" : getText(colorMode ? R.string.custom_color_theme : R.string.settings)); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { if (view == optAutoTurnOff || view == optAutoIdleTurnOff) { lastMenuView = (SettingView)view; UI.prepare(menu); final int s = ((view == optAutoTurnOff) ? Player.turnOffTimerSelectedMinutes : Player.idleTurnOffTimerSelectedMinutes); final int c = ((view == optAutoTurnOff) ? Player.turnOffTimerCustomMinutes : Player.idleTurnOffTimerCustomMinutes); menu.add(0, 0, 0, R.string.never) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(s <= 0 ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, c, 0, getMinuteString(c)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(s == c ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 1, 1); menu.add(2, 60, 0, getMinuteString(60)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(s == 60 ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(2, 90, 1, getMinuteString(90)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(s == 90 ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(2, 120, 2, getMinuteString(120)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(s == 120 ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 2, 4); menu.add(3, -2, 0, R.string.custom) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(s != c && s != 60 && s != 90 && s != 120 && s > 0 ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optForcedLocale) { final Context ctx = getApplication(); final int o = UI.forcedLocale; lastMenuView = optForcedLocale; UI.prepare(menu); menu.add(0, UI.LOCALE_NONE, 0, R.string.standard_language) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_NONE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, UI.LOCALE_DE, 0, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_DE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_DE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.LOCALE_US, 1, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_US)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_US) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.LOCALE_ES, 2, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_ES)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_ES) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.LOCALE_FR, 3, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_FR)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_FR) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.LOCALE_PTBR, 4, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_PTBR)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_PTBR) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.LOCALE_RU, 5, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_RU)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_RU) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.LOCALE_UK, 6, UI.getLocaleDescriptionFromCode(ctx, UI.LOCALE_UK)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.LOCALE_UK) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optTheme) { final Context ctx = getApplication(); final int o = UI.theme; lastMenuView = optTheme; UI.prepare(menu); menu.add(0, UI.THEME_CUSTOM, 0, UI.getThemeString(ctx, UI.THEME_CUSTOM)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_CUSTOM) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, UI.THEME_FPLAY, 0, UI.getThemeString(ctx, UI.THEME_FPLAY)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_FPLAY) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.THEME_CREAMY, 1, UI.getThemeString(ctx, UI.THEME_CREAMY)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_CREAMY) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.THEME_DARK_LIGHT, 2, UI.getThemeString(ctx, UI.THEME_DARK_LIGHT)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_DARK_LIGHT) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.THEME_BLUE_ORANGE, 3, UI.getThemeString(ctx, UI.THEME_BLUE_ORANGE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_BLUE_ORANGE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.THEME_BLUE, 4, UI.getThemeString(ctx, UI.THEME_BLUE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_BLUE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.THEME_ORANGE, 5, UI.getThemeString(ctx, UI.THEME_ORANGE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_ORANGE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.THEME_LIGHT, 6, UI.getThemeString(ctx, UI.THEME_LIGHT)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.THEME_LIGHT) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optVolumeControlType) { lastMenuView = optVolumeControlType; UI.prepare(menu); menu.add(0, Player.VOLUME_CONTROL_STREAM, 0, R.string.volume_control_type_integrated) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((Player.volumeControlType == Player.VOLUME_CONTROL_STREAM) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, Player.VOLUME_CONTROL_DB, 0, R.string.volume_control_type_decibels) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((Player.volumeControlType == Player.VOLUME_CONTROL_DB) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, Player.VOLUME_CONTROL_PERCENT, 1, R.string.volume_control_type_percentage) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((Player.volumeControlType == Player.VOLUME_CONTROL_PERCENT) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 1, 2); menu.add(2, Player.VOLUME_CONTROL_NONE, 0, R.string.noneM) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((Player.volumeControlType == Player.VOLUME_CONTROL_NONE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optExtraInfoMode) { lastMenuView = optExtraInfoMode; UI.prepare(menu); final int o = Song.extraInfoMode; for (int i = Song.EXTRA_ARTIST; i <= Song.EXTRA_ARTIST_ALBUM; i++) { menu.add(0, i, i, getExtraInfoModeString(i)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == i) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } } else if (view == optForceOrientation) { lastMenuView = optForceOrientation; UI.prepare(menu); final int o = UI.forcedOrientation; menu.add(0, 0, 0, R.string.none) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == 0) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, -1, 0, R.string.landscape) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o < 0) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, 1, 1, R.string.portrait) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o > 0) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optTransition) { lastMenuView = optTransition; UI.prepare(menu); final Context ctx = getApplication(); final int o = UI.transition; menu.add(0, UI.TRANSITION_NONE, 0, UI.getTransitionString(ctx, UI.TRANSITION_NONE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.TRANSITION_NONE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, UI.TRANSITION_FADE, 0, UI.getTransitionString(ctx, UI.TRANSITION_FADE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.TRANSITION_FADE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.TRANSITION_SLIDE, 1, UI.getTransitionString(ctx, UI.TRANSITION_SLIDE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.TRANSITION_SLIDE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, UI.TRANSITION_ZOOM, 2, UI.getTransitionString(ctx, UI.TRANSITION_ZOOM)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.TRANSITION_ZOOM) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(2, UI.TRANSITION_DISSOLVE, 3, UI.getTransitionString(ctx, UI.TRANSITION_DISSOLVE)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((o == UI.TRANSITION_DISSOLVE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optScrollBarSongList || view == optScrollBarBrowser) { lastMenuView = (SettingView)view; UI.prepare(menu); final int d = ((view == optScrollBarSongList) ? UI.songListScrollBarType : UI.browserScrollBarType); if (view == optScrollBarBrowser) menu.add(0, BgListView.SCROLLBAR_INDEXED, 0, R.string.indexed_if_possible) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((d == BgListView.SCROLLBAR_INDEXED) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(0, BgListView.SCROLLBAR_LARGE, 1, R.string.large) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((d == BgListView.SCROLLBAR_LARGE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(0, BgListView.SCROLLBAR_SYSTEM, 2, R.string.system_integrated) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((d != BgListView.SCROLLBAR_INDEXED && d != BgListView.SCROLLBAR_LARGE && d != BgListView.SCROLLBAR_NONE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 3); menu.add(1, BgListView.SCROLLBAR_NONE, 0, R.string.none) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((d == BgListView.SCROLLBAR_NONE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optFadeInFocus || view == optFadeInPause || view == optFadeInOther) { lastMenuView = (SettingView)view; UI.prepare(menu); final int d = ((view == optFadeInFocus) ? Player.fadeInIncrementOnFocus : ((view == optFadeInPause) ? Player.fadeInIncrementOnPause : Player.fadeInIncrementOnOther)); menu.add(0, 0, 0, R.string.none) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((d <= 0) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, 250, 0, R.string.dshort) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((d >= 250) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, 125, 1, R.string.dmedium) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(((d >= 125) && (d < 250)) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, 62, 2, R.string.dlong) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(((d > 0) && (d < 125)) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optHeadsetHook1 || view == optHeadsetHook2 || view == optHeadsetHook3) { lastMenuView = (SettingView)view; UI.prepare(menu); final int pressCount = ((view == optHeadsetHook1) ? 1 : ((view == optHeadsetHook2) ? 2 : 3)); final int action = Player.getHeadsetHookAction(pressCount); menu.add(0, 0, 0, R.string.nothing) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((action == 0) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); UI.separator(menu, 0, 1); menu.add(1, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0, getText(R.string.play) + "/" + getText(R.string.pause)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((action == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, KeyEvent.KEYCODE_MEDIA_NEXT, 1, R.string.next) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((action == KeyEvent.KEYCODE_MEDIA_NEXT) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); menu.add(1, KeyEvent.KEYCODE_MEDIA_PREVIOUS, 2, R.string.previous) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((action == KeyEvent.KEYCODE_MEDIA_PREVIOUS) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } else if (view == optBtSize) { lastMenuView = optBtSize; UI.prepare(menu); final int size = Player.getBluetoothVisualizerSize(); for (int i = 0; i <= 6; i++) { menu.add(0, i, i, Integer.toString(1 << (2 + i))) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((size == i) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } } else if (view == optBtSpeed) { lastMenuView = optBtSpeed; UI.prepare(menu); final int speed = Player.getBluetoothVisualizerSpeed(); for (int i = 0; i <= 2; i++) { menu.add(0, i, i, Integer.toString(3 - i)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((speed == i) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } } else if (view == optBtFramesToSkip) { lastMenuView = optBtFramesToSkip; UI.prepare(menu); final int framesToSkip = Player.getBluetoothVisualizerFramesToSkipIndex(); for (int i = 0; i <= 11; i++) { menu.add(0, i, i, Integer.toString(Player.getBluetoothVisualizerFramesPerSecond(i))) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((framesToSkip == i) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } } else if (view == optBytesBeforeDecoding) { lastMenuView = optBytesBeforeDecoding; UI.prepare(menu); final int bytesBeforeDecodingIndex = Player.getBytesBeforeDecodingIndex(); for (int i = 0; i <= 7; i++) { menu.add(0, i, i, getBytesBeforeDecodingString(i)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((bytesBeforeDecodingIndex == i) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } } else if (view == optSecondsBeforePlayback) { lastMenuView = optSecondsBeforePlayback; UI.prepare(menu); final int secondsBeforePlaybackIndex = Player.getSecondsBeforePlaybackIndex(); for (int i = 0; i <= 4; i++) { menu.add(0, i, i, getSecondsBeforePlaybackString(i)) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable((secondsBeforePlaybackIndex == i) ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK)); } } } @Override public boolean onMenuItemClick(MenuItem item) { //NullPointerException reported at Play Store.... :/ final ActivityHost ctx = getHostActivity(); final Application app = (ctx == null ? null : ctx.getApplication()); if (item == null || lastMenuView == null || ctx == null || app == null) return true; if (lastMenuView == optAutoTurnOff || lastMenuView == optAutoIdleTurnOff) { if (item.getItemId() >= 0) { if (lastMenuView == optAutoTurnOff) { Player.setTurnOffTimer(item.getItemId()); optAutoTurnOff.setSecondaryText(getAutoTurnOffString()); } else { Player.setIdleTurnOffTimer(item.getItemId()); optAutoIdleTurnOff.setSecondaryText(getAutoIdleTurnOffString()); } } else { final LinearLayout l = (LinearLayout)UI.createDialogView(ctx, null); l.addView(UI.createDialogTextView(ctx, 0, null, getText(R.string.msg_turn_off))); final LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); p.topMargin = UI.dialogMargin; txtCustomMinutes = UI.createDialogEditText(ctx, 0, p, Integer.toString((lastMenuView == optAutoTurnOff) ? Player.turnOffTimerCustomMinutes : Player.idleTurnOffTimerCustomMinutes), ctx.getText(R.string.msg_turn_off), InputType.TYPE_CLASS_NUMBER); l.addView(txtCustomMinutes); UI.prepareDialogAndShow((new AlertDialog.Builder(ctx)) .setTitle(R.string.msg_turn_off_title) .setView(l) .setPositiveButton(R.string.ok, this) .setNegativeButton(R.string.cancel, this) .create()); } } else if (lastMenuView == optForcedLocale) { if (item.getItemId() != UI.forcedLocale) { UI.setForcedLocale(app, ctx, item.getItemId(), true); WidgetMain.updateWidgets(app); onCleanupLayout(); onCreateLayout(false); System.gc(); } } else if (lastMenuView == optTheme) { if (item.getItemId() == UI.THEME_CUSTOM) { startActivity(new ActivitySettings(true, false), 0, null, false); } else { UI.setTheme(ctx, item.getItemId()); onCleanupLayout(); onCreateLayout(false); System.gc(); } } else if (lastMenuView == optVolumeControlType) { Player.setVolumeControlType(item.getItemId()); optVolumeControlType.setSecondaryText(getVolumeString()); } else if (lastMenuView == optExtraInfoMode) { Song.extraInfoMode = item.getItemId(); optExtraInfoMode.setSecondaryText(getExtraInfoModeString(Song.extraInfoMode)); Player.songs.updateExtraInfo(); WidgetMain.updateWidgets(app); } else if (lastMenuView == optForceOrientation) { UI.forcedOrientation = item.getItemId(); ctx.setRequestedOrientation((UI.forcedOrientation == 0) ? ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED : ((UI.forcedOrientation < 0) ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)); optForceOrientation.setSecondaryText(getOrientationString()); } else if (lastMenuView == optTransition) { UI.setTransition(item.getItemId()); optTransition.setSecondaryText(UI.getTransitionString(app, item.getItemId())); } else if (lastMenuView == optScrollBarSongList) { UI.songListScrollBarType = item.getItemId(); optScrollBarSongList.setSecondaryText(getScrollBarString(item.getItemId())); } else if (lastMenuView == optScrollBarBrowser) { UI.browserScrollBarType = item.getItemId(); optScrollBarBrowser.setSecondaryText(getScrollBarString(item.getItemId())); list.updateVerticalScrollbar(); } else if (lastMenuView == optFadeInFocus) { Player.fadeInIncrementOnFocus = item.getItemId(); optFadeInFocus.setSecondaryText(getFadeInString(item.getItemId())); } else if (lastMenuView == optFadeInPause) { Player.fadeInIncrementOnPause = item.getItemId(); optFadeInPause.setSecondaryText(getFadeInString(item.getItemId())); } else if (lastMenuView == optFadeInOther) { Player.fadeInIncrementOnOther = item.getItemId(); optFadeInOther.setSecondaryText(getFadeInString(item.getItemId())); } else if (lastMenuView == optHeadsetHook1 || lastMenuView == optHeadsetHook2 || lastMenuView == optHeadsetHook3) { final int pressCount = ((lastMenuView == optHeadsetHook1) ? 1 : ((lastMenuView == optHeadsetHook2) ? 2 : 3)); Player.setHeadsetHookAction(pressCount, item.getItemId()); lastMenuView.setSecondaryText(getHeadsetHookString(pressCount)); } else if (lastMenuView == optBtSize) { Player.setBluetoothVisualizerSize(item.getItemId()); optBtSize.setSecondaryText(getSizeString()); if (Player.bluetoothVisualizerController != null) ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).syncSize(); } else if (lastMenuView == optBtSpeed) { Player.setBluetoothVisualizerSpeed(item.getItemId()); optBtSpeed.setSecondaryText(getSpeedString()); if (Player.bluetoothVisualizerController != null) ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).syncSpeed(); } else if (lastMenuView == optBtFramesToSkip) { Player.setBluetoothVisualizerFramesToSkipIndex(item.getItemId()); optBtFramesToSkip.setSecondaryText(getFramesToSkipString()); if (Player.bluetoothVisualizerController != null) ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).syncFramesToSkip(); } else if (lastMenuView == optBytesBeforeDecoding) { Player.setBytesBeforeDecodingIndex(item.getItemId()); optBytesBeforeDecoding.setSecondaryText(getBytesBeforeDecodingString(item.getItemId())); } else if (lastMenuView == optSecondsBeforePlayback) { Player.setSecondsBeforePlayingIndex(item.getItemId()); optSecondsBeforePlayback.setSecondaryText(getSecondsBeforePlaybackString(item.getItemId())); } configsChanged = true; return true; } private String getBytesBeforeDecodingString(int index) { return (Player.getBytesBeforeDecoding(index) >> 10) + " KiB"; } private String getSecondsBeforePlaybackString(int index) { final int sec = Player.getSecondsBeforePlayback(index); return UI.formatIntAsFloat(sec / 100, false, true) + " " + ((sec == 1000) ? getText(R.string.second) : getText(R.string.seconds)); } private String getMinuteString(int minutes) { if (minutes <= 0) return getText(R.string.never).toString(); if (minutes == 1) return "1 " + getText(R.string.minute).toString(); return minutes + " " + getText(R.string.minutes).toString(); } private String getAutoTurnOffString() { return getMinuteString(Player.getTurnOffTimerMinutesLeft()); } private String getAutoIdleTurnOffString() { return getMinuteString(Player.getIdleTurnOffTimerMinutesLeft()); } private String getVolumeString() { switch (Player.volumeControlType) { case Player.VOLUME_CONTROL_DB: return getText(R.string.volume_control_type_decibels).toString(); case Player.VOLUME_CONTROL_PERCENT: return getText(R.string.volume_control_type_percentage).toString(); case Player.VOLUME_CONTROL_NONE: return getText(R.string.noneM).toString(); default: return getText(R.string.volume_control_type_integrated).toString(); } } private String getExtraInfoModeString(int extraMode) { switch (extraMode) { case Song.EXTRA_ARTIST: return getText(R.string.artist).toString(); case Song.EXTRA_ALBUM: return getText(R.string.album).toString(); case Song.EXTRA_TRACK_ARTIST: return getText(R.string.track) + "/" + getText(R.string.artist); case Song.EXTRA_TRACK_ALBUM: return getText(R.string.track) + "/" + getText(R.string.album); case Song.EXTRA_TRACK_ARTIST_ALBUM: return getText(R.string.track) + "/" + getText(R.string.artist) + "/" + getText(R.string.album); default: return getText(R.string.artist) + "/" + getText(R.string.album); } } private String getOrientationString() { final int o = UI.forcedOrientation; return getText((o == 0) ? R.string.none : ((o < 0) ? R.string.landscape : R.string.portrait)).toString(); } private String getFadeInString(int duration) { return getText((duration >= 250) ? R.string.dshort : ((duration >= 125) ? R.string.dmedium : ((duration > 0) ? R.string.dlong : R.string.none))).toString(); } private String getScrollBarString(int scrollBarType) { return getText(((scrollBarType == BgListView.SCROLLBAR_INDEXED) ? R.string.indexed_if_possible : ((scrollBarType == BgListView.SCROLLBAR_LARGE) ? R.string.large : ((scrollBarType == BgListView.SCROLLBAR_NONE) ? R.string.none : R.string.system_integrated)))).toString(); } private String getFramesToSkipString() { return Integer.toString(Player.getBluetoothVisualizerFramesPerSecond(Player.getBluetoothVisualizerFramesToSkipIndex())); } private String getSizeString() { return Integer.toString(1 << (2 + Player.getBluetoothVisualizerSize())); } private String getSpeedString() { return Integer.toString(3 - Player.getBluetoothVisualizerSpeed()); } private String getHeadsetHookString(int pressCount) { switch (Player.getHeadsetHookAction(pressCount)) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: return getText(R.string.play) + "/" + getText(R.string.pause); case KeyEvent.KEYCODE_MEDIA_NEXT: return getText(R.string.next).toString(); case KeyEvent.KEYCODE_MEDIA_PREVIOUS: return getText(R.string.previous).toString(); } return getText(R.string.nothing).toString(); } @SuppressWarnings("deprecation") private void prepareHeader(TextView hdr) { hdr.setMaxLines(2); hdr.setEllipsize(TruncateAt.END); hdr.setPadding(UI.controlMargin, UI.controlMargin, UI.controlMargin, UI.controlMargin); if (UI.isLargeScreen) UI.largeText(hdr); else UI.mediumText(hdr); hdr.setTextColor(UI.colorState_text_highlight_static); hdr.setBackgroundDrawable(new ColorDrawable(UI.color_highlight)); } private void addHeader(Context ctx, int resId, SettingView previousControl, int index) { final TextView hdr = new TextView(ctx); hdr.setText(resId); hdr.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); prepareHeader(hdr); headers[index] = hdr; hdr.setTag(index); panelSettings.addView(hdr); if (previousControl != null) { if (UI.is3D) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)previousControl.getLayoutParams(); if (params == null) params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(0, 0, 0, UI.controlSmallMargin); previousControl.setLayoutParams(params); } else { previousControl.setHidingSeparator(true); } } } private SettingView addOption(SettingView view) { if (firstViewAdded == null) firstViewAdded = view; lastViewAdded = view; panelSettings.addView(view); view.setOnClickListener(this); view.setNextFocusLeftId(R.id.btnAbout); view.setNextFocusRightId(R.id.btnGoBack); return view; } private boolean cancelGoBack() { if (colorMode && changed) { checkingReturn = true; UI.prepareDialogAndShow((new AlertDialog.Builder(getHostActivity())) .setTitle(R.string.oops) .setView(UI.createDialogView(getHostActivity(), getText(R.string.discard_theme))) .setPositiveButton(R.string.ok, this) .setNegativeButton(R.string.cancel, null) .create()); return true; } return false; } private int validate() { //hard = -1 //impossible = -2 final int color_list = colorViews[UI.IDX_COLOR_LIST].getColor(); final int color_text_listitem = colorViews[UI.IDX_COLOR_TEXT_LISTITEM].getColor(); final int color_window = colorViews[UI.IDX_COLOR_WINDOW].getColor(); final int color_text = colorViews[UI.IDX_COLOR_TEXT].getColor(); final int color_selected_grad_lt = colorViews[UI.IDX_COLOR_SELECTED_GRAD_LT].getColor(); final int color_selected_grad_dk = colorViews[UI.IDX_COLOR_SELECTED_GRAD_DK].getColor(); final int color_text_selected = colorViews[UI.IDX_COLOR_TEXT_SELECTED].getColor(); final int color_menu = colorViews[UI.IDX_COLOR_MENU].getColor(); final int color_text_menu = colorViews[UI.IDX_COLOR_TEXT_MENU].getColor(); final int color_highlight = colorViews[UI.IDX_COLOR_HIGHLIGHT].getColor(); final int color_text_highlight = colorViews[UI.IDX_COLOR_TEXT_HIGHLIGHT].getColor(); final int color_text_listitem_secondary = colorViews[UI.IDX_COLOR_TEXT_LISTITEM_SECONDARY].getColor(); final double crList = ColorUtils.contrastRatio(color_list, color_text_listitem); final double crWindow = ColorUtils.contrastRatio(color_window, color_text); final double crSel = ColorUtils.contrastRatio(ColorUtils.blend(color_selected_grad_lt, color_selected_grad_dk, 0.5f), color_text_selected); final double crMenu = ColorUtils.contrastRatio(color_menu, color_text_menu); if (crList < MIN_THRESHOLD || crWindow < MIN_THRESHOLD || crSel < MIN_THRESHOLD || crMenu < MIN_THRESHOLD) return -2; if (crList < 6.5 || crWindow < 6.5 || crSel < 6.5 || crMenu < 6.5) return -1; //these colors are considered nonessential, therefore their thresholds are lower, //and only warnings are generated when they are violated final double crHighlight = ColorUtils.contrastRatio(color_highlight, color_text_highlight); final double crListSecondary = ColorUtils.contrastRatio(color_list, color_text_listitem_secondary); if (crHighlight < 5 || crListSecondary < 5) return -1; return 0; } private void applyTheme(View sourceView) { final byte[] colors = UI.serializeThemeToArray(); for (int i = 0; i < colorViews.length; i++) UI.serializeThemeColor(colors, i * 3, colorViews[i].getColor()); UI.customColors = colors; UI.setTheme(getHostActivity(), UI.THEME_CUSTOM); changed = false; finish(0, sourceView, true); } private void loadColors(boolean createControls, boolean forceCurrent) { final Context ctx = getHostActivity(); final int[] colorOrder = new int[] { UI.IDX_COLOR_DIVIDER, UI.IDX_COLOR_TEXT_HIGHLIGHT, UI.IDX_COLOR_HIGHLIGHT, UI.IDX_COLOR_TEXT, UI.IDX_COLOR_TEXT_DISABLED, UI.IDX_COLOR_WINDOW, UI.IDX_COLOR_CONTROL_MODE, UI.IDX_COLOR_VISUALIZER, UI.IDX_COLOR_TEXT_LISTITEM, UI.IDX_COLOR_TEXT_LISTITEM_SECONDARY, UI.IDX_COLOR_LIST, UI.IDX_COLOR_TEXT_MENU, UI.IDX_COLOR_MENU_BORDER, UI.IDX_COLOR_MENU_ICON, UI.IDX_COLOR_MENU, UI.IDX_COLOR_TEXT_SELECTED, UI.IDX_COLOR_SELECTED_BORDER, UI.IDX_COLOR_SELECTED_GRAD_LT, UI.IDX_COLOR_SELECTED_GRAD_DK, UI.IDX_COLOR_SELECTED_PRESSED, UI.IDX_COLOR_FOCUSED_BORDER, UI.IDX_COLOR_FOCUSED_GRAD_LT, UI.IDX_COLOR_FOCUSED_GRAD_DK, UI.IDX_COLOR_FOCUSED_PRESSED }; final byte[] colors = ((UI.customColors != null && UI.customColors.length >= 72 && !forceCurrent) ? UI.customColors : UI.serializeThemeToArray()); if (createControls) colorViews = new SettingView[colorOrder.length]; for (int i = 0; i < colorOrder.length; i++) { final int idx = colorOrder[i]; if (createControls) colorViews[idx] = new SettingView(ctx, null, UI.getThemeColorDescription(ctx, idx).toString(), null, false, false, true); colorViews[idx].setColor(UI.deserializeThemeColor(colors, idx * 3)); } if (createControls) { optLoadCurrentTheme = new SettingView(ctx, UI.ICON_THEME, getText(R.string.load_colors_from_current_theme).toString(), null, false, false, false); int hIdx = 0; headers = new TextView[6]; addHeader(ctx, R.string.color_theme, optLoadCurrentTheme, hIdx++); addOption(optLoadCurrentTheme); for (int i = 0; i < colorOrder.length; i++) { final int idx = colorOrder[i]; switch (i) { case 0: addHeader(ctx, R.string.general, optLoadCurrentTheme, hIdx++); break; case 8: addHeader(ctx, R.string.list2, colorViews[colorOrder[i - 1]], hIdx++); break; case 11: addHeader(ctx, R.string.menu, colorViews[colorOrder[i - 1]], hIdx++); break; case 15: addHeader(ctx, R.string.selection, colorViews[colorOrder[i - 1]], hIdx++); break; case 20: addHeader(ctx, R.string.keyboard_focus, colorViews[colorOrder[i - 1]], hIdx++); break; } //don't show this to the user as it is not atually being used... if (idx != UI.IDX_COLOR_TEXT_DISABLED) addOption(colorViews[idx]); } lblTitle.setVisibility(View.GONE); currentHeader = -1; } } @Override public boolean onBackPressed() { return cancelGoBack(); } private void setListPadding() { //for lblTitle to look nice, we must have no paddings if (panelSettings != null) UI.prepareViewPaddingForLargeScreen(panelSettings, 0, 0); if (lblTitle != null) { final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)lblTitle.getLayoutParams(); lp.leftMargin = UI.getViewPaddingForLargeScreen(); lp.rightMargin = lp.leftMargin; lblTitle.setLayoutParams(lp); } } private void refreshBluetoothStatus(boolean postAgain) { if (optBtMessage == null) return; if (Player.bluetoothVisualizerLastErrorMessage != 0) { btErrorMessage = Player.bluetoothVisualizerLastErrorMessage; Player.bluetoothVisualizerLastErrorMessage = 0; BackgroundActivityMonitor.bluetoothEnded(); } if (Player.bluetoothVisualizerController != null) { btErrorMessage = 0; if (Player.bluetoothVisualizerState == Player.BLUETOOTH_VISUALIZER_STATE_CONNECTING) { if (btMessageText != R.string.bt_scanning) { btMessageText = R.string.bt_scanning; optBtMessage.setText(getText(R.string.bt_scanning).toString()); } } else { btMessageText = 0; optBtMessage.setText(getText(R.string.bt_packets_sent).toString() + " " + ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).getPacketsSent()); } } else { if (btErrorMessage != 0) { if (btMessageText != btErrorMessage) { btMessageText = btErrorMessage; optBtMessage.setText(getText(btErrorMessage).toString()); } } else if (btMessageText != R.string.bt_inactive) { btMessageText = R.string.bt_inactive; optBtMessage.setText(getText(R.string.bt_inactive).toString()); } } if (optBtConnect != null && optBtStart != null) { switch (Player.bluetoothVisualizerState) { case Player.BLUETOOTH_VISUALIZER_STATE_CONNECTED: case Player.BLUETOOTH_VISUALIZER_STATE_TRANSMITTING: if (btConnectText != R.string.bt_disconnect) { btConnectText = R.string.bt_disconnect; optBtConnect.setText(getText(R.string.bt_disconnect).toString()); } if (Player.bluetoothVisualizerState == Player.BLUETOOTH_VISUALIZER_STATE_TRANSMITTING) { if (btStartText != R.string.bt_stop) { btStartText = R.string.bt_stop; optBtStart.setText(getText(R.string.bt_stop).toString()); optBtStart.setIcon(UI.ICON_PAUSE); } } else { if (btStartText != R.string.bt_start) { btStartText = R.string.bt_start; optBtStart.setText(getText(R.string.bt_start).toString()); optBtStart.setIcon(UI.ICON_PLAY); } } break; default: if (btConnectText != R.string.bt_connect) { btConnectText = R.string.bt_connect; optBtConnect.setText(getText(R.string.bt_connect).toString()); } if (btStartText != R.string.bt_start) { btStartText = R.string.bt_start; optBtStart.setText(getText(R.string.bt_start).toString()); optBtStart.setIcon(UI.ICON_PLAY); } break; } } if (postAgain) MainHandler.postToMainThreadDelayed(this, 1000); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (!bluetoothMode || optBtConnect == null) return; if (requestCode == BluetoothConnectionManager.REQUEST_ENABLE && resultCode == Activity.RESULT_OK) onClick(startTransmissionOnConnection ? optBtStart : optBtConnect); } @SuppressWarnings("deprecation") @Override protected void onCreateLayout(boolean firstCreation) { setContentView(R.layout.activity_settings); btnGoBack = (BgButton)findViewById(R.id.btnGoBack); btnGoBack.setOnClickListener(this); btnGoBack.setIcon(UI.ICON_GOBACK); btnBluetooth = (BgButton)findViewById(R.id.btnBluetooth); btnBluetooth.setOnClickListener(this); btnAbout = (BgButton)findViewById(R.id.btnAbout); btnAbout.setOnClickListener(this); boolean showBluetooth = false; if (colorMode) { btnAbout.setText(R.string.apply_theme); } else if (bluetoothMode) { btnAbout.setText(R.string.tutorial); btnAbout.setCompoundDrawables(new TextIconDrawable(UI.ICON_LINK, UI.colorState_text_visualizer_reactive.getDefaultColor(), UI.defaultControlContentsSize), null, null, null); } else { try { showBluetooth = (BluetoothAdapter.getDefaultAdapter() != null); } catch (Throwable ex) { ex.printStackTrace(); } if (showBluetooth) { btnBluetooth.setIcon(UI.ICON_BLUETOOTH); final TextView sep = (TextView)findViewById(R.id.sep); final RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(UI.strokeSize, UI.defaultControlContentsSize); rp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); rp.addRule(RelativeLayout.LEFT_OF, R.id.btnAbout); rp.leftMargin = UI.controlMargin; rp.rightMargin = UI.controlMargin; sep.setLayoutParams(rp); sep.setBackgroundDrawable(new ColorDrawable(UI.color_highlight)); sep.setVisibility(View.VISIBLE); btnBluetooth.setVisibility(View.VISIBLE); } btnAbout.setCompoundDrawables(new TextIconDrawable(UI.ICON_INFORMATION, UI.color_text, UI.defaultControlContentsSize), null, null, null); } btnGoBack.setNextFocusDownId(2); btnBluetooth.setNextFocusDownId(2); btnAbout.setNextFocusDownId(2); btnAbout.setNextFocusRightId(2); UI.setNextFocusForwardId(btnAbout, 2); btnGoBack.setNextFocusUpId(3); btnBluetooth.setNextFocusUpId(3); btnAbout.setNextFocusUpId(3); btnGoBack.setNextFocusLeftId(3); if (!showBluetooth) { UI.setNextFocusForwardId(btnGoBack, R.id.btnAbout); btnGoBack.setNextFocusRightId(R.id.btnAbout); btnAbout.setNextFocusLeftId(R.id.btnGoBack); } else { UI.setNextFocusForwardId(btnGoBack, R.id.btnBluetooth); btnGoBack.setNextFocusRightId(R.id.btnBluetooth); btnAbout.setNextFocusLeftId(R.id.btnBluetooth); } lastColorView = -1; final Context ctx = getHostActivity(); list = (ObservableScrollView)findViewById(R.id.list); list.setHorizontalFadingEdgeEnabled(false); list.setVerticalFadingEdgeEnabled(false); list.setFadingEdgeLength(0); if (!UI.isLargeScreen) UI.offsetTopEdgeEffect(list); //for lblTitle to look nice, we must have no paddings list.setBackgroundDrawable(new ColorDrawable(UI.color_list_bg)); panelControls = (RelativeLayout)findViewById(R.id.panelControls); panelSettings = (LinearLayout)findViewById(R.id.panelSettings); lblTitle = (TextView)findViewById(R.id.lblTitle); prepareHeader(lblTitle); if (UI.isLargeScreen) setListPadding(); list.setOnScrollListener(this); if (colorMode) { loadColors(true, false); } else if (bluetoothMode) { optBtMessage = new SettingView(ctx, UI.ICON_INFORMATION, "", null, false, false, false); optBtConnect = new SettingView(ctx, UI.ICON_BLUETOOTH, "", null, false, false, false); optBtStart = new SettingView(ctx, Player.bluetoothVisualizerState == Player.BLUETOOTH_VISUALIZER_STATE_TRANSMITTING ? UI.ICON_PAUSE : UI.ICON_PLAY, "", null, false, false, false); optBtFramesToSkip = new SettingView(ctx, UI.ICON_CLOCK, getText(R.string.bt_fps).toString(), getFramesToSkipString(), false, false, false); optBtSize = new SettingView(ctx, UI.ICON_VISUALIZER, getText(R.string.bt_sample_count).toString(), getSizeString(), false, false, false); optBtVUMeter = new SettingView(ctx, UI.ICON_VISUALIZER, getText(R.string.bt_vumeter).toString(), null, true, Player.isBluetoothUsingVUMeter(), false); optBtSpeed = new SettingView(ctx, UI.ICON_VISUALIZER, getText(R.string.sustain).toString(), getSpeedString(), false, false, false); refreshBluetoothStatus(true); headers = new TextView[3]; addHeader(ctx, R.string.information, optBtMessage, 0); addOption(optBtMessage); addHeader(ctx, R.string.general, optBtMessage, 1); addOption(optBtConnect); addOption(optBtStart); addHeader(ctx, R.string.settings, optBtStart, 2); //addOption(optBtVUMeter); addOption(optBtFramesToSkip); addOption(optBtSize); addOption(optBtSpeed); currentHeader = -1; } else { if (!UI.isCurrentLocaleCyrillic()) { optUseAlternateTypeface = new SettingView(ctx, UI.ICON_DYSLEXIA, getText(R.string.opt_use_alternate_typeface).toString(), null, true, UI.isUsingAlternateTypeface, false); } optAutoTurnOff = new SettingView(ctx, UI.ICON_CLOCK, getText(R.string.opt_auto_turn_off).toString(), getAutoTurnOffString(), false, false, false); optAutoIdleTurnOff = new SettingView(ctx, UI.ICON_CLOCK, getText(R.string.opt_auto_idle_turn_off).toString(), getAutoIdleTurnOffString(), false, false, false); optAutoTurnOffPlaylist = new SettingView(ctx, UI.ICON_REPEATNONE, getText(R.string.opt_auto_turn_off_playlist).toString(), null, true, Player.turnOffWhenPlaylistEnds, false); optKeepScreenOn = new SettingView(ctx, UI.ICON_SCREEN, getText(R.string.opt_keep_screen_on).toString(), null, true, UI.keepScreenOn, false); optTheme = new SettingView(ctx, UI.ICON_THEME, getText(R.string.color_theme).toString() + UI.collonNoSpace(), UI.getThemeString(ctx, UI.theme), false, false, false); optFlat = new SettingView(ctx, UI.ICON_FLAT, getText(R.string.flat_details).toString(), null, true, UI.isFlat, false); optBorders = new SettingView(ctx, UI.ICON_TRANSPARENT, getText(R.string.borders).toString(), null, true, UI.hasBorders, false); optPlayWithLongPress = new SettingView(ctx, UI.ICON_PLAY, getText(R.string.play_with_long_press).toString(), null, true, UI.playWithLongPress, false); optExpandSeekBar = new SettingView(ctx, UI.ICON_SEEKBAR, getText(R.string.expand_seek_bar).toString(), null, true, UI.expandSeekBar, false); optVolumeControlType = new SettingView(ctx, UI.ICON_VOLUME4, getText(R.string.opt_volume_control_type).toString(), getVolumeString(), false, false, false); optDoNotAttenuateVolume = new SettingView(ctx, UI.ICON_INFORMATION, getText(R.string.opt_do_not_attenuate_volume).toString(), null, true, Player.doNotAttenuateVolume, false); opt3D = new SettingView(ctx, UI.ICON_DIVIDER, "3D", null, true, UI.is3D, false); optIsDividerVisible = new SettingView(ctx, UI.ICON_DIVIDER, getText(R.string.opt_is_divider_visible).toString(), null, true, UI.isDividerVisible, false); optIsVerticalMarginLarge = new SettingView(ctx, UI.ICON_SPACELIST, getText(R.string.opt_is_vertical_margin_large).toString(), null, true, UI.isVerticalMarginLarge, false); optExtraSpacing = new SettingView(ctx, UI.ICON_SPACEHEADER, getText(R.string.opt_extra_spacing).toString(), null, true, UI.extraSpacing, false); if (!UI.isLargeScreen) optPlaceTitleAtTheBottom = new SettingView(ctx, UI.ICON_SPACEHEADER, getText(R.string.place_title_at_the_bottom).toString(), null, true, UI.placeTitleAtTheBottom, false); optForcedLocale = new SettingView(ctx, UI.ICON_LANGUAGE, getText(R.string.opt_language).toString(), UI.getLocaleDescriptionFromCode(ctx, UI.forcedLocale), false, false, false); if (UI.isLargeScreen) optPlacePlaylistToTheRight = new SettingView(ctx, UI.ICON_HAND, getText(R.string.place_the_playlist_to_the_right).toString(), null, true, UI.controlsToTheLeft, false); optScrollBarToTheLeft = new SettingView(ctx, UI.ICON_HAND, getText(R.string.scrollbar_to_the_left).toString(), null, true, UI.scrollBarToTheLeft, false); optScrollBarSongList = new SettingView(ctx, UI.ICON_SCROLLBAR, getText(R.string.scrollbar_playlist).toString(), getScrollBarString(UI.songListScrollBarType), false, false, false); optScrollBarBrowser = new SettingView(ctx, UI.ICON_SCROLLBAR, getText(R.string.scrollbar_browser_type).toString(), getScrollBarString(UI.browserScrollBarType), false, false, false); optWidgetTransparentBg = new SettingView(ctx, UI.ICON_TRANSPARENT, getText(R.string.transparent_background).toString(), null, true, UI.widgetTransparentBg, false); optWidgetTextColor = new SettingView(ctx, UI.ICON_PALETTE, getText(R.string.text_color).toString(), null, false, false, true); optWidgetTextColor.setColor(UI.widgetTextColor); optWidgetIconColor = new SettingView(ctx, UI.ICON_PALETTE, getText(R.string.icon_color).toString(), null, false, false, true); optWidgetIconColor.setColor(UI.widgetIconColor); optHandleCallKey = new SettingView(ctx, UI.ICON_DIAL, getText(R.string.opt_handle_call_key).toString(), null, true, Player.handleCallKey, false); optHeadsetHook1 = new SettingView(ctx, UI.ICON_HEADSETHOOK1, getText(R.string.headset_hook_1).toString(), getHeadsetHookString(1), false, false, false); optHeadsetHook2 = new SettingView(ctx, UI.ICON_HEADSETHOOK2, getText(R.string.headset_hook_2).toString(), getHeadsetHookString(2), false, false, false); optHeadsetHook3 = new SettingView(ctx, UI.ICON_HEADSETHOOK3, getText(R.string.headset_hook_3).toString(), getHeadsetHookString(3), false, false, false); optPlayWhenHeadsetPlugged = new SettingView(ctx, UI.ICON_HEADSET, getText(R.string.opt_play_when_headset_plugged).toString(), null, true, Player.playWhenHeadsetPlugged, false); optBlockBackKey = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_block_back_key).toString(), null, true, UI.blockBackKey, false); optBackKeyAlwaysReturnsToPlayerWhenBrowsing = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_back_key_always_returns_to_player_when_browsing).toString(), null, true, UI.backKeyAlwaysReturnsToPlayerWhenBrowsing, false); optWrapAroundList = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_wrap_around_list).toString(), null, true, UI.wrapAroundList, false); optDoubleClickMode = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_double_click_mode).toString(), null, true, UI.doubleClickMode, false); optMarqueeTitle = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_marquee_title).toString(), null, true, UI.marqueeTitle, false); optPrepareNext = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_prepare_next).toString(), null, true, Player.nextPreparationEnabled, false); optClearListWhenPlayingFolders = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_clear_list_when_playing_folders).toString(), null, true, Player.clearListWhenPlayingFolders, false); optGoBackWhenPlayingFolders = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.opt_go_back_when_playing_folders).toString(), null, true, Player.goBackWhenPlayingFolders, false); optExtraInfoMode = new SettingView(ctx, UI.ICON_SETTINGS, getText(R.string.secondary_line_of_text).toString(), getExtraInfoModeString(Song.extraInfoMode), false, false, false); optForceOrientation = new SettingView(ctx, UI.ICON_ORIENTATION, getText(R.string.opt_force_orientation).toString(), getOrientationString(), false, false, false); optTransition = new SettingView(ctx, UI.ICON_TRANSITION, getText(R.string.transition).toString(), UI.getTransitionString(ctx, UI.transition), false, false, false); optAnimations = new SettingView(ctx, UI.ICON_TRANSITION, getText(R.string.animations).toString(), null, true, UI.animationEnabled, false); optNotFullscreen = new SettingView(ctx, UI.ICON_SCREEN, getText(R.string.fullscreen).toString(), null, true, !UI.notFullscreen, false); optFadeInFocus = new SettingView(ctx, UI.ICON_FADE, getText(R.string.opt_fade_in_focus).toString(), getFadeInString(Player.fadeInIncrementOnFocus), false, false, false); optFadeInPause = new SettingView(ctx, UI.ICON_FADE, getText(R.string.opt_fade_in_pause).toString(), getFadeInString(Player.fadeInIncrementOnPause), false, false, false); optFadeInOther = new SettingView(ctx, UI.ICON_FADE, getText(R.string.opt_fade_in_other).toString(), getFadeInString(Player.fadeInIncrementOnOther), false, false, false); optAnnounceCurrentSong = new SettingView(ctx, UI.ICON_MIC, getText(R.string.announce_current_song).toString(), null, true, Player.announceCurrentSong, false); optFollowCurrentSong = new SettingView(ctx, UI.ICON_SCROLLBAR, getText(R.string.follow_current_song).toString(), null, true, Player.followCurrentSong, false); optBytesBeforeDecoding = new SettingView(ctx, UI.ICON_RADIO, getText(R.string.bytes_before_decoding).toString(), getBytesBeforeDecodingString(Player.getBytesBeforeDecodingIndex()), false, false, false); optSecondsBeforePlayback = new SettingView(ctx, UI.ICON_RADIO, getText(R.string.seconds_before_playback).toString(), getSecondsBeforePlaybackString(Player.getSecondsBeforePlaybackIndex()), false, false, false); int hIdx = 0; headers = new TextView[(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) ? 8 : 7]; addHeader(ctx, R.string.msg_turn_off_title, optAutoTurnOffPlaylist, hIdx++); addOption(optAutoTurnOff); addOption(optAutoIdleTurnOff); addOption(optAutoTurnOffPlaylist); addHeader(ctx, R.string.hdr_display, optAutoTurnOffPlaylist, hIdx++); addOption(optKeepScreenOn); addOption(optTheme); addOption(opt3D); addOption(optFlat); addOption(optBorders); if (!UI.is3D) addOption(optIsDividerVisible); addOption(optExtraInfoMode); addOption(optForceOrientation); addOption(optTransition); addOption(optAnimations); addOption(optNotFullscreen); addOption(optIsVerticalMarginLarge); addOption(optExtraSpacing); if (!UI.isLargeScreen) addOption(optPlaceTitleAtTheBottom); if (!UI.isCurrentLocaleCyrillic()) addOption(optUseAlternateTypeface); addOption(optForcedLocale); addHeader(ctx, R.string.accessibility, optForcedLocale, hIdx++); if (UI.isLargeScreen) addOption(optPlacePlaylistToTheRight); addOption(optAnnounceCurrentSong); addOption(optScrollBarToTheLeft); addHeader(ctx, R.string.scrollbar, optScrollBarToTheLeft, hIdx++); addOption(optFollowCurrentSong); addOption(optScrollBarSongList); addOption(optScrollBarBrowser); addHeader(ctx, R.string.widget, optScrollBarBrowser, hIdx++); addOption(optWidgetTransparentBg); addOption(optWidgetTextColor); addOption(optWidgetIconColor); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { addHeader(ctx, R.string.radio, optWidgetIconColor, hIdx++); addOption(optBytesBeforeDecoding); addOption(optSecondsBeforePlayback); } addHeader(ctx, R.string.hdr_playback, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) ? optSecondsBeforePlayback : optWidgetIconColor, hIdx++); addOption(optPlayWhenHeadsetPlugged); addOption(optHandleCallKey); addOption(optHeadsetHook1); addOption(optHeadsetHook2); addOption(optHeadsetHook3); addOption(optPlayWithLongPress); addOption(optExpandSeekBar); addOption(optVolumeControlType); addOption(optDoNotAttenuateVolume); addOption(optFadeInFocus); addOption(optFadeInPause); addOption(optFadeInOther); addHeader(ctx, R.string.hdr_behavior, optFadeInOther, hIdx); addOption(optBackKeyAlwaysReturnsToPlayerWhenBrowsing); addOption(optClearListWhenPlayingFolders); addOption(optGoBackWhenPlayingFolders); addOption(optBlockBackKey); addOption(optWrapAroundList); addOption(optDoubleClickMode); addOption(optMarqueeTitle); addOption(optPrepareNext); lblTitle.setVisibility(View.GONE); currentHeader = -1; } firstViewAdded.setId(2); firstViewAdded.setNextFocusUpId(R.id.btnAbout); firstViewAdded = null; lastViewAdded.setId(3); lastViewAdded.setNextFocusDownId(R.id.btnGoBack); lastViewAdded = null; UI.prepareControlContainer(panelControls, false, UI.isLargeScreen); if (UI.isLargeScreen) btnAbout.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._22sp); btnAbout.setDefaultHeight(); } @Override protected void onPause() { if (!colorMode && !bluetoothMode) Player.turnOffTimerObserver = null; } @Override protected void onResume() { if (!colorMode && !bluetoothMode) { Player.turnOffTimerObserver = this; if (optAutoTurnOff != null) optAutoTurnOff.setSecondaryText(getAutoTurnOffString()); if (optAutoIdleTurnOff != null) optAutoIdleTurnOff.setSecondaryText(getAutoIdleTurnOffString()); } } @Override protected void onOrientationChanged() { if (UI.isLargeScreen) setListPadding(); } @Override protected void onCleanupLayout() { btnGoBack = null; btnBluetooth = null; btnAbout = null; list = null; lblTitle = null; panelControls = null; panelSettings = null; if (headers != null) { for (int i = headers.length - 1; i >= 0; i headers[i] = null; headers = null; } optLoadCurrentTheme = null; optUseAlternateTypeface = null; optAutoTurnOff = null; optAutoIdleTurnOff = null; optAutoTurnOffPlaylist = null; optKeepScreenOn = null; optTheme = null; optFlat = null; optBorders = null; optPlayWithLongPress = null; optExpandSeekBar = null; optVolumeControlType = null; optDoNotAttenuateVolume = null; opt3D = null; optIsDividerVisible = null; optIsVerticalMarginLarge = null; optExtraSpacing = null; optPlaceTitleAtTheBottom = null; optForcedLocale = null; optPlacePlaylistToTheRight = null; optScrollBarToTheLeft = null; optScrollBarSongList = null; optScrollBarBrowser = null; optWidgetTransparentBg = null; optWidgetTextColor = null; optWidgetIconColor = null; optHandleCallKey = null; optHeadsetHook1 = null; optHeadsetHook2 = null; optHeadsetHook3 = null; optPlayWhenHeadsetPlugged = null; optBlockBackKey = null; optBackKeyAlwaysReturnsToPlayerWhenBrowsing = null; optWrapAroundList = null; optDoubleClickMode = null; optMarqueeTitle = null; optPrepareNext = null; optClearListWhenPlayingFolders = null; optGoBackWhenPlayingFolders = null; optExtraInfoMode = null; optForceOrientation = null; optTransition = null; optAnimations = null; optNotFullscreen = null; optFadeInFocus = null; optFadeInPause = null; optFadeInOther = null; optBtMessage = null; optBtConnect = null; optBtStart = null; optBtFramesToSkip = null; optBtSize = null; optBtVUMeter = null; optBtSpeed = null; optAnnounceCurrentSong = null; optFollowCurrentSong = null; optBytesBeforeDecoding = null; optSecondsBeforePlayback = null; lastMenuView = null; if (colorViews != null) { for (int i = colorViews.length - 1; i >= 0; i colorViews[i] = null; colorViews = null; } } @Override protected void onDestroy() { if (!colorMode && !bluetoothMode && configsChanged) MainHandler.postToMainThread(this); } @Override public void onClick(View view) { if (view == btnGoBack) { if (!cancelGoBack()) finish(0, view, true); return; } if (view == btnBluetooth && !colorMode && !bluetoothMode) { try { getHostActivity().startActivity(new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS)); } catch (Throwable ex) { ex.printStackTrace(); } return; } if (colorViews != null) { for (int i = colorViews.length - 1; i >= 0; i if (view == colorViews[i]) { lastColorView = i; ColorPickerView.showDialog(getHostActivity(), colorViews[i].getColor(), null, this); return; } } } else if (bluetoothMode) { if (view == btnAbout) { try { getHostActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/carlosrafaelgn/FPlayArduino"))); } catch (Throwable ex) { ex.printStackTrace(); } } else if (view == optBtConnect) { if (Player.bluetoothVisualizerController == null) { startTransmissionOnConnection = false; Player.startBluetoothVisualizer(getHostActivity(), false); refreshBluetoothStatus(false); } else if (Player.bluetoothVisualizerState != Player.BLUETOOTH_VISUALIZER_STATE_CONNECTING) { Player.stopBluetoothVisualizer(); refreshBluetoothStatus(false); } } else if (view == optBtStart) { if (Player.bluetoothVisualizerController != null) { switch (Player.bluetoothVisualizerState) { case Player.BLUETOOTH_VISUALIZER_STATE_CONNECTED: ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).startTransmission(); refreshBluetoothStatus(false); break; case Player.BLUETOOTH_VISUALIZER_STATE_TRANSMITTING: ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).stopTransmission(); refreshBluetoothStatus(false); break; } } else if (Player.bluetoothVisualizerState != Player.BLUETOOTH_VISUALIZER_STATE_CONNECTING) { startTransmissionOnConnection = true; Player.startBluetoothVisualizer(getHostActivity(), true); refreshBluetoothStatus(false); } } else if (view == optBtVUMeter) { Player.setBluetoothUsingVUMeter(optBtVUMeter.isChecked()); if (Player.bluetoothVisualizerController != null) ((BluetoothVisualizerControllerJni)Player.bluetoothVisualizerController).syncDataType(); } else if (view == optBtSize || view == optBtSpeed || view == optBtFramesToSkip) { CustomContextMenu.openContextMenu(view, this); } return; } if (view == optLoadCurrentTheme) { if (colorMode) loadColors(false, true); } else if (view == btnAbout) { if (colorMode) { checkingReturn = false; switch (validate()) { case -1: UI.prepareDialogAndShow((new AlertDialog.Builder(getHostActivity())) .setTitle(R.string.oops) .setView(UI.createDialogView(getHostActivity(), getText(R.string.hard_theme))) .setPositiveButton(R.string.ok, this) .setNegativeButton(R.string.cancel, null) .create()); return; case -2: UI.prepareDialogAndShow((new AlertDialog.Builder(getHostActivity())) .setTitle(R.string.oops) .setView(UI.createDialogView(getHostActivity(), getText(R.string.unreadable_theme))) .setPositiveButton(R.string.got_it, null) .create()); return; } applyTheme(view); } else { startActivity(new ActivityAbout(), 0, view, true); } } else if (!UI.isCurrentLocaleCyrillic() && view == optUseAlternateTypeface) { final boolean desired = optUseAlternateTypeface.isChecked(); UI.setUsingAlternateTypeface(getHostActivity(), desired); if (UI.isUsingAlternateTypeface != desired) { optUseAlternateTypeface.setChecked(UI.isUsingAlternateTypeface); } else { onCleanupLayout(); onCreateLayout(false); System.gc(); } } else if (view == optKeepScreenOn) { UI.keepScreenOn = optKeepScreenOn.isChecked(); if (UI.keepScreenOn) addWindowFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); else clearWindowFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else if (view == optNotFullscreen) { UI.notFullscreen = !optNotFullscreen.isChecked(); if (UI.notFullscreen) clearWindowFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); else addWindowFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else if (view == opt3D) { UI.is3D = opt3D.isChecked(); UI.updateColorListBg(); onCleanupLayout(); onCreateLayout(false); System.gc(); } else if (view == optIsDividerVisible) { UI.isDividerVisible = optIsDividerVisible.isChecked(); if (!UI.is3D) { for (int i = panelSettings.getChildCount() - 1; i >= 0; i final View v = panelSettings.getChildAt(i); if (v != null && (v instanceof SettingView)) v.invalidate(); } } } else if (view == optIsVerticalMarginLarge) { final int oldVerticalMargin = UI.verticalMargin; UI.setVerticalMarginLarge(optIsVerticalMarginLarge.isChecked()); for (int i = panelSettings.getChildCount() - 1; i >= 0; i final View v = panelSettings.getChildAt(i); if (v != null && (v instanceof SettingView)) ((SettingView)v).updateVerticalMargin(oldVerticalMargin); } } else if (view == optExtraSpacing) { UI.extraSpacing = optExtraSpacing.isChecked(); onCleanupLayout(); onCreateLayout(false); System.gc(); } else if (view == optPlaceTitleAtTheBottom) { UI.placeTitleAtTheBottom = optPlaceTitleAtTheBottom.isChecked(); } else if (view == optFlat) { UI.setFlat(optFlat.isChecked()); //onCleanupLayout(); //onCreateLayout(false); System.gc(); } else if (view == optBorders) { UI.hasBorders = optBorders.isChecked(); } else if (view == optHandleCallKey) { Player.handleCallKey = optHandleCallKey.isChecked(); } else if (view == optPlayWhenHeadsetPlugged) { Player.playWhenHeadsetPlugged = optPlayWhenHeadsetPlugged.isChecked(); } else if (view == optPlacePlaylistToTheRight) { UI.controlsToTheLeft = optPlacePlaylistToTheRight.isChecked(); } else if (view == optScrollBarToTheLeft) { UI.scrollBarToTheLeft = optScrollBarToTheLeft.isChecked(); list.updateVerticalScrollbar(); } else if (view == optWidgetTransparentBg) { UI.widgetTransparentBg = optWidgetTransparentBg.isChecked(); WidgetMain.updateWidgets(getApplication()); } else if (view == optWidgetTextColor) { ColorPickerView.showDialog(getHostActivity(), UI.widgetTextColor, view, this); } else if (view == optWidgetIconColor) { ColorPickerView.showDialog(getHostActivity(), UI.widgetIconColor, view, this); } else if (view == optBlockBackKey) { UI.blockBackKey = optBlockBackKey.isChecked(); } else if (view == optBackKeyAlwaysReturnsToPlayerWhenBrowsing) { UI.backKeyAlwaysReturnsToPlayerWhenBrowsing = optBackKeyAlwaysReturnsToPlayerWhenBrowsing.isChecked(); } else if (view == optWrapAroundList) { UI.wrapAroundList = optWrapAroundList.isChecked(); } else if (view == optDoubleClickMode) { UI.doubleClickMode = optDoubleClickMode.isChecked(); } else if (view == optDoNotAttenuateVolume) { Player.doNotAttenuateVolume = optDoNotAttenuateVolume.isChecked(); } else if (view == optMarqueeTitle) { UI.marqueeTitle = optMarqueeTitle.isChecked(); } else if (view == optPrepareNext) { Player.nextPreparationEnabled = optPrepareNext.isChecked(); } else if (view == optClearListWhenPlayingFolders) { Player.clearListWhenPlayingFolders = optClearListWhenPlayingFolders.isChecked(); } else if (view == optGoBackWhenPlayingFolders) { Player.goBackWhenPlayingFolders = optGoBackWhenPlayingFolders.isChecked(); } else if (view == optPlayWithLongPress) { UI.playWithLongPress = optPlayWithLongPress.isChecked(); } else if (view == optExpandSeekBar) { UI.expandSeekBar = optExpandSeekBar.isChecked(); } else if (view == optAnimations) { UI.animationEnabled = optAnimations.isChecked(); } else if (view == optAutoTurnOffPlaylist) { Player.turnOffWhenPlaylistEnds = optAutoTurnOffPlaylist.isChecked(); } else if (view == optAnnounceCurrentSong) { Player.announceCurrentSong = optAnnounceCurrentSong.isChecked(); } else if (view == optFollowCurrentSong) { Player.followCurrentSong = optFollowCurrentSong.isChecked(); } else if (view == optAutoTurnOff || view == optAutoIdleTurnOff || view == optTheme || view == optForcedLocale || view == optVolumeControlType || view == optExtraInfoMode || view == optForceOrientation || view == optTransition || view == optFadeInFocus || view == optFadeInPause || view == optFadeInOther || view == optScrollBarSongList || view == optScrollBarBrowser || view == optHeadsetHook1 || view == optHeadsetHook2 || view == optHeadsetHook3 || view == optBytesBeforeDecoding || view == optSecondsBeforePlayback) { lastMenuView = null; CustomContextMenu.openContextMenu(view, this); return; } configsChanged = true; } @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { if (colorMode) { if (checkingReturn) { changed = false; finish(0, null, false); } else { applyTheme(null); } } else if (txtCustomMinutes != null) { try { int m = Integer.parseInt(txtCustomMinutes.getText().toString()); configsChanged = true; if (lastMenuView == optAutoTurnOff) { Player.setTurnOffTimer(m); optAutoTurnOff.setSecondaryText(getAutoTurnOffString()); } else { Player.setIdleTurnOffTimer(m); optAutoIdleTurnOff.setSecondaryText(getAutoIdleTurnOffString()); } } catch (Throwable ex) { ex.printStackTrace(); } txtCustomMinutes = null; } } } @Override public void onPlayerTurnOffTimerTick() { if (optAutoTurnOff != null) optAutoTurnOff.setSecondaryText(getAutoTurnOffString()); } @Override public void onPlayerIdleTurnOffTimerTick() { if (optAutoIdleTurnOff != null) optAutoIdleTurnOff.setSecondaryText(getAutoIdleTurnOffString()); } private void validateColor(int idx1, int idx2) { final boolean err = (ColorUtils.contrastRatio((idx1 == UI.IDX_COLOR_SELECTED_GRAD_LT) ? ColorUtils.blend(colorViews[UI.IDX_COLOR_SELECTED_GRAD_LT].getColor(), colorViews[UI.IDX_COLOR_SELECTED_GRAD_DK].getColor(), 0.5f) : colorViews[idx1].getColor(), colorViews[idx2].getColor()) < MIN_THRESHOLD); colorViews[idx1].showErrorView(err); colorViews[idx2].showErrorView(err); if (idx1 == UI.IDX_COLOR_SELECTED_GRAD_LT) colorViews[UI.IDX_COLOR_SELECTED_GRAD_DK].showErrorView(err); } @Override public void onColorPicked(ColorPickerView picker, View parentView, int color) { if (colorMode && lastColorView >= 0) { if (colorViews[lastColorView].getColor() != color) { changed = true; colorViews[lastColorView].setColor(color); switch (lastColorView) { case UI.IDX_COLOR_WINDOW: case UI.IDX_COLOR_TEXT: validateColor(UI.IDX_COLOR_WINDOW, UI.IDX_COLOR_TEXT); break; case UI.IDX_COLOR_LIST: case UI.IDX_COLOR_TEXT_LISTITEM: validateColor(UI.IDX_COLOR_LIST, UI.IDX_COLOR_TEXT_LISTITEM); break; case UI.IDX_COLOR_SELECTED_GRAD_LT: case UI.IDX_COLOR_SELECTED_GRAD_DK: case UI.IDX_COLOR_TEXT_SELECTED: validateColor(UI.IDX_COLOR_SELECTED_GRAD_LT, UI.IDX_COLOR_TEXT_SELECTED); break; case UI.IDX_COLOR_MENU: case UI.IDX_COLOR_TEXT_MENU: validateColor(UI.IDX_COLOR_MENU, UI.IDX_COLOR_TEXT_MENU); break; } } lastColorView = -1; } else if (parentView == optWidgetTextColor) { UI.widgetTextColor = color; optWidgetTextColor.setColor(color); WidgetMain.updateWidgets(getApplication()); } else if (parentView == optWidgetIconColor) { UI.widgetIconColor = color; optWidgetIconColor.setColor(color); WidgetMain.updateWidgets(getApplication()); } } @Override public void onScroll(ObservableScrollView view, int l, int t, int oldl, int oldt) { if (headers == null || panelSettings == null || lblTitle == null || oldt == t) return; if (t < 0) t = 0; int i = view.getPreviousChildIndexWithClass(TextView.class, t); if (i <= 0) { if (t == 0) { currentHeader = -1; lblTitle.setVisibility(View.GONE); return; } else { i = 0; } } i = (Integer)panelSettings.getChildAt(i).getTag(); if (currentHeader < 0) { lblTitle.setVisibility(View.VISIBLE); lblTitle.bringToFront(); //neat workaround to partially hide lblTitle ;) panelControls.bringToFront(); } if (currentHeader != i) { currentHeader = i; lblTitle.setText(headers[i].getText()); } RelativeLayout.LayoutParams lp; if (i < (headers.length - 1) && headers[i + 1].getTop() < (t + lblTitle.getHeight())) { lp = (RelativeLayout.LayoutParams)lblTitle.getLayoutParams(); lp.topMargin = headers[i + 1].getTop() - (t + lblTitle.getHeight()); lblTitle.setLayoutParams(lp); lblTitleOk = false; } else if (!lblTitleOk) { lp = (RelativeLayout.LayoutParams)lblTitle.getLayoutParams(); lp.topMargin = 0; lblTitle.setLayoutParams(lp); lblTitleOk = true; } } @Override public void run() { if (bluetoothMode) refreshBluetoothStatus(true); else if (Player.state < Player.STATE_TERMINATING && Player.getService() != null) Player.saveConfig(Player.getService(), false); } }
package br.ufrn.imd.netfrix.view; import java.sql.ResultSet; import java.sql.SQLException; import br.ufrn.imd.netfrix.MainApp; import br.ufrn.imd.netfrix.util.DataBase; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; public class LoginViewController { @FXML private TextField txtEmail; @FXML private TextField txtPassword; @FXML private Button btnLogin; @FXML private Label loginMsgError; private MainApp mainApp; public LoginViewController() { } @FXML private void handleLoginClick() throws ClassNotFoundException, SQLException { String email = this.txtEmail.getText(); String password = this.txtPassword.getText(); System.out.println(email); System.out.println(password); tryLogin(email, password); } public void tryLogin(String email, String password) throws SQLException, ClassNotFoundException { String query = "SELECT id FROM users WHERE email = '" + email + "' AND password = '" + password + "'"; try { ResultSet result = DataBase.dbExecuteQuery(query); if (result.next()) { loginMsgError.setText("Login feito com sucesso!"); } else { loginMsgError.setText("Ops, informações erradas"); } } catch (SQLException e) { System.out.println("While searching an user with " + email + " email, an error occurred: " + e); throw e; } } public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; } }
package org.jboss.aerogear.unifiedpush.rest.config; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.OPTIONS; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.jboss.aerogear.unifiedpush.rest.AbstractEndpoint; import org.jboss.aerogear.unifiedpush.rest.authentication.AuthenticationHelper; import org.jboss.aerogear.unifiedpush.service.impl.spring.IConfigurationService; import org.keycloak.representations.adapters.config.AdapterConfig; import org.keycloak.util.SystemPropertiesJsonParserFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Configuration endpoint to aerobase client applications */ @Controller @Path("/keycloak/config") public class KeycloakConfigurationEndpoint extends AbstractEndpoint { private static final Logger logger = LoggerFactory.getLogger(AuthenticationHelper.class); @Inject private IConfigurationService configurationService; @OPTIONS public Response crossOriginForApplication(@Context HttpHeaders headers) { return appendPreflightResponseHeaders(headers, Response.ok()).build(); } @OPTIONS @Path("/gsg") public Response crossOriginForGsgApplication(@Context HttpHeaders headers) { return appendPreflightResponseHeaders(headers, Response.ok()).build(); } /* * Default unifiedpush-server (aerobase-app). */ @GET @Produces(MediaType.APPLICATION_JSON) public Response configurationFile(@Context HttpHeaders headers) { Long timestamp = System.currentTimeMillis(); ObjectMapper mapper = new ObjectMapper(new SystemPropertiesJsonParserFactory()); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); AdapterConfig adapterConfig = new AdapterConfig(); adapterConfig.setRealm(configurationService.getUpsRealm()); adapterConfig.setAuthServerUrl(configurationService.getOAuth2Url()); // When Running using http, allow none https requests adapterConfig.setSslRequired(configurationService.getOAuth2Url().startsWith("https") ? "external" : "none"); adapterConfig.setPublicClient(true); adapterConfig.setResource("aerobase-app"); logger.debug("Preparing adapterConfig took (" + (System.currentTimeMillis() - timestamp) + ") millis."); try { return appendAllowOriginHeader(headers, Response.ok(mapper.writeValueAsString(adapterConfig))).build(); } catch (JsonProcessingException e) { return Response.serverError().build(); } } /* * Config to aerobase getting starter guide . */ @GET @Path("/gsg") @Produces(MediaType.APPLICATION_JSON) public Response configurationGsgFile(@Context HttpHeaders headers) { ObjectMapper mapper = new ObjectMapper(new SystemPropertiesJsonParserFactory()); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); AdapterConfig adapterConfig = new AdapterConfig(); adapterConfig.setRealm(configurationService.getUpsRealm()); adapterConfig.setAuthServerUrl(configurationService.getOAuth2Url()); // When Running using http, allow none https requests adapterConfig.setSslRequired(configurationService.getOAuth2Url().startsWith("https") ? "external" : "none"); adapterConfig.setPublicClient(true); adapterConfig.setResource("aerobase-gsg"); try { return appendAllowOriginHeader(headers, Response.ok(mapper.writeValueAsString(adapterConfig))).build(); } catch (JsonProcessingException e) { return Response.serverError().build(); } } }
package org.sagebionetworks.table.cluster; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_ETAG; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_ID; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_VERSION; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.dbo.dao.table.TableModelTestUtils; import org.sagebionetworks.repo.model.entity.IdAndVersion; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnMultiValueFunction; import org.sagebionetworks.repo.model.table.ColumnMultiValueFunctionQueryFilter; import org.sagebionetworks.repo.model.table.ColumnSingleValueFilterOperator; import org.sagebionetworks.repo.model.table.ColumnSingleValueQueryFilter; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.FacetType; import org.sagebionetworks.repo.model.table.QueryFilter; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.table.SelectColumn; import org.sagebionetworks.repo.model.table.TextMatchesQueryFilter; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.table.cluster.columntranslation.RowMetadataColumnTranslationReference; import org.sagebionetworks.table.cluster.columntranslation.SchemaColumnTranslationReference; import org.sagebionetworks.table.cluster.description.IndexDescription; import org.sagebionetworks.table.cluster.description.MaterializedViewIndexDescription; import org.sagebionetworks.table.cluster.description.TableIndexDescription; import org.sagebionetworks.table.cluster.description.ViewIndexDescription; import org.sagebionetworks.table.query.ParseException; import org.sagebionetworks.table.query.TableQueryParser; import org.sagebionetworks.table.query.model.ActualIdentifier; import org.sagebionetworks.table.query.model.ArrayHasPredicate; import org.sagebionetworks.table.query.model.BooleanPrimary; import org.sagebionetworks.table.query.model.CharacterStringLiteral; import org.sagebionetworks.table.query.model.ColumnNameReference; import org.sagebionetworks.table.query.model.ColumnReference; import org.sagebionetworks.table.query.model.DerivedColumn; import org.sagebionetworks.table.query.model.ExactNumericLiteral; import org.sagebionetworks.table.query.model.FromClause; import org.sagebionetworks.table.query.model.FunctionReturnType; import org.sagebionetworks.table.query.model.GeneralLiteral; import org.sagebionetworks.table.query.model.GroupByClause; import org.sagebionetworks.table.query.model.HasPredicate; import org.sagebionetworks.table.query.model.InPredicate; import org.sagebionetworks.table.query.model.Pagination; import org.sagebionetworks.table.query.model.Predicate; import org.sagebionetworks.table.query.model.QuerySpecification; import org.sagebionetworks.table.query.model.RegularIdentifier; import org.sagebionetworks.table.query.model.SelectList; import org.sagebionetworks.table.query.model.SqlContext; import org.sagebionetworks.table.query.model.TableNameCorrelation; import org.sagebionetworks.table.query.model.UnsignedLiteral; import org.sagebionetworks.table.query.model.UnsignedNumericLiteral; import org.sagebionetworks.table.query.model.ValueExpressionPrimary; import org.sagebionetworks.table.query.util.SqlElementUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @ExtendWith(MockitoExtension.class) public class SQLTranslatorUtilsTest { private static final String DATE1 = "11-11-11"; private static final String DATE1TIME = "1320969600000"; private static final String DATE2TIME = "1298332800000"; private static final String DATE2 = "11-02-22"; @Mock private ColumnNameReference mockHasQuoteValue; @Mock private ResultSet mockResultSet; @Mock private ColumnLookup mockColumnLookup; @Captor private ArgumentCaptor<ColumnReference> columnRefCapture; ColumnModel columnFoo; ColumnModel columnHasSpace; ColumnModel columnBar; ColumnModel columnId; ColumnModel columnSpecial; ColumnModel columnDouble; ColumnModel columnDate; ColumnModel columnQuoted; List<ColumnModel> schema; private SchemaProvider schemaProvider; private Map<String, ColumnModel> columnNameMap; private TableAndColumnMapper singleTableMapper; List<SelectColumn> selectList; ColumnTypeInfo[] infoArray; Long rowId; Long rowVersion; Long userId; IdAndVersion tableIdAndVersion; String etag; @BeforeEach public void before() throws Exception { columnFoo = TableModelTestUtils.createColumn(111L, "foo", ColumnType.STRING); columnHasSpace = TableModelTestUtils.createColumn(222L, "has space", ColumnType.STRING); columnBar = TableModelTestUtils.createColumn(333L, "bar", ColumnType.STRING); columnId = TableModelTestUtils.createColumn(444L, "id", ColumnType.INTEGER); String specialChars = "Specialchars~!@ columnSpecial = TableModelTestUtils.createColumn(555L, specialChars, ColumnType.DOUBLE); columnDouble = TableModelTestUtils.createColumn(777L, "aDouble", ColumnType.DOUBLE); columnDate = TableModelTestUtils.createColumn(888L, "aDate", ColumnType.DATE); columnQuoted = TableModelTestUtils.createColumn(999L, "colWith\"Quotes\"InIt", ColumnType.STRING); schema = Lists.newArrayList(columnFoo, columnHasSpace, columnBar, columnId, columnSpecial, columnDouble, columnDate, columnQuoted); columnNameMap = schema.stream() .collect(Collectors.toMap(ColumnModel::getName, Function.identity())); schemaProvider = (IdAndVersion tableId) ->{ return schema; }; SelectColumn one = new SelectColumn(); one.setColumnType(ColumnType.STRING); SelectColumn two = new SelectColumn(); two.setColumnType(ColumnType.BOOLEAN); selectList = Lists.newArrayList(one, two); infoArray = SQLTranslatorUtils.getColumnTypeInfoArray(selectList); rowId = 123L; rowVersion = 2L; userId = 1L; etag = "anEtag"; tableIdAndVersion = IdAndVersion.parse("syn123.456"); singleTableMapper = new TableAndColumnMapper(new TableQueryParser("select * from syn123.456").querySpecification(), schemaProvider); } @Test public void testIsNumericType(){ assertFalse(SQLTranslatorUtils.isNumericType(ColumnType.BOOLEAN)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.DATE)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.DOUBLE)); assertFalse(SQLTranslatorUtils.isNumericType(ColumnType.ENTITYID)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.SUBMISSIONID)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.EVALUATIONID)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.FILEHANDLEID)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.INTEGER)); assertFalse(SQLTranslatorUtils.isNumericType(ColumnType.LARGETEXT)); assertFalse(SQLTranslatorUtils.isNumericType(ColumnType.LINK)); assertFalse(SQLTranslatorUtils.isNumericType(ColumnType.STRING)); assertTrue(SQLTranslatorUtils.isNumericType(ColumnType.USERID)); } @Test public void testIsNumericTypeNull(){ assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.isNumericType(null); }); } @Test public void testIsNumericAllTypes(){ // Should work for all types without errors for(ColumnType type: ColumnType.values()){ SQLTranslatorUtils.isNumericType(type); } } @Test public void testGetBaseColulmnTypeNoQuotes(){ when(mockHasQuoteValue.hasQuotesRecursive()).thenReturn(false); // call under test ColumnType type = SQLTranslatorUtils.getBaseColulmnType(mockHasQuoteValue); ColumnType expected = ColumnType.DOUBLE; assertEquals(expected, type); } @Test public void testGetBaseColulmnTypeWithQuotes(){ when(mockHasQuoteValue.hasQuotesRecursive()).thenReturn(true); // call under test ColumnType type = SQLTranslatorUtils.getBaseColulmnType(mockHasQuoteValue); ColumnType expected = ColumnType.STRING; assertEquals(expected, type); } @Test public void testGetSelectColumnsConstantString() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.empty()); DerivedColumn derivedColumn = new TableQueryParser("'constant'").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("constant", results.getName()); assertEquals(ColumnType.STRING, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(null); } @Test public void testGetSelectColumnsConstantDouble() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.empty()); DerivedColumn derivedColumn = new TableQueryParser("1.23").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("1.23", results.getName()); assertEquals(ColumnType.DOUBLE, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(null); } @Test public void testGetSelectColumnsRowIdLower() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(RowMetadataColumnTranslationReference.ROW_ID.getColumnTranslationReference())); DerivedColumn derivedColumn = new TableQueryParser("ROW_ID").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("ROW_ID", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("ROW_ID", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsRowIdUpper() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(RowMetadataColumnTranslationReference.ROW_ID.getColumnTranslationReference())); DerivedColumn derivedColumn = new TableQueryParser("ROW_ID").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("ROW_ID", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("ROW_ID", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsCountRowId() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(RowMetadataColumnTranslationReference.ROW_ID.getColumnTranslationReference())); DerivedColumn derivedColumn = new TableQueryParser("count(row_id)").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("COUNT(row_id)", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("row_id", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsRowVersionUpper() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(RowMetadataColumnTranslationReference.ROW_VERSION.getColumnTranslationReference())); DerivedColumn derivedColumn = new TableQueryParser("ROW_VERSION").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("ROW_VERSION", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("ROW_VERSION", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsCountStar() throws ParseException{ DerivedColumn derivedColumn = new TableQueryParser("count(*)").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("COUNT(*)", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); } @Test public void testGetSelectColumnsCountStarAs() throws ParseException{ DerivedColumn derivedColumn = new TableQueryParser("count(*) as \"has space\"").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("has space", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); } @Test public void testGetSelectColumnsCountNoMatch() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.empty()); DerivedColumn derivedColumn = new TableQueryParser("count(no_match)").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("COUNT(no_match)", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("no_match", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsCountMatch() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnHasSpace))); DerivedColumn derivedColumn = new TableQueryParser("count(`has space`)").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("COUNT(`has space`)", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("`has space`", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsCountMatchAs() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnHasSpace))); DerivedColumn derivedColumn = new TableQueryParser("count(`has space`) as bar").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("bar", results.getName()); assertEquals(ColumnType.INTEGER, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("`has space`", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsSimpleMatch() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnFoo))); DerivedColumn derivedColumn = new TableQueryParser("foo").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("foo", results.getName()); assertEquals(columnFoo.getColumnType(), results.getColumnType()); assertEquals(columnFoo.getId(), results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("foo", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsMatchAs() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnBar))); DerivedColumn derivedColumn = new TableQueryParser("bar as foo").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("foo", results.getName()); assertEquals(columnBar.getColumnType(), results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("bar", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsSum() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnId))); DerivedColumn derivedColumn = new TableQueryParser("sum( id )").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("SUM(id)", results.getName()); assertEquals(columnId.getColumnType(), results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("id", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsMax() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnBar))); DerivedColumn derivedColumn = new TableQueryParser("max( bar )").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("MAX(bar)", results.getName()); assertEquals(columnBar.getColumnType(), results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("bar", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsAvg() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnId))); DerivedColumn derivedColumn = new TableQueryParser("avg( id )").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("AVG(id)", results.getName()); assertEquals(ColumnType.DOUBLE, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("id", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsCurrentUser() throws ParseException{ DerivedColumn derivedColumn = new TableQueryParser("current_user()").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("CURRENT_USER()", results.getName()); assertEquals(ColumnType.USERID, results.getColumnType()); assertEquals(null, results.getId()); } @Test public void testGetSelectColumnsSpecial() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnSpecial))); DerivedColumn derivedColumn = new TableQueryParser("\""+columnSpecial.getName()+"\"").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals(columnSpecial.getName(), results.getName()); assertEquals(ColumnType.DOUBLE, results.getColumnType()); assertEquals(columnSpecial.getId(), results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("\""+columnSpecial.getName()+"\"", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsMySqlFunction() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnFoo))); DerivedColumn derivedColumn = new TableQueryParser("from_unixtime(foo)").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("FROM_UNIXTIME(foo)", results.getName()); assertEquals(ColumnType.STRING, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("foo", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsColumnNameWithQuotes() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnQuoted))); DerivedColumn derivedColumn = new TableQueryParser("\"colWith\"\"Quotes\"\"InIt\"").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("colWith\"Quotes\"InIt", results.getName()); assertEquals(ColumnType.STRING, results.getColumnType()); assertEquals("999", results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("\"colWith\"\"Quotes\"\"InIt\"", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsAliasNameWithQuotes() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.of(new SchemaColumnTranslationReference(columnFoo))); DerivedColumn derivedColumn = new TableQueryParser("foo as \"aliasWith\"\"Quotes\"\"InIt\"").derivedColumn(); // call under test SelectColumn results = SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); assertNotNull(results); assertEquals("aliasWith\"Quotes\"InIt", results.getName()); assertEquals(ColumnType.STRING, results.getColumnType()); assertEquals(null, results.getId()); verify(mockColumnLookup).lookupColumnReference(columnRefCapture.capture()); assertEquals("foo", columnRefCapture.getValue().toSql()); } @Test public void testGetSelectColumnsSimpleMismatch() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn(Optional.empty()); DerivedColumn derivedColumn = new TableQueryParser("fo0").derivedColumn(); // call under test try { SQLTranslatorUtils.getSelectColumns(derivedColumn, mockColumnLookup); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { String message = e.getMessage(); assertTrue(message.contains("fo0")); assertTrue(message.contains("Unknown column")); } } @Test public void testGetSelectColumnsSelectStar() throws ParseException{ boolean isAggregate = false; SelectList element = new TableQueryParser("*").selectList(); assertThrows(IllegalStateException.class, () -> { // call under test. SQLTranslatorUtils.getSelectColumns(element, mockColumnLookup, isAggregate); }); } @Test public void testGetSelectColumnsSelectActualColumnsAggregate() throws ParseException { when(mockColumnLookup.lookupColumnReference(any())).thenReturn( Optional.of(new SchemaColumnTranslationReference(columnFoo)), Optional.of(new SchemaColumnTranslationReference(columnBar))); boolean isAggregate = true; SelectList element = new TableQueryParser("foo, bar").selectList(); // call under test. List<SelectColumn> results = SQLTranslatorUtils.getSelectColumns(element, mockColumnLookup, isAggregate); assertNotNull(results); assertEquals(2, results.size()); for (SelectColumn select : results) { assertNull(select.getId(), "This is an aggregate so all column ids must be null."); } } @Test public void testGetSelectColumnsSelectActualColumnsNotAggregate() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn( Optional.of(new SchemaColumnTranslationReference(columnFoo)), Optional.of(new SchemaColumnTranslationReference(columnBar))); boolean isAggregate = false; SelectList element = new TableQueryParser("foo, bar").selectList(); // call under test. List<SelectColumn> results = SQLTranslatorUtils.getSelectColumns(element, mockColumnLookup, isAggregate); assertNotNull(results); assertEquals(2, results.size()); for (SelectColumn select : results) { assertNotNull( "This is not an aggregate, and all selects match the schema so all columns should have a column ID.", select.getId()); } } @Test public void testGetSelectColumnsSelectConstantNotAggregate() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn( Optional.of(new SchemaColumnTranslationReference(columnFoo))); boolean isAggregate = false; SelectList element = new TableQueryParser("foo, 'some constant'").selectList(); // call under test. List<SelectColumn> results = SQLTranslatorUtils.getSelectColumns(element, mockColumnLookup, isAggregate); assertNotNull(results); assertEquals(2, results.size()); for (SelectColumn select : results) { assertNull(select.getId(), "This is not an aggregate but since one select does not match the schema, all column Ids should be null."); } } @Test public void testGetSelectColumnsSelectConstantAggregate() throws ParseException{ when(mockColumnLookup.lookupColumnReference(any())).thenReturn( Optional.of(new SchemaColumnTranslationReference(columnFoo))); boolean isAggregate = true; SelectList element = new TableQueryParser("foo, 'some constant'").selectList(); // call under test. List<SelectColumn> results = SQLTranslatorUtils.getSelectColumns(element, mockColumnLookup, isAggregate); assertNotNull(results); assertEquals(2, results.size()); for (SelectColumn select : results) { assertNull(select.getId(), "This is an aggregate and one select does not match the schema so all column Ids should be null."); } } @Test public void testAddRowIdAndVersionToSelect() throws ParseException{ SelectList element = new TableQueryParser("foo, 'has space'").selectList(); List<String> toAdd = Arrays.asList("ROW_ID", "ROW_VERSION"); SQLTranslatorUtils.addMetadataColumnsToSelect(element, toAdd); assertEquals("foo, 'has space', ROW_ID, ROW_VERSION", element.toSql()); for(DerivedColumn derivedColumn: element.createIterable(DerivedColumn.class)) { assertNotNull(derivedColumn.getParent()); } } @Test public void testReadWithHeadersWithEtagRow() throws SQLException{ when(mockResultSet.getLong(ROW_ID)).thenReturn(rowId); when(mockResultSet.getLong(ROW_VERSION)).thenReturn(rowVersion); when(mockResultSet.getString(ROW_ETAG)).thenReturn(etag); when(mockResultSet.getString(1)).thenReturn("aString"); when(mockResultSet.getString(2)).thenReturn("true"); boolean withHeaders = true; boolean withEtag = true; // call under test. Row result = SQLTranslatorUtils.readRow(mockResultSet, withHeaders, withEtag, infoArray); verify(mockResultSet).getLong(ROW_ID); verify(mockResultSet).getLong(ROW_VERSION); verify(mockResultSet).getString(ROW_ETAG); assertNotNull(result); assertEquals(rowId, result.getRowId()); assertEquals(rowVersion, result.getVersionNumber()); assertNotNull(result.getValues()); assertEquals(2, result.getValues().size()); assertEquals("aString", result.getValues().get(0)); assertEquals(Boolean.TRUE.toString(), result.getValues().get(1)); } @Test public void testReadWithoutHeadersWithEtagRow() throws SQLException{ when(mockResultSet.getString(1)).thenReturn("aString"); when(mockResultSet.getString(2)).thenReturn("true"); boolean withHeaders = false; boolean withEtag = true; // call under test. Row result = SQLTranslatorUtils.readRow(mockResultSet, withHeaders, withEtag, infoArray); verify(mockResultSet, never()).getLong(ROW_ID); verify(mockResultSet, never()).getLong(ROW_VERSION); verify(mockResultSet, never()).getString(ROW_ETAG); assertNotNull(result); assertEquals(null, result.getRowId()); assertEquals(null, result.getVersionNumber()); assertNotNull(result.getValues()); assertEquals(2, result.getValues().size()); assertEquals("aString", result.getValues().get(0)); assertEquals(Boolean.TRUE.toString(), result.getValues().get(1)); } @Test public void testReadWithoutHeadersWithoutEtagRow() throws SQLException{ when(mockResultSet.getString(1)).thenReturn("aString"); when(mockResultSet.getString(2)).thenReturn("true"); boolean withHeaders = false; boolean withEtag = false; // call under test. Row result = SQLTranslatorUtils.readRow(mockResultSet, withHeaders, withEtag, infoArray); verify(mockResultSet, never()).getLong(ROW_ID); verify(mockResultSet, never()).getLong(ROW_VERSION); verify(mockResultSet, never()).getString(ROW_ETAG); assertNotNull(result); assertEquals(null, result.getRowId()); assertEquals(null, result.getVersionNumber()); assertNotNull(result.getValues()); assertEquals(2, result.getValues().size()); assertEquals("aString", result.getValues().get(0)); assertEquals(Boolean.TRUE.toString(), result.getValues().get(1)); } @Test public void testReadWithHeadersWithoutEtagRow() throws SQLException{ when(mockResultSet.getLong(ROW_ID)).thenReturn(rowId); when(mockResultSet.getLong(ROW_VERSION)).thenReturn(rowVersion); when(mockResultSet.getString(1)).thenReturn("aString"); when(mockResultSet.getString(2)).thenReturn("true"); boolean withHeaders = true; boolean withEtag = false; // call under test. Row result = SQLTranslatorUtils.readRow(mockResultSet, withHeaders, withEtag, infoArray); verify(mockResultSet).getLong(ROW_ID); verify(mockResultSet).getLong(ROW_VERSION); verify(mockResultSet, never()).getString(ROW_ETAG); assertNotNull(result); assertEquals(rowId, result.getRowId()); assertEquals(rowVersion, result.getVersionNumber()); assertNotNull(result.getValues()); assertEquals(2, result.getValues().size()); assertEquals("aString", result.getValues().get(0)); assertEquals(Boolean.TRUE.toString(), result.getValues().get(1)); } @Test public void testTranslateTableName() throws ParseException{ QuerySpecification model = new TableQueryParser("select * from syn123").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); TableNameCorrelation tableNameCorrelation = model.getFirstElementOfType(TableNameCorrelation.class); // call under test Optional<TableNameCorrelation> optional = SQLTranslatorUtils.translateTableName(tableNameCorrelation, mapper); assertTrue(optional.isPresent()); assertEquals("T123",optional.get().toSql()); } @Test public void testTranslateTableNameWithVerion() throws ParseException{ QuerySpecification model = new TableQueryParser("select * from syn123.456").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123.456"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); TableNameCorrelation tableNameCorrelation = model.getFirstElementOfType(TableNameCorrelation.class); // call under test Optional<TableNameCorrelation> optional = SQLTranslatorUtils.translateTableName(tableNameCorrelation, mapper); assertTrue(optional.isPresent()); assertEquals("T123_456",optional.get().toSql()); } @Test public void testTranslateTableNameWithJoin() throws ParseException { QuerySpecification model = new TableQueryParser("select * FROM syn123 r join syn456 t").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); for (TableNameCorrelation tableNameCorrelation : model.createIterable(TableNameCorrelation.class)) { // call under test SQLTranslatorUtils.translateTableName(tableNameCorrelation, mapper) .ifPresent(replacement -> tableNameCorrelation.replaceElement(replacement)); } assertEquals("SELECT * FROM T123 _A0 JOIN T456 _A1", model.toSql()); } @Test public void testTranslateTableNameWithJoinAndVersion() throws ParseException { QuerySpecification model = new TableQueryParser("select * FROM syn123.3 r join syn456.1 t").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123.3"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456.1"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); for (TableNameCorrelation tableNameCorrelation : model.createIterable(TableNameCorrelation.class)) { // call under test SQLTranslatorUtils.translateTableName(tableNameCorrelation, mapper) .ifPresent(replacement -> tableNameCorrelation.replaceElement(replacement)); } assertEquals("SELECT * FROM T123_3 _A0 JOIN T456_1 _A1", model.toSql()); } @Test public void testTranslateOrderBySimple() throws ParseException{ ValueExpressionPrimary column = new TableQueryParser("foo").valueExpressionPrimary(); column.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(column, singleTableMapper); assertEquals("_C111_", column.toSql()); } @Test public void testTranslateOrderByFunction() throws ParseException{ ValueExpressionPrimary column = new TableQueryParser("max(foo)").valueExpressionPrimary(); column.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(column, singleTableMapper); assertEquals("MAX(_C111_)", column.toSql()); } @Test public void testTranslateOrderByRowId() throws ParseException{ ValueExpressionPrimary column = new TableQueryParser("ROW_ID").valueExpressionPrimary(); column.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(column, singleTableMapper); assertEquals("ROW_ID", column.toSql()); } @Test public void testTranslateOrderByConstant() throws ParseException{ ValueExpressionPrimary column = new TableQueryParser("'constant'").valueExpressionPrimary(); column.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(column, singleTableMapper); assertEquals("'constant'", column.toSql()); } @Test public void testTranslateOrderByDouble() throws ParseException{ ValueExpressionPrimary column = new TableQueryParser("aDouble").valueExpressionPrimary(); column.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(column, singleTableMapper); assertEquals("_C777_", column.toSql()); } @Test public void testTranslateSelectOrderByFunction() throws ParseException{ ValueExpressionPrimary column = new TableQueryParser("sum(aDouble)").valueExpressionPrimary(); column.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(column, singleTableMapper); assertEquals("SUM(_C777_)", column.toSql()); } @Test public void testReplaceBooleanFunctionIsNaN() throws ParseException{ BooleanPrimary element = new TableQueryParser("isNaN(_C777_)").booleanPrimary(); SQLTranslatorUtils.replaceBooleanFunction(element, singleTableMapper); assertEquals("( _DBL_C777_ IS NOT NULL AND _DBL_C777_ = 'NaN' )", element.toSql()); } @Test public void testReplaceBooleanFunctionIsInfinity() throws ParseException{ BooleanPrimary element = new TableQueryParser("isInfinity(_C777_)").booleanPrimary(); SQLTranslatorUtils.replaceBooleanFunction(element, singleTableMapper); assertEquals("( _DBL_C777_ IS NOT NULL AND _DBL_C777_ IN ( '-Infinity', 'Infinity' ) )", element.toSql()); } @Test public void testReplaceBooleanFunctionNonDoubleColumn() throws ParseException{ BooleanPrimary element = new TableQueryParser("isInfinity(_C444_)").booleanPrimary(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.replaceBooleanFunction(element, singleTableMapper); }); } @Test public void testReplaceBooleanFunctionUnknownColumn() throws ParseException{ BooleanPrimary element = new TableQueryParser("isInfinity(someUnknown)").booleanPrimary(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.replaceBooleanFunction(element, singleTableMapper); }); } @Test public void testReplaceBooleanFunctionNotBooleanFunction() throws ParseException{ BooleanPrimary element = new TableQueryParser("id = 123").booleanPrimary(); SQLTranslatorUtils.replaceBooleanFunction(element, singleTableMapper); assertEquals("id = 123", element.toSql(), "Non-BooleanFunctions should not be changed by this method."); } @Test public void testReplaceBooleanFunctionSearchCondition() throws ParseException{ BooleanPrimary element = new TableQueryParser("(id = 123 OR id = 456)").booleanPrimary(); SQLTranslatorUtils.replaceBooleanFunction(element, singleTableMapper); assertEquals("( id = 123 OR id = 456 )", element.toSql(), "SearchConditions should not be changed by this method."); } @Test public void testReplaceArrayHasPredicate_ReferencedColumn_FalseIsList() throws ParseException { columnFoo.setColumnType(ColumnType.STRING);//not a list type singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has ('asdf', 'qwerty', 'yeet')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of the ArrayHasPredicate when replaceArrayHasPredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), new HashMap<>(), singleTableMapper); String message = assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); }).getMessage(); assertEquals("The HAS keyword only works for columns that hold list values", message); } @Test public void testReplaceArrayHasPredicate_ReferencedColumn_unknown() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); //should not ever happen since translate would have to translate column name to something that it didnt have in its maping BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("_C723895794567246_ has ('asdf', 'qwerty', 'yeet')"); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); }); } @Test public void testReplaceArrayHasPredicate_Has() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has ('asdf', 'qwerty', 'yeet')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of when replaceArrayHasPredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), new HashMap<>(), singleTableMapper); SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); assertEquals("ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_456_INDEX_C111_ WHERE _C111__UNNEST IN ( :b0, :b1, :b2 ) )", booleanPrimary.toSql()); } @Test public void testReplaceArrayHasPredicate_NotHas() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo not has ('asdf', 'qwerty', 'yeet')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of when replaceArrayHasPredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), new HashMap<>(), singleTableMapper); SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); assertEquals("ROW_ID NOT IN ( SELECT ROW_ID_REF_C111_ FROM T123_456_INDEX_C111_ WHERE _C111__UNNEST IN ( :b0, :b1, :b2 ) )", booleanPrimary.toSql()); } @Test public void testTranslate_Has_onEntityIdList() throws ParseException { columnFoo.setColumnType(ColumnType.ENTITYID_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has ('syn123', 456, 'syn789')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); HashMap<String, Object> parameters = new HashMap<>(); //method under test SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), parameters, singleTableMapper); //parameter mapping should have stripped out the "syn" prefixes Map<String, Object> expected = ImmutableMap.of( "b0", 123L, "b1", 456L, "b2", 789L ); assertEquals(expected, parameters); } @Test public void testReplaceArrayHasPredicate_NotAnArrayHasPredicate() throws ParseException{ BooleanPrimary notArrayHasPredicate = SqlElementUtils.createBooleanPrimary("foo IN (\"123\", \"456\")"); //call translate so that bind variable replacement occurs, matching the state of when replaceArrayHasPredicate is called in actual code. SQLTranslatorUtils.translate(notArrayHasPredicate.getFirstElementOfType(InPredicate.class), new HashMap<>(), singleTableMapper); String beforeCallSqll = notArrayHasPredicate.toSql(); SQLTranslatorUtils.replaceArrayHasPredicate(notArrayHasPredicate, singleTableMapper); //if not an ArrayHasPredicate, nothing should have changed assertEquals(beforeCallSqll, notArrayHasPredicate.toSql()); } @Test public void testReplaceArrayHasPredicateWithHasLike() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); });; HashMap<String, Object> parameters = new HashMap<>(); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has_like ('asdf%', 'qwerty', 'yeet')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of when replaceArrayHasLikePredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), parameters, singleTableMapper); SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); assertEquals("ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_456_INDEX_C111_ WHERE _C111__UNNEST LIKE :b0 OR _C111__UNNEST LIKE :b1 OR _C111__UNNEST LIKE :b2 )", booleanPrimary.toSql()); assertEquals(ImmutableMap.of( "b0", "asdf%", "b1", "qwerty", "b2", "yeet" ), parameters); } @Test public void testReplaceArrayHasPredicateWithHasLikeAndEscape() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); HashMap<String, Object> parameters = new HashMap<>(); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has_like ('asdf%', 'qwerty', 'yeet') escape '_'"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of when replaceArrayHasLikePredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), parameters, singleTableMapper); SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); assertEquals("ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_456_INDEX_C111_ WHERE _C111__UNNEST LIKE :b0 ESCAPE :b3 OR _C111__UNNEST LIKE :b1 ESCAPE :b3 OR _C111__UNNEST LIKE :b2 ESCAPE :b3 )", booleanPrimary.toSql()); assertEquals(ImmutableMap.of( "b0", "asdf%", "b1", "qwerty", "b2", "yeet", "b3", "_" ), parameters); } @Test public void testReplaceArrayHasPredicateWithHasLikeAndReferencedColumnNotMultiValue() throws ParseException { columnFoo.setColumnType(ColumnType.STRING);//not a list type singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has_like ('asdf', 'qwerty', 'yeet')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of the ArrayHasPredicate when replaceArrayHasPredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), new HashMap<>(), singleTableMapper); String message = assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); }).getMessage(); assertEquals("The HAS_LIKE keyword only works for columns that hold list values", message); } @Test public void testReplaceArrayHasPredicateWithHasLikeAndSingleValue() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Collections.singletonList(columnFoo); }); BooleanPrimary booleanPrimary = SqlElementUtils.createBooleanPrimary("foo has_like ('asdf%')"); booleanPrimary.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(booleanPrimary, singleTableMapper); //call translate so that bind variable replacement occurs, matching the state of when replaceArrayHasPredicate is called in actual code. SQLTranslatorUtils.translate(booleanPrimary.getFirstElementOfType(ArrayHasPredicate.class), new HashMap<>(), singleTableMapper); SQLTranslatorUtils.replaceArrayHasPredicate(booleanPrimary, singleTableMapper); assertEquals("ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_456_INDEX_C111_ WHERE _C111__UNNEST LIKE :b0 )", booleanPrimary.toSql()); } @Test public void testAppendJoinsToFromClause() throws ParseException { FromClause fromClause = new TableQueryParser("from syn123").fromClause(); Set<String> columnIdsToJoin = Collections.emptySet(); SQLTranslatorUtils.appendJoinsToFromClause(singleTableMapper, fromClause, columnIdsToJoin); } @Test public void testAppendJoinsToFromClauseWithEmptyIdsAndJoin() throws ParseException { FromClause fromClause = new TableQueryParser("from syn123 join syn456").fromClause(); Set<String> columnIdsToJoin = Collections.emptySet(); SQLTranslatorUtils.appendJoinsToFromClause(singleTableMapper, fromClause, columnIdsToJoin); } @Test public void testAppendJoinsToFromClauseWithColumnIdsAndJoin() throws ParseException { FromClause fromClause = new TableQueryParser("from syn123 join syn456").fromClause(); Set<String> columnIdsToJoin = Sets.newHashSet("11"); String message = assertThrows(IllegalArgumentException.class, ()->{ SQLTranslatorUtils.appendJoinsToFromClause(singleTableMapper, fromClause, columnIdsToJoin); }).getMessage(); assertEquals("UNEST cannot be used with a JOIN", message); } @Test public void tesTranslateArrayFunction_columnNotFound() throws ParseException { //_C987654_ does not exist QuerySpecification querySpecification = TableQueryParser.parserQuery( "SELECT UNNEST(_C987654_) FROM T123 ORDER BY UNNEST(_C987654_)" ); String errorMessage = assertThrows(IllegalArgumentException.class, () -> { //method under test SQLTranslatorUtils.translateArrayFunctions(querySpecification, singleTableMapper); }).getMessage(); assertEquals("Unknown column reference: _C987654_", errorMessage); } @Test public void tesTranslateArrayFunctionWithJoin() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Arrays.asList(columnFoo); }); QuerySpecification querySpecification = TableQueryParser.parserQuery( "SELECT UNNEST(_C111_) FROM T123 join T456 ORDER BY UNNEST(_C111_)" ); String errorMessage = assertThrows(IllegalArgumentException.class, () -> { //method under test SQLTranslatorUtils.translateArrayFunctions(querySpecification, singleTableMapper); }).getMessage(); assertEquals("UNEST cannot be used with a JOIN", errorMessage); } @Test public void tesTranslateArrayFunction_columnNotInSchema() throws ParseException { //can not perform UNNEST on one of the metadata columns QuerySpecification querySpecification = TableQueryParser.parserQuery( "SELECT UNNEST(ROW_ID) FROM T123 ORDER BY UNNEST(ROW_ID)" ); String errorMessage = assertThrows(IllegalArgumentException.class, () -> { //method under test SQLTranslatorUtils.translateArrayFunctions(querySpecification, singleTableMapper); }).getMessage(); assertEquals("UNNEST() may only be used on columns defined in the schema", errorMessage); } @Test public void tesTranslateArrayFunction_columnNotListType() throws ParseException { columnFoo.setColumnType(ColumnType.STRING); //_C111_ is a STRING type instead of STRING_LIST QuerySpecification querySpecification = TableQueryParser.parserQuery( "SELECT UNNEST(_C111_) FROM T123 ORDER BY UNNEST(_C111_)" ); String errorMessage = assertThrows(IllegalArgumentException.class, () -> { //method under test SQLTranslatorUtils.translateArrayFunctions(querySpecification, singleTableMapper); }).getMessage(); assertEquals("UNNEST() only works for columns that hold list values", errorMessage); } @Test public void tesTranslateArrayFunction_multipleColumns() throws ParseException { columnFoo.setColumnType(ColumnType.STRING_LIST); columnBar.setColumnType(ColumnType.STRING_LIST); singleTableMapper = new TableAndColumnMapper( new TableQueryParser("select * from syn123.456").querySpecification(), (IdAndVersion tableId) -> { return Arrays.asList(columnFoo, columnBar); }); QuerySpecification querySpecification = TableQueryParser.parserQuery( "SELECT _C222_, UNNEST(_C111_), UNNEST(_C333_) FROM T123 ORDER BY UNNEST(_C111_), UNNEST(_C333_)" ); //method under test SQLTranslatorUtils.translateArrayFunctions(querySpecification, singleTableMapper); String expected = "SELECT _C222_, _C111__UNNEST, _C333__UNNEST " + "FROM T123 " + "LEFT JOIN T123_456_INDEX_C111_ ON T123.ROW_ID = T123_456_INDEX_C111_.ROW_ID_REF_C111_ " + "LEFT JOIN T123_456_INDEX_C333_ ON T123.ROW_ID = T123_456_INDEX_C333_.ROW_ID_REF_C333_ " + "ORDER BY _C111__UNNEST, _C333__UNNEST"; assertEquals(expected, querySpecification.toSql()); } @Test public void testTranslate_PredicateColumnReferenceNotExist() throws ParseException { //reference a column not found in schema Predicate predicate = SqlElementUtils.createPredicate("NOTINSCHEMA <> 1"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); assertThrows(IllegalArgumentException.class, () -> { // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); }); } @Test public void testComparisonPredicate() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo <> 1"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ <> :b0", predicate.toSql()); assertEquals("1", parameters.get("b0")); } @Test public void testStringComparisonPredicate() throws ParseException { Predicate predicate = SqlElementUtils.createPredicate("foo <> 'aaa'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ <> :b0", predicate.toSql()); assertEquals("aaa", parameters.get("b0")); } @Test public void testStringComparisonBooleanPredicate() throws ParseException { Predicate predicate = SqlElementUtils.createPredicate("foo = true"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ = TRUE", predicate.toSql()); assertEquals(0, parameters.size()); } @Test public void testComparisonPredicateDateNumber() throws ParseException { Predicate predicate = SqlElementUtils.createPredicate("aDate <> 1"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ <> :b0", predicate.toSql()); assertEquals(new Long(1), parameters.get("b0")); } @Test public void testComparisonPredicateDateString() throws ParseException { Predicate predicate = SqlElementUtils.createPredicate("aDate <> '2011-11-11'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ <> :b0", predicate.toSql()); assertEquals(Long.parseLong(DATE1TIME), parameters.get("b0")); } @Test public void testComparisonPredicateDateParsing() throws ParseException { for (String date : new String[] { DATE1, "2011-11-11", "2011-11-11 0:00", "2011-11-11 0:00:00", "2011-11-11 0:00:00.0", "2011-11-11 0:00:00.00", "2011-11-11 0:00:00.000" }) { HashMap<String, Object> parameters = new HashMap<String, Object>(); Predicate predicate = SqlElementUtils.createPredicate("aDate <> '" + date + "'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ <> :b0", predicate.toSql()); assertEquals(Long.parseLong(DATE1TIME), parameters.get("b0")); } for (String date : new String[] { "2001-01-01", "2001-01-01", "2001-1-1", "2001-1-01", "2001-01-1" }) { HashMap<String, Object> parameters = new HashMap<String, Object>(); Predicate predicate = SqlElementUtils.createPredicate("aDate <> '" + date + "'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ <> :b0", predicate.toSql()); assertEquals(Long.parseLong("978307200000"), parameters.get("b0")); } for (String date : new String[] { "2011-11-11 01:01:01.001", "2011-11-11 1:01:1.001", "2011-11-11 1:1:1.001" }) { HashMap<String, Object> parameters = new HashMap<String, Object>(); Predicate predicate = SqlElementUtils.createPredicate("aDate <> '" + date + "'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ <> :b0", predicate.toSql()); assertEquals(Long.parseLong("1320973261001"), parameters.get("b0")); } } @Test public void testInPredicateOne() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo in(1)"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ IN ( :b0 )", predicate.toSql()); assertEquals("1", parameters.get("b0")); } @Test public void testInPredicateMore() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo in(1,2,3)"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ IN ( :b0, :b1, :b2 )", predicate.toSql()); assertEquals("1", parameters.get("b0")); assertEquals("2", parameters.get("b1")); assertEquals("3", parameters.get("b2")); } @Test public void testInPredicateDate() throws ParseException { Predicate predicate = SqlElementUtils.createPredicate("aDate in('" + DATE1 + "','" + DATE2 + "')"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ IN ( :b0, :b1 )", predicate.toSql()); assertEquals(Long.parseLong(DATE1TIME), parameters.get("b0")); assertEquals(Long.parseLong(DATE2TIME), parameters.get("b1")); } @Test public void testBetweenPredicate() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo between 1 and 2"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ BETWEEN :b0 AND :b1", predicate.toSql()); assertEquals("1", parameters.get("b0")); assertEquals("2", parameters.get("b1")); } @Test public void testBetweenPredicateDate() throws ParseException { Predicate predicate = SqlElementUtils.createPredicate("aDate between '" + DATE1 + "' and '" + DATE2 + "'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C888_ BETWEEN :b0 AND :b1", predicate.toSql()); assertEquals(Long.parseLong(DATE1TIME), parameters.get("b0")); assertEquals(Long.parseLong(DATE2TIME), parameters.get("b1")); } @Test public void testBetweenPredicateNot() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo not between 1 and 2"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ NOT BETWEEN :b0 AND :b1", predicate.toSql()); assertEquals("1", parameters.get("b0")); assertEquals("2", parameters.get("b1")); } @Test public void testLikePredicate() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo like 'bar%'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ LIKE :b0", predicate.toSql()); assertEquals("bar%",parameters.get("b0")); } @Test public void testLikePredicateEscape() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo like 'bar|_' escape '|'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ LIKE :b0 ESCAPE :b1", predicate.toSql()); assertEquals("bar|_",parameters.get("b0")); assertEquals("|",parameters.get("b1")); } @Test public void testLikePredicateNot() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo not like 'bar%'"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ NOT LIKE :b0", predicate.toSql()); assertEquals("bar%",parameters.get("b0")); } @Test public void testNullPredicate() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo is null"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ IS NULL", predicate.toSql()); } @Test public void testNullPredicateNot() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("foo is not null"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HashMap<String, Object> parameters = new HashMap<String, Object>(); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C111_ IS NOT NULL", predicate.toSql()); } @Test public void testTranslateRightHandeSideNullElement(){ UnsignedLiteral element = null; Map<String, Object> parameters = new HashMap<String, Object>(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.STRING, parameters); }); } @Test public void testTranslateRightHandeSideNullParameters() throws ParseException{ UnsignedLiteral element = new TableQueryParser("'aString'").unsignedLiteral(); Map<String, Object> parameters = null; assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.STRING, parameters); }); } @Test public void testTranslateRightHandeSideNullColumn() throws ParseException{ UnsignedLiteral element = new TableQueryParser("'aString'").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translateRightHandeSide(element, null, parameters); }); } @Test public void testTranslateRightHandeSideString() throws ParseException{ UnsignedLiteral element = new TableQueryParser("'aString'").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.STRING, parameters); assertEquals(":b0", element.toSqlWithoutQuotes()); assertEquals("aString", parameters.get("b0")); } @Test public void testTranslateRightHandeSideInteger() throws ParseException{ UnsignedLiteral element = new TableQueryParser("123456").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.INTEGER, parameters); assertEquals(":b0", element.toSqlWithoutQuotes()); assertEquals(new Long(123456), parameters.get("b0")); } @Test public void testTranslateRightHandeSideIntegerLikeValue() throws ParseException{ UnsignedLiteral element = new TableQueryParser("'12345%'").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.INTEGER, parameters); assertEquals(":b0", element.toSqlWithoutQuotes()); assertEquals("12345%", parameters.get("b0")); } @Test public void testTranslateRightHandeSideDouble() throws ParseException{ UnsignedLiteral element = new TableQueryParser("1.45").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.DOUBLE, parameters); assertEquals(":b0", element.toSqlWithoutQuotes()); assertEquals(new Double(1.45), parameters.get("b0")); } @Test public void testTranslateRightHandeSideDateString() throws ParseException{ UnsignedLiteral element = new TableQueryParser("'16-01-29 13:55:33.999'").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.DATE, parameters); assertEquals(":b0", element.toSqlWithoutQuotes()); assertEquals(new Long(1454075733999L), parameters.get("b0")); } @Test public void testTranslateRightHandeSideDateEpoch() throws ParseException{ UnsignedLiteral element = new TableQueryParser("1454075733999").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.DATE, parameters); assertEquals(":b0", element.toSqlWithoutQuotes()); assertEquals(new Long(1454075733999L), parameters.get("b0")); } @Test public void testTranslateRightHandeSideInterval() throws ParseException{ UnsignedLiteral element = new TableQueryParser("INTERVAL 3 MONTH").unsignedLiteral(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateRightHandeSide(element, ColumnType.DATE, parameters); assertEquals("INTERVAL 3 MONTH", element.toSqlWithoutQuotes()); } @Test public void testTranslateRightHandeSideIntervalPredicate() throws ParseException{ HasPredicate predicate = (HasPredicate) new TableQueryParser("aDate > NOW() + INTERVAL 1 MONTH)").predicate().getChild(); Map<String, Object> parameters = new HashMap<String, Object>(); for(UnsignedLiteral us: predicate.getRightHandSideValues()) { SQLTranslatorUtils.translateRightHandeSide(us, ColumnType.DATE, parameters); } assertEquals("aDate > NOW()+INTERVAL 1 MONTH", predicate.toSqlWithoutQuotes()); } @Test public void testTranslateRightHandeSideWithLiteralInContextOfMySqlFunction() throws ParseException{ Predicate predicate = new TableQueryParser("foo = LOWER('sOme StinG')").predicate(); predicate.recursiveSetParent(); UnsignedLiteral literal = predicate.getFirstElementOfType(UnsignedLiteral.class); String sqlBefore = literal.toSql(); assertEquals("'sOme StinG'", sqlBefore); Map<String, Object> parameters = new HashMap<String, Object>(); // call under test SQLTranslatorUtils.translateRightHandeSide(literal, ColumnType.STRING, parameters); assertEquals("sOme StinG", literal.toSqlWithoutQuotes()); } @Test public void testTranslateRightHandeSideWithLiteralNotInContextOfMysqlFunction() throws ParseException{ Predicate predicate = new TableQueryParser("foo = 'sOme StinG'").predicate(); predicate.recursiveSetParent(); UnsignedLiteral literal = predicate.getFirstElementOfType(UnsignedLiteral.class); String sqlBefore = literal.toSql(); assertEquals("'sOme StinG'", sqlBefore); Map<String, Object> parameters = new HashMap<String, Object>(); // call under test SQLTranslatorUtils.translateRightHandeSide(literal, ColumnType.STRING, parameters); assertEquals(":b0", literal.toSqlWithoutQuotes()); assertEquals("sOme StinG", parameters.get("b0")); } @Test public void testTranslateGroupByMultiple() throws ParseException{ GroupByClause element = new TableQueryParser("group by foo, id").groupByClause(); element.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(element, singleTableMapper); assertEquals("GROUP BY _C111_, _C444_", element.toSql()); } @Test public void testTranslateGroupByDouble() throws ParseException{ GroupByClause element = new TableQueryParser("group by aDouble").groupByClause(); element.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(element, singleTableMapper); assertEquals("GROUP BY _C777_", element.toSql()); } @Test public void testTranslateGroupByQuotes() throws ParseException{ GroupByClause element = new TableQueryParser("group by \""+columnSpecial.getName()+"\"").groupByClause(); element.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(element, singleTableMapper); assertEquals("GROUP BY _C555_", element.toSql()); } @Test public void testTranslateGroupByUnknown() throws ParseException{ GroupByClause element = new TableQueryParser("group by doesNotExist").groupByClause(); element.recursiveSetParent(); SQLTranslatorUtils.translateAllColumnReferences(element, singleTableMapper); assertEquals("GROUP BY doesNotExist", element.toSql()); } @Test public void testTranslateGroupByNull() throws ParseException{ GroupByClause element = null; assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translateAllColumnReferences(element, singleTableMapper); }); } @Test public void testTranslateGroupByMapNull() throws ParseException{ GroupByClause element = new TableQueryParser("group by doesNotExist").groupByClause(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translateAllColumnReferences(element, null); }); } @Test public void testTranslateHasPredicate() throws ParseException{ Predicate predicate = SqlElementUtils.createPredicate("id <> 3"); SQLTranslatorUtils.translateAllColumnReferences(predicate, singleTableMapper); HasPredicate hasPredicate = predicate.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); // call under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("_C444_ <> :b0",predicate.toSql()); assertEquals(new Long(3), parameters.get("b0")); } @Test public void testTranslateHasPredicateUnknownColumn() throws ParseException{ Predicate element = new TableQueryParser("_D999_ IS NOT NULL").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); assertThrows( IllegalArgumentException.class, () -> { SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); }); assertEquals("_D999_ IS NOT NULL",element.toSql()); } @Test public void testTranslateHasPredicateNullElement() throws ParseException{ HasPredicate hasPredicate = null; Map<String, Object> parameters = new HashMap<String, Object>(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); }); } @Test public void testTranslateHasPredicateNullParameters() throws ParseException{ Predicate element = new TableQueryParser("id <> 3").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = null; assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); }); } @Test public void testTranslateHasPredicateNullMap() throws ParseException{ Predicate element = new TableQueryParser("id <> 3").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translate(hasPredicate, parameters, null); }); } @Test public void testTranslateHasPredicate_ROW_ID_column() throws ParseException{ Predicate element = new TableQueryParser("ROW_ID <> 3").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); //method under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("ROW_ID <> :b0", element.toSql()); assertEquals(3L, parameters.get("b0")); } @Test public void testTranslateHasPredicate_ROW_VERSION_column() throws ParseException{ Predicate element = new TableQueryParser("ROW_VERSION <> 54").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); //method under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("ROW_VERSION <> :b0", element.toSql()); assertEquals(54L, parameters.get("b0")); } @Test public void testTranslateHasPredicate_ROW_BENEFACTOR_column() throws ParseException{ Predicate element = new TableQueryParser("ROW_BENEFACTOR <> 54").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); //method under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("ROW_BENEFACTOR <> :b0", element.toSql()); assertEquals(54L, parameters.get("b0")); } @Test public void testTranslateHasPredicate_ROW_ETAG_column() throws ParseException{ String uuid = UUID.randomUUID().toString(); Predicate element = new TableQueryParser("ROW_ETAG <> '" + uuid + "'").predicate(); HasPredicate hasPredicate = element.getFirstElementOfType(HasPredicate.class); Map<String, Object> parameters = new HashMap<String, Object>(); //method under test SQLTranslatorUtils.translate(hasPredicate, parameters, singleTableMapper); assertEquals("ROW_ETAG <> :b0", element.toSql()); assertEquals(uuid, parameters.get("b0")); } @Test public void testTranslatePagination() throws ParseException{ Pagination element = new TableQueryParser("limit 1 offset 9").pagination(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translate(element, parameters); assertEquals("LIMIT :b0 OFFSET :b1", element.toSql()); assertEquals(new Long(1), parameters.get("b0")); assertEquals(new Long(9), parameters.get("b1")); } @Test public void testTranslatePaginationNoOffset() throws ParseException{ Pagination element = new TableQueryParser("limit 1").pagination(); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translate(element, parameters); assertEquals("LIMIT :b0", element.toSql()); assertEquals(new Long(1), parameters.get("b0")); } @Test public void testTranslatePaginationNull() throws ParseException{ Pagination element = null; Map<String, Object> parameters = new HashMap<String, Object>(); assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translate(element, parameters); }); } @Test public void testTranslatePaginationParametersNull() throws ParseException{ Pagination element = new TableQueryParser("limit 1").pagination(); Map<String, Object> parameters = null; assertThrows(IllegalArgumentException.class, () -> { SQLTranslatorUtils.translate(element, parameters); }); } @Test public void testTranslateModelSimple() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123",element.toSql()); } @Test public void testTranslateModelSelectFunction() throws ParseException{ QuerySpecification element = new TableQueryParser("select sum(foo) from syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT SUM(_C111_) FROM T123",element.toSql()); } @Test public void testTranslateModelSelectDouble() throws ParseException{ QuerySpecification element = new TableQueryParser("select aDouble from syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT CASE WHEN _DBL_C777_ IS NULL THEN _C777_ ELSE _DBL_C777_ END FROM T123",element.toSql()); } @Test public void testTranslateModelSelectDoubleFunction() throws ParseException{ QuerySpecification element = new TableQueryParser("select sum(aDouble) from syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT SUM(_C777_) FROM T123",element.toSql()); } @Test public void testTranslateModelWhere() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where id > 2").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE _C444_ > :b0",element.toSql()); assertEquals(new Long(2), parameters.get("b0")); } @Test public void testTranslateModelWhereBetween() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where id between '1' and 2").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE _C444_ BETWEEN :b0 AND :b1",element.toSql()); assertEquals(new Long(1), parameters.get("b0")); assertEquals(new Long(2), parameters.get("b1")); } @Test public void testTranslateModelWhereIn() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where id in ('1',2,3)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE _C444_ IN ( :b0, :b1, :b2 )",element.toSql()); assertEquals(new Long(1), parameters.get("b0")); assertEquals(new Long(2), parameters.get("b1")); assertEquals(new Long(3), parameters.get("b2")); } @Test public void testTranslateModelWhereLike() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where id like '%3'").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE _C444_ LIKE :b0",element.toSql()); assertEquals("%3", parameters.get("b0")); } @Test public void testTranslateModelWhereNull() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where id is not null").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE _C444_ IS NOT NULL",element.toSql()); } @Test public void testTranslateModelWhereIsTrue() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where id is true").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE _C444_ IS TRUE",element.toSql()); } @Test public void testTranslateModelWhereIsNaN() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where isNaN(aDouble)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE ( _DBL_C777_ IS NOT NULL AND _DBL_C777_ = 'NaN' )",element.toSql()); } @Test public void testTranslateModelWhereIsInfinity() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 where isInfinity(aDouble)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 WHERE ( _DBL_C777_ IS NOT NULL AND _DBL_C777_ IN ( '-Infinity', 'Infinity' ) )",element.toSql()); } @Test public void testTranslateModelGroupBy() throws ParseException{ QuerySpecification element = new TableQueryParser("select bar, count(foo) from syn123 group by bar").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C333_, COUNT(_C111_) FROM T123 GROUP BY _C333_",element.toSql()); } @Test public void testTranslateModelOrderBy() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 order by bar").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 ORDER BY _C333_",element.toSql()); } @Test public void testTranslateModelOrderByFunction() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 order by max(bar)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 ORDER BY MAX(_C333_)",element.toSql()); } @Test public void testTranslateModelOrderDouble() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 order by aDouble").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 ORDER BY _C777_",element.toSql()); } @Test public void testTranslateModelOrderDoubleAs() throws ParseException{ QuerySpecification element = new TableQueryParser("select aDouble as f1 from syn123 order by f1").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT CASE WHEN _DBL_C777_ IS NULL THEN _C777_ ELSE _DBL_C777_ END AS f1 FROM T123 ORDER BY f1",element.toSql()); } @Test public void testTranslateModelOrderFunctionDouble() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo from syn123 order by min(aDouble)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_ FROM T123 ORDER BY MIN(_C777_)",element.toSql()); } @Test public void testTranslateModelSelectArithmetic() throws ParseException{ QuerySpecification element = new TableQueryParser("select -(2+2)*10 FROM syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT -(2+2)*10 FROM T123",element.toSql()); } @Test public void testTranslateModelSelectArithmeticRightHandSide() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = -(2+3)*10").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = -(:b0+:b1)*:b2",element.toSql()); assertEquals("2", parameters.get("b0")); assertEquals("3", parameters.get("b1")); assertEquals("10", parameters.get("b2")); } @Test public void testTranslateModelSelectArithmeticFunction() throws ParseException{ QuerySpecification element = new TableQueryParser("select sum((id+foo)/aDouble) as \"sum\" from syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT SUM((_C444_+_C111_)/_C777_) AS `sum` FROM T123",element.toSql()); } /** * This use case is referenced in PLFM-4566. * @throws ParseException */ @Test public void testTranslateModelSelectArithmeticGroupByOrderBy() throws ParseException{ QuerySpecification element = new TableQueryParser("select foo%10, count(*) from syn123 group by foo%10 order by foo%10").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C111_%10, COUNT(*) FROM T123 GROUP BY _C111_%10 ORDER BY _C111_%10",element.toSql()); } /** * Column reference on the right-hand-side should be replaced with a valid reference to that columnn. * @throws ParseException */ @Test public void testTranslateModelRegularIdentiferRightHandSideColumnReference() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = bar").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = _C333_",element.toSql()); } /** * Regular Identifier on the right-hand-side that does not match a column should be treated as a * column reference. * * @throws ParseException */ @Test public void testTranslateModelRegularIdentiferRightHandSideNotColumnReference() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = notReference").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = notReference",element.toSql()); } /** * Column reference on the right-hand-side should be replaced with a valid reference to that column. * @throws ParseException */ @Test public void testTranslateModelDelimitedIdentiferRightHandSideColumnReference() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = \"bar\"").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = _C333_",element.toSql()); } /** * Column reference on the right-hand-side should be replaced with a valid reference to that column. * @throws ParseException */ @Test public void testTranslateModelDelimitedIdentiferRightHandSideMultipleColumnReference() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = \"bar\" + \"foo\"").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = _C333_+_C111_",element.toSql()); } /** * Regular Identifier on the right-hand-side that does not match a column should be treated as a * column reference in backticks. See: PLFM-3867. * * @throws ParseException */ @Test public void testTranslateModelDelemitedIdentiferRightHandSideNotColumnReference() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = \"notReference\"").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = `notReference`",element.toSql()); } @Test public void testTranslateModelArithmeticAndColumnReferenceOnRightHandSide() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = 2*3/bar").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = :b0*:b1/_C333_",element.toSql()); assertEquals("2", parameters.get("b0")); assertEquals("3", parameters.get("b1")); } @Test public void testTranslateModelArithmeticAndColumnReferenceOnRightHandSide2() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo = (2+3)/bar").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ = (:b0+:b1)/_C333_",element.toSql()); } @Test public void testTranslateModelArithmeticGroupBy() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 group by bar/456 - min(bar)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 GROUP BY _C333_/456-MIN(_C333_)",element.toSql()); } @Test public void testTranslateMySqlFunctionRightHandSide() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo > unix_timestamp(CURRENT_TIMESTAMP - INTERVAL 1 MONTH)/1000").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ > UNIX_TIMESTAMP(CURRENT_TIMESTAMP-INTERVAL 1 MONTH)/:b0",element.toSql()); assertEquals("1000", parameters.get("b0")); } /** * Double quoted alias should be wrapped in backticks. * See PLFM-4736 * @throws ParseException */ @Test public void testTranslateDoubleQuotedAliasOrder() throws ParseException{ QuerySpecification element = new TableQueryParser("select bar as \"a1\", count(foo) as \"a2\" from syn123 group by \"a1\" order by \"a2\" desc").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT _C333_ AS `a1`, COUNT(_C111_) AS `a2` FROM T123 GROUP BY `a1` ORDER BY `a2` DESC",element.toSql()); } /** * Value in double quotes. Any value in double quotes should be treated as a column reference in backticks. * See: PLFM-3866 * @throws ParseException */ @Test public void testTranslateValueInDoubleQuotes() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo in(\"one\",\"two\")").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ IN ( `one`, `two` )",element.toSql()); } @Test public void testTranslateModel_InPredicate_ValueNoQuotes() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where id in(1, 2)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C444_ IN ( :b0, :b1 )",element.toSql()); assertEquals(1L, parameters.get("b0")); assertEquals(2L, parameters.get("b1")); } @Test public void testTranslateModel_InPredicate_ValueSingleQuotes() throws ParseException{ QuerySpecification element = new TableQueryParser("select * from syn123 where foo in('asdf', 'qwerty')").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals("SELECT * FROM T123 WHERE _C111_ IN ( :b0, :b1 )",element.toSql()); assertEquals("asdf", parameters.get("b0")); assertEquals("qwerty", parameters.get("b1")); } @Test public void testTranslateModel_HASKeyword() throws ParseException { columnDouble.setColumnType(ColumnType.INTEGER_LIST); columnFoo.setColumnType(ColumnType.STRING_LIST); QuerySpecification element = new TableQueryParser( "select * from syn123 where aDouble has (1,2,3) and ( foo has ('yah') or bar = 'yeet')").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals( "SELECT * FROM T123 WHERE ROW_ID IN ( SELECT ROW_ID_REF_C777_ FROM T123_INDEX_C777_ WHERE _C777__UNNEST IN ( :b0, :b1, :b2 ) ) AND ( ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_INDEX_C111_ WHERE _C111__UNNEST IN ( :b3 ) ) OR _C333_ = :b4 )",element.toSql()); assertEquals(1L, parameters.get("b0")); assertEquals(2L, parameters.get("b1")); assertEquals(3L, parameters.get("b2")); assertEquals("yah", parameters.get("b3")); assertEquals("yeet", parameters.get("b4")); } @Test public void testTranslateModelWithHasLikeKeyword() throws ParseException { columnDouble.setColumnType(ColumnType.INTEGER_LIST); columnFoo.setColumnType(ColumnType.STRING_LIST); QuerySpecification element = new TableQueryParser( "select * from syn123 where aDouble has (1,2,3) and ( foo has_like ('yah%', 'wow') or bar = 'yeet')").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals( "SELECT * FROM T123 WHERE ROW_ID IN ( SELECT ROW_ID_REF_C777_ FROM T123_INDEX_C777_ WHERE _C777__UNNEST IN ( :b0, :b1, :b2 ) ) AND ( ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_INDEX_C111_ WHERE _C111__UNNEST LIKE :b3 OR _C111__UNNEST LIKE :b4 ) OR _C333_ = :b5 )",element.toSql()); assertEquals(1L, parameters.get("b0")); assertEquals(2L, parameters.get("b1")); assertEquals(3L, parameters.get("b2")); assertEquals("yah%", parameters.get("b3")); assertEquals("wow", parameters.get("b4")); assertEquals("yeet", parameters.get("b5")); } @Test public void testTranslateModelWithHasLikeKeywordAndEscape() throws ParseException { columnDouble.setColumnType(ColumnType.INTEGER_LIST); columnFoo.setColumnType(ColumnType.STRING_LIST); QuerySpecification element = new TableQueryParser( "select * from syn123 where aDouble has (1,2,3) and ( foo has_like ('yah%', 'wow') escape '_' or bar = 'yeet')").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); assertEquals( "SELECT * FROM T123 WHERE ROW_ID IN ( SELECT ROW_ID_REF_C777_ FROM T123_INDEX_C777_ WHERE _C777__UNNEST IN ( :b0, :b1, :b2 ) ) AND ( ROW_ID IN ( SELECT ROW_ID_REF_C111_ FROM T123_INDEX_C111_ WHERE _C111__UNNEST LIKE :b3 ESCAPE :b5 OR _C111__UNNEST LIKE :b4 ESCAPE :b5 ) OR _C333_ = :b6 )",element.toSql()); assertEquals(1L, parameters.get("b0")); assertEquals(2L, parameters.get("b1")); assertEquals(3L, parameters.get("b2")); assertEquals("yah%", parameters.get("b3")); assertEquals("wow", parameters.get("b4")); assertEquals("_", parameters.get("b5")); assertEquals("yeet", parameters.get("b6")); } @Test public void testTranslateModel_UnnestArrayColumn() throws ParseException{ columnFoo.setColumnType(ColumnType.STRING_LIST);//not a list type QuerySpecification element = new TableQueryParser("select unnest(foo) , count(*) from syn123 where bar in ('asdf', 'qwerty') group by Unnest(foo)").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); String expectedSql = "SELECT _C111__UNNEST, COUNT(*) " + "FROM T123 " + "LEFT JOIN T123_INDEX_C111_ ON T123.ROW_ID = T123_INDEX_C111_.ROW_ID_REF_C111_ " + "WHERE _C333_ IN ( :b0, :b1 ) " + "GROUP BY _C111__UNNEST"; assertEquals(expectedSql,element.toSql()); assertEquals("asdf", parameters.get("b0")); assertEquals("qwerty", parameters.get("b1")); } @Test public void testTranslateModel_CurrentUserFunction() throws ParseException{ QuerySpecification element = new TableQueryParser("select count(*) from syn123 where bar = CURRENT_USER()").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); String expectedSql = "SELECT COUNT(*) FROM T123 WHERE _C333_ = :b0"; assertEquals(expectedSql, element.toSql()); assertEquals(userId.toString(), parameters.get("b0")); } @Test public void testTranslateModel_translateSynapseFunctions() throws ParseException{ QuerySpecification element = new TableQueryParser("select bar, CURRENT_USER() from syn123 where bar = CURRENT_USER()").querySpecification(); // call under test SQLTranslatorUtils.translateSynapseFunctions(element, userId); assertEquals("SELECT bar, 1 FROM syn123 WHERE bar = 1", element.toSql()); } @Test public void testTranslateModel_UnnestArrayColumn_multipleJoins() throws ParseException{ columnFoo.setColumnType(ColumnType.STRING_LIST);//not a list type columnBar.setColumnType(ColumnType.STRING_LIST);//not a list type QuerySpecification element = new TableQueryParser("select unnest(foo) , unnest(bar) from syn123").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); String expectedSql = "SELECT _C111__UNNEST, _C333__UNNEST " + "FROM T123 LEFT JOIN T123_INDEX_C111_ " + "ON T123.ROW_ID = T123_INDEX_C111_.ROW_ID_REF_C111_ LEFT JOIN T123_INDEX_C333_ " + "ON T123.ROW_ID = T123_INDEX_C333_.ROW_ID_REF_C333_"; assertEquals(expectedSql, element.toSql()); assertTrue(parameters.isEmpty()); } @Test public void testGetColumnTypeInfoArray(){ SelectColumn one = new SelectColumn(); one.setColumnType(ColumnType.STRING); SelectColumn two = new SelectColumn(); two.setColumnType(ColumnType.ENTITYID); SelectColumn three = new SelectColumn(); three.setColumnType(ColumnType.INTEGER); List<SelectColumn> selectColumns = Lists.newArrayList(one, two, three); ColumnTypeInfo[] expected = new ColumnTypeInfo[]{ ColumnTypeInfo.STRING, ColumnTypeInfo.ENTITYID, ColumnTypeInfo.INTEGER, }; ColumnTypeInfo[] results = SQLTranslatorUtils.getColumnTypeInfoArray(selectColumns); assertTrue(Arrays.equals(expected, results)); } @Test public void testValidateSelectColumnWithRealReference() { SelectColumn selectColumn = new SelectColumn(); selectColumn.setName("model"); SQLTranslatorUtils.validateSelectColumn(selectColumn, null, new SchemaColumnTranslationReference(columnFoo), new ActualIdentifier(new RegularIdentifier("someColumn"))); } @Test public void testValidateSelectColumnWithFunction() { SelectColumn selectColumn = new SelectColumn(); selectColumn.setName("function"); SQLTranslatorUtils.validateSelectColumn(selectColumn, FunctionReturnType.DOUBLE, null, new ActualIdentifier(new RegularIdentifier("someColumn"))); } @Test public void testValidateSelectColumnWithStringConstant() { SelectColumn selectColumn = new SelectColumn(); selectColumn.setName("contant"); SQLTranslatorUtils.validateSelectColumn(selectColumn, null, null, new UnsignedLiteral(new GeneralLiteral(new CharacterStringLiteral("constant")))); } @Test public void testValidateSelectColumnWithNumber() { SelectColumn selectColumn = new SelectColumn(); selectColumn.setName("contant"); SQLTranslatorUtils.validateSelectColumn(selectColumn, null, null, new UnsignedLiteral(new UnsignedNumericLiteral(new ExactNumericLiteral(1L)))); } @Test public void testValidateSelectColumnInvalid() { SelectColumn selectColumn = new SelectColumn(); selectColumn.setName("invalid"); try { SQLTranslatorUtils.validateSelectColumn(selectColumn, null, null, new ActualIdentifier(new RegularIdentifier("invalid"))); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { String message = e.getMessage(); assertTrue(message.contains("invalid")); assertTrue(message.contains("Unknown column")); } } @Test public void testTranslateQueryFiltersWithNOrullEmptyList() { assertThrows(IllegalArgumentException.class, () -> // method under test SQLTranslatorUtils.translateQueryFilters(null) ); assertThrows(IllegalArgumentException.class, () -> // method under test SQLTranslatorUtils.translateQueryFilters(Collections.emptyList()) ); } @Test public void testTranslateQueryFiltersWithSingleColumns() { ColumnSingleValueQueryFilter filter = new ColumnSingleValueQueryFilter(); filter.setColumnName("myCol"); filter.setOperator(ColumnSingleValueFilterOperator.LIKE); filter.setValues(Arrays.asList("foo%", "%bar","%baz%")); // method under test String searchCondition = SQLTranslatorUtils.translateQueryFilters(Arrays.asList(filter)); assertEquals("(\"myCol\" LIKE 'foo%' OR \"myCol\" LIKE '%bar' OR \"myCol\" LIKE '%baz%')", searchCondition); } @Test public void testTranslateQueryFiltersWithMultipleColumns(){ ColumnSingleValueQueryFilter filter = new ColumnSingleValueQueryFilter(); filter.setColumnName("myCol"); filter.setOperator(ColumnSingleValueFilterOperator.LIKE); filter.setValues(Arrays.asList("foo%", "%bar","%baz%")); ColumnSingleValueQueryFilter filter2 = new ColumnSingleValueQueryFilter(); filter2.setColumnName("otherCol"); filter2.setOperator(ColumnSingleValueFilterOperator.LIKE); filter2.setValues(Arrays.asList("%asdf")); // method under test String searchCondition = SQLTranslatorUtils.translateQueryFilters(Arrays.asList(filter, filter2)); assertEquals("(\"myCol\" LIKE 'foo%' OR \"myCol\" LIKE '%bar' OR \"myCol\" LIKE '%baz%') AND (\"otherCol\" LIKE '%asdf')", searchCondition); } @Test public void testTranslateQueryFiltersWithLikeFilterAndsingleValues(){ ColumnSingleValueQueryFilter filter = new ColumnSingleValueQueryFilter(); filter.setColumnName("myCol"); filter.setOperator(ColumnSingleValueFilterOperator.LIKE); filter.setValues(Arrays.asList("foo%")); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(\"myCol\" LIKE 'foo%')", builder.toString()); } @Test public void testTranslateQueryFiltersWithLikeFilterAndmultipleValues(){ ColumnSingleValueQueryFilter filter = new ColumnSingleValueQueryFilter(); filter.setColumnName("myCol"); filter.setOperator(ColumnSingleValueFilterOperator.LIKE); filter.setValues(Arrays.asList("foo%", "%bar","%baz%")); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(\"myCol\" LIKE 'foo%' OR \"myCol\" LIKE '%bar' OR \"myCol\" LIKE '%baz%')", builder.toString()); } @Test public void testTranslateQueryFiltersWithLikeFilterAndnullEmptyColName(){ ColumnSingleValueQueryFilter filter = new ColumnSingleValueQueryFilter(); filter.setOperator(ColumnSingleValueFilterOperator.LIKE); filter.setValues(Arrays.asList("foo%", "%bar","%baz%")); StringBuilder builder = new StringBuilder(); filter.setColumnName(null); assertThrows(IllegalArgumentException.class, ()-> // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter) ); filter.setColumnName(""); assertThrows(IllegalArgumentException.class, ()-> // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter) ); } @Test public void testTranslateQueryFiltersWithLikeFilterAndNullOrEmptyValues(){ ColumnSingleValueQueryFilter filter = new ColumnSingleValueQueryFilter(); filter.setColumnName("myCol"); StringBuilder builder = new StringBuilder(); filter.setOperator(ColumnSingleValueFilterOperator.LIKE); filter.setValues(null); assertThrows(IllegalArgumentException.class, ()-> // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter) ); filter.setValues(Collections.emptyList()); assertThrows(IllegalArgumentException.class, ()-> // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter) ); } @Test public void testTranslateQueryFiltersWithHasFilterAndmultipleValues(){ ColumnMultiValueFunctionQueryFilter filter = new ColumnMultiValueFunctionQueryFilter() .setColumnName("myCol") .setFunction(ColumnMultiValueFunction.HAS) .setValues(Arrays.asList("foo%", "%bar","%baz%")); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(\"myCol\" HAS ('foo%', '%bar', '%baz%'))", builder.toString()); } @Test public void testTranslateQueryFiltersWithHasLikeFilterAndmultipleValues(){ ColumnMultiValueFunctionQueryFilter filter = new ColumnMultiValueFunctionQueryFilter() .setColumnName("myCol") .setFunction(ColumnMultiValueFunction.HAS_LIKE) .setValues(Arrays.asList("foo%", "%bar","%baz%")); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(\"myCol\" HAS_LIKE ('foo%', '%bar', '%baz%'))", builder.toString()); } @Test public void testTranslateQueryFiltersWithHasFilterAndSingleValue(){ ColumnMultiValueFunctionQueryFilter filter = new ColumnMultiValueFunctionQueryFilter() .setColumnName("myCol") .setFunction(ColumnMultiValueFunction.HAS) .setValues(Arrays.asList("foo%")); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(\"myCol\" HAS ('foo%'))", builder.toString()); } @Test public void testTranslateQueryFiltersWithHasLikeFilterAndSingleValue(){ ColumnMultiValueFunctionQueryFilter filter = new ColumnMultiValueFunctionQueryFilter() .setColumnName("myCol") .setFunction(ColumnMultiValueFunction.HAS_LIKE) .setValues(Arrays.asList("foo%")); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(\"myCol\" HAS_LIKE ('foo%'))", builder.toString()); } @Test public void testTranslateQueryFiltersWithTextMatchesFilter(){ TextMatchesQueryFilter filter = new TextMatchesQueryFilter() .setSearchExpression("some search string"); StringBuilder builder = new StringBuilder(); // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); assertEquals("(TEXT_MATCHES('some search string'))", builder.toString()); } @Test public void testTranslateQueryFiltersWithTextMatchesFilterAndNullOrEmptyValue(){ TextMatchesQueryFilter filter = new TextMatchesQueryFilter() .setSearchExpression(null); StringBuilder builder = new StringBuilder(); String message = assertThrows(IllegalArgumentException.class, () -> { // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); }).getMessage(); assertEquals("TextMatchesQueryFilter.searchExpression is required and must not be the empty string.", message); filter.setSearchExpression(" "); message = assertThrows(IllegalArgumentException.class, () -> { // method under test SQLTranslatorUtils.translateQueryFilters(builder, filter); }).getMessage(); assertEquals("TextMatchesQueryFilter.searchExpression is required and must not be a blank string.", message); } @Test public void testTranslateQueryFiltersWithUnknownImplementation(){ QueryFilter filter = new QueryFilter(){ @Override public JSONObjectAdapter initializeFromJSONObject(JSONObjectAdapter jsonObjectAdapter) throws JSONObjectAdapterException { return null; } @Override public JSONObjectAdapter writeToJSONObject(JSONObjectAdapter jsonObjectAdapter) throws JSONObjectAdapterException { return null; } @Override public String getConcreteType() { return null; } @Override public QueryFilter setConcreteType(String concreteType) { return null; } }; assertThrows(IllegalArgumentException.class, ()-> // method under test SQLTranslatorUtils.translateQueryFilters(new StringBuilder(), filter) ); } @Test public void testGetColumnType() throws ParseException { ColumnModel column = schema.get(0); ColumnReference columnReference = new ColumnReference(null, SqlElementUtils.createColumnName(column.getName())); // Call under test ColumnType columnType = SQLTranslatorUtils.getColumnType(singleTableMapper, columnReference); assertEquals(column.getColumnType(), columnType); } @Test public void testGetColumnTypeWithImplicitType() throws ParseException { ColumnReference columnReference = new ColumnReference(null, SqlElementUtils.createColumnName("column"), ColumnType.DOUBLE); // Call under test ColumnType columnType = SQLTranslatorUtils.getColumnType(singleTableMapper, columnReference); assertEquals(ColumnType.DOUBLE, columnType); } @Test public void testGetColumnTypeWithNonExistingColumn() throws ParseException { ColumnReference columnReference = new ColumnReference(null, SqlElementUtils.createColumnName("nonexisting")); String message = assertThrows(IllegalArgumentException.class, () -> { // Call under test SQLTranslatorUtils.getColumnType(singleTableMapper, columnReference); }).getMessage(); assertEquals("Column does not exist: nonexisting", message); } @Test public void testGetColumnTypeWithNullColumnReference() throws ParseException { ColumnReference columnReference = null; String message = assertThrows(IllegalArgumentException.class, () -> { // Call under test SQLTranslatorUtils.getColumnType(singleTableMapper, columnReference); }).getMessage(); assertEquals("columnReference is required.", message); } @Test public void testGetColumnTypeWithNullColumnReferenceLookup() throws ParseException { singleTableMapper = null; ColumnReference columnReference = new ColumnReference(null, SqlElementUtils.createColumnName(schema.get(0).getName())); String message = assertThrows(IllegalArgumentException.class, () -> { // Call under test SQLTranslatorUtils.getColumnType(singleTableMapper, columnReference); }).getMessage(); assertEquals("TableAndColumnMapper is required.", message); } @Test public void testTranslateModelWithTextMatchesPredicate() throws ParseException{ QuerySpecification element = new TableQueryParser("SELECT * from syn123 where TEXT_MATCHES('some text')").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); String expectedSql = "SELECT * FROM T123 WHERE MATCH(ROW_SEARCH_CONTENT) AGAINST(:b0)"; assertEquals(expectedSql, element.toSql()); assertEquals(Collections.singletonMap("b0", "some text"), parameters); } @Test public void testTranslateModelWithTextMatchesPredicateMultiple() throws ParseException{ QuerySpecification element = new TableQueryParser("SELECT * from syn123 where TEXT_MATCHES('some text') AND (foo = 'bar' OR TEXT_MATCHES('some other text'))").querySpecification(); TableAndColumnMapper mapper = new TableAndColumnMapper(element, schemaProvider); Map<String, Object> parameters = new HashMap<String, Object>(); SQLTranslatorUtils.translateModel(element, parameters, userId, mapper); String expectedSql = "SELECT * FROM T123 WHERE MATCH(ROW_SEARCH_CONTENT) AGAINST(:b0) AND ( _C111_ = :b1 OR MATCH(ROW_SEARCH_CONTENT) AGAINST(:b2) )"; assertEquals(expectedSql, element.toSql()); assertEquals(ImmutableMap.of("b0", "some text", "b1", "bar", "b2", "some other text"), parameters); } @Test public void testTranslateColumnReferencedWithMultipleTablesMatchFristTable() throws ParseException { QuerySpecification model = new TableQueryParser("select t.foo from syn123 t join syn456").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A0._C111_", translated.get().toSql()); } @Test public void testTranslateColumnReferencedWithMultipleTablesMatchSecondTable() throws ParseException { QuerySpecification model = new TableQueryParser("select syn456.bar from syn123 t join syn456").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C333_", translated.get().toSql()); } @Test public void testTranslateColumnReferencedWithSingleTable() throws ParseException { QuerySpecification model = new TableQueryParser("select t.foo from syn123 t").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_C111_", translated.get().toSql()); } @Test public void testTranslateColumnReferencedWithNoMatch() throws ParseException { QuerySpecification model = new TableQueryParser("select notAColumn from syn123 t").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertFalse(translated.isPresent()); } @Test public void testCreateDoubleExpanstionWithOneTable() { int tableCount = 1; String translatedTableAliaName = "_A1"; String translatedColumnName = "_C333_"; ColumnReference ref = SQLTranslatorUtils.createDoubleExpanstion(tableCount, translatedTableAliaName, translatedColumnName); assertEquals("CASE WHEN _DBL_C333_ IS NULL THEN _C333_ ELSE _DBL_C333_ END", ref.toSql()); } @Test public void testCreateDoubleExpanstionWithMOreThanOneTable() { int tableCount = 2; String translatedTableAliaName = "_A1"; String translatedColumnName = "_C333_"; ColumnReference ref = SQLTranslatorUtils.createDoubleExpanstion(tableCount, translatedTableAliaName, translatedColumnName); assertEquals("CASE WHEN _A1._DBL_C333_ IS NULL THEN _A1._C333_ ELSE _A1._DBL_C333_ END", ref.toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelect() throws ParseException { QuerySpecification model = new TableQueryParser("select r.aDouble from syn123 t join syn456 r").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("CASE WHEN _A1._DBL_C777_ IS NULL THEN _A1._C777_ ELSE _A1._DBL_C777_ END", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectWithBuildContext() throws ParseException { QuerySpecification model = new TableQueryParser("select r.aDouble from syn123 t join syn456 r").querySpecification(); model.setSqlContext(SqlContext.build); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectSingleTable() throws ParseException { QuerySpecification model = new TableQueryParser("select r.aDouble from syn456 r").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("CASE WHEN _DBL_C777_ IS NULL THEN _C777_ ELSE _DBL_C777_ END", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectSingleTableBuildContext() throws ParseException { QuerySpecification model = new TableQueryParser("select r.aDouble from syn456 r").querySpecification(); model.setSqlContext(SqlContext.build); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleNotInSelect() throws ParseException { QuerySpecification model = new TableQueryParser("select * from syn123 t join syn456 r where r.aDouble > 1.0").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleNotInSelectWithBuildContext() throws ParseException { QuerySpecification model = new TableQueryParser("select * from syn123 t join syn456 r where r.aDouble > 1.0").querySpecification(); model.setSqlContext(SqlContext.build); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectAsSetFunctionParameter() throws ParseException { QuerySpecification model = new TableQueryParser("select max(r.aDouble) from syn123 t join syn456 r").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectAsSetFunctionParameterWithBuildContext() throws ParseException { QuerySpecification model = new TableQueryParser("select max(r.aDouble) from syn123 t join syn456 r").querySpecification(); model.setSqlContext(SqlContext.build); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectAsMySQLFunctionParameter() throws ParseException { QuerySpecification model = new TableQueryParser("select round(r.aDouble) from syn123 t join syn456 r").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectAsMySQLFunctionParameterWithBuildContext() throws ParseException { QuerySpecification model = new TableQueryParser("select round(r.aDouble) from syn123 t join syn456 r").querySpecification(); model.setSqlContext(SqlContext.build); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithDoubleInSelectAsUnestParameter() throws ParseException { QuerySpecification model = new TableQueryParser("select unnest(r.aDouble) from syn123 t join syn456 r").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1._C777_", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithRowIdAndMultipleTables() throws ParseException { QuerySpecification model = new TableQueryParser("select r.ROW_ID from syn123 t join syn456 r").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); map.put(IdAndVersion.parse("syn456"), Arrays.asList(columnNameMap.get("aDouble"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("_A1.ROW_ID", translated.get().toSql()); } @Test public void testTranslateColumnReferenceWithRowIdAndSingleTable() throws ParseException { QuerySpecification model = new TableQueryParser("select ROW_ID from syn123").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); ColumnReference columnReference = model.getFirstElementOfType(ColumnReference.class); // call under test Optional<ColumnReference> translated = SQLTranslatorUtils.translateColumnReference(columnReference, mapper); assertTrue(translated.isPresent()); assertEquals("ROW_ID", translated.get().toSql()); } @Test public void testGetSchemaOfDerivedColumnWithSimpleString() throws ParseException { QuerySpecification model = new TableQueryParser("select foo from syn123").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("has space"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); DerivedColumn dc = model.getFirstElementOfType(DerivedColumn.class); ColumnModel expected = new ColumnModel(); expected.setName("foo"); expected.setColumnType(ColumnType.STRING); expected.setMaximumSize(columnNameMap.get("foo").getMaximumSize()); expected.setId(null); // call under test assertEquals(expected, SQLTranslatorUtils.getSchemaOfDerivedColumn(dc, mapper)); } @Test public void testGetSchemaOfDerivedColumnWithFacetsAndDefault() throws ParseException { QuerySpecification model = new TableQueryParser("select foo from syn123").querySpecification(); ColumnModel cm = new ColumnModel(); cm.setColumnType(ColumnType.INTEGER); cm.setDefaultValue("123"); cm.setFacetType(FacetType.range); cm.setName("foo"); cm.setId("111"); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(cm)); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); DerivedColumn dc = model.getFirstElementOfType(DerivedColumn.class); ColumnModel expected = new ColumnModel(); expected.setName("foo"); expected.setColumnType(ColumnType.INTEGER); expected.setDefaultValue("123"); expected.setFacetType(FacetType.range); expected.setId(null); // call under test assertEquals(expected, SQLTranslatorUtils.getSchemaOfDerivedColumn(dc, mapper)); } @Test public void testAddLongWithNull() { assertEquals(null, SQLTranslatorUtils.addLongsWithNull(null, null)); assertEquals(123L, SQLTranslatorUtils.addLongsWithNull(null, 123L)); assertEquals(123L, SQLTranslatorUtils.addLongsWithNull(123L, null)); assertEquals(4L, SQLTranslatorUtils.addLongsWithNull(3L, 1L)); } @Test public void testGetSchemaOfDerivedColumnWithEachType() throws ParseException { for(ColumnModel cm: TableModelTestUtils.createOneOfEachType()) { cm.setName("foo"); QuerySpecification model = new TableQueryParser("select foo from syn123").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(cm)); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); DerivedColumn dc = model.getFirstElementOfType(DerivedColumn.class); ColumnModel expected = new ColumnModel(); expected.setName("foo"); expected.setColumnType(cm.getColumnType()); expected.setMaximumSize(cm.getMaximumSize()); expected.setMaximumListLength(cm.getMaximumListLength()); expected.setId(null); expected.setFacetType(cm.getFacetType()); // call under test assertEquals(expected, SQLTranslatorUtils.getSchemaOfDerivedColumn(dc, mapper)); } } @Test public void testGetSchemaOfDerivedColumnWithDerivedAddition() throws ParseException { QuerySpecification model = new TableQueryParser("select foo + bar from syn123").querySpecification(); Map<IdAndVersion, List<ColumnModel>> map = new LinkedHashMap<>(); map.put(IdAndVersion.parse("syn123"), Arrays.asList(columnNameMap.get("foo"), columnNameMap.get("bar"))); TableAndColumnMapper mapper = new TableAndColumnMapper(model, new TestSchemaProvider(map)); DerivedColumn dc = model.getFirstElementOfType(DerivedColumn.class); ColumnModel expected = new ColumnModel(); expected.setName("foo+bar"); expected.setColumnType(ColumnType.STRING); expected.setMaximumSize(columnNameMap.get("foo").getMaximumSize() + columnNameMap.get("bar").getMaximumSize()); expected.setId(null); // call under test assertEquals(expected, SQLTranslatorUtils.getSchemaOfDerivedColumn(dc, mapper)); } @Test public void testCreateMaterializedViewInsertSqlWithDependentView() { IdAndVersion materializedViewId = IdAndVersion.parse("syn123"); IdAndVersion viewId = IdAndVersion.parse("syn111"); List<ColumnModel> schemaOfSelect = Arrays.asList(columnFoo, columnBar); String outputSQL = "select _C111_,_C333_, ROW_BENEFACTOR from T111"; List<IndexDescription> dependencies = Arrays.asList(new ViewIndexDescription(viewId, EntityType.entityview)); IndexDescription indexDescription = new MaterializedViewIndexDescription(materializedViewId, dependencies); // call under test String result = SQLTranslatorUtils.createMaterializedViewInsertSql(schemaOfSelect, outputSQL, indexDescription); assertEquals("INSERT INTO T123 (_C111_,_C333_,ROW_BENEFACTOR_T111) select _C111_,_C333_, ROW_BENEFACTOR from T111", result); } @Test public void testCreateMaterializedViewInsertSqlWithDependentTable() { IdAndVersion materializedViewId = IdAndVersion.parse("syn123"); IdAndVersion tableId = IdAndVersion.parse("syn111"); List<ColumnModel> schemaOfSelect = Arrays.asList(columnFoo, columnBar); String outputSQL = "select _c1_, _c2_ from T111"; List<IndexDescription> dependencies = Arrays.asList(new TableIndexDescription(tableId)); IndexDescription indexDescription = new MaterializedViewIndexDescription(materializedViewId, dependencies); // call under test String result = SQLTranslatorUtils.createMaterializedViewInsertSql(schemaOfSelect, outputSQL, indexDescription); assertEquals("INSERT INTO T123 (_C111_,_C333_) select _c1_, _c2_ from T111", result); } }
package com.arrow.acn.client.api; import org.apache.commons.lang3.Validate; import com.arrow.acs.AcsUtils; import com.arrow.acs.client.api.ApiConfig; import com.arrow.acs.client.api.MqttHttpChannel; public final class AcnClient { private ApiConfig apiConfig; private AccountApi accountApi; private ConfigBackupApi configBackupApi; private CoreEventApi coreEventApi; private CoreUserApi coreUserApi; private DeviceActionApi deviceActionApi; private DeviceApi deviceApi; private DeviceStateApi deviceStateApi; private DeviceTypeApi deviceTypeApi; private GatewayApi gatewayApi; private NodeApi nodeApi; private NodeTypeApi nodeTypeApi; private RTUFirmwareApi rtuFirmwareApi; private SoftwareReleaseScheduleApi softwareReleaseScheduleApi; private SoftwareReleaseTransApi softwareReleaseTransApi; private TelemetryApi telemetryApi; private TelemetryUnitApi telemetryUnitApi; private UserApi userApi; private MqttHttpChannel mqttHttpChannel; public AcnClient(ApiConfig apiConfig) { AcsUtils.notNull(apiConfig, "apiConfig is not set"); this.apiConfig = apiConfig; } public void setApiConfig(ApiConfig apiConfig) { Validate.notNull(apiConfig, "apiConfig is not set"); this.apiConfig = apiConfig; if (accountApi != null) getAccountApi().setApiConfig(apiConfig); if (configBackupApi != null) getConfigBackupApi().setApiConfig(apiConfig); if (coreEventApi != null) getCoreEventApi().setApiConfig(apiConfig); if (coreUserApi != null) getCoreUserApi().setApiConfig(apiConfig); if (deviceActionApi != null) getDeviceActionApi().setApiConfig(apiConfig); if (deviceApi != null) getDeviceApi().setApiConfig(apiConfig); if (deviceStateApi != null) getDeviceStateApi().setApiConfig(apiConfig); if (deviceTypeApi != null) getDeviceTypeApi().setApiConfig(apiConfig); if (gatewayApi != null) getGatewayApi().setApiConfig(apiConfig); if (nodeApi != null) getNodeApi().setApiConfig(apiConfig); if (nodeTypeApi != null) getNodeTypeApi().setApiConfig(apiConfig); if (rtuFirmwareApi != null) getRTUFirmwareApi().setApiConfig(apiConfig); if (softwareReleaseScheduleApi != null) getSoftwareReleaseScheduleApi().setApiConfig(apiConfig); if (softwareReleaseTransApi != null) getSoftwareReleaseTransApi().setApiConfig(apiConfig); if (telemetryApi != null) getTelemetryApi().setApiConfig(apiConfig); if (telemetryUnitApi != null) getTelemetryUnitApi().setApiConfig(apiConfig); if (userApi != null) getUserApi().setApiConfig(apiConfig); } public void setMqttHttpChannel(MqttHttpChannel mqttHttpChannel) { Validate.notNull(mqttHttpChannel, "mqttHttpChannel is not set"); this.mqttHttpChannel = mqttHttpChannel; if (accountApi != null) getAccountApi().setMqttHttpChannel(mqttHttpChannel); if (configBackupApi != null) getConfigBackupApi().setMqttHttpChannel(mqttHttpChannel); if (coreEventApi != null) getCoreEventApi().setMqttHttpChannel(mqttHttpChannel); if (coreUserApi != null) getCoreUserApi().setMqttHttpChannel(mqttHttpChannel); if (deviceActionApi != null) getDeviceActionApi().setMqttHttpChannel(mqttHttpChannel); if (deviceApi != null) getDeviceApi().setMqttHttpChannel(mqttHttpChannel); if (deviceStateApi != null) getDeviceStateApi().setMqttHttpChannel(mqttHttpChannel); if (deviceTypeApi != null) getDeviceTypeApi().setMqttHttpChannel(mqttHttpChannel); if (gatewayApi != null) getGatewayApi().setMqttHttpChannel(mqttHttpChannel); if (nodeApi != null) getNodeApi().setMqttHttpChannel(mqttHttpChannel); if (nodeTypeApi != null) getNodeTypeApi().setMqttHttpChannel(mqttHttpChannel); if (rtuFirmwareApi != null) getRTUFirmwareApi().setMqttHttpChannel(mqttHttpChannel); if (softwareReleaseScheduleApi != null) getSoftwareReleaseScheduleApi().setMqttHttpChannel(mqttHttpChannel); if (softwareReleaseTransApi != null) getSoftwareReleaseTransApi().setMqttHttpChannel(mqttHttpChannel); if (telemetryApi != null) getTelemetryApi().setMqttHttpChannel(mqttHttpChannel); if (telemetryUnitApi != null) getTelemetryUnitApi().setMqttHttpChannel(mqttHttpChannel); if (userApi != null) getUserApi().setMqttHttpChannel(mqttHttpChannel); } public MqttHttpChannel getMqttHttpChannel() { return mqttHttpChannel; } public ApiConfig getApiConfig() { return apiConfig; } public synchronized AccountApi getAccountApi() { return accountApi != null ? accountApi : (accountApi = new AccountApi(apiConfig, mqttHttpChannel)); } public synchronized CoreEventApi getCoreEventApi() { return coreEventApi != null ? coreEventApi : (coreEventApi = new CoreEventApi(apiConfig, mqttHttpChannel)); } public synchronized CoreUserApi getCoreUserApi() { return coreUserApi != null ? coreUserApi : (coreUserApi = new CoreUserApi(apiConfig, mqttHttpChannel)); } public synchronized DeviceActionApi getDeviceActionApi() { return deviceActionApi != null ? deviceActionApi : (deviceActionApi = new DeviceActionApi(apiConfig, mqttHttpChannel)); } public synchronized DeviceApi getDeviceApi() { return deviceApi != null ? deviceApi : (deviceApi = new DeviceApi(apiConfig, mqttHttpChannel)); } public synchronized DeviceStateApi getDeviceStateApi() { return deviceStateApi != null ? deviceStateApi : (deviceStateApi = new DeviceStateApi(apiConfig, mqttHttpChannel)); } public synchronized GatewayApi getGatewayApi() { return gatewayApi != null ? gatewayApi : (gatewayApi = new GatewayApi(apiConfig, mqttHttpChannel)); } public synchronized NodeApi getNodeApi() { return nodeApi != null ? nodeApi : (nodeApi = new NodeApi(apiConfig, mqttHttpChannel)); } public synchronized NodeTypeApi getNodeTypeApi() { return nodeTypeApi != null ? nodeTypeApi : (nodeTypeApi = new NodeTypeApi(apiConfig, mqttHttpChannel)); } public synchronized SoftwareReleaseScheduleApi getSoftwareReleaseScheduleApi() { return softwareReleaseScheduleApi != null ? softwareReleaseScheduleApi : (softwareReleaseScheduleApi = new SoftwareReleaseScheduleApi(apiConfig, mqttHttpChannel)); } public synchronized SoftwareReleaseTransApi getSoftwareReleaseTransApi() { return softwareReleaseTransApi != null ? softwareReleaseTransApi : (softwareReleaseTransApi = new SoftwareReleaseTransApi(apiConfig, mqttHttpChannel)); } public synchronized TelemetryApi getTelemetryApi() { return telemetryApi != null ? telemetryApi : (telemetryApi = new TelemetryApi(apiConfig, mqttHttpChannel)); } public synchronized ConfigBackupApi getConfigBackupApi() { return configBackupApi != null ? configBackupApi : (configBackupApi = new ConfigBackupApi(apiConfig, mqttHttpChannel)); } public synchronized RTUFirmwareApi getRTUFirmwareApi() { return rtuFirmwareApi != null ? rtuFirmwareApi : (rtuFirmwareApi = new RTUFirmwareApi(apiConfig, mqttHttpChannel)); } public synchronized TelemetryUnitApi getTelemetryUnitApi() { return telemetryUnitApi != null ? telemetryUnitApi : (telemetryUnitApi = new TelemetryUnitApi(apiConfig, mqttHttpChannel)); } public synchronized DeviceTypeApi getDeviceTypeApi() { return deviceTypeApi != null ? deviceTypeApi : (deviceTypeApi = new DeviceTypeApi(apiConfig, mqttHttpChannel)); } public synchronized UserApi getUserApi() { return userApi != null ? userApi : (userApi = new UserApi(apiConfig, mqttHttpChannel)); } }
package net.canadensys.harvester.occurrence.reader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import net.canadensys.dataportal.occurrence.model.OccurrenceRawModel; import net.canadensys.harvester.ItemMapperIF; import net.canadensys.harvester.ItemReaderIF; import net.canadensys.harvester.occurrence.SharedParameterEnum; import net.canadensys.harvester.occurrence.mapper.OccurrenceMapper; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.gbif.dwca.io.Archive; import org.gbif.dwca.io.ArchiveFactory; import org.gbif.dwca.io.UnsupportedArchiveException; import com.google.common.collect.Lists; /** * Item reader for Darwin Core Archive. * * @author canadensys * */ public class DwcaItemReader extends AbstractDwcaReaderSupport implements ItemReaderIF<OccurrenceRawModel> { // get log4j handler private static final Logger LOGGER = Logger.getLogger(DwcaItemReader.class); private final AtomicBoolean canceled = new AtomicBoolean(false); private final ItemMapperIF<OccurrenceRawModel> mapper = new OccurrenceMapper(); private final List<String> dwcaIdExcludeList = Lists.newArrayList(); @Override public OccurrenceRawModel read() { OccurrenceRawModel occurrenceRawModel; do { if (canceled.get() || !rowsIt.hasNext()) { return null; } // ImmutableMap from Google Collections? Map<String, Object> properties = new HashMap<String, Object>(); int i = 0; String[] data = rowsIt.next(); for (String currHeader : headers) { properties.put(currHeader, data[i]); i++; } // check if some default values must be handled if (defaultValues != null) { for (String defaultValueCol : defaultValues.keySet()) { properties.put(defaultValueCol, defaultValues.get(defaultValueCol)); } } occurrenceRawModel = mapper.mapElement(properties); } while (shouldSkipRecord(occurrenceRawModel)); return occurrenceRawModel; } /** * Responsible to set DWCA_USED_TERMS */ @Override public void openReader(Map<SharedParameterEnum, Object> sharedParameters) { dwcaFilePath = (String) sharedParameters.get(SharedParameterEnum.DWCA_PATH); if (mapper == null) { throw new IllegalStateException("No mapper defined"); } if (StringUtils.isBlank(dwcaFilePath)) { throw new IllegalStateException("sharedParameters missing: DWCA_PATH is required."); } File dwcaFile = new File(dwcaFilePath); Archive dwcArchive; try { dwcArchive = ArchiveFactory.openArchive(dwcaFile); prepareReader(dwcArchive.getCore()); } catch (UnsupportedArchiveException e) { LOGGER.fatal("Can't open DwcaItemReader", e); } catch (IOException e) { LOGGER.fatal("Can't open DwcaItemReader", e); } // only use terms we know List<String> usedDwcTerms = getDwcaUsedTerms(); // set the used dwc terms used by this archive sharedParameters.put(SharedParameterEnum.DWCA_USED_TERMS, usedDwcTerms); } /** * Method used to discard(skip) some records allowing to partially import a resource. * This option should be used carefully in exceptional circumstance when an archive needs to be harvested * and faulty records (no or duplicated coredId) can not be fixed. * * @param occurrenceRawModel * @return */ private boolean shouldSkipRecord(OccurrenceRawModel occurrenceRawModel) { if (!dwcaIdExcludeList.isEmpty()) { return dwcaIdExcludeList.contains(occurrenceRawModel.getDwcaid()); } return false; } /** * Get headers found in the archive that can be mapped to OccurrenceRawModel. * * @return list of terms (simpleName) */ private List<String> getDwcaUsedTerms() { OccurrenceRawModel testModel = new OccurrenceRawModel(); List<String> usedDwcTerms = new ArrayList<String>(); for (String currHeader : headers) { if (PropertyUtils.isWriteable(testModel, currHeader)) { usedDwcTerms.add(currHeader); } else { LOGGER.warn("Property [" + currHeader + "] is not found or writeable in OccurrenceRawModel"); } } if (defaultValues != null) { for (String currHeader : defaultValues.keySet()) { if (PropertyUtils.isWriteable(testModel, currHeader)) { usedDwcTerms.add(currHeader); } else { LOGGER.warn("Property [" + currHeader + "] is not found or writeable in OccurrenceRawModel"); } } } return usedDwcTerms; } @Override public void closeReader() { super.closeReader(); } @Override public void abort() { canceled.set(true); } }
package com.domker.androidtoy.activity; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.domker.androidtoy.R; import com.domker.androidtoy.sound.SoundManager; /** * * * @ClassName: PianoActivity * @author wanlipeng * @date 2016120 5:00:31 */ public class PianoActivity extends Activity { private SoundManager soundManager = null; private OnClickListener onPianoKeyClickListener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.buttonPlay: playKeys(); break; case R.id.buttonClear: clearKeyShow(); break; case R.id.buttonSplite: default: if (v instanceof Button) { Button button = (Button) v; addKeyShow((String) button.getText()); } break; } } }; private final int[] buttonIds = { R.id.button_1, R.id.button_2, R.id.button_3, R.id.button_4, R.id.button_5, R.id.button_6, R.id.button_7, R.id.button_21, R.id.button_22, R.id.button_23, R.id.button_24, R.id.button_25, R.id.button_26, R.id.button_27 }; private TextView mTextShow = null; private List<String> keys = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.piano_layout); initPianoButtons(); soundManager = new SoundManager(this); } @Override protected void onDestroy() { super.onDestroy(); soundManager.onDestroy(); } private void initPianoButtons() { for (int id : buttonIds) { initButton(id); } mTextShow = (TextView) this.findViewById(R.id.textViewPiano); // init play key this.findViewById(R.id.buttonPlay).setOnClickListener(onPianoKeyClickListener); this.findViewById(R.id.buttonClear).setOnClickListener(onPianoKeyClickListener); this.findViewById(R.id.buttonSplite).setOnClickListener(onPianoKeyClickListener); } private void initButton(int buttonId) { this.findViewById(buttonId).setOnClickListener(onPianoKeyClickListener); } /** * * * @param key */ private void addKeyShow(String key) { String show = mTextShow.getText().toString(); if (TextUtils.isEmpty(show)) { mTextShow.setText(key); } else { mTextShow.setText(show + " " + key); } keys.add(key); } private void playKeys() { for (String key : keys) { float count = 1; if ("|".equals(key)) { count = 0.25f; } else { soundManager.playSound(key); } try { Thread.sleep((int)(300 * count)); } catch (InterruptedException e) { e.printStackTrace(); } } } private void clearKeyShow() { mTextShow.setText(""); keys.clear(); } }
package com.example.webappsampler; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.connectsdk.device.ConnectableDevice; import com.connectsdk.device.ConnectableDeviceListener; import com.connectsdk.device.DevicePicker; import com.connectsdk.discovery.CapabilityFilter; import com.connectsdk.discovery.DiscoveryManager; import com.connectsdk.service.DeviceService; import com.connectsdk.service.DeviceService.PairingType; import com.connectsdk.service.capability.WebAppLauncher; import com.connectsdk.service.capability.listeners.ResponseListener; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.sessions.WebAppSession; public class FullscreenActivity extends Activity { private Button mLaunchButton; private Button mCloseButton; private Button mSendButton; private EditText mMessageText; private TextView mStatusTextView; private DevicePicker mDevicePicker; private ConnectableDevice mDevice; private WebAppSession mWebAppSession; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); mLaunchButton = (Button) findViewById(R.id.launchButton); mLaunchButton.setOnClickListener(mLaunchClickListener); mCloseButton = (Button) findViewById(R.id.closeButton); mCloseButton.setOnClickListener(mCloseClickListener); mSendButton = (Button) findViewById(R.id.sendButton); mSendButton.setOnClickListener(sendClickListener); mMessageText = (EditText) findViewById(R.id.messageText); mStatusTextView = (TextView) findViewById(R.id.statusTextView); DiscoveryManager.init(getApplicationContext()); CapabilityFilter webAppFilter = new CapabilityFilter(WebAppLauncher.Launch, WebAppLauncher.Close, WebAppLauncher.Message_Send); DiscoveryManager.getInstance().setCapabilityFilters(webAppFilter); DiscoveryManager.getInstance().start(); mDevicePicker = new DevicePicker(this); } private void handleConnectSuccess() { mLaunchButton.setEnabled(false); mCloseButton.setEnabled(true); mSendButton.setEnabled(true); mMessageText.setEnabled(true); } private void cleanup() { if (mWebAppSession != null) { mWebAppSession.disconnectFromWebApp(); mWebAppSession = null; } if (mDevice != null) { mDevice.removeListener(mDeviceListener); mDevice.disconnect(); mDevice = null; } mLaunchButton.setEnabled(true); mCloseButton.setEnabled(false); mSendButton.setEnabled(false); mMessageText.setEnabled(false); } private void log(String message) { String currentMessage = mStatusTextView.getText().toString(); String newMessage = message + "\n" + currentMessage; mStatusTextView.setText(newMessage); } private View.OnClickListener mLaunchClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (mWebAppSession != null || mDevice != null) cleanup(); AlertDialog alertDialog = mDevicePicker.getPickerDialog("Select a device", mDeviceSelectListener); alertDialog.show(); } }; private View.OnClickListener mCloseClickListener = new View.OnClickListener() { @Override public void onClick(View v) { log("Closing web app"); mWebAppSession.close(null); mWebAppSession = null; cleanup(); } }; private View.OnClickListener sendClickListener = new View.OnClickListener() { @Override public void onClick(View v) { final String message = mMessageText.getText().toString(); log("Sending message: \"" + message + "\""); mWebAppSession.sendMessage(message, new ResponseListener<Object>() { @Override public void onError(ServiceCommandError error) { log("Could not send message, disconnecting..."); cleanup(); } @Override public void onSuccess(Object object) { log("Message \"" + message + "\" sent successfully."); } }); mMessageText.setText(""); } }; private AdapterView.OnItemClickListener mDeviceSelectListener = new AdapterView.OnItemClickListener() { public void onItemClick(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) { mStatusTextView.setText(""); mDevice = (ConnectableDevice)arg0.getItemAtPosition(arg2); log("Connecting to device " + mDevice.getFriendlyName()); mDevice.addListener(mDeviceListener); mDevice.connect(); }; }; private ConnectableDeviceListener mDeviceListener = new ConnectableDeviceListener() { @Override public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) { // since we haven't enabled pairing, we don't need to solve for this case } @Override public void onDeviceReady(ConnectableDevice device) { log("Connected to device " + device.getFriendlyName()); String webAppId = null; if (device.getServiceByName("Chromecast")!= null) webAppId = "DDCEDE96"; else if (device.getServiceByName("webOS TV") != null) webAppId = "SampleWebApp"; if (webAppId != null) { log("Launching web app with id " + webAppId); device.getWebAppLauncher().launchWebApp(webAppId, mWebAppLaunchListener); } } @Override public void onDeviceDisconnected(ConnectableDevice device) { log("Disconnected from device"); cleanup(); } @Override public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) { log("Could not connect to device " + error.getLocalizedMessage()); cleanup(); } @Override public void onCapabilityUpdated(ConnectableDevice device, List<String> added, List<String> removed) { // we can ignore this case } }; private WebAppSession.LaunchListener mWebAppLaunchListener = new WebAppSession.LaunchListener() { @Override public void onError(ServiceCommandError error) { log("Web app could not be launched: " + error.getLocalizedMessage()); cleanup(); } @Override public void onSuccess(WebAppSession webAppSession) { log("Web app launch successful, connecting... "); mWebAppSession = webAppSession; mWebAppSession.connect(mWebAppConnectListener); } }; private ResponseListener<Object> mWebAppConnectListener = new ResponseListener<Object>() { public void onSuccess(Object object) { log("Web app connected!"); handleConnectSuccess(); }; @Override public void onError(ServiceCommandError error) { log("Web app could not be connected: " + error.getLocalizedMessage()); cleanup(); } }; }
package com.inmobi.messaging.consumer.databus; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.inmobi.databus.CheckpointProvider; import com.inmobi.databus.Cluster; import com.inmobi.databus.DatabusConfig; import com.inmobi.databus.DatabusConfigParser; import com.inmobi.databus.FSCheckpointProvider; import com.inmobi.databus.SourceStream; import com.inmobi.messaging.ClientConfig; import com.inmobi.messaging.Message; import com.inmobi.messaging.consumer.AbstractMessageConsumer; /** * Consumes data from the configured databus stream topic. * * Initializes the databus configuration from the configuration file specified * by the configuration {@value #databusConfigFileKey}, the default value is * {@value #DEFAULT_DATABUS_CONFIG_FILE} * * Consumer can specify a comma separated list of clusters from which the stream * should be streamed via configuration {@value #databusClustersConfig}. If no * such configuration exists, it will stream from all the source clusters of the * stream. * * This consumer supports mark and reset. Whenever user calls mark, the current * consumption will be check-pointed in a directory configurable via * {@value #checkpointDirConfig}. The default value for value for checkpoint * directory is <code>.</code>. After reset(), consumer will start reading * messages from last check-pointed position. * * Maximum consumer buffer size is configurable via {@value #queueSizeConfig}. * The default value is {@value #DEFAULT_QUEUE_SIZE}. Consumer would wait for * space in the buffer, if buffer is full. Wait time for consumer if buffer is * full is configurable via {@value #waitTimeForBufferFullConfig}, and default * value is {@value #DEFAULT_WAIT_TIME_FOR_BUFFER_FULL}. * * If consumer is reading from the file that is currently being written by * producer, consumer will wait for flush to happen on the file. The wait time * for flush is configurable via {@value #waitTimeForFlushConfig}, and default * value is {@value #DEFAULT_WAIT_TIME_FOR_FLUSH} * * Initializes partition readers for each active collector on the stream. * TODO: Dynamically detect if new collectors are added and start readers for * them */ public class DatabusConsumer extends AbstractMessageConsumer { private static final Log LOG = LogFactory.getLog(DatabusConsumer.class); public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class .getName(); public static final int DEFAULT_QUEUE_SIZE = 1000; public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 1000; // 1 second public static final long DEFAULT_WAIT_TIME_FOR_BUFFER_FULL = 1000; // 1second public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml"; public static final String queueSizeConfig = "databus.consumer.buffer.size"; public static final String waitTimeForFlushConfig = "databus.consumer.waittime.forcollectorflush"; public static final String waitTimeForBufferFullConfig = "databus.consumer.waittime.forbufferfull"; public static final String checkpointDirConfig = "databus.consumer.checkpoint.dir"; public static final String databusConfigFileKey = "databus.conf"; public static final String databusClustersConfig = "databus.consumer.clusters"; private static final long ONE_DAY_IN_MILLIS = 1 * 24 * 60 * 60 * 1000; private DatabusConfig databusConfig; private BlockingQueue<QueueEntry> buffer; private String databusCheckpointDir; private final Map<PartitionId, PartitionReader> readers = new HashMap<PartitionId, PartitionReader>(); private CheckpointProvider checkpointProvider; private Checkpoint currentCheckpoint; private long waitTimeForFlush; private long waitTimeForBufferFull; private int bufferSize; private String[] clusters; @Override protected void init(ClientConfig config) { super.init(config); initializeConfig(config); start(); } void initializeConfig(ClientConfig config) { bufferSize = config.getInteger(queueSizeConfig, DEFAULT_QUEUE_SIZE); buffer = new LinkedBlockingQueue<QueueEntry>(bufferSize); databusCheckpointDir = config.getString(checkpointDirConfig, "."); waitTimeForFlush = config.getLong(waitTimeForFlushConfig, DEFAULT_WAIT_TIME_FOR_FLUSH); waitTimeForBufferFull = config.getLong(waitTimeForBufferFullConfig, DEFAULT_WAIT_TIME_FOR_BUFFER_FULL); String clusterStr = config.getString(databusClustersConfig); if (clusterStr != null) { clusters = clusterStr.split(","); } this.checkpointProvider = new FSCheckpointProvider(databusCheckpointDir); try { byte[] chkpointData = checkpointProvider.read(getChkpointKey()); if (chkpointData != null) { this.currentCheckpoint = new Checkpoint(chkpointData); } else { Map<PartitionId, PartitionCheckpoint> partitionsChkPoints = new HashMap<PartitionId, PartitionCheckpoint>(); this.currentCheckpoint = new Checkpoint(partitionsChkPoints); } String fileName = config.getString(databusConfigFileKey, DEFAULT_DATABUS_CONFIG_FILE); DatabusConfigParser parser = new DatabusConfigParser(fileName); databusConfig = parser.getConfig(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } LOG.info("Databus consumer initialized with streamName:" + topicName + " consumerName:" + consumerName + " startTime:" + startTime + " queueSize:" + bufferSize + " checkPoint:" + currentCheckpoint); } Map<PartitionId, PartitionReader> getPartitionReaders() { return readers; } Checkpoint getCurrentCheckpoint() { return currentCheckpoint; } DatabusConfig getDatabusConfig() { return databusConfig; } CheckpointProvider getCheckpointProvider() { return checkpointProvider; } int getBufferSize() { return bufferSize; } @Override public synchronized Message next() { QueueEntry entry; try { entry = buffer.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } currentCheckpoint.set(entry.partitionId, entry.partitionChkpoint); return entry.message; } private synchronized void start() { createPartitionReaders(); for (PartitionReader reader : readers.values()) { reader.start(); } } private void createPartitionReaders() { Map<PartitionId, PartitionCheckpoint> partitionsChkPoints = currentCheckpoint.getPartitionsCheckpoint(); if (!databusConfig.getSourceStreams().containsKey(topicName)) { throw new RuntimeException("Stream " + topicName + " does not exist"); } SourceStream sourceStream = databusConfig.getSourceStreams().get(topicName); LOG.debug("Stream name: " + sourceStream.getName()); Set<String> clusterNames; if (clusters != null) { clusterNames = new HashSet<String>(); for (String c : clusters) { if (sourceStream.getSourceClusters().contains(c)) { clusterNames.add(c); } } } else { clusterNames = sourceStream.getSourceClusters(); } long currentMillis = System.currentTimeMillis(); for (String c : clusterNames) { LOG.debug("Creating partition readers for cluster:" + c); Cluster cluster = databusConfig.getClusters().get(c); long retentionMillis = sourceStream.getRetentionInDays(c) * ONE_DAY_IN_MILLIS; Date allowedStartTime = new Date( currentMillis- retentionMillis); try { FileSystem fs = FileSystem.get(cluster.getHadoopConf()); Path path = new Path(cluster.getDataDir(), topicName); LOG.debug("Stream dir: " + path); FileStatus[] list = fs.listStatus(path); if (list == null || list.length == 0) { LOG.warn("No collector dirs available in stream directory"); return; } for (FileStatus status : list) { String collector = status.getPath().getName(); LOG.debug("Collector is " + collector); PartitionId id = new PartitionId(cluster.getName(), collector); if (partitionsChkPoints.get(id) == null) { partitionsChkPoints.put(id, null); } Date partitionTimestamp = startTime; if (startTime == null && partitionsChkPoints.get(id) == null) { LOG.info("There is no startTime passed and no checkpoint exists" + " for the partition: " + id + " starting from the start" + " of the stream."); partitionTimestamp = allowedStartTime; } else if (startTime != null && startTime.before(allowedStartTime)) { LOG.info("Start time passed is before the start of the stream," + " starting from the start of the stream."); partitionTimestamp = allowedStartTime; } else { LOG.info("Creating partition with timestamp: " + partitionTimestamp + " checkpoint:" + partitionsChkPoints.get(id)); } PartitionReader reader = new PartitionReader(id, partitionsChkPoints.get(id), cluster, buffer, topicName, partitionTimestamp, waitTimeForFlush, waitTimeForBufferFull); readers.put(id, reader); LOG.info("Created partition " + id); } } catch (IOException e) { throw new RuntimeException(e); } } } private String getChkpointKey() { return consumerName + "_" + topicName; } @Override public synchronized void reset() { // restart the service, consumer will start streaming from the last saved // checkpoint close(); try { this.currentCheckpoint = new Checkpoint( checkpointProvider.read(getChkpointKey())); LOG.info("Resetting to checkpoint:" + currentCheckpoint); } catch (IOException e) { throw new RuntimeException(e); } // reset to last marked position, ignore start time startTime = null; start(); } @Override public synchronized void mark() { try { checkpointProvider.checkpoint(getChkpointKey(), currentCheckpoint.toBytes()); LOG.info("Committed checkpoint:" + currentCheckpoint); } catch (IOException e) { throw new RuntimeException(e); } } @Override public synchronized void close() { for (PartitionReader reader : readers.values()) { reader.close(); } readers.clear(); buffer.clear(); buffer = new LinkedBlockingQueue<QueueEntry>(bufferSize); } @Override public boolean isMarkSupported() { return true; } }
package com.polidea.rxandroidble.mockrxandroidble; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.support.annotation.NonNull; import com.polidea.rxandroidble.NotificationSetupMode; import com.polidea.rxandroidble.RxBleConnection; import com.polidea.rxandroidble.RxBleDeviceServices; import com.polidea.rxandroidble.RxBleRadioOperationCustom; import com.polidea.rxandroidble.exceptions.BleConflictingNotificationAlreadySetException; import com.polidea.rxandroidble.internal.connection.ImmediateSerializedBatchAckStrategy; import com.polidea.rxandroidble.internal.util.ObservableUtil; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import rx.Completable; import rx.Observable; import rx.functions.Action0; import rx.functions.Actions; import rx.functions.Func1; import static rx.Observable.just; public class RxBleConnectionMock implements RxBleConnection { /** * Value used to enable notification for a client configuration descriptor */ private static final byte[] ENABLE_NOTIFICATION_VALUE = {0x01, 0x00}; /** * Value used to enable indication for a client configuration descriptor */ private static final byte[] ENABLE_INDICATION_VALUE = {0x02, 0x00}; /** * Value used to disable notifications or indicatinos */ private static final byte[] DISABLE_NOTIFICATION_VALUE = {0x00, 0x00}; private static final UUID CLIENT_CHARACTERISTIC_CONFIG_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private HashMap<UUID, Observable<Observable<byte[]>>> notificationObservableMap = new HashMap<>(); private HashMap<UUID, Observable<Observable<byte[]>>> indicationObservableMap = new HashMap<>(); private RxBleDeviceServices rxBleDeviceServices; private int rssi; private int currentMtu = 23; private Map<UUID, Observable<byte[]>> characteristicNotificationSources; public RxBleConnectionMock(RxBleDeviceServices rxBleDeviceServices, int rssi, Map<UUID, Observable<byte[]>> characteristicNotificationSources) { this.rxBleDeviceServices = rxBleDeviceServices; this.rssi = rssi; this.characteristicNotificationSources = characteristicNotificationSources; } @Override public Observable<Integer> requestMtu(final int mtu) { return Observable.fromCallable(new Callable<Integer>() { @Override public Integer call() throws Exception { currentMtu = mtu; return mtu; } }); } @Override public int getMtu() { return currentMtu; } @Override public Observable<RxBleDeviceServices> discoverServices() { return Observable.just(rxBleDeviceServices); } @Override public Observable<RxBleDeviceServices> discoverServices(long timeout, @NonNull TimeUnit timeUnit) { return Observable.just(rxBleDeviceServices); } @Override public Observable<BluetoothGattCharacteristic> getCharacteristic(@NonNull final UUID characteristicUuid) { return discoverServices() .flatMap(new Func1<RxBleDeviceServices, Observable<? extends BluetoothGattCharacteristic>>() { @Override public Observable<? extends BluetoothGattCharacteristic> call(RxBleDeviceServices rxBleDeviceServices) { return rxBleDeviceServices.getCharacteristic(characteristicUuid); } }); } @Override public Observable<byte[]> readCharacteristic(@NonNull UUID characteristicUuid) { return getCharacteristic(characteristicUuid).map(new Func1<BluetoothGattCharacteristic, byte[]>() { @Override public byte[] call(BluetoothGattCharacteristic bluetoothGattCharacteristic) { return bluetoothGattCharacteristic.getValue(); } }); } @Override public Observable<byte[]> readCharacteristic(@NonNull BluetoothGattCharacteristic characteristic) { return Observable.just(characteristic.getValue()); } @Override public Observable<byte[]> readDescriptor(@NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid, @NonNull final UUID descriptorUuid) { return discoverServices() .flatMap(new Func1<RxBleDeviceServices, Observable<BluetoothGattDescriptor>>() { @Override public Observable<BluetoothGattDescriptor> call(RxBleDeviceServices rxBleDeviceServices) { return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid); } }) .map(new Func1<BluetoothGattDescriptor, byte[]>() { @Override public byte[] call(BluetoothGattDescriptor bluetoothGattDescriptor) { return bluetoothGattDescriptor.getValue(); } }); } @Override public Observable<byte[]> readDescriptor(@NonNull BluetoothGattDescriptor descriptor) { return Observable.just(descriptor.getValue()); } @Override public Observable<Integer> readRssi() { return Observable.just(rssi); } @Override public Observable<Observable<byte[]>> setupNotification(@NonNull UUID characteristicUuid) { return setupNotification(characteristicUuid, NotificationSetupMode.DEFAULT); } @Override public Observable<Observable<byte[]>> setupNotification(@NonNull BluetoothGattCharacteristic characteristic) { return setupNotification(characteristic, NotificationSetupMode.DEFAULT); } @Override public Observable<Observable<byte[]>> setupNotification(@NonNull final UUID characteristicUuid, @NonNull final NotificationSetupMode setupMode) { if (indicationObservableMap.containsKey(characteristicUuid)) { return Observable.error(new BleConflictingNotificationAlreadySetException(characteristicUuid, true)); } Observable<Observable<byte[]>> availableObservable = notificationObservableMap.get(characteristicUuid); if (availableObservable != null) { return availableObservable; } Observable<Observable<byte[]>> newObservable = createCharacteristicNotificationObservable(characteristicUuid, setupMode, false) .doOnUnsubscribe(new Action0() { @Override public void call() { dismissCharacteristicNotification(characteristicUuid, setupMode, false); } }) .map(new Func1<Observable<byte[]>, Observable<byte[]>>() { @Override public Observable<byte[]> call(Observable<byte[]> notificationDescriptorData) { return observeOnCharacteristicChangeCallbacks(characteristicUuid); } }) .replay(1) .refCount(); notificationObservableMap.put(characteristicUuid, newObservable); return newObservable; } @Override public Observable<Observable<byte[]>> setupNotification(@NonNull BluetoothGattCharacteristic characteristic, @NonNull NotificationSetupMode setupMode) { return setupNotification(characteristic.getUuid(), setupMode); } @Override public Observable<Observable<byte[]>> setupIndication(@NonNull UUID characteristicUuid) { return setupIndication(characteristicUuid, NotificationSetupMode.DEFAULT); } @Override public Observable<Observable<byte[]>> setupIndication(@NonNull BluetoothGattCharacteristic characteristic) { return setupIndication(characteristic.getUuid(), NotificationSetupMode.DEFAULT); } @Override public Observable<Observable<byte[]>> setupIndication(@NonNull final UUID characteristicUuid, @NonNull final NotificationSetupMode setupMode) { if (notificationObservableMap.containsKey(characteristicUuid)) { return Observable.error(new BleConflictingNotificationAlreadySetException(characteristicUuid, false)); } Observable<Observable<byte[]>> availableObservable = indicationObservableMap.get(characteristicUuid); if (availableObservable != null) { return availableObservable; } Observable<Observable<byte[]>> newObservable = createCharacteristicNotificationObservable(characteristicUuid, setupMode, true) .doOnUnsubscribe(new Action0() { @Override public void call() { dismissCharacteristicNotification(characteristicUuid, setupMode, true); } }) .map(new Func1<Observable<byte[]>, Observable<byte[]>>() { @Override public Observable<byte[]> call(Observable<byte[]> notificationDescriptorData) { return observeOnCharacteristicChangeCallbacks(characteristicUuid); } }) .replay(1) .refCount(); indicationObservableMap.put(characteristicUuid, newObservable); return newObservable; } @Override public Observable<Observable<byte[]>> setupIndication(@NonNull BluetoothGattCharacteristic characteristic, @NonNull NotificationSetupMode setupMode) { return setupIndication(characteristic.getUuid(), setupMode); } @Override public Observable<BluetoothGattCharacteristic> writeCharacteristic( @NonNull final BluetoothGattCharacteristic bluetoothGattCharacteristic) { return getCharacteristic(bluetoothGattCharacteristic.getUuid()) .map(new Func1<BluetoothGattCharacteristic, Boolean>() { @Override public Boolean call(BluetoothGattCharacteristic characteristic) { return characteristic.setValue(bluetoothGattCharacteristic.getValue()); } }) .flatMap(new Func1<Boolean, Observable<? extends BluetoothGattCharacteristic>>() { @Override public Observable<? extends BluetoothGattCharacteristic> call(Boolean ignored) { return Observable.just(bluetoothGattCharacteristic); } }); } @Override public Observable<byte[]> writeCharacteristic(@NonNull BluetoothGattCharacteristic bluetoothGattCharacteristic, @NonNull byte[] data) { bluetoothGattCharacteristic.setValue(data); return Observable.just(data); } @Override public LongWriteOperationBuilder createNewLongWriteBuilder() { return new LongWriteOperationBuilder() { private Observable<BluetoothGattCharacteristic> bluetoothGattCharacteristicObservable; private int maxBatchSize = 20; // default private byte[] bytes; private WriteOperationAckStrategy writeOperationAckStrategy = // default new ImmediateSerializedBatchAckStrategy(); @Override public LongWriteOperationBuilder setBytes(@NonNull byte[] bytes) { this.bytes = bytes; return this; } @Override public LongWriteOperationBuilder setCharacteristicUuid(@NonNull final UUID uuid) { bluetoothGattCharacteristicObservable = discoverServices().flatMap( new Func1<RxBleDeviceServices, Observable<BluetoothGattCharacteristic>>() { @Override public Observable<BluetoothGattCharacteristic> call(RxBleDeviceServices rxBleDeviceServices) { return rxBleDeviceServices.getCharacteristic(uuid); } } ); return this; } @Override public LongWriteOperationBuilder setCharacteristic( @NonNull BluetoothGattCharacteristic bluetoothGattCharacteristic) { bluetoothGattCharacteristicObservable = Observable.just(bluetoothGattCharacteristic); return this; } @Override public LongWriteOperationBuilder setMaxBatchSize(int maxBatchSize) { this.maxBatchSize = maxBatchSize; return this; } @Override public LongWriteOperationBuilder setWriteOperationAckStrategy(@NonNull WriteOperationAckStrategy writeOperationAckStrategy) { this.writeOperationAckStrategy = writeOperationAckStrategy; return this; } @Override public Observable<byte[]> build() { if (bluetoothGattCharacteristicObservable == null) { throw new IllegalArgumentException("setCharacteristicUuid() or setCharacteristic() needs to be called before build()"); } if (bytes == null) { throw new IllegalArgumentException("setBytes() needs to be called before build()"); } final boolean excess = bytes.length % maxBatchSize > 0; final AtomicInteger numberOfBatches = new AtomicInteger(bytes.length / maxBatchSize + (excess ? 1 : 0)); return Observable .fromCallable(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return numberOfBatches.get() > 0; } }) .compose(writeOperationAckStrategy) .repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Void> onWriteFinished) { return onWriteFinished .takeWhile(new Func1<Void, Boolean>() { @Override public Boolean call(Void aVoid) { return numberOfBatches.decrementAndGet() > 0; } }); } }) .toCompletable() .andThen(Observable.just(bytes)); } }; } @Override public Observable<byte[]> writeCharacteristic(@NonNull UUID characteristicUuid, @NonNull final byte[] data) { return getCharacteristic(characteristicUuid) .map(new Func1<BluetoothGattCharacteristic, Boolean>() { @Override public Boolean call(BluetoothGattCharacteristic characteristic) { return characteristic.setValue(data); } }) .flatMap(new Func1<Boolean, Observable<? extends byte[]>>() { @Override public Observable<? extends byte[]> call(Boolean ignored) { return Observable.just(data); } }); } @Override public Observable<byte[]> writeDescriptor(@NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid, @NonNull final UUID descriptorUuid, @NonNull final byte[] data) { return discoverServices() .flatMap(new Func1<RxBleDeviceServices, Observable<BluetoothGattDescriptor>>() { @Override public Observable<BluetoothGattDescriptor> call(RxBleDeviceServices rxBleDeviceServices) { return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid); } }) .map(new Func1<BluetoothGattDescriptor, Boolean>() { @Override public Boolean call(BluetoothGattDescriptor bluetoothGattDescriptor) { return bluetoothGattDescriptor.setValue(data); } }).flatMap(new Func1<Boolean, Observable<? extends byte[]>>() { @Override public Observable<? extends byte[]> call(Boolean ignored) { return Observable.just(data); } }); } @Override public Observable<byte[]> writeDescriptor(@NonNull final BluetoothGattDescriptor descriptor, @NonNull final byte[] data) { return Completable.fromAction(new Action0() { @Override public void call() { descriptor.setValue(data); } }) .andThen(Observable.just(data)); } private Observable<Observable<byte[]>> createCharacteristicNotificationObservable(final UUID characteristicUuid, NotificationSetupMode setupMode, boolean isIndication) { return setupCharacteristicNotification(characteristicUuid, setupMode, true, isIndication) .flatMap(new Func1<Boolean, Observable<Boolean>>() { @Override public Observable<Boolean> call(Boolean onNext) { return ObservableUtil.justOnNext(onNext); } }) .flatMap(new Func1<Boolean, Observable<? extends Observable<byte[]>>>() { @Override public Observable<? extends Observable<byte[]>> call(Boolean bluetoothGattDescriptorPair) { if (!characteristicNotificationSources.containsKey(characteristicUuid)) { return Observable.error(new IllegalStateException("Lack of notification source for given characteristic")); } return Observable.just(characteristicNotificationSources.get(characteristicUuid)); } }); } private void dismissCharacteristicNotification(UUID characteristicUuid, NotificationSetupMode setupMode, boolean isIndication) { notificationObservableMap.remove(characteristicUuid); setupCharacteristicNotification(characteristicUuid, setupMode, false, isIndication) .subscribe( Actions.empty(), Actions.<Throwable>toAction1(Actions.empty()) ); } @NonNull private Observable<BluetoothGattDescriptor> getClientConfigurationDescriptor(UUID characteristicUuid) { return getCharacteristic(characteristicUuid) .map(new Func1<BluetoothGattCharacteristic, BluetoothGattDescriptor>() { @Override public BluetoothGattDescriptor call(BluetoothGattCharacteristic bluetoothGattCharacteristic) { BluetoothGattDescriptor bluetoothGattDescriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID); if (bluetoothGattDescriptor == null) { //adding notification descriptor if not present bluetoothGattDescriptor = new BluetoothGattDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID, 0); bluetoothGattCharacteristic.addDescriptor(bluetoothGattDescriptor); } return bluetoothGattDescriptor; } }); } @NonNull private Observable<byte[]> observeOnCharacteristicChangeCallbacks(UUID characteristicUuid) { return characteristicNotificationSources.get(characteristicUuid); } @NonNull private Observable<Boolean> setupCharacteristicNotification( final UUID bluetoothGattCharacteristicUUID, final NotificationSetupMode setupMode, final boolean enabled, final boolean isIndication ) { if (setupMode == NotificationSetupMode.DEFAULT) { final byte[] enableValue = isIndication ? ENABLE_INDICATION_VALUE : ENABLE_NOTIFICATION_VALUE; return getClientConfigurationDescriptor(bluetoothGattCharacteristicUUID) .flatMap(new Func1<BluetoothGattDescriptor, Observable<byte[]>>() { @Override public Observable<byte[]> call(BluetoothGattDescriptor bluetoothGattDescriptor) { return writeDescriptor(bluetoothGattDescriptor, enabled ? enableValue : DISABLE_NOTIFICATION_VALUE); } }) .map(new Func1<byte[], Boolean>() { @Override public Boolean call(byte[] ignored) { return true; } }); } else { return just(true); } } @Override public <T> Observable<T> queue(@NonNull RxBleRadioOperationCustom<T> operation) { throw new UnsupportedOperationException("Mock does not support queuing custom operation."); } }
package test; import static org.junit.Assert.*; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import clue.BadConfigFormatException; import clue.Board; import clue.BoardCell; public class TestBoardAdjacencies { private static Board board; LinkedList<Integer> list; Set<BoardCell> targets; @Before public void setUp() { board = new Board(); try { board.loadConfigFiles("ClueBoard.csv", "legend.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (BadConfigFormatException e) { e.printStackTrace(); } board.calcAdjacencies(); list = null; targets = null; } // Red: adjacency list tests, inside room @Test public void testAdjacenciesInsideRooms1() { list = board.getAdjList(board.calcIndex(1, 1)); Assert.assertEquals(0, list.size()); } @Test public void testAdjacenciesInsideRooms2() { list = board.getAdjList(board.calcIndex(4, 18)); Assert.assertEquals(0, list.size()); } @Test public void testAdjacenciesInsideRooms3() { list = board.getAdjList(board.calcIndex(11, 6)); Assert.assertEquals(0, list.size()); } @Test public void testAdjacenciesInsideRooms4() { list = board.getAdjList(board.calcIndex(22, 11)); Assert.assertEquals(0, list.size()); } // Purple: adjacency list tests, room exits @Test public void testAdjacenciesRoomExits1() { list = board.getAdjList(board.calcIndex(5, 12)); Assert.assertTrue(list.contains(board.calcIndex(6, 12))); Assert.assertEquals(1, list.size()); } @Test public void testAdjacenciesRoomExits2() { list = board.getAdjList(board.calcIndex(10, 18)); Assert.assertTrue(list.contains(board.calcIndex(10, 17))); Assert.assertEquals(1, list.size()); } @Test public void testAdjacenciesRoomExits3() { list = board.getAdjList(board.calcIndex(11, 7)); Assert.assertTrue(list.contains(board.calcIndex(11, 8))); Assert.assertEquals(1, list.size()); } @Test public void testAdjacenciesRoomExits4() { list = board.getAdjList(board.calcIndex(16, 16)); Assert.assertTrue(list.contains(board.calcIndex(15, 16))); Assert.assertEquals(1, list.size()); } // Green: adjacency list tests beside room entrance @Test public void testAdjacenciesRoomEntrances1() { list = board.getAdjList(board.calcIndex(6, 13)); assertTrue(list.contains(board.calcIndex(5, 13))); assertTrue(list.contains(board.calcIndex(6, 14))); assertTrue(list.contains(board.calcIndex(7, 13))); assertTrue(list.contains(board.calcIndex(6, 12))); assertEquals(4, list.size()); } @Test public void testAdjacenciesRoomEntrances2() { list = board.getAdjList(board.calcIndex(10, 17)); assertTrue(list.contains(board.calcIndex(9, 17))); assertTrue(list.contains(board.calcIndex(10, 18))); assertTrue(list.contains(board.calcIndex(11, 17))); assertTrue(list.contains(board.calcIndex(10, 16))); assertEquals(4, list.size()); } @Test public void testAdjacenciesRoomEntrances3() { list = board.getAdjList(board.calcIndex(15, 14)); assertTrue(list.contains(board.calcIndex(14, 14))); assertTrue(list.contains(board.calcIndex(15, 15))); assertTrue(list.contains(board.calcIndex(15, 13))); assertEquals(3, list.size()); } @Test public void testAdjacenciesRoomEntrances4() { list = board.getAdjList(board.calcIndex(14, 8)); assertTrue(list.contains(board.calcIndex(13, 8))); assertTrue(list.contains(board.calcIndex(14, 9))); assertTrue(list.contains(board.calcIndex(15, 8))); assertTrue(list.contains(board.calcIndex(14, 7))); assertEquals(4, list.size()); } @Test public void testAdjacenciesRoomEntrances5() { list = board.getAdjList(board.calcIndex(4, 15)); assertTrue(list.contains(board.calcIndex(3, 15))); assertTrue(list.contains(board.calcIndex(5, 15))); assertEquals(2, list.size()); } // Light purple: walkway scenarios @Test public void testAdjacenciesWalkways1() { list = board.getAdjList(board.calcIndex(0, 15)); assertTrue(list.contains(board.calcIndex(1, 15))); assertEquals(1, list.size()); } @Test public void testAdjacenciesWalkways2() { list = board.getAdjList(board.calcIndex(5, 18)); assertTrue(list.contains(board.calcIndex(5, 19))); assertTrue(list.contains(board.calcIndex(6, 18))); assertTrue(list.contains(board.calcIndex(5, 17))); assertEquals(3, list.size()); } @Test public void testAdjacenciesWalkways3() { list = board.getAdjList(board.calcIndex(7, 22)); assertTrue(list.contains(board.calcIndex(6, 22))); assertTrue(list.contains(board.calcIndex(7, 21))); assertEquals(2, list.size()); } @Test public void testAdjacenciesWalkways4() { list = board.getAdjList(board.calcIndex(10, 16)); assertTrue(list.contains(board.calcIndex(9, 16))); assertTrue(list.contains(board.calcIndex(10, 17))); assertTrue(list.contains(board.calcIndex(11, 16))); assertTrue(list.contains(board.calcIndex(10, 15))); assertEquals(4, list.size()); } @Test public void testAdjacenciesWalkways5() { list = board.getAdjList(board.calcIndex(16, 0)); assertTrue(list.contains(board.calcIndex(15, 0))); assertTrue(list.contains(board.calcIndex(16, 1))); assertEquals(2, list.size()); } // Light blue: test targets @Test public void testTargetsOneStep() { board.calcTargets(4, 10, 1); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(3, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 10)))); assertEquals(2, targets.size()); board.calcTargets(14, 13, 1); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 13)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 12)))); assertEquals(3, targets.size()); } // Light blue: test targets @Test public void testTargetsTwoSteps() { board.calcTargets(4, 10, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(2, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertEquals(3, targets.size()); board.calcTargets(14, 13, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 14)))); assertEquals(4, targets.size()); board.calcTargets(8, 9, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 8)))); assertEquals(6, targets.size()); board.calcTargets(15, 4, 2); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 2)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 3)))); assertEquals(4, targets.size()); } // Light blue: test targets @Test public void testTargetsThreeSteps() { board.calcTargets(4, 10, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(1, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertEquals(4, targets.size()); board.calcTargets(14, 13, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 15)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 16)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 15)))); assertEquals(7, targets.size()); board.calcTargets(8, 9, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(11, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 8)))); assertEquals(10, targets.size()); board.calcTargets(15, 4, 3); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 1)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 3)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 2)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 5)))); assertEquals(8, targets.size()); } // Light blue: test targets @Test public void testTargetsFourSteps() { board.calcTargets(4, 10, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(0, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 11)))); assertEquals(7, targets.size()); board.calcTargets(14, 13, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(12, 15)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 16)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 15)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 17)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 13)))); // Door assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 14)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 16)))); assertEquals(12, targets.size()); board.calcTargets(8, 9, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(5, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 11)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 10)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 12)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 9)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(11, 8)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(12, 9)))); assertEquals(14, targets.size()); board.calcTargets(15, 4, 4); targets = board.getTargets(); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 4)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 6)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 5)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 7)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 0)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(15, 2)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 1)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(16, 3)))); assertTrue(targets.contains(board.getCellAt(board.calcIndex(17, 2)))); // Door assertEquals(9, targets.size()); } // Black: enter room targets @Test public void testTargetsIntoRoom1() { board.calcTargets(7, 3, 3); targets = board.getTargets(); Assert.assertEquals(8, targets.size()); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(6, 1)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 0)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 1)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 2)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 3)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 4)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 6)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 5)))); } // Black: enter room targets @Test public void testTargetsIntoRoom2() { board.calcTargets(11, 9, 3); targets = board.getTargets(); Assert.assertEquals(9,targets.size()); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 9)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(9, 8)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(11, 8)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 8)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(14, 9)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(13, 10)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 9)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(12, 9)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(10, 10)))); } // Light green: exit room targets @Test public void testTargetsRoomExits1() { board.calcTargets(6, 1, 1); targets= board.getTargets(); Assert.assertEquals(1, targets.size()); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 1)))); board.calcTargets(6, 1, 2); targets = board.getTargets(); Assert.assertEquals(3, targets.size()); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(8, 1)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 0)))); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(7, 2)))); } // Light green: exit room targets @Test public void testTargetsRoomExits2() { board.calcTargets(0, 11, 1); targets= board.getTargets(); Assert.assertEquals(1, targets.size()); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(0, 10)))); board.calcTargets(0, 11, 3); targets = board.getTargets(); Assert.assertEquals(1, targets.size()); Assert.assertTrue(targets.contains(board.getCellAt(board.calcIndex(2, 10)))); } }
package com.tagmycode.netbeans; import com.tagmycode.plugin.Framework; import com.tagmycode.plugin.FrameworkConfig; import com.tagmycode.sdk.authentication.TagMyCodeApiProduction; import java.awt.BorderLayout; import java.awt.Frame; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.util.NbBundle.Messages; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; @ConvertAsProperties( dtd = "-//com.tagmycode.netbeans//TagMyCode//EN", autostore = false ) @TopComponent.Description( preferredID = "TagMyCodeTopComponent", iconBase = "com/tagmycode/netbeans/resources/tagmycode.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS ) @TopComponent.Registration(mode = "output", openAtStartup = true) @ActionID(category = "Window", id = "com.tagmycode.netbeans.TagMyCodeTopComponent") @ActionReference(path = "Menu/Window" /*, position = 333 */) @TopComponent.OpenActionRegistration( displayName = "#CTL_TagMyCodeAction", preferredID = "TagMyCodeTopComponent" ) @Messages({ "CTL_TagMyCodeAction=TagMyCode", "CTL_TagMyCodeTopComponent=TagMyCode", "HINT_TagMyCodeTopComponent=This is a TagMyCode window" }) public final class TagMyCodeTopComponent extends TopComponent { private Framework framework; public TagMyCodeTopComponent() { initTagMyCode(); initComponents(); add(framework.getMainWindow().getMainComponent(), BorderLayout.CENTER); revalidate(); repaint(); setName(Bundle.CTL_TagMyCodeTopComponent()); setToolTipText(Bundle.HINT_TagMyCodeTopComponent()); } private void initTagMyCode() { final FrameworkConfig frameworkConfig = new FrameworkConfig(new PasswordKeyChain(), new PreferencesManager(), new MessageManager(), new TaskFactory(), getMainFrame()); framework = new Framework(new TagMyCodeApiProduction(), frameworkConfig, new Secret()); framework.start(); } public Framework getFramework() { if (framework == null) { initTagMyCode(); } return framework; } public static TagMyCodeTopComponent getInstance() { TopComponent comp = WindowManager.getDefault() .findTopComponent("TagMyCodeTopComponent"); return TagMyCodeTopComponent.class.cast(comp); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setLayout(new java.awt.BorderLayout()); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables @Override public void componentOpened() { // TODO add custom code on component opening } @Override public void componentClosed() { } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at p.setProperty("version", "1.0"); } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); } public Frame getMainFrame() { return WindowManager.getDefault().getMainWindow(); } }
package com.xruby.runtime.builtin; import java.util.Iterator; import java.util.Map; import com.xruby.runtime.lang.CommonRubyID; import com.xruby.runtime.lang.RubyAPI; import com.xruby.runtime.lang.RubyBlock; import com.xruby.runtime.lang.RubyClass; import com.xruby.runtime.lang.RubyException; import com.xruby.runtime.lang.RubyID; import com.xruby.runtime.lang.RubyMethod; import com.xruby.runtime.lang.RubyNoArgMethod; import com.xruby.runtime.lang.RubyObject; import com.xruby.runtime.lang.RubyOneArgMethod; import com.xruby.runtime.lang.RubyRuntime; import com.xruby.runtime.lang.RubyValue; import com.xruby.runtime.lang.RubyVarArgMethod; import com.xruby.runtime.lang.StringMap; import com.xruby.runtime.value.ObjectFactory; import com.xruby.runtime.value.RubyArray; import com.xruby.runtime.value.RubyString; class Object_operator_equal extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (receiver == arg) { return ObjectFactory.TRUE_VALUE; } else { return ObjectFactory.FALSE_VALUE; } } } class Object_clone extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { return (RubyValue) receiver.clone(); } } class Object_singleton_methods extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { boolean all = true; if (args != null && !RubyAPI.testTrueFalse(args.get(0))) { all = false; } RubyArray a = new RubyArray(); if (all) { receiver.getSingletonClass().collectClassMethodNames(a, RubyMethod.PUBLIC); } else { receiver.getSingletonClass().collectOwnMethodNames(a, RubyMethod.PUBLIC); } return a; } } class Object_extend extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == args) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments (0 for 1)"); } for (RubyValue v : args) { RubyAPI.callPublicOneArgMethod(v, receiver, null, CommonRubyID.extendObjectID); } return receiver; } } class Object_alloc extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { return new RubyObject((RubyClass) receiver); } } class Object_object_id extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { //Object.hashCode() javadoc: //As much as is reasonably practical, the hashCode method defined //by class Object does return distinct integers for distinct objects. return ObjectFactory.createFixnum(receiver.hashCode()); } } class Object_hash extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { return ObjectFactory.createFixnum(receiver.hashCode()); } } class Object_freeze extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { receiver.freeze(); return receiver; } } class Object_frozen_question extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { return receiver.frozen() ? ObjectFactory.TRUE_VALUE : ObjectFactory.FALSE_VALUE; } } class Object_inspect extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { if (!(receiver instanceof RubyObject)) { return RubyAPI.callPublicMethod(receiver, null, null, CommonRubyID.toSID); } StringBuffer sb = new StringBuffer(); sb.append(" sb.append(receiver.getRubyClass().getRealClass().getName()); sb.append(":0x"); int hash = receiver.hashCode(); sb.append(Integer.toHexString(hash)); String sep = ""; Map vars = receiver.getInstanceVariables(); if (vars != null) { for (Iterator iter = vars.keySet().iterator(); iter.hasNext();) { RubyID id = (RubyID)iter.next(); sb.append(sep); sb.append(" "); sb.append(StringMap.id2name(id)); sb.append("="); sb.append(((RubyString)RubyAPI.callPublicMethod((RubyValue)vars.get(id), null, null, StringMap.intern("inspect")))).toString(); sep = ","; } } sb.append(">"); return ObjectFactory.createString(sb.toString()); } } public class ObjectClassBuilder { public static void initialize() { RubyClass c = RubyRuntime.ObjectClass; RubyMethod equal = new Object_operator_equal(); c.defineMethod("==", equal); c.defineMethod("equal?", equal); RubyMethod clone = new Object_clone(); c.defineMethod("clone", clone); c.defineMethod("dup", clone); c.defineMethod("extend", new Object_extend()); c.defineMethod("freeze", new Object_freeze()); c.defineMethod("frozen?", new Object_frozen_question()); RubyMethod object_id = new Object_object_id(); c.defineMethod("object_id", object_id); c.defineMethod("__id__", object_id); c.defineMethod("hash", new Object_hash()); c.defineMethod("inspect", new Object_inspect()); c.defineMethod("singleton_methods", new Object_singleton_methods()); c.defineAllocMethod(new Object_alloc()); } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // Modifications: // 2007 Jun 22: Iterate over the proper array in the four-argument send // method. - dj@opennms.org // 2007 Jun 22: Make the static sendTest(...) method non-static. // - dj@opennms.org // 2007 Jun 22: Make the static send(...) method non-static and do some // various code cleanup. - dj@opennms.org // 2007 Jun 21: Always use SnmpHelpers.createSnmpSession() to create SNMP // sessions, including eliminating static Snmp object used // for sending traps. Improve error reporting. - dj@opennms.org // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.snmp.snmp4j; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Category; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.snmp.CollectionTracker; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.opennms.netmgt.snmp.SnmpObjId; import org.opennms.netmgt.snmp.SnmpStrategy; import org.opennms.netmgt.snmp.SnmpTrapBuilder; import org.opennms.netmgt.snmp.SnmpV1TrapBuilder; import org.opennms.netmgt.snmp.SnmpValue; import org.opennms.netmgt.snmp.SnmpValueFactory; import org.opennms.netmgt.snmp.SnmpWalker; import org.opennms.netmgt.snmp.TrapNotificationListener; import org.opennms.netmgt.snmp.TrapProcessorFactory; import org.snmp4j.CommandResponderEvent; import org.snmp4j.CommunityTarget; import org.snmp4j.MessageDispatcher; import org.snmp4j.PDU; import org.snmp4j.PDUv1; import org.snmp4j.Snmp; import org.snmp4j.Target; import org.snmp4j.TransportMapping; import org.snmp4j.event.ResponseEvent; import org.snmp4j.mp.MPv3; import org.snmp4j.mp.MessageProcessingModel; import org.snmp4j.mp.PduHandle; import org.snmp4j.mp.SnmpConstants; import org.snmp4j.security.SecurityLevel; import org.snmp4j.security.SecurityModel; import org.snmp4j.security.SecurityModels; import org.snmp4j.security.SecurityProtocols; import org.snmp4j.security.USM; import org.snmp4j.security.UsmUser; import org.snmp4j.smi.Address; import org.snmp4j.smi.GenericAddress; import org.snmp4j.smi.IpAddress; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.SMIConstants; import org.snmp4j.smi.UdpAddress; import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; public class Snmp4JStrategy implements SnmpStrategy { private static Map<TrapNotificationListener, RegistrationInfo> s_registrations = new HashMap<TrapNotificationListener, RegistrationInfo>(); private static boolean s_initialized = false; private Snmp4JValueFactory m_valueFactory; /** * Initialize for v3 communications */ private static void initialize() { if (s_initialized) { return; } // LogFactory.setLogFactory(new Log4jLogFactory()); MPv3.setEnterpriseID(5813); USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); SecurityModels.getInstance().addSecurityModel(usm); s_initialized = true; } public Snmp4JStrategy() { initialize(); } /** * SNMP4J createWalker implemenetation. * * @param snmpAgentConfig * @param name * @param tracker */ public SnmpWalker createWalker(SnmpAgentConfig snmpAgentConfig, String name, CollectionTracker tracker) { return new Snmp4JWalker(new Snmp4JAgentConfig(snmpAgentConfig), name, tracker); } /** * Not yet implemented. Use a walker. */ public SnmpValue[] getBulk(SnmpAgentConfig agentConfig, SnmpObjId[] oid) { return null; } public SnmpValue set(SnmpAgentConfig agentConfig, SnmpObjId oid, SnmpValue value) { if (log().isDebugEnabled()) log().debug("set: OID: "+oid+" value: " + value.toString() + " for Agent:"+agentConfig); SnmpObjId[] oids = {oid}; SnmpValue[] values = {value}; return set(agentConfig, oids,values)[0]; } public SnmpValue[] set(SnmpAgentConfig snmpAgentConfig, SnmpObjId[] oids, SnmpValue[] values) { Snmp4JAgentConfig agentConfig = new Snmp4JAgentConfig(snmpAgentConfig); if (log().isDebugEnabled()) log().debug("get: OID: "+oids+" values: " + values + " for Agent:"+agentConfig); return send(agentConfig, PDU.SET, oids, values); } /** * SNMP4J get helper that takes a single SnmpObjId * and calls get with an array.lenght =1 and returns * the first element of the returned array of SnmpValue. * * @param agentConfig * @param oid * */ public SnmpValue get(SnmpAgentConfig agentConfig, SnmpObjId oid) { if (log().isDebugEnabled()) log().debug("get: OID: "+oid+" for Agent:"+agentConfig); SnmpObjId[] oids = {oid}; SnmpValue[] values = get(agentConfig, oids); return values[0]; } /** * SnmpGet implementation. * * @param agentConfig * @param oids * @return * Returns an array of Snmp4JValues. If the * get was unsuccessful, then the first elment * of the array will be null and lenth of 1. */ public SnmpValue[] get(SnmpAgentConfig snmpAgentConfig, SnmpObjId[] oids) { Snmp4JAgentConfig agentConfig = new Snmp4JAgentConfig(snmpAgentConfig); if (log().isDebugEnabled()) log().debug("get: OID: "+oids+" for Agent:"+agentConfig); return send(agentConfig, PDU.GET, oids); } /** * SNMP4J getNext implementation * * @param agentConfig * @param oid * */ public SnmpValue getNext(SnmpAgentConfig agentConfig, SnmpObjId oid) { if (log().isDebugEnabled()) log().debug("getNext: OID: "+oid+" for Agent:"+agentConfig); SnmpObjId[] oids = { oid }; SnmpValue[] values = getNext(agentConfig, oids); return values[0]; } /** * SNMP GetNext implementation. * * @param agentConfig * @param oids * @return * Returns an array of Snmp4JValues. If the * getNext was unsuccessful, then the first element * of the array will be null and length of 1. */ public SnmpValue[] getNext(SnmpAgentConfig snmpAgentConfig, SnmpObjId[] oids) { Snmp4JAgentConfig agentConfig = new Snmp4JAgentConfig(snmpAgentConfig); if (log().isDebugEnabled()) log().debug("get: OID: "+oids+" for Agent:"+agentConfig); return send(agentConfig, PDU.GETNEXT, oids); } /** * Sends and SNMP4J request pdu. The attributes in SnmpAgentConfig should have been * adapted from default SnmpAgentConfig values to those compatible with the SNMP4J library. * * @param agentConfig * @param pduType TODO * @param oids * @return */ protected SnmpValue[] send(Snmp4JAgentConfig agentConfig, int pduType, SnmpObjId[] oids) { SnmpValue[] values = { null }; Snmp session = null; try { session = SnmpHelpers.createSnmpSession(agentConfig); session.listen(); session.getUSM().addUser((agentConfig.getSecurityName()), new UsmUser(agentConfig.getSecurityName(), agentConfig.getAuthProtocol(), agentConfig.getAuthPassPhrase(), agentConfig.getPrivProtocol(), agentConfig.getPrivPassPhrase())); Target target = agentConfig.getTarget(); PDU pdu = SnmpHelpers.createPDU(agentConfig.getVersion()); pdu.setType(pduType); //TODO:log this if (!buildPdu(pdu, oids)) return null; ResponseEvent responseEvent = session.send(pdu, target); if (responseEvent.getResponse() == null) { log().warn("send: Timeout. Agent: "+agentConfig); } else if (responseEvent.getResponse().get(0).getSyntax() == SMIConstants.SYNTAX_NULL) { values[0] = null; } else if (responseEvent.getError() != null) { log().warn("send: Error during get operation. Error: "+responseEvent.getError().getLocalizedMessage()); } else if (responseEvent.getResponse().getType() == PDU.REPORT) { log().warn("send: Error during get operation. Report returned with varbinds: "+responseEvent.getResponse().getVariableBindings()); } else if (responseEvent.getResponse().getVariableBindings().size() < 1) { log().warn("send: Received PDU with 0 varbinds."); } else { values = new Snmp4JValue[responseEvent.getResponse().getVariableBindings().size()]; for (int i=0; i<values.length; i++) { values[i] = new Snmp4JValue(responseEvent.getResponse().get(i).getVariable()); } if (log().isDebugEnabled()) log().debug("send: Snmp operation successful. Value: "+values); } } catch (IOException e) { log().error("getNext: Could not create Snmp session for Agent: "+agentConfig+". " + e, e); } finally { if (session != null) { try { session.close(); } catch (IOException e) { log().error("send: Error closinging SNMP connection: " + e, e); } } } return values; } /** * Sends and SNMP4J request pdu. The attributes in SnmpAgentConfig should have been * adapted from default SnmpAgentConfig values to those compatible with the SNMP4J library. * * @param agentConfig * @param pduType TODO * @param oids * @return */ private SnmpValue[] send(Snmp4JAgentConfig agentConfig, int pduType, SnmpObjId[] oids, SnmpValue[] values) { SnmpValue[] retvalues = { null }; Snmp session = null; try { session = SnmpHelpers.createSnmpSession(agentConfig); session.listen(); session.getUSM().addUser((agentConfig.getSecurityName()), new UsmUser(agentConfig.getSecurityName(), agentConfig.getAuthProtocol(), agentConfig.getAuthPassPhrase(), agentConfig.getPrivProtocol(), agentConfig.getPrivPassPhrase())); Target target = agentConfig.getTarget(); PDU pdu = SnmpHelpers.createPDU(agentConfig.getVersion()); pdu.setType(pduType); //TODO:log this if (!buildPdu(pdu, oids, values)) return null; ResponseEvent responseEvent = session.send(pdu, target); if (responseEvent.getResponse() == null) { log().warn("send: Timeout. Agent: "+agentConfig); } else if (responseEvent.getResponse().get(0).getSyntax() == SMIConstants.SYNTAX_NULL) { values[0] = null; } else if (responseEvent.getError() != null) { log().warn("send: Error during get operation. Error: "+responseEvent.getError().getLocalizedMessage()); } else if (responseEvent.getResponse().getType() == PDU.REPORT) { log().warn("send: Error during get operation. Report returned with varbinds: "+responseEvent.getResponse().getVariableBindings()); } else if (responseEvent.getResponse().getVariableBindings().size() < 1) { log().warn("send: Received PDU with 0 varbinds."); } else { retvalues = new Snmp4JValue[responseEvent.getResponse().getVariableBindings().size()]; for (int i=0; i<retvalues.length; i++) { retvalues[i] = new Snmp4JValue(responseEvent.getResponse().get(i).getVariable()); } if (log().isDebugEnabled()) log().debug("send: Snmp operation successful. Value: "+values); } } catch (IOException e) { log().error("getNext: Could not create Snmp session for Agent: "+agentConfig+". " + e, e); } finally { if (session != null) { try { session.close(); } catch (IOException e) { log().error("send: Error closinging SNMP connection: " + e, e); } } } return retvalues; } private boolean buildPdu(PDU pdu, SnmpObjId[] oids) { VariableBinding vb; for (int i=0; i<oids.length; i++) { vb = new VariableBinding(new OID(oids[i].toString())); pdu.add(vb); } if (pdu.getVariableBindings().size() == oids.length) { return true; } else { return false; } } private boolean buildPdu(PDU pdu, SnmpObjId[] oids, SnmpValue[] values) { VariableBinding vb = null; if (values == null) return buildPdu(pdu,oids); if (oids.length != values.length) return false; for (int i=0; i<oids.length; i++) { vb = new VariableBinding(new OID(oids[i].toString()), new Snmp4JValue(values[0].getType(),values[0].getBytes()).getVariable()); pdu.add(vb); } if (pdu.getVariableBindings().size() == oids.length) { return true; } else { return false; } } private Category log() { return ThreadCategory.getInstance(getClass()); } public SnmpValueFactory getValueFactory() { if (m_valueFactory == null) m_valueFactory = new Snmp4JValueFactory(); return m_valueFactory; } public static class RegistrationInfo { public TrapNotificationListener m_listener; int m_trapPort; Snmp m_trapSession; Snmp4JTrapNotifier m_trapHandler; private TransportMapping m_transportMapping; RegistrationInfo(TrapNotificationListener listener, int trapPort) { if (listener == null) throw new NullPointerException("listener is null"); m_listener = listener; m_trapPort = trapPort; } public boolean equals(Object obj) { if (obj instanceof RegistrationInfo) { RegistrationInfo info = (RegistrationInfo) obj; return (m_listener == info.m_listener) && (m_trapPort == info.m_trapPort); } return false; } public int hashCode() { return (m_listener.hashCode() ^ m_trapPort); } public void setSession(Snmp trapSession) { m_trapSession = trapSession; } public Snmp getSession() { return m_trapSession; } public void setHandler(Snmp4JTrapNotifier trapHandler) { m_trapHandler = trapHandler; } public Snmp4JTrapNotifier getHandler() { return m_trapHandler; } public int getPort() { return m_trapPort; } public void setTransportMapping(TransportMapping transport) { m_transportMapping = transport; } public TransportMapping getTransportMapping() { return m_transportMapping; } } public void registerForTraps(TrapNotificationListener listener, TrapProcessorFactory processorFactory, int snmpTrapPort) throws IOException { RegistrationInfo info = new RegistrationInfo(listener, snmpTrapPort); Snmp4JTrapNotifier m_trapHandler = new Snmp4JTrapNotifier(listener, processorFactory); info.setHandler(m_trapHandler); TransportMapping transport = new DefaultUdpTransportMapping(new UdpAddress(snmpTrapPort)); info.setTransportMapping(transport); Snmp snmp = new Snmp(transport); snmp.addCommandResponder(m_trapHandler); info.setSession(snmp); s_registrations.put(listener, info); snmp.listen(); } public void unregisterForTraps(TrapNotificationListener listener, int snmpTrapPort) throws IOException { RegistrationInfo info = s_registrations.remove(listener); info.getSession().close(); } public SnmpV1TrapBuilder getV1TrapBuilder() { return new Snmp4JV1TrapBuilder(this); } public SnmpTrapBuilder getV2TrapBuilder() { return new Snmp4JV2TrapBuilder(this); } public void send(String agentAddress, int port, String community, PDU pdu) throws Exception { Snmp session = null; try { session = SnmpHelpers.createSnmpSession(); Address targetAddress = GenericAddress.parse("udp:"+agentAddress+"/"+port); CommunityTarget target = new CommunityTarget(targetAddress, new OctetString(community.getBytes())); target.setVersion(pdu instanceof PDUv1 ? SnmpConstants.version1 : SnmpConstants.version2c); session.send(pdu, target); } catch (IOException e) { log().error("send: Could not create Snmp session for " + agentAddress + "/" + port + ": " + e, e); } finally { if (session != null) { try { session.close(); } catch (IOException e) { log().error("send: Could not close SNMP session: " + e, e); } } } } public void sendTest(String agentAddress, int port, String community, PDU pdu) { for (RegistrationInfo info : s_registrations.values()) { if (port == info.getPort()) { Snmp snmp = info.getSession(); MessageDispatcher dispatcher = snmp.getMessageDispatcher(); TransportMapping transport = info.getTransportMapping(); int securityModel = (pdu instanceof PDUv1 ? SecurityModel.SECURITY_MODEL_SNMPv1 :SecurityModel.SECURITY_MODEL_SNMPv2c); int messageModel = (pdu instanceof PDUv1 ? MessageProcessingModel.MPv1 : MessageProcessingModel.MPv2c); CommandResponderEvent e = new CommandResponderEvent(dispatcher, transport, new IpAddress(agentAddress), messageModel, securityModel, community.getBytes(), SecurityLevel.NOAUTH_NOPRIV, new PduHandle(), pdu, 1000, null); info.getHandler().processPdu(e); } } } }
package org.smeup.sys.dk.compiler.rpj.writer; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.eclipse.datatools.modelbase.sql.query.QueryExpressionBody; import org.eclipse.datatools.modelbase.sql.query.QuerySelect; import org.eclipse.datatools.modelbase.sql.query.QuerySelectStatement; import org.eclipse.datatools.modelbase.sql.query.QueryStatement; import org.eclipse.datatools.modelbase.sql.query.ValueExpressionVariable; import org.eclipse.datatools.modelbase.sql.query.helper.StatementHelper; import org.eclipse.emf.ecore.EObject; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.ArrayCreation; import org.eclipse.jdt.core.dom.ArrayInitializer; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Assignment.Operator; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.MarkerAnnotation; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.smeup.sys.db.esql.CursorType; import org.smeup.sys.db.esql.QCursor; import org.smeup.sys.db.esql.QCursorTerm; import org.smeup.sys.db.esql.QStatement; import org.smeup.sys.db.esql.QStatementTerm; import org.smeup.sys.db.esql.annotation.CursorDef; import org.smeup.sys.db.syntax.QQueryParser; import org.smeup.sys.dk.compiler.DevelopmentKitCompilerRuntimeException; import org.smeup.sys.dk.compiler.QCompilationSetup; import org.smeup.sys.dk.compiler.QCompilationUnit; import org.smeup.sys.dk.compiler.QCompilerLinker; import org.smeup.sys.dk.compiler.QCompilerManager; import org.smeup.sys.dk.compiler.QDevelopmentKitCompilerFactory; import org.smeup.sys.dk.compiler.UnitScope; import org.smeup.sys.dk.compiler.rpj.RPJCallableUnitInfo; import org.smeup.sys.dk.compiler.rpj.RPJContextHelper; import org.smeup.sys.dk.compiler.rpj.dbl.DBLQuerySelectWriter; import org.smeup.sys.dk.core.annotation.Supported; import org.smeup.sys.dk.core.annotation.ToDo; import org.smeup.sys.dk.core.annotation.Unsupported; import org.smeup.sys.dk.test.annotation.TestStarted; import org.smeup.sys.il.core.term.QTerm; import org.smeup.sys.il.data.QBufferedData; import org.smeup.sys.il.data.QBufferedElement; import org.smeup.sys.il.data.QData; import org.smeup.sys.il.data.annotation.Entry; import org.smeup.sys.il.data.annotation.Main; import org.smeup.sys.il.data.annotation.Open; import org.smeup.sys.il.data.annotation.Optional; import org.smeup.sys.il.data.annotation.PostMain; import org.smeup.sys.il.data.annotation.PreMain; import org.smeup.sys.il.data.annotation.Snap; import org.smeup.sys.il.data.def.QPointerDef; import org.smeup.sys.il.data.term.QDataTerm; import org.smeup.sys.il.data.term.QRemap; import org.smeup.sys.il.esam.QDataSet; import org.smeup.sys.il.esam.QDataSetTerm; import org.smeup.sys.il.esam.QDisplay; import org.smeup.sys.il.esam.QDisplayTerm; import org.smeup.sys.il.esam.QIntegratedLanguageEsamPackage; import org.smeup.sys.il.esam.QKSDataSet; import org.smeup.sys.il.esam.QKeyListTerm; import org.smeup.sys.il.esam.QPrint; import org.smeup.sys.il.esam.QPrintTerm; import org.smeup.sys.il.esam.QRRDataSet; import org.smeup.sys.il.esam.QSMDataSet; import org.smeup.sys.il.esam.annotation.FileDef; import org.smeup.sys.il.expr.IntegratedLanguageExpressionRuntimeException; import org.smeup.sys.il.expr.QExpression; import org.smeup.sys.il.expr.QExpressionParser; import org.smeup.sys.il.expr.QTermExpression; import org.smeup.sys.il.flow.QAnnotationTest; import org.smeup.sys.il.flow.QBlock; import org.smeup.sys.il.flow.QCallableUnit; import org.smeup.sys.il.flow.QConversion; import org.smeup.sys.il.flow.QDataSection; import org.smeup.sys.il.flow.QEntry; import org.smeup.sys.il.flow.QEntryParameter; import org.smeup.sys.il.flow.QIntegratedLanguageFlowFactory; import org.smeup.sys.il.flow.QMethodExec; import org.smeup.sys.il.flow.QModule; import org.smeup.sys.il.flow.QParameterList; import org.smeup.sys.il.flow.QProcedure; import org.smeup.sys.il.flow.QPrototype; import org.smeup.sys.il.flow.QRoutine; import org.smeup.sys.il.flow.QUnit; import org.smeup.sys.mi.core.util.QLists; import org.smeup.sys.os.file.QExternalFile; public abstract class JDTCallableUnitWriter extends JDTUnitWriter { private QExpressionParser expressionParser; private QQueryParser queryParser; public JDTCallableUnitWriter(JDTNamedNodeWriter root, QCompilationUnit compilationUnit, QCompilationSetup compilationSetup, String name, UnitScope scope) { super(root, compilationUnit, compilationSetup, name, scope); expressionParser = getCompilationUnit().getContext().get(QExpressionParser.class); queryParser = getCompilationUnit().getContext().get(QQueryParser.class); } @SuppressWarnings("unchecked") public void writeLabels(Collection<String> labels, boolean private_, boolean static_) { if (labels.isEmpty()) return; EnumDeclaration enumType = getAST().newEnumDeclaration(); enumType.setName(getAST().newSimpleName("TAG")); if (private_) enumType.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD)); else enumType.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); if (static_) enumType.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); // elements int num = 0; for (String label : labels) { EnumConstantDeclaration constantDeclaration = getAST().newEnumConstantDeclaration(); constantDeclaration.setName(getAST().newSimpleName(getCompilationUnit().normalizeLabelName(label))); enumType.enumConstants().add(num, constantDeclaration); num++; } getTarget().bodyDeclarations().add(enumType); } @SuppressWarnings("unchecked") public void writeMessages(Collection<String> messages) { EnumDeclaration enumType = getAST().newEnumDeclaration(); enumType.setName(getAST().newSimpleName("QCPFMSG")); enumType.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); enumType.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); // elements int num = 0; for (String message : messages) { if (message.equalsIgnoreCase("CPF0000")) continue; EnumConstantDeclaration constantDeclaration = getAST().newEnumConstantDeclaration(); constantDeclaration.setName(getAST().newSimpleName(normalizeEnumName(message))); enumType.enumConstants().add(num, constantDeclaration); num++; } getTarget().bodyDeclarations().add(enumType); } @SuppressWarnings("unchecked") public void writeModuleFields(List<String> modules, UnitScope scope) { for (String module : modules) { VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); FieldDeclaration field = getAST().newFieldDeclaration(variable); // writeAnnotation(field, ModuleDef.class, "name", moduleName); writeAnnotation(field, Inject.class); // writeAnnotation(field, Named.class, "value", moduleName); // TODO remove me if ((module.equalsIgnoreCase("£MUB") || module.equalsIgnoreCase("£MDV")) && !(getCompilationUnit().getNode() instanceof QProcedure)) field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); else { switch (scope) { case FRIENDLY: break; case PRIVATE: field.modifiers().add(getAST().newModifier(ModifierKeyword.PRIVATE_KEYWORD)); break; case PROTECTED: field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); break; case PUBLIC: field.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); break; } } String moduleName = getCompilationUnit().normalizeTypeName(module); field.setType(getAST().newSimpleType(getAST().newName(moduleName))); variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeModuleName(module))); getTarget().bodyDeclarations().add(field); } } public void writeDataFields(QDataSection dataSection, UnitScope scope) { List<String> fields = new ArrayList<String>(); // fields for (QDataTerm<?> dataTerm : dataSection.getDatas()) { if (dataTerm.getDefinition() == null) continue; dataTerm = getCompilationUnit().getDataTerm(dataTerm.getName(), false); if (fields.contains(getCompilationUnit().normalizeTermName(dataTerm.getName()))) continue; writeField(dataTerm, false, scope); fields.add(getCompilationUnit().normalizeTermName(dataTerm.getName())); } } @SuppressWarnings("unchecked") public void writeDataSets(List<QDataSetTerm> dataSets) throws IOException { writeImport(QDataSet.class); for (QDataSetTerm dataSetTerm : dataSets) { VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); FieldDeclaration field = getAST().newFieldDeclaration(variable); String className = null; if (dataSetTerm.isKeyedAccess()) { writeImport(QKSDataSet.class); className = QKSDataSet.class.getSimpleName(); } else { if (dataSetTerm.getFacet(QExternalFile.class) != null) { writeImport(QRRDataSet.class); className = QRRDataSet.class.getSimpleName(); } else { writeImport(QSMDataSet.class); className = QSMDataSet.class.getSimpleName(); } } Type dataSetType = getAST().newSimpleType(getAST().newSimpleName(className)); ParameterizedType parType = getAST().newParameterizedType(dataSetType); QCompilerLinker compilerLinker = dataSetTerm.getFacet(QCompilerLinker.class); if (compilerLinker != null) { writeImport(compilerLinker.getLinkedClass()); parType.typeArguments().add(getAST().newSimpleType(getAST().newName(compilerLinker.getLinkedClass().getSimpleName()))); } else { String argument = dataSetTerm.getFormatName(); if (argument == null) argument = dataSetTerm.getName(); parType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(argument))); } if (!((SimpleType) parType.typeArguments().get(0)).getName().toString().equals(dataSetTerm.getName())) writeAnnotation(field, FileDef.class, "name", dataSetTerm.getName()); EObject eDataSet = (EObject) dataSetTerm; if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getFileTerm_UserOpen())) writeAnnotation(field, FileDef.class, "userOpen", dataSetTerm.isUserOpen()); if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getFileTerm_InfoStruct())) writeAnnotation(field, FileDef.class, "info", getCompilationUnit().normalizeTermName(dataSetTerm.getInfoStruct())); if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getDataSetTerm_Prefix())) writeAnnotation(field, FileDef.class, "prefix", dataSetTerm.getPrefix()); if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getDataSetTerm_ExternalFile())) { QDataTerm<?> externalFileTerm = getCompilationUnit().getDataTerm(dataSetTerm.getExternalFile(), true); writeAnnotation(field, FileDef.class, "externalFile", getCompilationUnit().getQualifiedName(externalFileTerm)); } if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getDataSetTerm_ExternalMember())) { QDataTerm<?> externalFileMember = getCompilationUnit().getDataTerm(dataSetTerm.getExternalMember(), true); writeAnnotation(field, FileDef.class, "externalMember", getCompilationUnit().getQualifiedName(externalFileMember)); } if (getCompilationUnit().getNode() instanceof QModule) field.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); else field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); field.modifiers().add(getAST().newModifier(ModifierKeyword.TRANSIENT_KEYWORD)); field.setType(parType); if (dataSetTerm.getFormatName() != null) variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(dataSetTerm.getFormatName()))); else variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(dataSetTerm.getName()))); getTarget().bodyDeclarations().add(field); // internal file definition if (compilerLinker == null && dataSetTerm.getFormat() != null) { if (dataSetTerm.getFormatName() != null) writeInnerRecord(dataSetTerm.getFormatName(), dataSetTerm.getFormat().getDefinition()); else writeInnerRecord(dataSetTerm.getName(), dataSetTerm.getFormat().getDefinition()); } } } public void writeKeyLists(List<QKeyListTerm> keyLists) { writeImport(QBufferedData.class); for (QKeyListTerm keyList : keyLists) if (!RPJContextHelper.containsArray(expressionParser, keyList)) writeKeyList(keyList); } @SuppressWarnings("unchecked") public void writeKeyList(QKeyListTerm keyList) { writeImport(QBufferedElement.class); VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(keyList.getName()))); FieldDeclaration field = getAST().newFieldDeclaration(variable); field.modifiers().add(getAST().newModifier(ModifierKeyword.PRIVATE_KEYWORD)); Type bufferedType = getAST().newSimpleType(getAST().newSimpleName(QBufferedElement.class.getSimpleName())); field.setType(getAST().newArrayType(bufferedType)); // array of bufferedData ArrayCreation arrayCreation = getAST().newArrayCreation(); arrayCreation.setType(getAST().newArrayType(getAST().newSimpleType(getAST().newSimpleName(QBufferedElement.class.getSimpleName())))); ArrayInitializer arrayInitializer = getAST().newArrayInitializer(); for (String keyField : keyList.getKeyFields()) { QExpression expression = expressionParser.parseExpression(keyField); Expression jdtExpression = JDTStatementHelper.buildExpression(getAST(), getCompilationUnit(), expression, null); arrayInitializer.expressions().add(jdtExpression); } arrayCreation.setInitializer(arrayInitializer); variable.setInitializer(arrayCreation); getTarget().bodyDeclarations().add(field); } @SuppressWarnings("unchecked") public void writeCursors(List<QCursorTerm> cursors) { writeImport(QCursor.class); writeImport(CursorType.class); for (QCursorTerm cursorTerm : cursors) { VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); FieldDeclaration field = getAST().newFieldDeclaration(variable); writeAnnotation(field, CursorDef.class, "type", cursorTerm.getCursorType()); if (cursorTerm.isHold()) writeAnnotation(field, CursorDef.class, "hold", cursorTerm.isHold()); if (cursorTerm.getStatementName() != null) writeAnnotation(field, CursorDef.class, "statement", getCompilationUnit().normalizeTermName(cursorTerm.getStatementName())); if (cursorTerm.getSql() != null) { try { List<ValueExpressionVariable> variables = StatementHelper.getAllVariablesInQueryStatement(queryParser.parseQuery(cursorTerm.getSql()).getQueryStatement()); if(variables.isEmpty()) writeAnnotation(field, CursorDef.class, "sql", cursorTerm.getSql()); } catch (SQLException e) { throw new DevelopmentKitCompilerRuntimeException("Invalid statement: " + cursorTerm); } } field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); field.modifiers().add(getAST().newModifier(ModifierKeyword.TRANSIENT_KEYWORD)); Type dataSetType = getAST().newSimpleType(getAST().newSimpleName(QCursor.class.getSimpleName())); field.setType(dataSetType); variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(cursorTerm.getName()))); getTarget().bodyDeclarations().add(field); } } @SuppressWarnings("unchecked") public void writeStatements(List<QStatementTerm> statements) { writeImport(QStatement.class); for (QStatementTerm statementTerm : statements) { VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); FieldDeclaration field = getAST().newFieldDeclaration(variable); field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); field.modifiers().add(getAST().newModifier(ModifierKeyword.TRANSIENT_KEYWORD)); Type dataSetType = getAST().newSimpleType(getAST().newSimpleName(QStatement.class.getSimpleName())); field.setType(dataSetType); variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(statementTerm.getName()))); getTarget().bodyDeclarations().add(field); } } @SuppressWarnings("unchecked") public void writeDisplays(List<QDisplayTerm> displays) throws IOException { writeImport(QDisplay.class); for (QDisplayTerm displayTerm : displays) { VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); FieldDeclaration field = getAST().newFieldDeclaration(variable); String className = null; QCompilerLinker compilerLinker = displayTerm.getFacet(QCompilerLinker.class); writeImport(QDisplay.class); className = QDisplay.class.getSimpleName(); Type displayType = getAST().newSimpleType(getAST().newSimpleName(className)); ParameterizedType parType = getAST().newParameterizedType(displayType); if (compilerLinker != null) { writeImport(compilerLinker.getLinkedClass()); parType.typeArguments().add(getAST().newSimpleType(getAST().newName(compilerLinker.getLinkedClass().getSimpleName()))); } else { String argument = displayTerm.getName(); parType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(argument))); } if (!((SimpleType) parType.typeArguments().get(0)).getName().toString().equals(displayTerm.getName())) writeAnnotation(field, FileDef.class, "name", displayTerm.getName()); EObject eDataSet = (EObject) displayTerm; if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getFileTerm_UserOpen())) writeAnnotation(field, FileDef.class, "userOpen", displayTerm.isUserOpen()); if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getFileTerm_InfoStruct())) writeAnnotation(field, FileDef.class, "info", getCompilationUnit().normalizeTermName(displayTerm.getInfoStruct())); if (getCompilationUnit().getNode() instanceof QModule) field.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); else field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); // field.modifiers().add(getAST().newModifier(ModifierKeyword.TRANSIENT_KEYWORD)); field.setType(parType); variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(displayTerm.getName()))); getTarget().bodyDeclarations().add(field); } } @SuppressWarnings("unchecked") public void writePrinters(List<QPrintTerm> printers) throws IOException { writeImport(QPrint.class); for (QPrintTerm printTerm : printers) { VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment(); FieldDeclaration field = getAST().newFieldDeclaration(variable); String className = null; QCompilerLinker compilerLinker = printTerm.getFacet(QCompilerLinker.class); writeImport(QPrint.class); className = QPrint.class.getSimpleName(); Type printerType = getAST().newSimpleType(getAST().newSimpleName(className)); ParameterizedType parType = getAST().newParameterizedType(printerType); if (compilerLinker != null) { writeImport(compilerLinker.getLinkedClass()); parType.typeArguments().add(getAST().newSimpleType(getAST().newName(compilerLinker.getLinkedClass().getSimpleName()))); } else { // String argument = printTerm.getName(); String argument = "PRT198"; writeImport("com.smeup.erp.file.prtf.XX.gen.PRT198"); parType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(argument))); } if (!((SimpleType) parType.typeArguments().get(0)).getName().toString().equals(printTerm.getName())) writeAnnotation(field, FileDef.class, "name", printTerm.getName()); EObject eDataSet = (EObject) printTerm; if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getFileTerm_UserOpen())) writeAnnotation(field, FileDef.class, "userOpen", printTerm.isUserOpen()); if (eDataSet.eIsSet(QIntegratedLanguageEsamPackage.eINSTANCE.getFileTerm_InfoStruct())) writeAnnotation(field, FileDef.class, "info", getCompilationUnit().normalizeTermName(printTerm.getInfoStruct())); if (getCompilationUnit().getNode() instanceof QModule) field.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); else field.modifiers().add(getAST().newModifier(ModifierKeyword.PROTECTED_KEYWORD)); // field.modifiers().add(getAST().newModifier(ModifierKeyword.TRANSIENT_KEYWORD)); field.setType(parType); variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(printTerm.getName()))); getTarget().bodyDeclarations().add(field); } } public void writeRoutines(QCallableUnit callableUnit, RPJCallableUnitInfo callableUnitInfo) { // special routines if (callableUnit.getFlowSection() != null) for (QRoutine routine : callableUnit.getFlowSection().getRoutines()) { if (!routine.getName().startsWith("*")) continue; writeRoutine(routine); } // main if (callableUnit.getMain() != null) { QRoutine routine = QIntegratedLanguageFlowFactory.eINSTANCE.createRoutine(); routine.setName("*MAIN"); routine.setMain(callableUnit.getMain()); MethodDeclaration methodDeclaration = writeRoutine(routine); if(callableUnit.getName().startsWith("MUTE")){ MarkerAnnotation entryAnnotation = getAST().newMarkerAnnotation(); entryAnnotation.setTypeName(getAST().newSimpleName(TestStarted.class.getSimpleName())); writeImport(TestStarted.class); writeRoutineTestMain(methodDeclaration, callableUnit); } } // snap if (!callableUnitInfo.getResetObjects().isEmpty()) writeSnapRoutine(callableUnit, callableUnitInfo); // routines if (callableUnit.getFlowSection() != null) for (QRoutine routine : callableUnit.getFlowSection().getRoutines()) { if (routine.getName().startsWith("*")) continue; writeRoutine(routine); } } public void writeSnapRoutine(QCallableUnit callableUnit, RPJCallableUnitInfo callableUnitInfo) { QRoutine routine = QIntegratedLanguageFlowFactory.eINSTANCE.createRoutine(); routine.setName("*SNAP"); routine.setMain(callableUnit.getMain()); QBlock block = QIntegratedLanguageFlowFactory.eINSTANCE.createBlock(); routine.setMain(block); for (String object : callableUnitInfo.getResetObjects()) { QMethodExec methodExec = QIntegratedLanguageFlowFactory.eINSTANCE.createMethodExec(); methodExec.setObject(object); methodExec.setMethod("snap"); block.getStatements().add(methodExec); } writeRoutine(routine); } @SuppressWarnings("unchecked") public MethodDeclaration writeRoutine(QRoutine routine) { MethodDeclaration methodDeclaration = getAST().newMethodDeclaration(); String routineName = getCompilationUnit().normalizeRoutineName(routine.getName()); if (routine.getName().equals("*INZSR")) { routineName = "_open"; MarkerAnnotation openAnnotation = getAST().newMarkerAnnotation(); openAnnotation.setTypeName(getAST().newSimpleName(Open.class.getSimpleName())); writeImport(Open.class); methodDeclaration.modifiers().add(openAnnotation); } else if (routine.getName().equals("*ENTRY")) { routineName = "_entry"; MarkerAnnotation preMainAnnotation = getAST().newMarkerAnnotation(); preMainAnnotation.setTypeName(getAST().newSimpleName(PreMain.class.getSimpleName())); writeImport(PreMain.class); methodDeclaration.modifiers().add(preMainAnnotation); } else if (routine.getName().equals("*MAIN")) { routineName = "_main"; MarkerAnnotation mainAnnotation = getAST().newMarkerAnnotation(); mainAnnotation.setTypeName(getAST().newSimpleName(Main.class.getSimpleName())); writeImport(Main.class); methodDeclaration.modifiers().add(mainAnnotation); } else if (routine.getName().equals("*SNAP")) { routineName = "_snap"; MarkerAnnotation mainAnnotation = getAST().newMarkerAnnotation(); mainAnnotation.setTypeName(getAST().newSimpleName(Snap.class.getSimpleName())); writeImport(Snap.class); methodDeclaration.modifiers().add(mainAnnotation); } else if (routine.getName().equals("*EXIT")) { routineName = "_exit"; MarkerAnnotation postMainAnnotation = getAST().newMarkerAnnotation(); postMainAnnotation.setTypeName(getAST().newSimpleName(PostMain.class.getSimpleName())); writeImport(PostMain.class); methodDeclaration.modifiers().add(postMainAnnotation); } getTarget().bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(getAST().newSimpleName(routineName)); methodDeclaration.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); // writeSuppressWarning(methodDeclaration); Block block = getAST().newBlock(); methodDeclaration.setBody(block); if (routine.getMain() == null) return methodDeclaration; // write java AST JDTStatementWriter statementWriter = getCompilationUnit().getContext().make(JDTStatementWriter.class); statementWriter.setAST(getAST()); statementWriter.getBlocks().push(block); if (routine.getMain() instanceof QBlock) { QBlock qBlock = (QBlock) routine.getMain(); for (org.smeup.sys.il.flow.QStatement qStatement : qBlock.getStatements()) qStatement.accept(statementWriter); } else routine.getMain().accept(statementWriter); statementWriter.getBlocks().pop(); return methodDeclaration; } @SuppressWarnings("unchecked") public void writePrototype(QPrototype prototype) { MethodDeclaration methodDeclaration = getAST().newMethodDeclaration(); getTarget().bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(prototype.getName()))); methodDeclaration.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); Block block = getAST().newBlock(); methodDeclaration.setBody(block); if (prototype.getDefinition() != null) { Type type = getJavaType(prototype); methodDeclaration.setReturnType2(type); } // TODO QExternalProgram QExternalFile externalFile = prototype.getFacet(QExternalFile.class); if (externalFile != null) { writePrototypeCall(prototype, externalFile.getName(), methodDeclaration, block); if (prototype.getDefinition() != null) { ReturnStatement returnStatement = getAST().newReturnStatement(); returnStatement.setExpression(getAST().newNullLiteral()); block.statements().add(returnStatement); } } else { QProcedure procedure = getCompilationUnit().getProcedure(prototype.getName(), false); if (procedure == null) throw new DevelopmentKitCompilerRuntimeException("Invalid procedure bind: " + prototype); if (procedure.getEntry() != null) writeEntry(methodDeclaration, procedure.getEntry()); writeLazyLoading(procedure, block); writeSetEntryParams(procedure, block); String namePrototype = getCompilationUnit().normalizeTermName(prototype.getName()); MethodInvocation methodInvocation = getAST().newMethodInvocation(); methodInvocation.setExpression(getAST().newName(namePrototype)); methodInvocation.setName(getAST().newSimpleName("qExec")); for (Object entryParameter : methodDeclaration.parameters()) { SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) entryParameter; methodInvocation.arguments().add(getAST().newSimpleName(singleVariableDeclaration.getName().toString())); } if (prototype.getDefinition() != null) { ReturnStatement returnStatement = getAST().newReturnStatement(); returnStatement.setExpression(methodInvocation); block.statements().add(returnStatement); } else { ExpressionStatement expressionStatement = getAST().newExpressionStatement(methodInvocation); block.statements().add(expressionStatement); } } } @SuppressWarnings("unchecked") private void writePrototypeCall(QPrototype prototype, String programName, MethodDeclaration methodDeclaration, Block block) { MethodInvocation methodInvocation = getAST().newMethodInvocation(); methodInvocation.setExpression(getAST().newSimpleName("qRPJ")); methodInvocation.setName(getAST().newSimpleName("qCall")); // program name QTermExpression expression = expressionParser.parseTerm(programName); Expression jdtExpression = JDTStatementHelper.buildExpression(getAST(), getCompilationUnit(), expression, String.class); methodInvocation.arguments().add(jdtExpression); // array of parameter ArrayInitializer arrayInitializer = getAST().newArrayInitializer(); if (prototype.getEntry() != null) { writeEntry(methodDeclaration, prototype.getEntry()); for (QEntryParameter<?> entryParameter : prototype.getEntry().getParameters()) { if (!(entryParameter.getDelegate() instanceof QDataTerm<?>)) throw new DevelopmentKitCompilerRuntimeException("Invalid parameter: " + entryParameter); QDataTerm<?> parameterDelegate = (QDataTerm<?>) entryParameter.getDelegate(); String parameterName = parameterDelegate.getName(); parameterName = getCompilationUnit().normalizeTermName(parameterName); // call parameter if (parameterDelegate.isConstant() && !parameterDelegate.getDataTermType().isMultiple() && !(parameterDelegate.getDefinition() instanceof QPointerDef)) { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setKind(ASTParser.K_EXPRESSION); parser.setSource(("qRPJ.qBox(" + parameterName + ")").toCharArray()); ASTNode node = parser.createAST(null); arrayInitializer.expressions().add((Expression) ASTNode.copySubtree(getAST(), (Expression) node)); } else arrayInitializer.expressions().add(getAST().newName(parameterName)); } } ArrayCreation arrayCreation = getAST().newArrayCreation(); arrayCreation.setType(getAST().newArrayType(getAST().newSimpleType(getAST().newSimpleName(QData.class.getSimpleName())))); arrayCreation.setInitializer(arrayInitializer); methodInvocation.arguments().add(arrayCreation); ExpressionStatement expressionStatement = getAST().newExpressionStatement(methodInvocation); block.statements().add(expressionStatement); } @SuppressWarnings("unchecked") private void writeLazyLoading(QProcedure procedure, Block block) { IfStatement ifStatement = getAST().newIfStatement(); String expression = getCompilationUnit().normalizeTermName(procedure.getName()) + " == null"; ifStatement.setExpression(buildExpression(expression)); Assignment assignment = getAST().newAssignment(); assignment.setLeftHandSide(buildExpression(getCompilationUnit().normalizeTermName(procedure.getName()))); assignment.setRightHandSide(buildExpression("qRPJ.bindProcedure(this, " + getCompilationUnit().normalizeTypeName(procedure.getName()) + ".class)")); assignment.setOperator(Operator.ASSIGN); ifStatement.setThenStatement(getAST().newExpressionStatement(assignment)); block.statements().add(ifStatement); } @SuppressWarnings("unchecked") private void writeSetEntryParams(QProcedure procedure, Block block) { List<QEntryParameter<?>> entryParameters = new ArrayList<QEntryParameter<?>>(); if (procedure.getEntry() != null) { entryParameters.addAll(procedure.getEntry().getParameters()); Collections.reverse(entryParameters); } int p = entryParameters.size(); IfStatement baseIf = null; IfStatement lastIf = null; for (QEntryParameter<?> entryParameter : entryParameters) { if (!entryParameter.isNullable()) break; // first if (entryParameters.size() == p) { IfStatement ifStatement = getAST().newIfStatement(); ifStatement.setExpression(buildExpression(getCompilationUnit().normalizeTermName(entryParameter.getName()) + " != null")); Expression expression = buildExpression(getCompilationUnit().normalizeTermName(procedure.getName()) + ".qPRO.qParms().eval(" + p + ")"); ExpressionStatement expressionStatement = getAST().newExpressionStatement(expression); ifStatement.setThenStatement(expressionStatement); Expression expressionElse = buildExpression(getCompilationUnit().normalizeTermName(procedure.getName()) + ".qPRO.qParms().eval(" + (p - 1) + ")"); ExpressionStatement expressionElseStatement = getAST().newExpressionStatement(expressionElse); ifStatement.setElseStatement(expressionElseStatement); baseIf = ifStatement; lastIf = ifStatement; } else { IfStatement ifStatement = getAST().newIfStatement(); ifStatement.setExpression(buildExpression(getCompilationUnit().normalizeTermName(entryParameter.getName()) + " != null")); Expression expression = buildExpression(getCompilationUnit().normalizeTermName(procedure.getName()) + ".qPRO.qParms().eval(" + p + ")"); ExpressionStatement expressionStatement = getAST().newExpressionStatement(expression); ifStatement.setThenStatement(expressionStatement); Expression expressionElse = buildExpression(getCompilationUnit().normalizeTermName(procedure.getName()) + ".qPRO.qParms().eval(" + (p - 1) + ")"); ExpressionStatement expressionElseStatement = getAST().newExpressionStatement(expressionElse); ifStatement.setElseStatement(expressionElseStatement); lastIf.setElseStatement(ifStatement); lastIf = ifStatement; } p } if (baseIf != null) block.statements().add(baseIf); } public void writeInnerProcedure(QProcedure procedure) { QCompilerManager compilerManager = getCompilationUnit().getContext().get(QCompilerManager.class); QCompilationUnit procedureCompilationUnit = compilerManager.createChildCompilationUnit(getCompilationUnit(), procedure); QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup(); try { boolean static_ = false; UnitScope scope = UnitScope.PROTECTED; switch (getCompilationSetup().getProcedureType()) { case INNER: break; case NESTED: static_ = true; scope = UnitScope.PUBLIC; break; } JDTProcedureWriter procedureWriter = new JDTProcedureWriter(this, procedureCompilationUnit, compilationSetup, getCompilationUnit().normalizeTermName(procedure.getName()), scope, static_); procedureWriter.writeProcedure(procedure); } catch (IOException e) { throw new DevelopmentKitCompilerRuntimeException("Invalid procedure: " + procedure, e); } finally { procedureCompilationUnit.close(); } } @SuppressWarnings("unchecked") public void writeMain(QParameterList parameterList, String name) { MethodDeclaration methodDeclaration = getAST().newMethodDeclaration(); getTarget().bodyDeclarations().add(methodDeclaration); MarkerAnnotation entryAnnotation = getAST().newMarkerAnnotation(); entryAnnotation.setTypeName(getAST().newSimpleName(Main.class.getSimpleName())); writeImport(Main.class); methodDeclaration.modifiers().add(entryAnnotation); methodDeclaration.setName(getAST().newSimpleName(name)); methodDeclaration.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); for (String parameterName : parameterList.getParameters()) { QDataTerm<?> dataTerm = getCompilationUnit().getDataTerm(parameterName, true); SingleVariableDeclaration parameterVariable = getAST().newSingleVariableDeclaration(); parameterVariable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(dataTerm.getName()))); Type type = getJavaType(dataTerm); parameterVariable.setType(type); QConversion conversion = dataTerm.getFacet(QConversion.class); if (conversion != null) { MarkerAnnotation conversionAnnotation = getAST().newMarkerAnnotation(); switch (conversion.getStatus()) { case POSSIBLE: break; case SUPPORTED: writeImport(Supported.class); conversionAnnotation.setTypeName(getAST().newSimpleName(Supported.class.getSimpleName())); parameterVariable.modifiers().add(conversionAnnotation); break; case TODO: writeImport(ToDo.class); conversionAnnotation.setTypeName(getAST().newSimpleName(ToDo.class.getSimpleName())); parameterVariable.modifiers().add(conversionAnnotation); break; case UNSUPPORTED: writeImport(Unsupported.class); conversionAnnotation.setTypeName(getAST().newSimpleName(Unsupported.class.getSimpleName())); parameterVariable.modifiers().add(conversionAnnotation); break; } } writeDataDefAnnotation(parameterVariable, dataTerm.getDefinition()); methodDeclaration.parameters().add(parameterVariable); } Block block = getAST().newBlock(); methodDeclaration.setBody(block); } @SuppressWarnings("unchecked") public void writeInit() { writeImport(QBufferedElement.class); MethodDeclaration methodDeclaration = getAST().newMethodDeclaration(); methodDeclaration.setName(getAST().newSimpleName("_init")); MarkerAnnotation entryAnnotation = getAST().newMarkerAnnotation(); entryAnnotation.setTypeName(getAST().newSimpleName(PostConstruct.class.getSimpleName())); writeImport(PostConstruct.class); methodDeclaration.modifiers().add(entryAnnotation); methodDeclaration.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); if (!(getCompilationUnit().getNode() instanceof QCallableUnit)) return; Block block = getAST().newBlock(); methodDeclaration.setBody(block); QCallableUnit callableUnit = (QCallableUnit) getCompilationUnit().getNode(); if (callableUnit.getFileSection() != null) { // redefined record dataSet for (QDataSetTerm dataSetTerm : callableUnit.getFileSection().getDataSets()) { // remap if (dataSetTerm.getFormat() != null) { for (QDataTerm<?> element : dataSetTerm.getFormat().getDefinition().getElements()) { QRemap remap = element.getFacet(QRemap.class); if (remap == null) continue; QDataTerm<?> remapDataTerm = getCompilationUnit().getDataTerm(remap.getName(), true); if (remapDataTerm == null) throw new IntegratedLanguageExpressionRuntimeException("Invalid term: " + remap); if (getCompilationUnit().equalsTermName(element.getName(), remapDataTerm.getName())) continue; MethodInvocation methodInvocation = getAST().newMethodInvocation(); methodInvocation.setName(getAST().newSimpleName("assign")); if (remap.getIndex() == null || remap.getIndex().isEmpty()) methodInvocation.setExpression(buildExpression(getCompilationUnit().getQualifiedName(remapDataTerm))); else methodInvocation.setExpression(buildExpression(getCompilationUnit().getQualifiedName(remapDataTerm) + ".get(" + Integer.parseInt(remap.getIndex()) + ")")); methodInvocation.arguments().add(buildExpression(getCompilationUnit().getQualifiedName(element))); ExpressionStatement expressionStatement = getAST().newExpressionStatement(methodInvocation); block.statements().add(expressionStatement); } } } // assign statement parameters for(QCursorTerm cursorTerm: callableUnit.getFileSection().getCursors()) { if(cursorTerm.getSql() == null) continue; try { QueryStatement queryStatement = queryParser.parseQuery(cursorTerm.getSql()).getQueryStatement(); List<ValueExpressionVariable> variables = StatementHelper.getAllVariablesInQueryStatement(queryStatement); if(variables.isEmpty()) continue; // array of bufferedData ArrayCreation arrayCreation = getAST().newArrayCreation(); arrayCreation.setType(getAST().newArrayType(getAST().newSimpleType(getAST().newSimpleName(QBufferedElement.class.getSimpleName())))); ArrayInitializer arrayInitializer = getAST().newArrayInitializer(); for(ValueExpressionVariable variable: variables) { QExpression expression = expressionParser.parseExpression(getCompilationUnit().normalizeTermName(variable.getName())); Expression jdtExpression = JDTStatementHelper.buildExpression(getAST(), getCompilationUnit(), expression, null); arrayInitializer.expressions().add(jdtExpression); } arrayCreation.setInitializer(arrayInitializer); DBLQuerySelectWriter querySelectWriter = new DBLQuerySelectWriter(); QuerySelectStatement selectStatement = (QuerySelectStatement) queryStatement; QueryExpressionBody query = selectStatement.getQueryExpr().getQuery(); queryStatement = queryParser.parseQuery(cursorTerm.getSql()).getQueryStatement(); String newSQLString = querySelectWriter.normalizeQuerySelect((QuerySelect) query); StringLiteral stringLiteral = getAST().newStringLiteral(); stringLiteral.setLiteralValue(newSQLString); MethodInvocation methodInvocation = getAST().newMethodInvocation(); methodInvocation.setName(getAST().newSimpleName("qCreateCursor")); methodInvocation.setExpression(getAST().newSimpleName("qSQL")); Name labelName = getAST().newName(new String[] { cursorTerm.getCursorType().getClass().getSimpleName(), cursorTerm.getCursorType().name() }); methodInvocation.arguments().add(labelName); methodInvocation.arguments().add(getAST().newBooleanLiteral(cursorTerm.isHold())); methodInvocation.arguments().add(stringLiteral); methodInvocation.arguments().add(arrayCreation); Assignment assignment = getAST().newAssignment(); assignment.setLeftHandSide(buildExpression(getCompilationUnit().getQualifiedName(cursorTerm))); assignment.setOperator(Operator.ASSIGN); assignment.setRightHandSide(methodInvocation); block.statements().add(getAST().newExpressionStatement(assignment)); } catch (SQLException e) { throw new DevelopmentKitCompilerRuntimeException("Invalid statement: " + cursorTerm); } } } if (!methodDeclaration.getBody().statements().isEmpty()) getTarget().bodyDeclarations().add(methodDeclaration); } @SuppressWarnings("unchecked") public void writeEntry(QParameterList parameterList, String name) { MethodDeclaration methodDeclaration = getAST().newMethodDeclaration(); getTarget().bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(getAST().newSimpleName(name)); MarkerAnnotation entryAnnotation = getAST().newMarkerAnnotation(); entryAnnotation.setTypeName(getAST().newSimpleName(Entry.class.getSimpleName())); writeImport(Entry.class); methodDeclaration.modifiers().add(entryAnnotation); methodDeclaration.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); Type returnType = getAST().newArrayType(getAST().newSimpleType(getAST().newSimpleName(QData.class.getSimpleName()))); methodDeclaration.setReturnType2(returnType); Block block = getAST().newBlock(); methodDeclaration.setBody(block); ArrayCreation arrayCreation = getAST().newArrayCreation(); arrayCreation.setType(getAST().newArrayType(getAST().newSimpleType(getAST().newSimpleName(QData.class.getSimpleName())))); ArrayInitializer arrayInitializer = getAST().newArrayInitializer(); arrayCreation.setInitializer(arrayInitializer); for (String parameterName : parameterList.getParameters()) { QExpression expression = expressionParser.parseExpression(parameterName); Expression jdtExpression = JDTStatementHelper.buildExpression(getAST(), getCompilationUnit(), expression, null); arrayInitializer.expressions().add(jdtExpression); } ReturnStatement returnStatement = getAST().newReturnStatement(); returnStatement.setExpression(arrayCreation); block.statements().add(returnStatement); } public void refactCallableUnit(QCallableUnit callableUnit) { refactUnit(callableUnit); // main if (callableUnit.getFlowSection() != null) { for (QUnit routine : callableUnit.getFlowSection().getRoutines()) refactUnit(routine); } } protected Expression buildExpression(String expression) { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setKind(ASTParser.K_EXPRESSION); parser.setSource(expression.toCharArray()); ASTNode node = parser.createAST(null); if (node.getLength() == 0) throw new IntegratedLanguageExpressionRuntimeException("Invalid java conversion: " + expression); Expression jdtExpression = (Expression) node; return (Expression) ASTNode.copySubtree(getAST(), jdtExpression); } @SuppressWarnings("unchecked") public void writeEntry(MethodDeclaration methodDeclaration, QEntry entry) { int p = 0; for (QEntryParameter<?> entryParameter : entry.getParameters()) { QTerm parameterDelegate = entryParameter.getDelegate(); SingleVariableDeclaration singleVar = getAST().newSingleVariableDeclaration(); if (entryParameter.isNullable()) writeAnnotation(singleVar, Optional.class); String parameterName = parameterDelegate.getName(); if (parameterName == null) parameterName = "arg" + p; singleVar.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(parameterName))); if (parameterDelegate instanceof QDataTerm) { QDataTerm<?> dataTerm = (QDataTerm<?>) parameterDelegate; // primitive if (dataTerm.isConstant() && !dataTerm.getDataTermType().isMultiple()) singleVar.setType(getJavaPrimitive(dataTerm)); else { Type type = getJavaType(dataTerm); singleVar.setType(type); } } else if (parameterDelegate instanceof QDataSetTerm) { Type dataSet = getAST().newSimpleType(getAST().newSimpleName(QDataSet.class.getSimpleName())); ParameterizedType parType = getAST().newParameterizedType(dataSet); parType.typeArguments().add(getAST().newWildcardType()); singleVar.setType(parType); } methodDeclaration.parameters().add(singleVar); p++; } } protected void loadModules(Collection<String> modules, String module, boolean recursive) { addModule(modules, module); QModule qModule = getCompilationUnit().getModule(module, true); for (String moduleName : qModule.getSetupSection().getModules()) { if (recursive) loadModules(modules, moduleName, recursive); else addModule(modules, module); } } @SuppressWarnings("unchecked") private void writeRoutineTestMain(MethodDeclaration methodDeclaration, QCallableUnit program) { QLists listUtil = getCompilationUnit().getContext().get(QLists.class); MarkerAnnotation entryAnnotation = getAST().newMarkerAnnotation(); entryAnnotation.setTypeName(getAST().newSimpleName(TestStarted.class.getSimpleName())); writeImport(TestStarted.class); listUtil.addFirst(methodDeclaration.modifiers(), entryAnnotation); Block assertionBlock = getAST().newBlock(); JDTStatementWriter statementWriter = getCompilationUnit().getContext().make(JDTStatementWriter.class); statementWriter.setAST(getAST()); statementWriter.getBlocks().push(assertionBlock); // test annotations for (QDataTerm<?> dataTerm : program.getDataSection().getDatas()) { for (QAnnotationTest annotationTest : dataTerm.getFacets(QAnnotationTest.class)) statementWriter.writeAssertion(annotationTest, dataTerm.toString()); } if (!assertionBlock.statements().isEmpty()) listUtil.addFirst(methodDeclaration.getBody().statements(), assertionBlock); statementWriter.getBlocks().pop(); } private void addModule(Collection<String> modules, String module) { if (!modules.contains(module)) modules.add(module); } }
package org.spoofax.jsglr2.integrationtest; import static java.util.Collections.sort; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr.client.imploder.IToken; import org.spoofax.jsglr2.JSGLR2; import org.spoofax.jsglr2.JSGLR2Result; import org.spoofax.jsglr2.JSGLR2Success; import org.spoofax.jsglr2.JSGLR2Variants; import org.spoofax.jsglr2.integration.IntegrationVariant; import org.spoofax.jsglr2.integration.ParseTableVariant; import org.spoofax.jsglr2.integration.WithParseTable; import org.spoofax.jsglr2.parseforest.ParseForestRepresentation; import org.spoofax.jsglr2.parser.IParser; import org.spoofax.jsglr2.parser.ParseException; import org.spoofax.jsglr2.parser.Position; import org.spoofax.jsglr2.parser.result.ParseResult; import org.spoofax.jsglr2.util.AstUtilities; import org.spoofax.terms.TermFactory; import org.spoofax.terms.io.binary.TermReader; public abstract class BaseTest implements WithParseTable { private static TermReader termReader = new TermReader(new TermFactory()); private static AstUtilities astUtilities = new AstUtilities(); protected BaseTest() { } public TermReader getTermReader() { return termReader; } protected Iterable<ParseTableWithOrigin> getParseTablesOrFailOnException(ParseTableVariant variant) { try { return getParseTables(variant); } catch(Exception e) { e.printStackTrace(); fail("Exception during reading parse table: " + e.getMessage()); return null; } } class TestVariant { IntegrationVariant variant; ParseTableWithOrigin parseTableWithOrigin; TestVariant(IntegrationVariant variant, ParseTableWithOrigin parseTableWithOrigin) { this.variant = variant; this.parseTableWithOrigin = parseTableWithOrigin; } String name() { return variant.name() + "(parseTableOrigin:" + parseTableWithOrigin.origin + ")"; } IParser<?> parser() { return JSGLR2Variants.getParser(parseTableWithOrigin.parseTable, variant.parser); } JSGLR2<IStrategoTerm> jsglr2() { return JSGLR2Variants.getJSGLR2(parseTableWithOrigin.parseTable, variant.jsglr2); } } protected Iterable<TestVariant> getTestVariants(Predicate<TestVariant> filter) { List<TestVariant> testVariants = new ArrayList<>(); for(IntegrationVariant variant : IntegrationVariant.testVariants()) { for(ParseTableWithOrigin parseTableWithOrigin : getParseTablesOrFailOnException(variant.parseTable)) { TestVariant testVariant = new TestVariant(variant, parseTableWithOrigin); if(filter.test(testVariant)) testVariants.add(testVariant); } } return testVariants; } protected Iterable<TestVariant> getTestVariants() { return getTestVariants(testVariant -> true); } protected void testParseSuccess(String inputString) { for(TestVariant variant : getTestVariants()) { ParseResult<?> parseResult = variant.parser().parse(inputString); assertEquals("Variant '" + variant.name() + "' failed parsing: ", true, parseResult.isSuccess()); } } protected void testParseFailure(String inputString) { for(TestVariant variant : getTestVariants()) { ParseResult<?> parseResult = variant.parser().parse(inputString); assertEquals("Variant '" + variant.name() + "' should fail: ", false, parseResult.isSuccess()); } } protected void testSuccessByAstString(String inputString, String expectedOutputAstString) { testSuccess(inputString, expectedOutputAstString, null, false); } protected void testSuccessByExpansions(String inputString, String expectedOutputAstString) { testSuccess(inputString, expectedOutputAstString, null, true); } protected void testIncrementalSuccessByExpansions(String[] inputStrings, String[] expectedOutputAstStrings) { testIncrementalSuccess(inputStrings, expectedOutputAstStrings, null, true); } protected void testSuccessByAstString(String startSymbol, String inputString, String expectedOutputAstString) { testSuccess(inputString, expectedOutputAstString, startSymbol, false); } protected void testSuccessByExpansions(String startSymbol, String inputString, String expectedOutputAstString) { testSuccess(inputString, expectedOutputAstString, startSymbol, true); } private void testSuccess(String inputString, String expectedOutputAstString, String startSymbol, boolean equalityByExpansions) { for(TestVariant variant : getTestVariants()) { IStrategoTerm actualOutputAst = testSuccess(variant, startSymbol, inputString); assertEqualAST("Variant '" + variant.name() + "' has incorrect AST", expectedOutputAstString, actualOutputAst, equalityByExpansions); } } protected IStrategoTerm testSuccess(TestVariant variant, String startSymbol, String inputString) { return testSuccess("Variant '" + variant.name() + "' failed parsing: ", "Variant '" + variant.name() + "' failed imploding: ", variant.jsglr2(), "", startSymbol, inputString); } private IStrategoTerm testSuccess(String parseFailMessage, String implodeFailMessage, JSGLR2<IStrategoTerm> jsglr2, String filename, String startSymbol, String inputString) { try { IStrategoTerm result = jsglr2.parseUnsafe(inputString, filename, startSymbol); // Fail here if imploding or tokenization failed assertNotNull(implodeFailMessage, result); return result; } catch(ParseException e) { // Fail here if parsing failed fail(parseFailMessage + e.failureType); } return null; } private void testIncrementalSuccess(String[] inputStrings, String[] expectedOutputAstStrings, String startSymbol, boolean equalityByExpansions) { for(TestVariant variant : getTestVariants( testVariant -> testVariant.variant.parser.parseForestRepresentation == ParseForestRepresentation.Incremental)) { IStrategoTerm actualOutputAst; String filename = "" + System.nanoTime(); // To ensure the results will be cached for(int i = 0; i < expectedOutputAstStrings.length; i++) { String inputString = inputStrings[i]; actualOutputAst = testSuccess("Variant '" + variant.name() + "' failed parsing at update " + i + ": ", "Variant '" + variant.name() + "' failed imploding at update " + i + ": ", variant.jsglr2(), filename, startSymbol, inputString); assertEqualAST("Variant '" + variant.name() + "' has incorrect AST at update " + i + ": ", expectedOutputAstStrings[i], actualOutputAst, equalityByExpansions); } } } private void assertEqualAST(String message, String expectedOutputAstString, IStrategoTerm actualOutputAst, boolean equalityByExpansions) { if(equalityByExpansions) { IStrategoTerm expectedOutputAst = termReader.parseFromString(expectedOutputAstString); assertEqualTermExpansions(message, expectedOutputAst, actualOutputAst); } else { assertEquals(message, expectedOutputAstString, actualOutputAst.toString()); } } protected static void assertEqualTermExpansions(IStrategoTerm expected, IStrategoTerm actual) { assertEqualTermExpansions(null, expected, actual); } protected static void assertEqualTermExpansions(String message, IStrategoTerm expected, IStrategoTerm actual) { List<String> expectedExpansion = toSortedStringList(astUtilities.expand(expected)); List<String> actualExpansion = toSortedStringList(astUtilities.expand(actual)); assertEquals(message, expectedExpansion, actualExpansion); } private static List<String> toSortedStringList(List<IStrategoTerm> astExpansion) { List<String> result = new ArrayList<>(astExpansion.size()); for(IStrategoTerm ast : astExpansion) { result.add(ast.toString()); } sort(result); return result; } protected void testTokens(String inputString, List<TokenDescriptor> expectedTokens) { for(TestVariant variant : getTestVariants()) { JSGLR2Result<?> jsglr2Result = variant.jsglr2().parseResult(inputString, "", null); assertTrue("Variant '" + variant.name() + "' failed", jsglr2Result.isSuccess()); JSGLR2Success<?> jsglr2Success = (JSGLR2Success<?>) jsglr2Result; List<TokenDescriptor> actualTokens = new ArrayList<>(); for(IToken token : (jsglr2Success).tokens) { actualTokens.add(TokenDescriptor.from(inputString, token)); } TokenDescriptor expectedStartToken = new TokenDescriptor("", IToken.TK_RESERVED, 0, 1, 1); TokenDescriptor actualStartToken = actualTokens.get(0); assertEquals("Start token incorrect:", expectedStartToken, actualStartToken); Position endPosition = Position.atEnd(inputString); int endLine = endPosition.line; int endColumn = endPosition.column; TokenDescriptor expectedEndToken = new TokenDescriptor("", IToken.TK_EOF, inputString.length(), endLine, endColumn - 1); TokenDescriptor actualEndToken = actualTokens.get(actualTokens.size() - 1); List<TokenDescriptor> actualTokensWithoutStartAndEnd = actualTokens.subList(1, actualTokens.size() - 1); assertThat(actualTokensWithoutStartAndEnd, is(expectedTokens)); assertEquals("End token incorrect:", expectedEndToken, actualEndToken); } } protected String getFileAsString(String filename) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("samples/" + filename).getPath())); return new String(encoded, StandardCharsets.UTF_8); } protected IStrategoTerm getFileAsAST(String filename) throws IOException { InputStream inputStream = getClass().getClassLoader().getResourceAsStream("samples/" + filename); return termReader.parseFromStream(inputStream); } }
package org.opendaylight.yangtools.yang.stmt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.opendaylight.yangtools.yang.stmt.StmtTestUtils.sourceForResource; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.common.XMLNamespace; import org.opendaylight.yangtools.yang.common.YangVersion; import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.DeviateKind; import org.opendaylight.yangtools.yang.model.api.Deviation; import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint; import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition; import org.opendaylight.yangtools.yang.model.api.FeatureDefinition; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.ModuleImport; import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.Status; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute; import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement; import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint; import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.TypeDefinitions; import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; import org.opendaylight.yangtools.yang.model.ri.type.BaseTypes; import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors; import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException; import org.opendaylight.yangtools.yang.parser.spi.source.SourceException; import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource; import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction; public class YangParserTest { private static final QNameModule FOO = QNameModule.create(XMLNamespace.of("urn:opendaylight.foo"), Revision.of("2013-02-27")); private static final QNameModule BAR = QNameModule.create(XMLNamespace.of("urn:opendaylight.bar"), Revision.of("2013-07-03")); private static final QNameModule BAZ = QNameModule.create(XMLNamespace.of("urn:opendaylight.baz"), Revision.of("2013-02-27")); private static SchemaContext CONTEXT; private static Module foo; private static Module bar; private static Module baz; @BeforeClass public static void beforeClass() throws Exception { CONTEXT = TestUtils.loadModules("/model"); foo = CONTEXT.findModules("foo").iterator().next(); bar = CONTEXT.findModules("bar").iterator().next(); baz = CONTEXT.findModules("baz").iterator().next(); } @Test public void testHeaders() throws ParseException { assertEquals("foo", foo.getName()); assertEquals(YangVersion.VERSION_1, foo.getYangVersion()); assertEquals(FOO.getNamespace(), foo.getNamespace()); assertEquals("foo", foo.getPrefix()); final Collection<? extends ModuleImport> imports = foo.getImports(); assertEquals(2, imports.size()); final ModuleImport import2 = TestUtils.findImport(imports, "br"); assertEquals("bar", import2.getModuleName()); assertEquals(BAR.getRevision(), import2.getRevision()); final ModuleImport import3 = TestUtils.findImport(imports, "bz"); assertEquals("baz", import3.getModuleName()); assertEquals(BAZ.getRevision(), import3.getRevision()); assertEquals(Optional.of("opendaylight"), foo.getOrganization()); assertEquals(Optional.of("http: assertEquals(Revision.ofNullable("2013-02-27"), foo.getRevision()); assertFalse(foo.getReference().isPresent()); } @Test public void testParseList() { final ContainerSchemaNode interfaces = (ContainerSchemaNode) bar.getDataChildByName(QName.create( bar.getQNameModule(), "interfaces")); final ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName(QName.create(bar.getQNameModule(), "ifEntry")); // test SchemaNode args assertEquals(QName.create(BAR, "ifEntry"), ifEntry.getQName()); assertFalse(ifEntry.getDescription().isPresent()); assertFalse(ifEntry.getReference().isPresent()); assertEquals(Status.CURRENT, ifEntry.getStatus()); assertEquals(0, ifEntry.getUnknownSchemaNodes().size()); // test DataSchemaNode args assertFalse(ifEntry.isAugmenting()); assertEquals(Optional.of(Boolean.TRUE), ifEntry.effectiveConfig()); // :TODO augment to ifEntry have when condition and so in consequence // ifEntry should be a context node ? // assertNull(constraints.getWhenCondition()); assertEquals(0, ifEntry.getMustConstraints().size()); ElementCountConstraint constraints = ifEntry.getElementCountConstraint().get(); assertEquals((Object) 1, constraints.getMinElements()); assertEquals((Object) 11, constraints.getMaxElements()); // test AugmentationTarget args final Collection<? extends AugmentationSchemaNode> availableAugmentations = ifEntry.getAvailableAugmentations(); assertEquals(2, availableAugmentations.size()); // test ListSchemaNode args final List<QName> expectedKey = new ArrayList<>(); expectedKey.add(QName.create(BAR, "ifIndex")); assertEquals(expectedKey, ifEntry.getKeyDefinition()); assertFalse(ifEntry.isUserOrdered()); // test DataNodeContainer args assertEquals(0, ifEntry.getTypeDefinitions().size()); assertEquals(4, ifEntry.getChildNodes().size()); assertEquals(0, ifEntry.getGroupings().size()); assertEquals(0, ifEntry.getUses().size()); final LeafSchemaNode ifIndex = (LeafSchemaNode) ifEntry.getDataChildByName(QName.create(bar.getQNameModule(), "ifIndex")); assertEquals(ifEntry.getKeyDefinition().get(0), ifIndex.getQName()); assertTrue(ifIndex.getType() instanceof Uint32TypeDefinition); assertEquals(Optional.of("minutes"), ifIndex.getType().getUnits()); final LeafSchemaNode ifMtu = (LeafSchemaNode) ifEntry.getDataChildByName(QName.create(bar.getQNameModule(), "ifMtu")); assertEquals(BaseTypes.int32Type(), ifMtu.getType()); } @Test public void testTypedefRangesResolving() throws ParseException { final LeafSchemaNode int32Leaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "int32-leaf")); final Int32TypeDefinition leafType = (Int32TypeDefinition) int32Leaf.getType(); assertEquals(QName.create(FOO, "int32-ext2"), leafType.getQName()); assertEquals(Optional.of("mile"), leafType.getUnits()); assertEquals(Optional.of("11"), leafType.getDefaultValue()); final RangeSet<? extends Number> rangeset = leafType.getRangeConstraint().get().getAllowedRanges(); final Set<? extends Range<? extends Number>> ranges = rangeset.asRanges(); assertEquals(1, ranges.size()); final Range<? extends Number> range = ranges.iterator().next(); assertEquals(12, range.lowerEndpoint().intValue()); assertEquals(20, range.upperEndpoint().intValue()); final Int32TypeDefinition firstBaseType = leafType.getBaseType(); assertEquals(QName.create(BAR, "int32-ext2"), firstBaseType.getQName()); assertEquals(Optional.of("mile"), firstBaseType.getUnits()); assertEquals(Optional.of("11"), firstBaseType.getDefaultValue()); final RangeSet<? extends Number> firstRangeset = firstBaseType.getRangeConstraint().get().getAllowedRanges(); final Set<? extends Range<? extends Number>> baseRanges = firstRangeset.asRanges(); assertEquals(2, baseRanges.size()); final Iterator<? extends Range<? extends Number>> it = baseRanges.iterator(); final Range<? extends Number> baseTypeRange1 = it.next(); assertEquals(3, baseTypeRange1.lowerEndpoint().intValue()); assertEquals(9, baseTypeRange1.upperEndpoint().intValue()); final Range<? extends Number> baseTypeRange2 = it.next(); assertEquals(11, baseTypeRange2.lowerEndpoint().intValue()); assertEquals(20, baseTypeRange2.upperEndpoint().intValue()); final Int32TypeDefinition secondBaseType = firstBaseType.getBaseType(); final QName baseQName = secondBaseType.getQName(); assertEquals("int32-ext1", baseQName.getLocalName()); assertEquals(BAR, baseQName.getModule()); assertEquals(Optional.empty(), secondBaseType.getUnits()); assertEquals(Optional.empty(), secondBaseType.getDefaultValue()); final Set<? extends Range<? extends Number>> secondRanges = secondBaseType.getRangeConstraint().get() .getAllowedRanges().asRanges(); assertEquals(1, secondRanges.size()); final Range<? extends Number> secondRange = secondRanges.iterator().next(); assertEquals(2, secondRange.lowerEndpoint().intValue()); assertEquals(20, secondRange.upperEndpoint().intValue()); assertEquals(BaseTypes.int32Type(), secondBaseType.getBaseType()); } @Test public void testTypedefPatternsResolving() { final LeafSchemaNode stringleaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "string-leaf")); assertTrue(stringleaf.getType() instanceof StringTypeDefinition); final StringTypeDefinition type = (StringTypeDefinition) stringleaf.getType(); final QName typeQName = type.getQName(); assertEquals("string-ext4", typeQName.getLocalName()); assertEquals(BAR, typeQName.getModule()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); List<PatternConstraint> patterns = type.getPatternConstraints(); assertEquals(1, patterns.size()); PatternConstraint pattern = patterns.iterator().next(); assertEquals("^(?:[e-z]*)$", pattern.getJavaPatternString()); assertEquals(1, type.getLengthConstraint().get().getAllowedRanges().asRanges().size()); final StringTypeDefinition baseType1 = type.getBaseType(); final QName baseType1QName = baseType1.getQName(); assertEquals("string-ext3", baseType1QName.getLocalName()); assertEquals(BAR, baseType1QName.getModule()); assertEquals(Optional.empty(), baseType1.getUnits()); assertEquals(Optional.empty(), baseType1.getDefaultValue()); patterns = baseType1.getPatternConstraints(); assertEquals(1, patterns.size()); pattern = patterns.iterator().next(); assertEquals("^(?:[b-u]*)$", pattern.getJavaPatternString()); assertEquals(1, baseType1.getLengthConstraint().get().getAllowedRanges().asRanges().size()); final StringTypeDefinition baseType2 = baseType1.getBaseType(); final QName baseType2QName = baseType2.getQName(); assertEquals("string-ext2", baseType2QName.getLocalName()); assertEquals(BAR, baseType2QName.getModule()); assertEquals(Optional.empty(), baseType2.getUnits()); assertEquals(Optional.empty(), baseType2.getDefaultValue()); assertTrue(baseType2.getPatternConstraints().isEmpty()); final RangeSet<Integer> baseType2Lengths = baseType2.getLengthConstraint().get().getAllowedRanges(); assertEquals(1, baseType2Lengths.asRanges().size()); Range<Integer> length = baseType2Lengths.span(); assertEquals(6, length.lowerEndpoint().intValue()); assertEquals(10, length.upperEndpoint().intValue()); final StringTypeDefinition baseType3 = baseType2.getBaseType(); assertEquals(QName.create(BAR, "string-ext1"), baseType3.getQName()); assertEquals(Optional.empty(), baseType3.getUnits()); assertEquals(Optional.empty(), baseType3.getDefaultValue()); patterns = baseType3.getPatternConstraints(); assertEquals(1, patterns.size()); pattern = patterns.iterator().next(); assertEquals("^(?:[a-k]*)$", pattern.getJavaPatternString()); final RangeSet<Integer> baseType3Lengths = baseType3.getLengthConstraint().get().getAllowedRanges(); assertEquals(1, baseType3Lengths.asRanges().size()); length = baseType3Lengths.span(); assertEquals(5, length.lowerEndpoint().intValue()); assertEquals(11, length.upperEndpoint().intValue()); assertEquals(BaseTypes.stringType(), baseType3.getBaseType()); } @Test public void testTypedefInvalidPatternsResolving() { final LeafSchemaNode multiplePatternStringLeaf = (LeafSchemaNode) foo .getDataChildByName(QName.create(foo.getQNameModule(), "multiple-pattern-string-leaf")); StringTypeDefinition type = (StringTypeDefinition) multiplePatternStringLeaf.getType(); assertEquals(QName.create(BAR, "multiple-pattern-string"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); List<PatternConstraint> patterns = type.getPatternConstraints(); assertEquals(2, patterns.size()); assertEquals("^(?:[A-Z]*-%22!\\^\\^)$", patterns.get(0).getJavaPatternString()); assertEquals("^(?:[e-z]*)$", patterns.get(1).getJavaPatternString()); assertEquals(1, type.getLengthConstraint().get().getAllowedRanges().asRanges().size()); final LeafSchemaNode multiplePatternDirectStringDefLeaf = (LeafSchemaNode) foo .getDataChildByName(QName.create(foo.getQNameModule(), "multiple-pattern-direct-string-def-leaf")); type = (StringTypeDefinition) multiplePatternDirectStringDefLeaf.getType(); assertEquals(QName.create(FOO, "string"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); patterns = type.getPatternConstraints(); assertEquals(3, patterns.size()); assertEquals("^(?:[e-z]*)$", patterns.get(0).getJavaPatternString()); assertEquals("^(?:[A-Z]*-%22!\\^\\^})$", patterns.get(1).getJavaPatternString()); assertEquals("^(?:[a-d]*)$", patterns.get(2).getJavaPatternString()); } @Test public void testTypedefLengthsResolving() { final LeafSchemaNode lengthLeaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "length-leaf")); final StringTypeDefinition type = (StringTypeDefinition) lengthLeaf.getType(); assertEquals(QName.create(FOO, "string-ext2"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); assertTrue(type.getPatternConstraints().isEmpty()); final RangeSet<Integer> typeLengths = type.getLengthConstraint().get().getAllowedRanges(); assertEquals(1, typeLengths.asRanges().size()); Range<Integer> length = typeLengths.span(); assertEquals(7, length.lowerEndpoint().intValue()); assertEquals(10, length.upperEndpoint().intValue()); final StringTypeDefinition baseType1 = type.getBaseType(); assertEquals(QName.create(BAR, "string-ext2"), baseType1.getQName()); assertEquals(Optional.empty(), baseType1.getUnits()); assertEquals(Optional.empty(), baseType1.getDefaultValue()); assertTrue(baseType1.getPatternConstraints().isEmpty()); final RangeSet<Integer> baseType2Lengths = baseType1.getLengthConstraint().get().getAllowedRanges(); assertEquals(1, baseType2Lengths.asRanges().size()); length = baseType2Lengths.span(); assertEquals(6, length.lowerEndpoint().intValue()); assertEquals(10, length.upperEndpoint().intValue()); final StringTypeDefinition baseType2 = baseType1.getBaseType(); assertEquals(QName.create(BAR, "string-ext1"), baseType2.getQName()); assertEquals(Optional.empty(), baseType2.getUnits()); assertEquals(Optional.empty(), baseType2.getDefaultValue()); final List<PatternConstraint> patterns = baseType2.getPatternConstraints(); assertEquals(1, patterns.size()); final PatternConstraint pattern = patterns.iterator().next(); assertEquals("^(?:[a-k]*)$", pattern.getJavaPatternString()); final RangeSet<Integer> baseType3Lengths = baseType2.getLengthConstraint().get().getAllowedRanges(); assertEquals(1, baseType3Lengths.asRanges().size()); length = baseType3Lengths.span(); assertEquals(5, length.lowerEndpoint().intValue()); assertEquals(11, length.upperEndpoint().intValue()); assertEquals(BaseTypes.stringType(), baseType2.getBaseType()); } @Test public void testTypedefDecimal1() { final LeafSchemaNode testleaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "decimal-leaf")); assertTrue(testleaf.getType() instanceof DecimalTypeDefinition); final DecimalTypeDefinition type = (DecimalTypeDefinition) testleaf.getType(); assertEquals(QName.create(BAR, "my-decimal-type"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); assertEquals(6, type.getFractionDigits()); assertEquals(1, type.getRangeConstraint().get().getAllowedRanges().asRanges().size()); final DecimalTypeDefinition typeBase = type.getBaseType(); assertEquals(QName.create(BAR, "decimal64"), typeBase.getQName()); assertEquals(Optional.empty(), typeBase.getUnits()); assertEquals(Optional.empty(), typeBase.getDefaultValue()); assertEquals(6, typeBase.getFractionDigits()); assertEquals(1, typeBase.getRangeConstraint().get().getAllowedRanges().asRanges().size()); assertNull(typeBase.getBaseType()); } @Test public void testTypedefDecimal2() { final LeafSchemaNode testleaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "decimal-leaf2")); assertTrue(testleaf.getType() instanceof DecimalTypeDefinition); final DecimalTypeDefinition type = (DecimalTypeDefinition) testleaf.getType(); assertEquals(QName.create(BAR, "my-decimal-type"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); assertEquals(6, type.getFractionDigits()); assertEquals(1, type.getRangeConstraint().get().getAllowedRanges().asRanges().size()); final DecimalTypeDefinition baseTypeDecimal = type.getBaseType(); assertEquals(6, baseTypeDecimal.getFractionDigits()); } @Test public void testTypedefUnion() { final LeafSchemaNode unionleaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "union-leaf")); assertTrue(unionleaf.getType() instanceof UnionTypeDefinition); final UnionTypeDefinition type = (UnionTypeDefinition) unionleaf.getType(); assertEquals(QName.create(BAR, "my-union-ext"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); final UnionTypeDefinition baseType = type.getBaseType(); assertEquals(QName.create(BAR, "my-union"), baseType.getQName()); assertEquals(Optional.empty(), baseType.getUnits()); assertEquals(Optional.empty(), baseType.getDefaultValue()); final UnionTypeDefinition unionType = baseType.getBaseType(); final List<TypeDefinition<?>> unionTypes = unionType.getTypes(); assertEquals(2, unionTypes.size()); final Int16TypeDefinition unionType1 = (Int16TypeDefinition) unionTypes.get(0); assertEquals(QName.create(BAR, "my-union"), baseType.getQName()); assertEquals(Optional.empty(), unionType1.getUnits()); assertEquals(Optional.empty(), unionType1.getDefaultValue()); final RangeConstraint<?> ranges = unionType1.getRangeConstraint().get(); assertEquals(1, ranges.getAllowedRanges().asRanges().size()); final Range<?> range = ranges.getAllowedRanges().span(); assertEquals((short)1, range.lowerEndpoint()); assertEquals((short)100, range.upperEndpoint()); assertEquals(BaseTypes.int16Type(), unionType1.getBaseType()); assertEquals(BaseTypes.int32Type(), unionTypes.get(1)); } @Test public void testNestedUnionResolving() { final LeafSchemaNode testleaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(), "custom-union-leaf")); assertTrue(testleaf.getType() instanceof UnionTypeDefinition); final UnionTypeDefinition type = (UnionTypeDefinition) testleaf.getType(); assertEquals(QName.create(BAZ, "union1"), type.getQName()); assertEquals(Optional.empty(), type.getUnits()); assertEquals(Optional.empty(), type.getDefaultValue()); final UnionTypeDefinition typeBase = type.getBaseType(); assertEquals(QName.create(BAZ, "union2"), typeBase.getQName()); assertEquals(Optional.empty(), typeBase.getUnits()); assertEquals(Optional.empty(), typeBase.getDefaultValue()); final UnionTypeDefinition union = typeBase.getBaseType(); final List<TypeDefinition<?>> unionTypes = union.getTypes(); assertEquals(2, unionTypes.size()); assertEquals(BaseTypes.int32Type(), unionTypes.get(0)); assertTrue(unionTypes.get(1) instanceof UnionTypeDefinition); final UnionTypeDefinition unionType1 = (UnionTypeDefinition) unionTypes.get(1); assertEquals(QName.create(BAR, "nested-union2"), unionType1.getQName()); assertEquals(Optional.empty(), unionType1.getUnits()); assertEquals(Optional.empty(), unionType1.getDefaultValue()); final UnionTypeDefinition nestedUnion = unionType1.getBaseType(); final List<TypeDefinition<?>> nestedUnion2Types = nestedUnion.getTypes(); assertEquals(2, nestedUnion2Types.size()); assertTrue(nestedUnion2Types.get(1) instanceof StringTypeDefinition); assertTrue(nestedUnion2Types.get(0) instanceof UnionTypeDefinition); final UnionTypeDefinition myUnionExt = (UnionTypeDefinition) nestedUnion2Types.get(0); assertEquals(QName.create(BAR, "my-union-ext"), myUnionExt.getQName()); assertEquals(Optional.empty(), myUnionExt.getUnits()); assertEquals(Optional.empty(), myUnionExt.getDefaultValue()); final UnionTypeDefinition myUnion = myUnionExt.getBaseType(); assertEquals(QName.create(BAR, "my-union"), myUnion.getQName()); assertEquals(Optional.empty(), myUnion.getUnits()); assertEquals(Optional.empty(), myUnion.getDefaultValue()); final UnionTypeDefinition myUnionBase = myUnion.getBaseType(); final List<TypeDefinition<?>> myUnionBaseTypes = myUnionBase.getTypes(); assertEquals(2, myUnionBaseTypes.size()); assertTrue(myUnionBaseTypes.get(0) instanceof Int16TypeDefinition); assertEquals(BaseTypes.int32Type(), myUnionBaseTypes.get(1)); final Int16TypeDefinition int16Ext = (Int16TypeDefinition) myUnionBaseTypes.get(0); assertEquals(TypeDefinitions.INT16, int16Ext.getQName()); assertEquals(Optional.empty(), int16Ext.getUnits()); assertEquals(Optional.empty(), int16Ext.getDefaultValue()); final Set<? extends Range<? extends Number>> ranges = int16Ext.getRangeConstraint().get().getAllowedRanges() .asRanges(); assertEquals(1, ranges.size()); final Range<? extends Number> range = ranges.iterator().next(); assertEquals(1, range.lowerEndpoint().intValue()); assertEquals(100, range.upperEndpoint().intValue()); assertEquals(BaseTypes.int16Type(), int16Ext.getBaseType()); } @Test public void testChoice() { final ContainerSchemaNode transfer = (ContainerSchemaNode) foo.getDataChildByName( QName.create(foo.getQNameModule(), "transfer")); final ChoiceSchemaNode how = (ChoiceSchemaNode) transfer.getDataChildByName( QName.create(foo.getQNameModule(), "how")); final Collection<? extends CaseSchemaNode> cases = how.getCases(); assertEquals(5, cases.size()); CaseSchemaNode input = null; CaseSchemaNode output = null; for (final CaseSchemaNode caseNode : cases) { if ("input".equals(caseNode.getQName().getLocalName())) { input = caseNode; } else if ("output".equals(caseNode.getQName().getLocalName())) { output = caseNode; } } assertNotNull(input); assertNotNull(output); } @Test public void testDeviation() { final Collection<? extends Deviation> deviations = foo.getDeviations(); assertEquals(1, deviations.size()); final Deviation dev = deviations.iterator().next(); assertEquals(Optional.of("system/user ref"), dev.getReference()); assertEquals(Absolute.of(QName.create(BAR, "interfaces"), QName.create(BAR, "ifEntry")), dev.getTargetPath()); assertEquals(DeviateKind.ADD, dev.getDeviates().iterator().next().getDeviateType()); } @Test public void testUnknownNode() { final ContainerSchemaNode network = (ContainerSchemaNode) baz.getDataChildByName( QName.create(baz.getQNameModule(), "network")); final Collection<? extends UnrecognizedStatement> unknownNodes = network.asEffectiveStatement().getDeclared() .declaredSubstatements(UnrecognizedStatement.class); assertEquals(1, unknownNodes.size()); assertEquals("point", unknownNodes.iterator().next().argument()); } @Test public void testFeature() { final Collection<? extends FeatureDefinition> features = baz.getFeatures(); assertEquals(3, features.size()); } @Test public void testExtension() { final Collection<? extends ExtensionDefinition> extensions = baz.getExtensionSchemaNodes(); assertEquals(1, extensions.size()); final ExtensionDefinition extension = extensions.iterator().next(); assertEquals("name", extension.getArgument()); assertEquals( Optional.of("Takes as argument a name string. Makes the code generator use the given name in the #define."), extension.getDescription()); assertTrue(extension.isYinElement()); } @Test public void testNotification() { final Collection<? extends NotificationDefinition> notifications = baz.getNotifications(); assertEquals(1, notifications.size()); final NotificationDefinition notification = notifications.iterator().next(); // test SchemaNode args assertEquals(QName.create(BAZ, "event"), notification.getQName()); assertFalse(notification.getDescription().isPresent()); assertFalse(notification.getReference().isPresent()); assertEquals(Status.CURRENT, notification.getStatus()); assertEquals(0, notification.getUnknownSchemaNodes().size()); // test DataNodeContainer args assertEquals(0, notification.getTypeDefinitions().size()); assertEquals(3, notification.getChildNodes().size()); assertEquals(0, notification.getGroupings().size()); assertEquals(0, notification.getUses().size()); final LeafSchemaNode eventClass = (LeafSchemaNode) notification.getDataChildByName( QName.create(baz.getQNameModule(), "event-class")); assertTrue(eventClass.getType() instanceof StringTypeDefinition); final LeafSchemaNode severity = (LeafSchemaNode) notification.getDataChildByName( QName.create(baz.getQNameModule(), "severity")); assertTrue(severity.getType() instanceof StringTypeDefinition); } @Test public void testRpc() { final Collection<? extends RpcDefinition> rpcs = baz.getRpcs(); assertEquals(1, rpcs.size()); final RpcDefinition rpc = rpcs.iterator().next(); assertEquals(Optional.of("Retrieve all or part of a specified configuration."), rpc.getDescription()); assertEquals(Optional.of("RFC 6241, Section 7.1"), rpc.getReference()); } @Test public void testTypePath() throws ParseException { final Collection<? extends TypeDefinition<?>> types = bar.getTypeDefinitions(); // int32-ext1 final Int32TypeDefinition int32ext1 = (Int32TypeDefinition) TestUtils.findTypedef(types, "int32-ext1"); assertEquals(QName.create(BAR, "int32-ext1"), int32ext1.getQName()); // int32-ext1/int32 assertEquals(BaseTypes.int32Type(), int32ext1.getBaseType()); } @Test public void testTypePath2() throws ParseException { final Collection<? extends TypeDefinition<?>> types = bar.getTypeDefinitions(); // my-decimal-type final DecimalTypeDefinition myDecType = (DecimalTypeDefinition) TestUtils.findTypedef(types, "my-decimal-type"); final QName myDecTypeQName = myDecType.getQName(); assertEquals(BAR, myDecTypeQName.getModule()); assertEquals("my-decimal-type", myDecTypeQName.getLocalName()); // my-base-int32-type/int32 final DecimalTypeDefinition dec64 = myDecType.getBaseType(); final QName dec64QName = dec64.getQName(); assertEquals(BAR, dec64QName.getModule()); assertEquals("decimal64", dec64QName.getLocalName()); } private static void checkOrder(final Collection<Module> modules) { final Iterator<Module> it = modules.iterator(); Module module = it.next(); assertEquals("m2", module.getName()); module = it.next(); assertEquals("m4", module.getName()); module = it.next(); assertEquals("m6", module.getName()); module = it.next(); assertEquals("m8", module.getName()); module = it.next(); assertEquals("m7", module.getName()); module = it.next(); assertEquals("m5", module.getName()); module = it.next(); assertEquals("m3", module.getName()); module = it.next(); assertEquals("m1", module.getName()); } private static void assertSetEquals(final Set<Module> s1, final Set<Module> s2) { assertEquals(s1, s2); final Iterator<Module> it = s1.iterator(); for (final Module m : s2) { assertEquals(m, it.next()); } } @Test public void testSubmodules() { final DataSchemaNode id = foo.getDataChildByName(QName.create(foo.getQNameModule(), "id")); assertNotNull(id); final DataSchemaNode subExt = foo.getDataChildByName(QName.create(foo.getQNameModule(), "sub-ext")); assertNotNull(subExt); final DataSchemaNode subTransfer = foo.getDataChildByName(QName.create(foo.getQNameModule(), "sub-transfer")); assertNotNull(subTransfer); assertEquals(2, foo.getExtensionSchemaNodes().size()); assertEquals(2, foo.getAugmentations().size()); } @Test public void unknownStatementInSubmoduleHeaderTest() throws IOException, URISyntaxException, ReactorException { final StatementStreamSource yang1 = sourceForResource("/yang-grammar-test/revisions-extension.yang"); final StatementStreamSource yang2 = sourceForResource("/yang-grammar-test/submodule-header-extension.yang"); TestUtils.parseYangSources(yang1, yang2); } @Test public void unknownStatementBetweenRevisionsTest() throws ReactorException { final SchemaContext result = RFC7950Reactors.defaultReactor().newBuild() .addSource(sourceForResource("/yang-grammar-test/revisions-extension.yang")) .addSource(sourceForResource("/yang-grammar-test/submodule-header-extension.yang")) .buildEffective(); assertNotNull(result); } @Test public void unknownStatementsInStatementsTest() { final StatementStreamSource yangFile1 = sourceForResource( "/yang-grammar-test/stmtsep-in-statements.yang"); final StatementStreamSource yangFile2 = sourceForResource( "/yang-grammar-test/stmtsep-in-statements2.yang"); final StatementStreamSource yangFile3 = sourceForResource( "/yang-grammar-test/stmtsep-in-statements-sub.yang"); final BuildAction reactor = RFC7950Reactors.defaultReactor().newBuild() .addSources(yangFile1, yangFile2, yangFile3); // TODO: change test or create new module in order to respect new statement parser validations try { final SchemaContext result = reactor.buildEffective(); } catch (final ReactorException e) { assertEquals(SomeModifiersUnresolvedException.class, e.getClass()); assertTrue(e.getCause() instanceof SourceException); assertTrue(e.getCause().getMessage().startsWith("aaa is not a YANG statement or use of extension")); } } }
package net.sf.cglib; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * @author Chris Nokleberg <a href="mailto:chris@nokleberg.com">chris@nokleberg.com</a> * @version $Id: MethodClosure.java,v 1.4 2002-12-21 21:44:25 herbyderby Exp $ */ abstract public class MethodClosure { /* package */ static final Class TYPE = MethodClosure.class; private static final String CLASS_PREFIX = "net.sf.cglib"; private static final String CLASS_SUFFIX = "$$ClosuredByCGLIB$$"; private static int index = 0; private static final FactoryCache cache = new FactoryCache(); private static final ClassLoader defaultLoader = TYPE.getClassLoader(); private static final MethodClosureKey keyFactory = (MethodClosureKey)KeyFactory.makeFactory(MethodClosureKey.class, null); // should be package-protected but causes problems on jdk1.2 public interface MethodClosureKey { public Object newInstance(Class delegateClass, String methodName, Class iface); } protected Object delegate; protected String eqMethod; public boolean equals(Object obj) { MethodClosure other = (MethodClosure)obj; return delegate == other.delegate && eqMethod.equals(other.eqMethod); } public int hashCode() { return delegate.hashCode() ^ eqMethod.hashCode(); } protected MethodClosure() { } abstract public MethodClosure newInstance(Object delegate); public static MethodClosure generate(Object delegate, String methodName, Class iface) { return generate(delegate, methodName, iface, null); } public static MethodClosure generate(Object delegate, String methodName, Class iface, ClassLoader loader) { if (loader == null) { loader = defaultLoader; } Class delegateClass = delegate.getClass(); Object key = keyFactory.newInstance(delegateClass, methodName, iface); MethodClosure factory; synchronized (cache) { factory = (MethodClosure)cache.get(loader, key); if (factory == null) { Method method = findProxiedMethod(delegateClass, methodName, iface); Class result = new Generator(getNextName(delegateClass), method, iface, loader).define(); factory = (MethodClosure)FactoryCache.newInstance(result, Constants.TYPES_EMPTY, null); cache.put(loader, key, factory); } } return factory.newInstance(delegate); } private static Method findProxiedMethod(Class delegateClass, String methodName, Class iface) { if (!iface.isInterface()) { throw new IllegalArgumentException(iface + " is not an interface"); } Method[] methods = iface.getDeclaredMethods(); if (methods.length != 1) { throw new IllegalArgumentException("expecting exactly 1 method in " + iface); } Method proxy = methods[0]; try { Method method = delegateClass.getMethod(methodName, proxy.getParameterTypes()); if (method == null) { throw new IllegalArgumentException("no matching method found"); } if (!proxy.getReturnType().isAssignableFrom(method.getReturnType())) { throw new IllegalArgumentException("incompatible return types"); } return method; } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } } // TODO: move to helper class private static String getNextName(Class cls) { String class_name = cls.getName() + CLASS_SUFFIX; if (class_name.startsWith("java")) { class_name = CLASS_PREFIX + class_name; } class_name += index++; return class_name; } private static class Generator extends CodeGenerator { private Method method; private Class iface; private Method proxy; public Generator(String className, Method method, Class iface, ClassLoader loader) { super(className, MethodClosure.class, loader); this.method = method; this.iface = iface; } protected void generate() throws NoSuchMethodException, NoSuchFieldException { declare_field(Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, String.class, "eqMethod"); declare_interface(iface); generateNullConstructor(); // generate proxied method begin_method(iface.getDeclaredMethods()[0]); load_this(); super_getfield("delegate"); checkcast(method.getDeclaringClass()); load_args(); invoke(method); return_value(); end_method(); // newInstance Method newInstance = MethodClosure.TYPE.getMethod("newInstance", TYPES_OBJECT); begin_method(newInstance); new_instance_this(); dup(); dup2(); invoke_constructor_this(); getstatic("eqMethod"); super_putfield("eqMethod"); load_arg(0); super_putfield("delegate"); return_value(); end_method(); // static initializer begin_static(); push(CodeGenerator.getMethodSignature(method)); putstatic("eqMethod"); return_value(); end_static(); } } }
package com.redhat.ceylon.eclipse.core.model; import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.isInCeylonClassesOutputFolder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.WorkingCopyOwner; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.env.AccessRestriction; import org.eclipse.jdt.internal.compiler.env.IBinaryAnnotation; import org.eclipse.jdt.internal.compiler.env.IBinaryMethod; import org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.env.ISourceType; import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding; import org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.PackageBinding; import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons; import org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter; import org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.core.ClassFile; import org.eclipse.jdt.internal.core.JavaProject; import org.eclipse.jdt.internal.core.SourceTypeElementInfo; import org.eclipse.jdt.internal.core.search.BasicSearchEngine; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.JDKUtils; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.util.Timer; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.loader.SourceDeclarationVisitor; import com.redhat.ceylon.compiler.loader.TypeParser; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.mirror.MethodMirror; import com.redhat.ceylon.compiler.loader.model.LazyClass; import com.redhat.ceylon.compiler.loader.model.LazyInterface; import com.redhat.ceylon.compiler.loader.model.LazyMethod; import com.redhat.ceylon.compiler.loader.model.LazyModule; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.loader.model.LazyValue; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder; import com.redhat.ceylon.eclipse.core.classpath.CeylonClasspathUtil; import com.redhat.ceylon.eclipse.core.classpath.CeylonProjectModulesContainer; import com.redhat.ceylon.eclipse.core.model.mirror.JDTClass; import com.redhat.ceylon.eclipse.core.model.mirror.JDTMethod; import com.redhat.ceylon.eclipse.core.model.mirror.SourceClass; import com.redhat.ceylon.eclipse.core.model.mirror.SourceDeclarationHolder; /** * A model loader which uses the JDT model. * * @author David Festal <david.festal@serli.com> */ public class JDTModelLoader extends AbstractModelLoader { private IJavaProject javaProject; private CompilerOptions compilerOptions; private ProblemReporter problemReporter; private LookupEnvironment lookupEnvironment; private boolean mustResetLookupEnvironment = false; public JDTModelLoader(final JDTModuleManager moduleManager, final Modules modules){ this.moduleManager = moduleManager; this.modules = modules; javaProject = moduleManager.getJavaProject(); if (javaProject != null) { compilerOptions = new CompilerOptions(javaProject.getOptions(true)); compilerOptions.ignoreMethodBodies = true; compilerOptions.storeAnnotations = true; problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()); } this.timer = new Timer(false); internalCreate(); } public JDTModuleManager getModuleManager() { return (JDTModuleManager) moduleManager; } private void internalCreate() { this.typeFactory = new GlobalTypeFactory(); this.typeParser = new TypeParser(this); this.timer = new Timer(false); createLookupEnvironment(); } public void createLookupEnvironment() { if (javaProject == null) { return; } try { lookupEnvironment = new LookupEnvironment(new ITypeRequestor() { private Parser basicParser; @Override public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { // case of SearchableEnvironment of an IJavaProject is used ISourceType sourceType = sourceTypes[0]; while (sourceType.getEnclosingType() != null) sourceType = sourceType.getEnclosingType(); if (sourceType instanceof SourceTypeElementInfo) { // get source SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType; IType type = elementInfo.getHandle(); ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit(); accept(sourceUnit, accessRestriction); } else { CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0); CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit( sourceTypes, SourceTypeConverter.FIELD_AND_METHOD // need field and methods | SourceTypeConverter.MEMBER_TYPE, // need member types // no need for field initialization lookupEnvironment.problemReporter, result); lookupEnvironment.buildTypeBindings(unit, accessRestriction); lookupEnvironment.completeTypeBindings(unit, true); } } @Override public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { BinaryTypeBinding btb = lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction); if (btb.isNestedType() && !btb.isStatic()) { for (MethodBinding method : btb.methods()) { if (method.isConstructor() && method.parameters.length > 0) { char[] signature = method.signature(); for (IBinaryMethod methodInfo : binaryType.getMethods()) { if (methodInfo.isConstructor()) { char[] methodInfoSignature = methodInfo.getMethodDescriptor(); if (new String(signature).equals(new String(methodInfoSignature))) { IBinaryAnnotation[] binaryAnnotation = methodInfo.getParameterAnnotations(0); if (binaryAnnotation == null) { if (methodInfo.getAnnotatedParametersCount() == method.parameters.length + 1) { AnnotationBinding[][] newParameterAnnotations = new AnnotationBinding[method.parameters.length][]; for (int i=0; i<method.parameters.length; i++) { IBinaryAnnotation[] goodAnnotations = null; try { goodAnnotations = methodInfo.getParameterAnnotations(i + 1); } catch(IndexOutOfBoundsException e) { break; } if (goodAnnotations != null) { AnnotationBinding[] parameterAnnotations = BinaryTypeBinding.createAnnotations(goodAnnotations, lookupEnvironment, new char[][][] {}); newParameterAnnotations[i] = parameterAnnotations; } } method.setParameterAnnotations(newParameterAnnotations); } } } } } } } } } @Override public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { // Switch the current policy and compilation result for this unit to the requested one. CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, compilerOptions.maxProblemsPerUnit); try { CompilationUnitDeclaration parsedUnit = basicParser().dietParse(sourceUnit, unitResult); lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction); lookupEnvironment.completeTypeBindings(parsedUnit, true); } catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } } // Display unit error in debug mode if (BasicSearchEngine.VERBOSE) { if (unitResult.problemCount > 0) { System.out.println(unitResult); } } } private Parser basicParser() { if (this.basicParser == null) { ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()); this.basicParser = new Parser(problemReporter, false); this.basicParser.reportOnlyOneSyntaxError = true; } return this.basicParser; } }, compilerOptions, problemReporter, ((JavaProject)javaProject).newSearchableNameEnvironment((WorkingCopyOwner)null)); lookupEnvironment.mayTolerateMissingType = true; } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO : remove when the bug in the AbstractModelLoader is corrected @Override public synchronized LazyPackage findOrCreatePackage(Module module, String pkgName) { LazyPackage pkg = super.findOrCreatePackage(module, pkgName); if (pkg.getModule() != null && pkg.getModule().isJava()){ pkg.setShared(true); } Module currentModule = pkg.getModule(); if (currentModule.equals(modules.getDefaultModule()) && ! currentModule.equals(module)) { currentModule.getPackages().remove(pkg); pkg.setModule(null); if (module != null) { module.getPackages().add(pkg); pkg.setModule(module); } } return pkg; } @Override public void loadStandardModules() { loadJDKModules(); /* * We start by loading java.lang because we will need it no matter what. */ Module jdkModule = findOrCreateModule(JAVA_BASE_MODULE_NAME, JDK_MODULE_VERSION); Module languageModule = getLanguageModule(); loadPackage(jdkModule, "java.lang", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.language", false); if (getModuleManager().isLoadDependenciesFromModelLoaderFirst() && !isBootstrap) { // loadPackage(languageModule, CEYLON_LANGUAGE, true); // loadPackage(languageModule, CEYLON_LANGUAGE_MODEL, true); // loadPackage(languageModule, CEYLON_LANGUAGE_MODEL_DECLARATION, true); } } private String getToplevelQualifiedName(final String pkgName, String name) { if (! Util.isInitialLowerCase(name)) { name = Util.quoteIfJavaKeyword(name); } String className = pkgName.isEmpty() ? name : Util.quoteJavaKeywords(pkgName) + "." + name; return className; } @Override public synchronized boolean loadPackage(Module module, String packageName, boolean loadDeclarations) { packageName = Util.quoteJavaKeywords(packageName); if(loadDeclarations && !loadedPackages.add(cacheKeyByModule(module, packageName))){ return true; } if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots(); IPackageFragment packageFragment = null; for (IPackageFragmentRoot root : roots) { // skip packages that are not present if(!root.exists()) continue; try { IClasspathEntry entry = root.getRawClasspathEntry(); //TODO: is the following really necessary? //Note that getContentKind() returns an undefined //value for a classpath container or variable if (entry.getEntryKind()!=IClasspathEntry.CPE_CONTAINER && entry.getEntryKind()!=IClasspathEntry.CPE_VARIABLE && entry.getContentKind()==IPackageFragmentRoot.K_SOURCE && !CeylonBuilder.isCeylonSourceEntry(entry)) { continue; } packageFragment = root.getPackageFragment(packageName); if(packageFragment.exists()){ if(!loadDeclarations) { // we found the package return true; }else{ try { // we have a few virtual types in java.lang that we need to load but they are not listed from class files if(packageName.equals("java.lang")){ Module jdkBaseModule = getJDKBaseModule(); convertToDeclaration(jdkBaseModule, JAVA_LANG_BOOLEAN_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_BYTE_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_SHORT_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_INT_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_LONG_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_FLOAT_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_DOUBLE_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_CHAR_ARRAY, DeclarationType.TYPE); convertToDeclaration(jdkBaseModule, JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE); } for (IClassFile classFile : packageFragment.getClassFiles()) { // skip removed class files if(!classFile.exists()) continue; IType type = classFile.getType(); if (type.exists() // only top-levels are added in source declarations && ! (type.isMember() || type.isAnonymous() || type.isLocal()) && !sourceDeclarations.containsKey(getToplevelQualifiedName(type.getPackageFragment().getElementName(), type.getTypeQualifiedName())) && ! isTypeHidden(module, type.getFullyQualifiedName())) { convertToDeclaration(module, type.getFullyQualifiedName(), DeclarationType.VALUE); } } for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) { // skip removed CUs if(!compilationUnit.exists()) continue; for (IType type : compilationUnit.getTypes()) { if (type.exists() && ! (type.isMember() || type.isAnonymous() || type.isLocal()) && !sourceDeclarations.containsKey(getToplevelQualifiedName(type.getPackageFragment().getElementName(), type.getTypeQualifiedName())) && ! isTypeHidden(module, type.getFullyQualifiedName())) { convertToDeclaration(module, type.getFullyQualifiedName(), DeclarationType.VALUE); } } } } catch (JavaModelException e) { e.printStackTrace(); } } } } catch (JavaModelException e) { e.printStackTrace(); } } } return false; } synchronized public void refreshNameEnvironment() { try { lookupEnvironment.nameEnvironment = ((JavaProject)javaProject).newSearchableNameEnvironment((WorkingCopyOwner)null); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } synchronized private LookupEnvironment getLookupEnvironment() { if (mustResetLookupEnvironment) { refreshNameEnvironment(); lookupEnvironment.reset(); mustResetLookupEnvironment = false; } return lookupEnvironment; } @Override public boolean searchAgain(Module module, String name) { String className = name.replace('.', '/'); if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (jdtModule.isCeylonBinaryArchive() || jdtModule.isJavaBinaryArchive()) { return jdtModule.containsClass(className + ".class") || jdtModule.containsClass(className + "_.class"); } else if (jdtModule.isProjectModule()) { for (IPackageFragmentRoot root : jdtModule.getPackageFragmentRoots()) { try { IFolder sourceFolder = (IFolder) root.getCorrespondingResource(); if (sourceFolder != null && sourceFolder.exists(new Path(className + ".java"))) { return true; } } catch (JavaModelException e) { } } return jdtModule.containsClass(className + ".class") || jdtModule.containsClass(className + "_.class"); } } return false; } @Override public boolean searchAgain(LazyPackage lazyPackage, String name) { return searchAgain(lazyPackage.getModule(), lazyPackage.getQualifiedName(lazyPackage.getQualifiedNameString(), name)); } @Override public synchronized ClassMirror lookupNewClassMirror(Module module, String name) { if (sourceDeclarations.containsKey(name)) { return new SourceClass(sourceDeclarations.get(name)); } ClassMirror mirror = buildClassMirror(name); if (mirror == null && lastPartHasLowerInitial(name)) { // We have to try the unmunged name first, so that we find the symbol // from the source in preference to the symbol from any // pre-existing .class file mirror = buildClassMirror(name+"_"); } return mirror; } private ClassMirror buildClassMirror(String name) { if (javaProject == null) { return null; } try { NameEnvironmentAnswer answer = null; LookupEnvironment theLookupEnvironment = getLookupEnvironment(); char[][] uncertainCompoundName = CharOperation.splitOn('.', name.toCharArray()); int numberOfParts = uncertainCompoundName.length; char[][] compoundName = null; for (int i=numberOfParts-1; i>0; i char[][] triedName = new char[0][]; for (int j=0; j<i; j++) { triedName = CharOperation.arrayConcat(triedName, uncertainCompoundName[j]); } char[] triedClassName = new char[0]; for (int k=i; k<numberOfParts; k++) { triedClassName = CharOperation.concat(triedClassName, uncertainCompoundName[k], '$'); } triedName = CharOperation.arrayConcat(triedName, triedClassName); answer = theLookupEnvironment.nameEnvironment.findType(triedName); if (answer != null) { compoundName = triedName; break; } } if (answer == null) { return null; } if (answer.isBinaryType()) { String className = CharOperation.charToString(answer.getBinaryType().getName()) + ".class"; ClassFile classFile = (ClassFile) javaProject.findElement(new Path(className)); if (classFile != null) { IPackageFragmentRoot fragmentRoot = classFile.getPackageFragmentRoot(); if (fragmentRoot != null) { if (isInCeylonClassesOutputFolder(fragmentRoot.getPath())) { return null; } } IFile classFileRsrc = (IFile) classFile.getCorrespondingResource(); if (classFileRsrc!=null && !classFileRsrc.exists()) { //the .class file has been deleted return null; } BinaryTypeBinding binaryTypeBinding = null; try { IBinaryType binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true); binaryTypeBinding = theLookupEnvironment.cacheBinaryType(binaryType, null); } catch(JavaModelException e) { if (! e.isDoesNotExist()) { throw e; } } if (binaryTypeBinding == null) { ReferenceBinding existingType = theLookupEnvironment.getCachedType(compoundName); if (existingType == null || ! (existingType instanceof BinaryTypeBinding)) { return null; } binaryTypeBinding = (BinaryTypeBinding) existingType; } return new JDTClass(binaryTypeBinding, theLookupEnvironment); } } else { ReferenceBinding referenceBinding = theLookupEnvironment.getType(compoundName); if (referenceBinding != null) { if (referenceBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding problemReferenceBinding = (ProblemReferenceBinding) referenceBinding; if (problemReferenceBinding.problemId() == ProblemReasons.InternalNameProvided) { referenceBinding = problemReferenceBinding.closestReferenceMatch(); } else { System.out.println(ProblemReferenceBinding.problemReasonString(problemReferenceBinding.problemId())); return null; } } return new JDTClass(referenceBinding, theLookupEnvironment); } } } catch (JavaModelException e) { e.printStackTrace(); } return null; } @Override public synchronized Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) { if (sourceDeclarations.containsKey(typeName)) { return sourceDeclarations.get(typeName).getModelDeclaration(); } try { return super.convertToDeclaration(module, typeName, declarationType); } catch(RuntimeException e) { // FIXME: pretty sure this is plain wrong as it ignores problems and especially ModelResolutionException and just plain hides them return null; } } @Override public void addModuleToClassPath(Module module, ArtifactResult artifact) { if(artifact != null && module instanceof LazyModule) ((LazyModule)module).loadPackageList(artifact); if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (! jdtModule.equals(getLanguageModule()) && jdtModule.isCeylonBinaryArchive()) { CeylonProjectModulesContainer container = CeylonClasspathUtil.getCeylonProjectModulesClasspathContainer(javaProject); if (container != null) { IPath modulePath = new Path(artifact.artifact().getPath()); IClasspathEntry newEntry = container.addNewClasspathEntryIfNecessary(modulePath); if (newEntry!=null) { try { JavaCore.setClasspathContainer(container.getPath(), new IJavaProject[] { javaProject }, new IClasspathContainer[] {new CeylonProjectModulesContainer(container)}, null); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } refreshNameEnvironment(); } } } // We don't need to add simple Java Jars progressively on the classpath } } @Override protected boolean isOverridingMethod(MethodMirror methodSymbol) { return ((JDTMethod)methodSymbol).isOverridingMethod(); } @Override protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { if (classMirror == null) { Unit unit = unitsByPackage.get(pkg); if(unit == null){ unit = new PackageTypeFactory(pkg); unit.setPackage(pkg); unitsByPackage.put(pkg, unit); } return unit; } Unit unit = null; JDTClass jdtClass = (JDTClass) classMirror; String unitName = jdtClass.getFileName(); if (!jdtClass.isBinary()) { // This search is for source Java classes since several classes might have the same file name // and live inside the same Java source file => into the same Unit for (Unit unitToTest : pkg.getUnits()) { if (unitToTest.getFilename().equals(unitName)) { return unitToTest; } } } ITypeRoot typeRoot = null; if (javaProject != null) { try { typeRoot = (ITypeRoot) javaProject.findElement(new Path(jdtClass.getJavaModelPath())); } catch (JavaModelException e) { e.printStackTrace(); } } StringBuilder sb = new StringBuilder(); List<String> parts = pkg.getName(); for (int i = 0; i < parts.size(); i++) { String part = parts.get(i); if (! part.isEmpty()) { sb.append(part); sb.append('/'); } } sb.append(jdtClass.getFileName()); String relativePath = sb.toString(); String fileName = jdtClass.getFileName(); String fullPath = jdtClass.getFullPath(); if (!jdtClass.isBinary()) { unit = new JavaCompilationUnit((org.eclipse.jdt.core.ICompilationUnit)typeRoot, fileName, relativePath, fullPath, pkg); } else { if (jdtClass.isCeylon()) { if (pkg.getModule() instanceof JDTModule) { JDTModule module = (JDTModule) pkg.getModule(); IProject originalProject = module.getOriginalProject(); if (originalProject != null) { unit = new CrossProjectBinaryUnit((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } else { unit = new CeylonBinaryUnit((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } } else { unit = new CeylonBinaryUnit((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } } else { unit = new JavaClassFile((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } } return unit; } @Override protected void logError(String message) { //System.err.println("ERROR: "+message); } @Override protected void logWarning(String message) { //System.err.println("WARNING: "+message); } @Override protected void logVerbose(String message) { //System.err.println("NOTE: "+message); } @Override public synchronized void removeDeclarations(List<Declaration> declarations) { List<Declaration> allDeclarations = new ArrayList<Declaration>(declarations.size()); allDeclarations.addAll(declarations); for (Declaration declaration : declarations) { retrieveInnerDeclarations(declaration, allDeclarations); } for (Declaration decl : allDeclarations) { String fqn = getToplevelQualifiedName(decl.getContainer().getQualifiedNameString(), decl.getName()); sourceDeclarations.remove(fqn); } super.removeDeclarations(allDeclarations); mustResetLookupEnvironment = true; } private void retrieveInnerDeclarations(Declaration declaration, List<Declaration> allDeclarations) { List<Declaration> members = declaration.getMembers(); allDeclarations.addAll(members); for (Declaration member : members) { retrieveInnerDeclarations(member, allDeclarations); } } private final Map<String, SourceDeclarationHolder> sourceDeclarations = new TreeMap<String, SourceDeclarationHolder>(); public synchronized Set<String> getSourceDeclarations() { Set<String> declarations = new HashSet<String>(); declarations.addAll(sourceDeclarations.keySet()); return declarations; } public synchronized SourceDeclarationHolder getSourceDeclaration(String declarationName) { return sourceDeclarations.get(declarationName); } public class PackageTypeFactory extends TypeFactory { public PackageTypeFactory(Package pkg) { super(moduleManager.getContext()); assert (pkg != null); setPackage(pkg); } } public class GlobalTypeFactory extends TypeFactory { public GlobalTypeFactory() { super(moduleManager.getContext()); } @Override public Package getPackage() { synchronized (JDTModelLoader.this) { if(super.getPackage() == null){ super.setPackage(modules.getLanguageModule() .getDirectPackage(Module.LANGUAGE_MODULE_NAME)); } return super.getPackage(); } } } public static interface SourceFileObjectManager { void setupSourceFileObjects(List<?> treeHolders); } public synchronized void setupSourceFileObjects(List<?> treeHolders) { addSourcePhasedUnits(treeHolders, true); } public synchronized void addSourcePhasedUnits(List<?> treeHolders, final boolean isSourceToCompile) { for (Object treeHolder : treeHolders) { if (treeHolder instanceof PhasedUnit) { final PhasedUnit unit = (PhasedUnit) treeHolder; final String pkgName = unit.getPackage().getQualifiedNameString(); unit.getCompilationUnit().visit(new SourceDeclarationVisitor(){ @Override public void loadFromSource(Tree.Declaration decl) { if (decl.getIdentifier()!=null) { String fqn = getToplevelQualifiedName(pkgName, decl.getIdentifier().getText()); if (! sourceDeclarations.containsKey(fqn)) { sourceDeclarations.put(fqn, new SourceDeclarationHolder(unit, decl, isSourceToCompile)); } } } }); } } } public void addSourceArchivePhasedUnits(List<PhasedUnit> sourceArchivePhasedUnits) { addSourcePhasedUnits(sourceArchivePhasedUnits, false); } public synchronized void clearCachesOnPackage(String packageName) { List<String> keysToRemove = new ArrayList<String>(classMirrorCache.size()); for (Entry<String, ClassMirror> element : classMirrorCache.entrySet()) { if (element.getValue() == null) { String className = element.getKey(); if (className != null) { String classPackageName =className.replaceAll("\\.[^\\.]+$", ""); if (classPackageName.equals(packageName)) { keysToRemove.add(className); } } } } for (String keyToRemove : keysToRemove) { classMirrorCache.remove(keyToRemove); } loadedPackages.remove(packageName); mustResetLookupEnvironment = true; } public synchronized void clearClassMirrorCacheForClass(JDTModule module, String classNameToRemove) { classMirrorCache.remove(cacheKeyByModule(module, classNameToRemove)); mustResetLookupEnvironment = true; } @Override protected LazyValue makeToplevelAttribute(ClassMirror classMirror) { if (classMirror instanceof SourceClass) { return (LazyValue) (((SourceClass) classMirror).getModelDeclaration()); } return super.makeToplevelAttribute(classMirror); } @Override protected LazyMethod makeToplevelMethod(ClassMirror classMirror) { if (classMirror instanceof SourceClass) { return (LazyMethod) (((SourceClass) classMirror).getModelDeclaration()); } return super.makeToplevelMethod(classMirror); } @Override protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror constructor, boolean forTopLevelObject) { if (classMirror instanceof SourceClass) { return (LazyClass) (((SourceClass) classMirror).getModelDeclaration()); } return super.makeLazyClass(classMirror, superClass, constructor, forTopLevelObject); } @Override protected LazyInterface makeLazyInterface(ClassMirror classMirror) { if (classMirror instanceof SourceClass) { return (LazyInterface) ((SourceClass) classMirror).getModelDeclaration(); } return super.makeLazyInterface(classMirror); } public TypeFactory getTypeFactory() { return (TypeFactory) typeFactory; } public synchronized Package findPackage(String quotedPkgName) { String pkgName = quotedPkgName.replace("$", ""); // in theory we only have one package with the same name per module in eclipse for(Package pkg : packagesByName.values()){ if(pkg.getNameAsString().equals(pkgName)) return pkg; } return null; } @Override protected Module findModuleForClassMirror(ClassMirror classMirror) { String pkgName = getPackageNameForQualifiedClassName(classMirror); return lookupModuleInternal(pkgName); } public void loadJDKModules() { for(String jdkModule : JDKUtils.getJDKModuleNames()) findOrCreateModule(jdkModule, JDK_MODULE_VERSION); for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames()) findOrCreateModule(jdkOracleModule, JDK_MODULE_VERSION); } @Override public synchronized LazyPackage findOrCreateModulelessPackage(String pkgName) { return (LazyPackage) findPackage(pkgName); } @Override public boolean isModuleInClassPath(Module module) { // TODO Check that returning true in any case is the right way to do. return super.isModuleInClassPath(module); } }
package org.kuali.rice.krad.data.jpa; import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.kuali.rice.core.api.criteria.OrderByField; import org.kuali.rice.core.api.criteria.OrderDirection; import org.kuali.rice.core.api.criteria.Predicate; import org.kuali.rice.core.api.criteria.PredicateFactory; import org.kuali.rice.core.api.criteria.QueryByCriteria; import org.kuali.rice.core.api.criteria.QueryResults; import org.kuali.rice.krad.data.CompoundKey; import org.kuali.rice.krad.data.DataObjectWrapper; import org.kuali.rice.krad.data.KradDataServiceLocator; import org.kuali.rice.krad.data.platform.MaxValueIncrementerFactory; import org.kuali.rice.krad.data.provider.PersistenceProvider; import org.kuali.rice.krad.test.KRADTestCase; import org.kuali.rice.krad.test.document.bo.AccountType; import org.kuali.rice.krad.test.document.bo.SimpleAccount; import org.kuali.rice.krad.test.document.bo.SimpleAccountExtension; import org.kuali.rice.test.BaselineTestCase; import org.kuali.rice.test.TestHarnessServiceLocator; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.transaction.UnexpectedRollbackException; import javax.sql.DataSource; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; import static org.junit.Assert.*; /** * Tests JPAPersistenceProvider */ // avoid wrapping test in rollback since JPA requires transaction boundary to flush @BaselineTestCase.BaselineMode(BaselineTestCase.Mode.CLEAR_DB) public class JpaPersistenceProviderTest extends KRADTestCase { /** * The PersistenceProvider being tested */ protected PersistenceProvider provider; /** * Obtains PersistenceProvider. */ @Before public void setup() { provider = getPersistenceProvider(); } /** * Derives a QueryByCriteria for a test object */ protected QueryByCriteria queryFor(Object a) { return QueryByCriteria.Builder.andAttributes(a, Arrays.asList(getPropertiesForQuery())).build(); } /** * Creates an unsaved test object */ protected Object createLinkedTestObject() { Object a = createTopLevelObject(); Object saved = getPersistenceProvider().save(a); addLinkedReferences(saved); return saved; } /** * Creates an unsaved, unlinked test object */ protected Object createUnlinkedTestObject() { Object a = createTopLevelObject(); Object saved = getPersistenceProvider().save(a); addUnlinkedReferences(saved); return saved; } /** * Assigns the next generated primary key value to the test object */ protected void assignPK(Object a) { setTestObjectPK(a, getNextTestObjectId()); } /** * Creates a test object and generates a matching query for it */ protected Map.Entry<Object, QueryByCriteria> createForQuery() { Object a = createLinkedTestObject(); QueryByCriteria qbc = queryFor(a); return new AbstractMap.SimpleImmutableEntry<Object, QueryByCriteria>(a, qbc); } /** * Generates a batch of test objects and returns a single query that will select them all. * The order of the returned list of test objects should match the order of the results returned * by the underlying platform (i.e., if they are returned in a sorted order, then the test object * list should be sorted). */ protected Map.Entry<List<Object>, QueryByCriteria.Builder> createForQuery(int count) { List<Object> objects = new ArrayList<Object>(); List<Predicate> predicates = new ArrayList<Predicate>(count); for (int i = 0; i < count; i++) { Object a = createLinkedTestObject(); objects.add(a); predicates.add(queryFor(a).getPredicate()); } QueryByCriteria.Builder qbc = QueryByCriteria.Builder.create(); qbc.setPredicates(PredicateFactory.or(predicates.toArray(new Predicate[count]))); return new AbstractMap.SimpleImmutableEntry<List<Object>, QueryByCriteria.Builder>(objects, qbc); } @Test public void testSimpleSave() { Object a = createTopLevelObject(); assertNull(getIdForLookup(a)); Object saved = provider.save(a); assertNotNull(getIdForLookup(saved)); assertTestObjectEquals(a, saved); } @Test public void testSaveLinkedSkipLinking() { Object a = createLinkedTestObject(); Object id = getIdForLookup(a); Object saved = provider.save(a); assertTestObjectIdentityEquals(a, saved); Object found = provider.find((Class<Object>)a.getClass(), id); assertTestObjectIdentityEquals(a, found); assertTestObjectIdentityEquals(saved, found); } // EclipseLink consumes the underlying exception itself and explicitly rolls back the transaction // resulting in just an opaque UnexpectedRollbackException coming out of Spring // (underlying exception is never translated by the PersistenceExceptionTranslator) // Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'ACCT_TYPE' cannot be null @Test(expected=UnexpectedRollbackException.class) public void testSaveUnlinkedSkipLinking() { Object a = createUnlinkedTestObject(); provider.save(a); fail("save should have resulted in an exception as references have not been linked correctly"); } @Test public void testFindMatching() { Map.Entry<Object, QueryByCriteria> pair = createForQuery(); Object a = pair.getKey(); QueryByCriteria qbc = pair.getValue(); Object saved = provider.save(a); assertTestObjectEquals(a, saved); QueryResults<Object> found = provider.findMatching((Class<Object>)a.getClass(), qbc); assertEquals(1, found.getResults().size()); assertTestObjectIdentityEquals(a, found.getResults().get(0)); provider.delete(found.getResults().get(0)); found = provider.findMatching((Class<Object>)a.getClass(), qbc); assertEquals(0, found.getResults().size()); } @Test(expected = InvalidDataAccessApiUsageException.class) public void testFindMatchingNullCriteria() { Map.Entry<Object, QueryByCriteria> pair = createForQuery(); Object a = pair.getKey(); provider.findMatching(a.getClass(), null); } /** * Ensures no errors or exceptions occur when the second parameter's predicate value is null */ @Test public void testFindMatchingEmptyCriteria() { Map.Entry<Object, QueryByCriteria> pair = createForQuery(); Object a = pair.getKey(); provider.findMatching(a.getClass(), QueryByCriteria.Builder.create().build()); } @Test public void testFindBySingleKey() { Object a = createLinkedTestObject(); Object saved = provider.save(a); assertTestObjectEquals(a, saved); Object id = getIdForLookup(saved); Object found = provider.find((Class<Object>)a.getClass(), id); assertTestObjectIdentityEquals(a, found); provider.delete(found); assertNull(provider.find((Class<Object>)a.getClass(), id)); } @Test public void testFindByCompoundKey() { Object a = createLinkedTestObject(); Object saved = provider.save(a); assertTestObjectEquals(a, saved); Map<String, Object> keys = new TreeMap<String, Object>(); DataObjectWrapper<Object> wrap = KradDataServiceLocator.getDataObjectService().wrap(saved); for (String propertyName : getPropertiesForQuery()) { keys.put(propertyName, wrap.getPropertyValue(propertyName)); } CompoundKey id = new CompoundKey(keys); Object found = provider.find((Class<Object>)a.getClass(), id); assertTestObjectIdentityEquals(a, found); provider.delete(found); assertNull(provider.find((Class<Object>)a.getClass(), id)); } @Test public void testFindWithResultsWindow() { Map.Entry<List<Object>, QueryByCriteria.Builder> fixture = createForQuery(10); List<Object> objects = fixture.getKey(); for (Object a: objects) { provider.save(a); } QueryByCriteria.Builder query = fixture.getValue(); query.setStartAtIndex(2); query.setMaxResults(5); // specify the order OrderByField.Builder orderBy = OrderByField.Builder.create(); orderBy.setFieldName("number"); orderBy.setOrderDirection(OrderDirection.ASCENDING); query.setOrderByFields(orderBy.build()); QueryResults<Object> results = provider.findMatching((Class<Object>) objects.get(0).getClass(), query.build()); assertEquals(5, results.getResults().size()); assertTestObjectIdentityEquals(objects.get(2), results.getResults().get(0)); assertTestObjectIdentityEquals(objects.get(3), results.getResults().get(1)); assertTestObjectIdentityEquals(objects.get(4), results.getResults().get(2)); assertTestObjectIdentityEquals(objects.get(5), results.getResults().get(3)); assertTestObjectIdentityEquals(objects.get(6), results.getResults().get(4)); } /** * Exercises the findAll method to ensure expected behavior */ @Test public void testFindAll() { Object a = createTopLevelObject(); QueryResults<Object> results = provider.findAll((Class<Object>)a.getClass()); assertEquals(0, results.getResults().size()); Object savedA = provider.save(a); results = provider.findAll((Class<Object>)a.getClass()); assertEquals(1, results.getResults().size()); provider.delete(savedA); results = provider.findAll((Class<Object>)a.getClass()); assertEquals(0, results.getResults().size()); } /** * Tests that deletion of a non-existent detached object does not result in a save of the object * via merge. */ @Test public void testDeleteNonExistentEntity() { Object a = createTopLevelObject(); assignPK(a); Object id = getIdForLookup(a); assertNull(provider.find((Class<Object>)a.getClass(), id)); provider.delete(a); assertNull(provider.find((Class<Object>)a.getClass(), id)); } /** * Test delete matching with null criteria, should throw an exception */ @Test(expected=InvalidDataAccessApiUsageException.class) public void testDeleteMatchingNullCriteria() { provider.deleteMatching(SimpleAccount.class, null); } /** * Test delete matching with empty criteria, should throw an exception */ @Test(expected=InvalidDataAccessApiUsageException.class) public void testDeleteMatchingEmptyCriteria() { provider.deleteMatching(SimpleAccount.class, QueryByCriteria.Builder.create().build()); } /** * Tests the deletion of non-existent detached objects. */ @Test public void testDeleteMatchingNonExistentEntity() { List<String> nameList = new ArrayList<String>(); // build three objects to test with Object a = createTopLevelObject(); assignPK(a); nameList.add(((SimpleAccount)a).getName()); Object b = createTopLevelObject(); assignPK(b); nameList.add(((SimpleAccount) b).getName()); Object c = createTopLevelObject(); assignPK(c); nameList.add(((SimpleAccount)c).getName()); // build the criteria for these three objects QueryByCriteria.Builder builder = QueryByCriteria.Builder.create(); builder.setPredicates(PredicateFactory.in("name", nameList)); QueryResults<Object> found = provider.findMatching((Class<Object>)a.getClass(), builder.build()); assertEquals(0, found.getResults().size()); provider.deleteMatching(a.getClass(), builder.build()); found = (provider.findMatching((Class<Object>)a.getClass(), builder.build())); assertEquals(0, found.getResults().size()); } /** * Tests the deletion of saved objects. */ @Test public void testDeleteMatchingAllSavedEntities() { List<String> nameList = new ArrayList<String>(); // build and save three objects to test with Object a = createTopLevelObject(); assignPK(a); Object savedA = provider.save(a); nameList.add(((SimpleAccount)savedA).getName()); Object b = createTopLevelObject(); assignPK(b); Object savedB = provider.save(b); nameList.add(((SimpleAccount) savedB).getName()); Object c = createTopLevelObject(); assignPK(c); Object savedC = provider.save(c); // did all three objects get saved? QueryResults<Object> found = provider.findAll((Class<Object>) savedA.getClass()); assertEquals(3, found.getResults().size()); // now delete part of the saved objects QueryByCriteria.Builder builder = QueryByCriteria.Builder.create(); builder.setPredicates(PredicateFactory.in("name", nameList)); provider.deleteMatching(a.getClass(), builder.build()); // were the two objects deleted found = provider.findAll((Class<Object>) savedA.getClass()); assertEquals(1, found.getResults().size()); Object lastObject = found.getResults().get(0); assertEquals(((SimpleAccount) lastObject).getName(), ((SimpleAccount)savedC).getName()); // clear the list and add the last object nameList.clear(); nameList.add(((SimpleAccount)savedC).getName()); // now delete the last object. builder = QueryByCriteria.Builder.create(); builder.setPredicates(PredicateFactory.in("name", nameList)); provider.deleteMatching(a.getClass(), builder.build()); // were all objects deleted? found = provider.findAll((Class<Object>) savedA.getClass()); assertEquals(0, found.getResults().size()); } /** * Exercises the deleteAll method to ensure expected behavior */ @Test public void testDeleteAll() { Object a = createTopLevelObject(); QueryResults<Object> results = provider.findAll((Class<Object>)a.getClass()); assertEquals(0, results.getResults().size()); provider.deleteAll(a.getClass()); results = provider.findAll((Class<Object>)a.getClass()); assertEquals(0, results.getResults().size()); Object savedA = provider.save(a); Object b = createTopLevelObject(); provider.save(b); results = provider.findAll((Class<Object>) a.getClass()); assertEquals(2, results.getResults().size()); provider.deleteAll(savedA.getClass()); results = provider.findAll((Class<Object>)a.getClass()); assertEquals(0, results.getResults().size()); } @Test public void testHandles() { Object a = createTopLevelObject(); assertTrue(provider.handles((Class<Object>)a.getClass())); Class guaranteedNotToBeMappedClass = this.getClass(); // assertFalse(provider.handles(guaranteedNotToBeMappedClass)); } protected Object createTopLevelObject() { SimpleAccount a = new SimpleAccount(); String name = RandomStringUtils.randomAlphanumeric(10); a.setName(name); return a; } protected void addLinkedReferences(Object o) { SimpleAccount a = (SimpleAccount)o; addUnlinkedReferences(a); //a.getAccountManager().setAmId(Long.parseLong(a.getNumber())); SimpleAccountExtension e = (SimpleAccountExtension) a.getExtension(); e.setAccountTypeCode(e.getAccountType().getAccountTypeCode()); e.setAccount(a); } protected void addUnlinkedReferences(Object o) { SimpleAccount a = (SimpleAccount)o; //AccountManager am = new AccountManager(); //am.setUserName(RandomStringUtils.randomAlphanumeric(10)); //a.setAccountManager(am); SimpleAccountExtension extension = new SimpleAccountExtension(); AccountType at = new AccountType(); at.setName(RandomStringUtils.randomAlphanumeric(10)); at.setAccountTypeCode(RandomStringUtils.randomAlphanumeric(2)); extension.setAccountType(at); a.setExtension(extension); } protected String[] getPropertiesForQuery() { return new String[] { "number", "name" }; } protected Object getIdForLookup(Object o) { SimpleAccount a = (SimpleAccount)o; return a.getNumber(); } protected String getNextTestObjectId() { DataSource dataSource = TestHarnessServiceLocator.getDataSource(); return MaxValueIncrementerFactory.getIncrementer(dataSource, "trvl_id_seq").nextStringValue(); } protected void setTestObjectPK(Object o, Object key) { SimpleAccount a = (SimpleAccount)o; a.setNumber((String) key); } protected void assertTestObjectIdentityEquals(Object oExpected, Object oActual) { SimpleAccount expected = (SimpleAccount)oExpected; SimpleAccount actual = (SimpleAccount)oActual; assertTestObjectEquals(expected, actual); assertEquals(expected.getNumber(), actual.getNumber()); } protected void assertTestObjectEquals(Object oExpected, Object oActual) { SimpleAccount expected = (SimpleAccount)oExpected; SimpleAccount actual = (SimpleAccount)oActual; assertEquals(expected.getAmId(), actual.getAmId()); assertEquals(expected.getName(), actual.getName()); if (expected.getExtension() != null) { SimpleAccountExtension e1 = (SimpleAccountExtension) expected.getExtension(); SimpleAccountExtension e2 = (SimpleAccountExtension) actual.getExtension(); assertEquals(e1.getAccount().getNumber(), e2.getAccount().getNumber()); assertEquals(e1.getAccountTypeCode(), e2.getAccountTypeCode()); if (e1.getAccountType() != null) { AccountType at1 = e1.getAccountType(); AccountType at2 = e2.getAccountType(); assertEquals(at1.getName(), at2.getName()); assertEquals(at1.getAccountTypeCode(), at2.getAccountTypeCode()); } } } protected PersistenceProvider getPersistenceProvider() { return getKRADTestHarnessContext().getBean("kradTestJpaPersistenceProvider", PersistenceProvider.class); } }
package org.ow2.proactive.scheduler.job; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import org.ow2.proactive.scheduler.common.job.JobPriority; import org.ow2.proactive.scheduler.common.job.JobType; import org.ow2.proactive.scheduler.task.internal.InternalTask; /** * Class TaskFlowJob. * This is the definition of a tasks flow job. * * @author The ProActive Team * @since ProActive Scheduling 0.9 */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class InternalTaskFlowJob extends InternalJob { /** * ProActive empty constructor. */ public InternalTaskFlowJob() { } /** * Create a new Tasks Flow Job with the given parameters. It provides methods to add or * remove tasks. * * @param name the current job name. * @param priority the priority of this job between 1 and 5. * @param cancelOnError true if the job has to run until its end or an user intervention. * @param description a short description of the job and what it will do. */ // * @param runtimeLimit the maximum execution time for this job given in millisecond. public InternalTaskFlowJob(String name, JobPriority priority, boolean cancelOnError, String description) { super(name, priority, cancelOnError, description); } /** * Append a list of tasks to this job. * * @param tasks the list of tasks to add. * @return true if the list of tasks have been correctly added to the job, * false if not. */ public boolean addTasks(List<InternalTask> tasks) { for (InternalTask td : tasks) { if (!addTask(td)) { return false; } } return true; } /** * @see org.ow2.proactive.scheduler.job.InternalJob#getType() */ @Override public JobType getType() { return JobType.TASKSFLOW; } }
package org.neo4j.server.enterprise; import static org.junit.Assert.assertEquals; import java.net.URI; import java.util.Map; import javax.ws.rs.core.MediaType; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.neo4j.ha.LocalhostZooKeeperCluster; import org.neo4j.helpers.Pair; import org.neo4j.kernel.Config; import org.neo4j.server.rest.domain.JsonHelper; import org.neo4j.test.TargetDirectory; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; public class HaServerFunctionalTest { private static final int[] ZOOKEEPER_PORTS = { 2181, 2182 }; @SuppressWarnings( "unchecked" ) private static final Pair<Integer/*ha port*/, Integer/*web port*/>[] SERVER_PORTS = new Pair[] { Pair.of( 6001, 7474 ), Pair.of( 6002, 7475 ) }; private static final TargetDirectory dir = TargetDirectory.forTest( HaServerFunctionalTest.class ); private static LocalhostZooKeeperCluster zooKeeper; public @Rule TestName testName = new TestName() { @Override public String getMethodName() { return HaServerFunctionalTest.class.getSimpleName() + "." + super.getMethodName(); } }; @BeforeClass public static void startZooKeeper() { if ( Config.osIsWindows() ) return; zooKeeper = new LocalhostZooKeeperCluster( dir, ZOOKEEPER_PORTS ); } @AfterClass public static void stopZooKeeper() { if ( zooKeeper != null ) zooKeeper.shutdown(); zooKeeper = null; dir.cleanup(); } private ServerCluster cluster; @After public void stopServer() { if ( cluster != null ) cluster.shutdown(); cluster = null; } @Test public void canStartUpServerCluster() throws Exception { if ( Config.osIsWindows() ) return; cluster = new ServerCluster( testName.getMethodName(), dir, zooKeeper, SERVER_PORTS ); } @Test public void canWriteToOneServerInTheClusterAndReadFromAnother() throws Exception { if ( Config.osIsWindows() ) return; cluster = new ServerCluster( testName.getMethodName(), dir, zooKeeper, SERVER_PORTS ); URI base = cluster.getRandomServerUri(); put( property( node( base, 0 ), "message" ), "hello world" ); cluster.updateAll(); base = cluster.getRandomServerUri( base ); assertEquals( "hello world", get( property( node( base, 0 ), "message" ) ) ); } @Test public void canWriteToOneServerInTheClusterThenReadFromAnotherAfterShuttingDownTheWriteServer() throws Exception { if ( Config.osIsWindows() ) return; cluster = new ServerCluster( testName.getMethodName(), dir, zooKeeper, SERVER_PORTS ); URI base = cluster.getRandomServerUri(); put( property( node( base, 0 ), "message" ), "hello world" ); cluster.updateAll(); cluster.kill( base ); base = cluster.getRandomServerUri(); assertEquals( "hello world", get( property( node( base, 0 ), "message" ) ) ); } private static URI node( URI base, int id ) { return URI.create( base + "db/data/node/" + id ); } private static URI property( URI entity, String key ) { return URI.create( entity + "/properties/" + key ); } private static Object get( URI property ) { ClientResponse response = Client.create().resource( property ).accept( MediaType.APPLICATION_JSON_TYPE ).type( MediaType.APPLICATION_JSON_TYPE ).get( ClientResponse.class ); try { if ( 200 == response.getStatus() ) { return JsonHelper.jsonToSingleValue( response.getEntity( String.class ) ); } else { Map<String, Object> data = JsonHelper.jsonToMap( response.getEntity( String.class ) ); throw new RuntimeException( data.get( "message" ).toString() ); } } catch ( Exception e ) { throw new RuntimeException( e ); } } private static void put( URI property, Object value ) { Client.create().resource( property ).accept( MediaType.APPLICATION_JSON_TYPE ).type( MediaType.APPLICATION_JSON_TYPE ).entity( JsonHelper.createJsonFrom( value ) ).put(); } }
package org.realityforge.replicant.server.transport; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.transaction.TransactionSynchronizationRegistry; import org.realityforge.replicant.server.Change; import org.realityforge.replicant.server.ChangeAccumulator; import org.realityforge.replicant.server.ChangeSet; import org.realityforge.replicant.server.ChannelAction; import org.realityforge.replicant.server.ChannelDescriptor; import org.realityforge.replicant.server.ChannelLink; import org.realityforge.replicant.server.EntityMessage; import org.realityforge.replicant.server.EntityMessageEndpoint; import org.realityforge.replicant.server.json.JsonEncoder; import org.realityforge.replicant.shared.transport.ReplicantContext; import org.realityforge.ssf.InMemorySessionManager; /** * Base class for session managers. */ public abstract class ReplicantSessionManagerImpl extends InMemorySessionManager<ReplicantSession> implements EntityMessageEndpoint, ReplicantSessionManager { private final ReadWriteLock _cacheLock = new ReentrantReadWriteLock(); private final HashMap<ChannelDescriptor, ChannelCacheEntry> _cache = new HashMap<>(); @Nullable protected String pollJsonData( @Nonnull final ReplicantSession session, final int lastSequenceAcked ) { final Packet packet = pollPacket( session, lastSequenceAcked ); if ( null != packet ) { return JsonEncoder. encodeChangeSet( packet.getSequence(), packet.getRequestID(), packet.getETag(), packet.getChangeSet() ); } else { return null; } } /** * Send messages to the specified session. * The requesting service must NOT have made any other changes that will be sent to the * client, otherwise this message will be discarded. * * @param session the session. * @param etag the etag for message if any. * @param changeSet the messages to be sent along to the client. * @return the packet created. */ protected Packet sendPacket( @Nonnull final ReplicantSession session, @Nullable final String etag, @Nonnull final ChangeSet changeSet ) { final String requestID = (String) getRegistry().getResource( ReplicantContext.REQUEST_ID_KEY ); getRegistry().putResource( ReplicantContext.REQUEST_COMPLETE_KEY, Boolean.FALSE ); return session.getQueue().addPacket( requestID, etag, changeSet ); } /** * @return the transaction synchronization registry. */ @Nonnull protected abstract TransactionSynchronizationRegistry getRegistry(); /** * @return the metadata for all the channels as an array. */ @Nonnull protected abstract ChannelMetaData[] getChannelMetaData(); @Nonnull @Override protected ReplicantSession newSessionInfo() { return new ReplicantSession( UUID.randomUUID().toString() ); } /** * @return the channel metadata. */ @Nonnull public ChannelMetaData getChannelMetaData( @Nonnull final ChannelDescriptor descriptor ) { return getChannelMetaData( descriptor.getChannelID() ); } /** * @return the channel metadata. */ @Nonnull public ChannelMetaData getChannelMetaData( final int channelID ) { final ChannelMetaData[] channelMetaData = getChannelMetaData(); if ( channelID >= channelMetaData.length ) { final String message = "Channel " + channelID + " not part of declared metadata: " + Arrays.asList( channelMetaData ); throw new IllegalStateException( message ); } return channelMetaData[ channelID ]; } /** * Return the next packet to send to the client. * The packet is only returned if the client has acked the previous message. * * @param session the session. * @param lastSequenceAcked the sequence that the client last ack'ed. * @return the packet or null if no packet is ready. */ @Nullable protected Packet pollPacket( @Nonnull final ReplicantSession session, final int lastSequenceAcked ) { final PacketQueue queue = session.getQueue(); queue.ack( lastSequenceAcked ); return queue.nextPacketToProcess(); } /** * Return session associated with specified ID. * * @throws RuntimeException if no such session is available. */ @Nonnull protected ReplicantSession ensureSession( @Nonnull final String sessionID ) { final ReplicantSession session = getSession( sessionID ); if ( null == session ) { throw newBadSessionException( sessionID ); } return session; } @Nonnull protected abstract RuntimeException newBadSessionException( @Nonnull String sessionID ); @Override public boolean saveEntityMessages( @Nullable final String sessionID, @Nullable final String requestID, @Nonnull final Collection<EntityMessage> messages, @Nullable final ChangeSet sessionChanges ) { //TODO: Rewrite this so that we add clients to indexes rather than searching through everyone for each change! getLock().readLock().lock(); final ChangeAccumulator accumulator = new ChangeAccumulator(); try { final Collection<ReplicantSession> sessions = getSessions().values(); for ( final EntityMessage message : messages ) { processDeleteMessages( message, sessions, accumulator ); } for ( final EntityMessage message : messages ) { processUpdateMessages( message, sessions, accumulator ); } final ReplicantSession initiatorSession = null != sessionID ? getSession( sessionID ) : null; if ( null != initiatorSession && null != sessionChanges ) { accumulator.addChanges( initiatorSession, sessionChanges.getChanges() ); accumulator.addActions( initiatorSession, sessionChanges.getChannelActions() ); } for ( final ReplicantSession session : getSessions().values() ) { expandLinks( session, accumulator.getChangeSet( session ) ); } } finally { getLock().readLock().unlock(); } return accumulator.complete( sessionID, requestID ); } protected abstract void processUpdateMessages( @Nonnull EntityMessage message, @Nonnull Collection<ReplicantSession> sessions, @Nonnull ChangeAccumulator accumulator ); protected abstract void processDeleteMessages( @Nonnull EntityMessage message, @Nonnull Collection<ReplicantSession> sessions, @Nonnull ChangeAccumulator accumulator ); @Override public void delinkSubscription( @Nonnull final ReplicantSession session, @Nonnull final ChannelDescriptor sourceGraph, @Nonnull final ChannelDescriptor targetGraph, @Nonnull final ChangeSet changeSet ) { final SubscriptionEntry sourceEntry = session.findSubscriptionEntry( sourceGraph ); final SubscriptionEntry targetEntry = session.findSubscriptionEntry( targetGraph ); if ( null != sourceEntry && null != targetEntry ) { delinkSubscriptionEntries( sourceEntry, targetEntry ); if ( targetEntry.canUnsubscribe() ) { performUnsubscribe( session, targetEntry, false, changeSet ); } } } @Override public void bulkDelinkSubscription( @Nonnull final ReplicantSession session, @Nonnull final ChannelDescriptor sourceGraph, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, @Nonnull final ChangeSet changeSet ) { for ( final Serializable id : subChannelIDs ) { delinkSubscription( session, sourceGraph, new ChannelDescriptor( channelID, id ), changeSet ); } } /** * Perform a a subscribe. * * @param cacheKey the opaque string that represents version of message client has cached locally. * @return The cache status of data returned as part of subscribe. */ @Nonnull protected CacheStatus subscribe( @Nonnull final String sessionID, @Nonnull final ChannelDescriptor descriptor, @Nullable final Object filter, @Nullable final String cacheKey, @Nonnull final ChangeSet changeSet ) { setupRegistryContext( sessionID ); final ReplicantSession session = ensureSession( sessionID ); session.setCacheKey( descriptor, cacheKey ); final CacheStatus status = subscribe( session, descriptor, true, filter, changeSet ); if ( status != CacheStatus.USE ) { session.setCacheKey( descriptor, null ); expandLinks( session, changeSet ); } return status; } protected void bulkSubscribe( @Nonnull final String sessionID, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, @Nullable final Object filter, final boolean explicitSubscribe, @Nonnull final ChangeSet changeSet ) { setupRegistryContext( sessionID ); final ReplicantSession session = ensureSession( sessionID ); bulkSubscribe( session, channelID, subChannelIDs, filter, explicitSubscribe, changeSet ); } protected void updateSubscription( @Nonnull final String sessionID, @Nonnull final ChannelDescriptor descriptor, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { setupRegistryContext( sessionID ); final ReplicantSession session = ensureSession( sessionID ); updateSubscription( session, descriptor, filter, changeSet ); expandLinks( session, changeSet ); } protected void bulkUpdateSubscription( @Nonnull final String sessionID, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { setupRegistryContext( sessionID ); final ReplicantSession session = ensureSession( sessionID ); bulkUpdateSubscription( session, channelID, subChannelIDs, filter, changeSet ); expandLinks( session, changeSet ); } protected void unsubscribe( @Nonnull final String sessionID, @Nonnull final ChannelDescriptor descriptor, @Nonnull final ChangeSet changeSet ) { setupRegistryContext( sessionID ); unsubscribe( ensureSession( sessionID ), descriptor, true, changeSet ); } @Override public void updateSubscription( @Nonnull final ReplicantSession session, @Nonnull final ChannelDescriptor descriptor, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { assert getChannelMetaData( descriptor ).getFilterType() == ChannelMetaData.FilterType.DYNAMIC; final SubscriptionEntry entry = session.getSubscriptionEntry( descriptor ); final Object originalFilter = entry.getFilter(); if ( !doFiltersMatch( filter, originalFilter ) ) { performUpdateSubscription( session, entry, originalFilter, filter, changeSet ); } } @Override public void bulkUpdateSubscription( @Nonnull final ReplicantSession session, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { final ChannelMetaData channelMetaData = getChannelMetaData( channelID ); assert channelMetaData.getFilterType() == ChannelMetaData.FilterType.DYNAMIC; final ArrayList<ChannelDescriptor> channelsToUpdate = new ArrayList<>(); for ( final Serializable subChannelID : subChannelIDs ) { final ChannelDescriptor descriptor = new ChannelDescriptor( channelID, subChannelID ); final SubscriptionEntry entry = session.getSubscriptionEntry( descriptor ); if ( !doFiltersMatch( filter, entry.getFilter() ) ) { channelsToUpdate.add( descriptor ); } } if ( channelsToUpdate.isEmpty() ) { return; } else if ( 1 == channelsToUpdate.size() ) { updateSubscription( session, channelsToUpdate.get( 0 ), filter, changeSet ); } else { final Object originalFilter = session.getSubscriptionEntry( channelsToUpdate.get( 0 ) ).getFilter(); final boolean bulkLoaded = bulkCollectDataForSubscriptionUpdate( session, channelsToUpdate, changeSet, originalFilter, filter ); if ( !bulkLoaded ) { for ( final ChannelDescriptor descriptor : channelsToUpdate ) { updateSubscription( session, descriptor, filter, changeSet ); } } } } @Override public void bulkSubscribe( @Nonnull final ReplicantSession session, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, @Nullable final Object filter, final boolean explicitSubscribe, @Nonnull final ChangeSet changeSet ) { assert getChannelMetaData( channelID ).isInstanceGraph(); final ArrayList<ChannelDescriptor> newChannels = new ArrayList<>(); //OriginalFilter => Channels final HashMap<Object, ArrayList<ChannelDescriptor>> channelsToUpdate = new HashMap<>(); for ( final Serializable root : subChannelIDs ) { final ChannelDescriptor descriptor = new ChannelDescriptor( channelID, root ); final SubscriptionEntry entry = session.findSubscriptionEntry( descriptor ); if ( null == entry ) { newChannels.add( descriptor ); } else { final ArrayList<ChannelDescriptor> descriptors = channelsToUpdate.computeIfAbsent( entry.getFilter(), k -> new ArrayList<>() ); descriptors.add( descriptor ); } } if ( !newChannels.isEmpty() ) { final boolean bulkLoaded = bulkCollectDataForSubscribe( session, newChannels, changeSet, filter, explicitSubscribe ); if ( !bulkLoaded ) { for ( final ChannelDescriptor descriptor : newChannels ) { subscribe( session, descriptor, true, filter, changeSet ); } } } if ( !channelsToUpdate.isEmpty() ) { for ( final Map.Entry<Object, ArrayList<ChannelDescriptor>> update : channelsToUpdate.entrySet() ) { final Object originalFilter = update.getKey(); final ArrayList<ChannelDescriptor> descriptors = update.getValue(); boolean bulkLoaded = false; if ( descriptors.size() > 1 ) { bulkLoaded = bulkCollectDataForSubscriptionUpdate( session, newChannels, changeSet, originalFilter, filter ); } if ( !bulkLoaded ) { for ( final ChannelDescriptor descriptor : descriptors ) { //Just call subscribe as it will do the "right" thing wrt to checking if it needs updates etc. subscribe( session, descriptor, true, filter, changeSet ); } } } } } @Nonnull @Override public CacheStatus subscribe( @Nonnull final ReplicantSession session, @Nonnull final ChannelDescriptor descriptor, final boolean explicitlySubscribe, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { if ( session.isSubscriptionEntryPresent( descriptor ) ) { final SubscriptionEntry entry = session.getSubscriptionEntry( descriptor ); if ( explicitlySubscribe ) { entry.setExplicitlySubscribed( true ); } final ChannelMetaData channelMetaData = getChannelMetaData( descriptor ); if ( channelMetaData.getFilterType() == ChannelMetaData.FilterType.DYNAMIC ) { updateSubscription( session, descriptor, filter, changeSet ); } else if ( channelMetaData.getFilterType() == ChannelMetaData.FilterType.STATIC ) { final Object existingFilter = entry.getFilter(); if ( !doFiltersMatch( filter, existingFilter ) ) { final String message = "Attempted to update filter on channel " + entry.getDescriptor() + " from " + existingFilter + " to " + filter + " for channel that has a static filter. Unsubscribe and resubscribe to channel."; throw new AttemptedToUpdateStaticFilterException( message ); } } return CacheStatus.IGNORE; } else { return performSubscribe( session, session.createSubscriptionEntry( descriptor ), explicitlySubscribe, filter, changeSet ); } } private boolean doFiltersMatch( final Object filter1, final Object filter2 ) { return ( null == filter2 && null == filter1 ) || ( null != filter2 && filter2.equals( filter1 ) ); } @Nonnull CacheStatus performSubscribe( @Nonnull final ReplicantSession session, @Nonnull final SubscriptionEntry entry, final boolean explicitSubscribe, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { if ( explicitSubscribe ) { entry.setExplicitlySubscribed( true ); } entry.setFilter( filter ); final ChannelDescriptor descriptor = entry.getDescriptor(); final ChannelMetaData channelMetaData = getChannelMetaData( descriptor ); if ( channelMetaData.isCacheable() ) { final ChannelCacheEntry cacheEntry = ensureCacheEntry( descriptor ); final String cacheKey = cacheEntry.getCacheKey(); if ( cacheKey.equals( session.getCacheKey( descriptor ) ) ) { return CacheStatus.USE; } else { final ChangeSet cacheChangeSet = new ChangeSet(); cacheChangeSet.merge( cacheEntry.getChangeSet(), true ); cacheChangeSet.addAction( descriptor, ChannelAction.Action.ADD, filter ); sendPacket( session, cacheKey, cacheChangeSet ); return CacheStatus.REFRESH; } } collectDataForSubscribe( session, descriptor, changeSet, filter ); changeSet.addAction( descriptor, ChannelAction.Action.ADD, filter ); return CacheStatus.REFRESH; } protected boolean deleteCacheEntry( @Nonnull final ChannelDescriptor descriptor ) { _cacheLock.writeLock().lock(); try { return null != _cache.remove( descriptor ); } finally { _cacheLock.writeLock().unlock(); } } /** * Return a CacheEntry for a specific channel. When this method returns the cache * data will have already been loaded. The cache data is loaded using a separate lock for * each channel cached. */ @Nonnull protected ChannelCacheEntry ensureCacheEntry( @Nonnull final ChannelDescriptor descriptor ) { assert getChannelMetaData( descriptor ).isCacheable(); final ChannelCacheEntry entry = getCacheEntry( descriptor ); entry.getLock().readLock().lock(); try { if ( entry.isInitialized() ) { return entry; } } finally { entry.getLock().readLock().unlock(); } entry.getLock().writeLock().lock(); try { //Make sure check again once we re-aquire the lock if ( entry.isInitialized() ) { return entry; } final ChangeSet changeSet = new ChangeSet(); final String cacheKey = collectDataForSubscribe( null, descriptor, changeSet, null ); assert null != cacheKey; entry.init( cacheKey, changeSet ); return entry; } finally { entry.getLock().writeLock().unlock(); } } /** * Get the CacheEntry for specified channel. Note that the cache is not necessarily * loaded at this stage. This is done to avoid using a global lock while loading data for a * particular cache entry. */ ChannelCacheEntry getCacheEntry( @Nonnull final ChannelDescriptor descriptor ) { _cacheLock.readLock().lock(); try { final ChannelCacheEntry entry = _cache.get( descriptor ); if ( null != entry ) { return entry; } } finally { _cacheLock.readLock().unlock(); } _cacheLock.writeLock().lock(); try { //Try again in case it has since been created ChannelCacheEntry entry = _cache.get( descriptor ); if ( null != entry ) { return entry; } entry = new ChannelCacheEntry( descriptor ); _cache.put( descriptor, entry ); return entry; } finally { _cacheLock.writeLock().unlock(); } } void performUpdateSubscription( @Nonnull final ReplicantSession session, @Nonnull final SubscriptionEntry entry, @Nullable final Object originalFilter, @Nullable final Object filter, @Nonnull final ChangeSet changeSet ) { assert getChannelMetaData( entry.getDescriptor() ).getFilterType() != ChannelMetaData.FilterType.NONE; entry.setFilter( filter ); final ChannelDescriptor descriptor = entry.getDescriptor(); collectDataForSubscriptionUpdate( session, entry.getDescriptor(), changeSet, originalFilter, filter ); changeSet.addAction( descriptor, ChannelAction.Action.UPDATE, filter ); } /** * @param session the client session performing subscribe or null if loading as part of cache * @return the cacheKey if any. The return value is ignored for non-cacheable channels. */ @Nullable protected abstract String collectDataForSubscribe( @Nullable final ReplicantSession session, @Nonnull final ChannelDescriptor descriptor, @Nonnull final ChangeSet changeSet, @Nullable final Object filter ); /** * This method is called in an attempt to use a more efficient method for bulk loading instance graphs. * Subclasses may return false form this method, in which case collectDataForSubscribe will be called * for each independent channel. * * @return true if method has actually bulk loaded all data, false otherwise. */ protected abstract boolean bulkCollectDataForSubscribe( @Nonnull ReplicantSession session, @Nonnull ArrayList<ChannelDescriptor> descriptors, @Nonnull ChangeSet changeSet, @Nullable Object filter, boolean explicitSubscribe ); protected abstract void collectDataForSubscriptionUpdate( @Nonnull ReplicantSession session, @Nonnull ChannelDescriptor descriptor, @Nonnull ChangeSet changeSet, @Nullable Object originalFilter, @Nullable Object filter ); /** * Hook method by which efficient bulk collection of data for subscription updates can occur. * It is expected that the hook does everything including updating SubscriptionEntry with new * filter, adding graph links etc. */ protected abstract boolean bulkCollectDataForSubscriptionUpdate( @Nonnull ReplicantSession session, @Nonnull ArrayList<ChannelDescriptor> descriptors, @Nonnull ChangeSet changeSet, @Nullable Object originalFilter, @Nullable Object filter ); protected void bulkUnsubscribe( @Nonnull final String sessionID, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, final boolean explicitUnsubscribe, @Nonnull final ChangeSet changeSet ) { setupRegistryContext( sessionID ); bulkUnsubscribe( ensureSession( sessionID ), channelID, subChannelIDs, explicitUnsubscribe, changeSet ); } @Override public void unsubscribe( @Nonnull final ReplicantSession session, @Nonnull final ChannelDescriptor descriptor, final boolean explicitUnsubscribe, @Nonnull final ChangeSet changeSet ) { final SubscriptionEntry entry = session.findSubscriptionEntry( descriptor ); if ( null != entry ) { performUnsubscribe( session, entry, explicitUnsubscribe, changeSet ); } } @Override public void bulkUnsubscribe( @Nonnull final ReplicantSession session, final int channelID, @Nonnull final Collection<Serializable> subChannelIDs, final boolean explicitUnsubscribe, @Nonnull final ChangeSet changeSet ) { for ( final Serializable subChannelID : subChannelIDs ) { unsubscribe( session, new ChannelDescriptor( channelID, subChannelID ), explicitUnsubscribe, changeSet ); } } protected void performUnsubscribe( @Nonnull final ReplicantSession session, @Nonnull final SubscriptionEntry entry, final boolean explicitUnsubscribe, @Nonnull final ChangeSet changeSet ) { if ( explicitUnsubscribe ) { entry.setExplicitlySubscribed( false ); } if ( entry.canUnsubscribe() ) { changeSet.addAction( entry.getDescriptor(), ChannelAction.Action.REMOVE, null ); for ( final ChannelDescriptor downstream : new ArrayList<>( entry.getOutwardSubscriptions() ) ) { delinkDownstreamSubscription( session, entry, downstream, changeSet ); } session.deleteSubscriptionEntry( entry ); } } private void delinkDownstreamSubscription( @Nonnull final ReplicantSession session, @Nonnull final SubscriptionEntry sourceEntry, @Nonnull final ChannelDescriptor downstream, @Nonnull final ChangeSet changeSet ) { final SubscriptionEntry downstreamEntry = session.findSubscriptionEntry( downstream ); if ( null != downstreamEntry ) { delinkSubscriptionEntries( sourceEntry, downstreamEntry ); performUnsubscribe( session, downstreamEntry, false, changeSet ); } } protected void delinkDownstreamSubscriptions( @Nonnull final ReplicantSession session, @Nonnull final SubscriptionEntry entry, @Nonnull final EntityMessage message, @Nonnull final ChangeAccumulator accumulator ) { // Delink any implicit subscriptions that was a result of the deleted entity final Set<ChannelLink> links = message.getLinks(); if ( null != links ) { for ( final ChannelLink link : links ) { delinkDownstreamSubscription( session, entry, link.getTargetChannel(), accumulator.getChangeSet( session ) ); } } } /** * Configure the SubscriptionEntries to reflect an auto graph link between the source and target graph. */ protected void linkSubscriptionEntries( @Nonnull final SubscriptionEntry sourceEntry, @Nonnull final SubscriptionEntry targetEntry ) { sourceEntry.registerOutwardSubscriptions( targetEntry.getDescriptor() ); targetEntry.registerInwardSubscriptions( sourceEntry.getDescriptor() ); } /** * Configure the SubscriptionEntries to reflect an auto graph delink between the source and target graph. */ protected void delinkSubscriptionEntries( @Nonnull final SubscriptionEntry sourceEntry, @Nonnull final SubscriptionEntry targetEntry ) { sourceEntry.deregisterOutwardSubscriptions( targetEntry.getDescriptor() ); targetEntry.deregisterInwardSubscriptions( sourceEntry.getDescriptor() ); } @SuppressWarnings( { "PMD.WhileLoopsMustUseBraces", "StatementWithEmptyBody" } ) protected void expandLinks( @Nonnull final ReplicantSession session, @Nonnull final ChangeSet changeSet ) { while ( expandLink( session, changeSet ) ) { //Ignore. } } /** * Iterate over all the ChannelLinks in change set attempting to "expand" them if they have to be * subscribed. The expand involves subscribing to the target graph. As soon as one is expanded * terminate search and return true, otherwise return false. */ protected boolean expandLink( @Nonnull final ReplicantSession session, @Nonnull final ChangeSet changeSet ) { for ( final Change change : changeSet.getChanges() ) { final EntityMessage entityMessage = change.getEntityMessage(); if ( entityMessage.isUpdate() ) { final Set<ChannelLink> links = entityMessage.getLinks(); if ( null != links ) { for ( final ChannelLink link : links ) { if ( expandLinkIfRequired( session, link, changeSet ) ) { return true; } } } } } return false; } /** * Determine if the specified ChannelLink needs to be expanded and do so. A ChannelLink needs to be * expanded if the session is subscribed to the source channel and shouldFollowLink returns true. * The `shouldFollowLink` method is only invoked if the target graph is filtered otherwise the link * is always followed. If a link should be followed the source graph and target graph are linked. * * If a subscription occurs then this method will immediately return false. This occurs as the changes * in the ChangeSet may have been modified as a result of the subscription and thus scanning of changeSet * needs to start again. */ boolean expandLinkIfRequired( @Nonnull final ReplicantSession session, @Nonnull final ChannelLink link, @Nonnull final ChangeSet changeSet ) { final ChannelDescriptor source = link.getSourceChannel(); final SubscriptionEntry sourceEntry = session.findSubscriptionEntry( source ); if ( null != sourceEntry ) { final ChannelDescriptor target = link.getTargetChannel(); final boolean targetUnfiltered = getChannelMetaData( target ).getFilterType() == ChannelMetaData.FilterType.NONE; if ( targetUnfiltered || shouldFollowLink( sourceEntry, target ) ) { final SubscriptionEntry targetEntry = session.findSubscriptionEntry( target ); if ( null == targetEntry ) { subscribe( session, target, false, targetUnfiltered ? null : sourceEntry.getFilter(), changeSet ); linkSubscriptionEntries( sourceEntry, session.getSubscriptionEntry( target ) ); return true; } linkSubscriptionEntries( sourceEntry, targetEntry ); } } return false; } protected abstract boolean shouldFollowLink( @Nonnull final SubscriptionEntry sourceEntry, @Nonnull final ChannelDescriptor target ); private void setupRegistryContext( @Nonnull final String sessionID ) { //Force the sessionID to the desired session in case call has not been set up by boundary getRegistry().putResource( ReplicantContext.SESSION_ID_KEY, sessionID ); } }
package de.larmic.butterfaces.component.showcase.table; import de.larmic.butterfaces.component.showcase.AbstractShowcaseComponent; import de.larmic.butterfaces.component.showcase.tree.SelectionAjaxType; import de.larmic.butterfaces.event.TableSingleSelectionListener; import javax.faces.model.SelectItem; import javax.faces.view.ViewScoped; import javax.inject.Named; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Named @ViewScoped public class TableShowcaseComponent extends AbstractShowcaseComponent implements Serializable, TableSingleSelectionListener<StringPair> { private final List<StringPair> stringPairs = new ArrayList<>(); private StringPair selectedValue = null; private String doSomethingWithRow = null; private SelectionAjaxType selectionAjaxType = SelectionAjaxType.AJAX; private FourthColumnWidthType fourthColumnWidthType = FourthColumnWidthType.NONE; private boolean tableCondensed; private boolean tableBordered; private boolean tableStriped = true; private boolean showRefreshButton = true; private boolean showToggleColumnButton = true; private String colWidthColumn1; private String colWidthColumn2; private String colWidthColumn3; private String colWidthColumn4; public List<StringPair> getStringRows() { if (stringPairs.isEmpty()) { stringPairs.add(new StringPair("r1c1", "r1c2")); stringPairs.add(new StringPair("r2c1", "r2c2")); stringPairs.add(new StringPair("r3c1", "r3c2")); stringPairs.add(new StringPair("r4c1", "r4c2")); stringPairs.add(new StringPair("r5c1", "r5c2")); stringPairs.add(new StringPair("r6c1", "r6c2")); stringPairs.add(new StringPair("r7c1", "r7c2")); } return stringPairs; } @Override public void processValueChange(final StringPair data) { this.selectedValue = data; } public List<SelectItem> getAjaxSelectionTypes() { final List<SelectItem> items = new ArrayList<>(); for (final SelectionAjaxType type : SelectionAjaxType.values()) { items.add(new SelectItem(type, type.label)); } return items; } public List<SelectItem> getTwoColumnWidthTypes() { final List<SelectItem> items = new ArrayList<>(); for (final FourthColumnWidthType type : FourthColumnWidthType.values()) { items.add(new SelectItem(type, type.label)); } return items; } public void doSomethingWithRow(final StringPair selectedValue) { this.doSomethingWithRow = "I have done something with " + (selectedValue == null ? "null" : selectedValue.getA()); } @Override protected void addJavaCode(final StringBuilder sb) { sb.append("package de.larmic.table.demo;\n\n"); if (this.selectionAjaxType == SelectionAjaxType.AJAX) { sb.append("import de.larmic.butterfaces.event.TableSingleSelectionListener;\n"); } sb.append("import javax.faces.view.ViewScoped;\n"); sb.append("import javax.inject.Named;\n\n"); sb.append("@ViewScoped\n"); sb.append("@Named\n"); if (this.selectionAjaxType == SelectionAjaxType.AJAX) { sb.append("public class MyBean implements Serializable, TableSingleSelectionListener {\n\n"); } else { sb.append("public class MyBean implements Serializable {\n\n"); } sb.append(" public List<StringPair> getValue() {\n"); sb.append(" final List<StringPair> pairs = new ArrayList<StringPair>();\n"); sb.append(" pairs.add(new StringPair(\"r1c1\", \"r1c2\"));\n"); sb.append(" pairs.add(new StringPair(\"r2c1\", \"r2c2\"));\n"); sb.append(" pairs.add(new StringPair(\"r3c1\", \"r3c2\"));\n"); sb.append(" pairs.add(new StringPair(\"r4c1\", \"r4c2\"));\n"); sb.append(" pairs.add(new StringPair(\"r5c1\", \"r5c2\"));\n"); sb.append(" pairs.add(new StringPair(\"r6c1\", \"r6c2\"));\n"); sb.append(" pairs.add(new StringPair(\"r7c1\", \"r7c2\"));\n"); sb.append(" return pairs;\n"); sb.append(" }\n\n"); if (selectionAjaxType != SelectionAjaxType.NONE) { sb.append(" private StringPair selectedRow;\n\n"); sb.append(" @Override\n"); sb.append(" public void processValueChange(final StringPair data) {\n"); sb.append(" this.selectedRow = data;\n"); sb.append(" }\n\n"); sb.append(" public StringPair getSelectedRow() {\n"); sb.append(" return selectedRow;\n"); sb.append(" }\n\n"); } sb.append("}\n\n"); sb.append("public class StringPair {\n\n"); sb.append(" private final String a;\n"); sb.append(" private final String b;\n\n"); sb.append(" public StringPair(final String a, final String b) {\n"); sb.append(" this.a = a;\n"); sb.append(" this.b = b;\n"); sb.append(" }\n\n"); sb.append(" // getter\n\n"); sb.append("}\n\n"); } @Override public String getXHtml() { final StringBuilder sb = new StringBuilder(); this.addXhtmlStart(sb); sb.append(" <b:table id=\"input\"\n"); this.appendString("var", "rowItem", sb); this.appendString("value", "#{myBean.value}", sb); this.appendBoolean("tableBordered", this.tableBordered, sb); this.appendBoolean("tableCondensed", this.tableCondensed, sb); this.appendBoolean("tableStriped", this.tableStriped, sb); this.appendBoolean("showRefreshButton", this.showRefreshButton, sb); this.appendBoolean("showToggleColumnButton", this.showToggleColumnButton, sb); this.appendBoolean("rendered", this.isRendered(), sb, true); if (selectionAjaxType == SelectionAjaxType.AJAX) { sb.append(" <f:ajax render=\"selectedRow\"/>\n"); } else if (selectionAjaxType == SelectionAjaxType.AJAX_DISABLED) { sb.append(" <f:ajax render=\"selectedRow\" disabled=\"true\"/>\n"); } sb.append(" <column id=\"column1\"\n"); if (fourthColumnWidthType == FourthColumnWidthType.PERCENT) { sb.append(" colWidth=\"10%\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.PX) { sb.append(" colWidth=\"50px\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.RELATIVE) { sb.append(" colWidth=\"5*\"\n"); } sb.append(" label=\"C1\">\n"); sb.append(" /* text */\n"); sb.append(" </column>\n"); sb.append(" <column id=\"column2\"\n"); if (fourthColumnWidthType == FourthColumnWidthType.PERCENT) { sb.append(" colWidth=\"75%\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.PX) { sb.append(" colWidth=\"30px\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.RELATIVE) { sb.append(" colWidth=\"1*\"\n"); } sb.append(" label=\"C2\">\n"); sb.append(" /* input text */\n"); sb.append(" </column>\n"); sb.append(" <column id=\"column3\"\n"); if (fourthColumnWidthType == FourthColumnWidthType.PERCENT) { sb.append(" colWidth=\"10%\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.PX) { sb.append(" colWidth=\"20px\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.RELATIVE) { sb.append(" colWidth=\"7*\"\n"); } sb.append(" label=\"C3\">\n"); sb.append(" /* action */\n"); sb.append(" </column>\n"); sb.append(" <column id=\"column4\"\n"); if (fourthColumnWidthType == FourthColumnWidthType.PERCENT) { sb.append(" colWidth=\"5%\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.PX) { sb.append(" colWidth=\"10px\"\n"); } else if (fourthColumnWidthType == FourthColumnWidthType.RELATIVE) { sb.append(" colWidth=\"1*\"\n"); } sb.append(" label=\"C4\">\n"); sb.append(" /* text */\n"); sb.append(" </column>\n"); sb.append(" </b:table>"); if (selectionAjaxType != SelectionAjaxType.NONE) { sb.append("\n\n <h:panelGroup id=\"selectedRow\">\n"); sb.append(" <h:output value=\"#{myBean.selectedRow.a}\"\n"); sb.append(" rendered=\"#{not empty myBean.selectedRow}\"/>\n"); sb.append(" <h:panelGroup/>"); } this.addXhtmlEnd(sb); return sb.toString(); } @Override protected String getEmptyDistanceString() { return " "; } public SelectionAjaxType getSelectionAjaxType() { return selectionAjaxType; } public void setSelectionAjaxType(final SelectionAjaxType selectionAjaxType) { this.selectionAjaxType = selectionAjaxType; } public StringPair getSelectedValue() { return this.selectedValue; } public String getDoSomethingWithRow() { return doSomethingWithRow; } public boolean isTableCondensed() { return tableCondensed; } public void setTableCondensed(boolean tableCondensed) { this.tableCondensed = tableCondensed; } public boolean isTableBordered() { return tableBordered; } public void setTableBordered(boolean tableBordered) { this.tableBordered = tableBordered; } public boolean isTableStriped() { return tableStriped; } public void setTableStriped(boolean tableStriped) { this.tableStriped = tableStriped; } public boolean isShowRefreshButton() { return showRefreshButton; } public void setShowRefreshButton(boolean showRefreshButton) { this.showRefreshButton = showRefreshButton; } public boolean isShowToggleColumnButton() { return showToggleColumnButton; } public void setShowToggleColumnButton(boolean showToggleColumnButton) { this.showToggleColumnButton = showToggleColumnButton; } public FourthColumnWidthType getFourthColumnWidthType() { return fourthColumnWidthType; } public void setFourthColumnWidthType(FourthColumnWidthType fourthColumnWidthType) { this.fourthColumnWidthType = fourthColumnWidthType; switch (this.fourthColumnWidthType) { case NONE: colWidthColumn1 = null; colWidthColumn2 = null; colWidthColumn3 = null; colWidthColumn4 = null; break; case PERCENT: colWidthColumn1 = "10%"; colWidthColumn2 = "75%"; colWidthColumn3 = "10%"; colWidthColumn4 = "5%"; break; case PX: colWidthColumn1 = "50px"; colWidthColumn2 = "30px"; colWidthColumn3 = "10px"; colWidthColumn4 = "10px"; break; case RELATIVE: colWidthColumn1 = "5*"; colWidthColumn2 = "1*"; colWidthColumn3 = "7*"; colWidthColumn3 = "1*"; break; } } public String getColWidthColumn1() { return colWidthColumn1; } public String getColWidthColumn2() { return colWidthColumn2; } public String getColWidthColumn3() { return colWidthColumn3; } public String getColWidthColumn4() { return colWidthColumn4; } }
package solutions.digamma.damas.standalone; import java.io.IOException; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import javax.ws.rs.ext.RuntimeDelegate; import org.glassfish.grizzly.http.server.CLStaticHttpHandler; import org.glassfish.grizzly.http.server.HttpHandler; import org.glassfish.grizzly.http.server.HttpServer; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import solutions.digamma.damas.config.Configuration; import solutions.digamma.damas.config.Fallback; import solutions.digamma.damas.logging.Logbook; /** * Application launcher. * * @author Ahmad Shahwan */ @Singleton public class Launcher { @Inject @Configuration({"http.port", "HTTP_PORT"}) @Fallback("8080") private Integer port; @Inject private Instance<Application> applications; @Inject private Logbook logger; private HttpServer server; @PostConstruct public void init() { boolean found = this.applications .stream() .map(this::register) .reduce(Boolean::logicalOr) .orElse(false); if (!found) { this.logger.severe( "No Web applications with a context path found."); return; } CLStaticHttpHandler docHandler = new CLStaticHttpHandler( this.getClass().getClassLoader(), "apidocs/"); this.server.getServerConfiguration() .addHttpHandler(docHandler, "/docs"); logger.info("Starting HTTP server."); try { this.server.start(); } catch (IOException e) { this.logger.severe( e, "Couldn't start HTTP server on port %d.", this.port); } logger.info("HTTP server started on port %d.", this.port); } private boolean register(Application application) { ApplicationPath annotation = application .getClass() .getAnnotation(ApplicationPath.class); if (annotation == null) { return false; } HttpHandler restHandler = RuntimeDelegate.getInstance() .createEndpoint(application, HttpHandler.class); this.server = HttpServer.createSimpleServer(null, this.port); String path = annotation.value(); String mapping = path.startsWith("/") ? path : "/".concat(path); this.server.getServerConfiguration() .addHttpHandler(restHandler, mapping); return true; } @PreDestroy public void dispose() { if (this.server != null) { logger.info("Shutting down HTTP server."); this.server.shutdown(); } } private void run() { try (WeldContainer weld = new Weld().initialize()) { weld.select(this.getClass()).get(); Thread.currentThread().join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public static void main(String[] argv) { new Launcher().run(); } }
package org.apache.lucene.spatial.strategy.util; import java.io.IOException; import java.util.WeakHashMap; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.spatial.base.shape.Shape; import org.apache.lucene.util.BytesRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class ShapeFieldCacheProvider<T extends Shape> { static final Logger log = LoggerFactory.getLogger(ShapeFieldCacheProvider.class); // it may be a List<T> or T WeakHashMap<IndexReader, ShapeFieldCache<T>> sidx = new WeakHashMap<IndexReader, ShapeFieldCache<T>>(); protected final int defaultSize; protected final String shapeField; public ShapeFieldCacheProvider(String shapeField, int defaultSize) { this.shapeField = shapeField; this.defaultSize = defaultSize; } protected abstract T readShape( BytesRef term ); public synchronized ShapeFieldCache<T> getCache(IndexReader reader) throws CorruptIndexException, IOException { ShapeFieldCache<T> idx = sidx.get(reader); if (idx != null) { return idx; } long startTime = System.currentTimeMillis(); log.info("Building Cache [" + reader.maxDoc() + "]"); idx = new ShapeFieldCache<T>(reader.maxDoc(),defaultSize); int count = 0; DocsEnum docs = null; Terms terms = reader.terms(shapeField); if (terms != null) { TermsEnum te = terms.iterator(); BytesRef term = te.next(); while (term != null) { T shape = readShape(term); if( shape != null ) { docs = te.docs(null, docs); Integer docid = docs.nextDoc(); while (docid != DocIdSetIterator.NO_MORE_DOCS) { idx.add( docid, shape ); docid = docs.nextDoc(); count++; } } term = te.next(); } } sidx.put(reader, idx); long elapsed = System.currentTimeMillis() - startTime; log.info("Cached: [" + count + " in " + elapsed + "ms] " + idx); return idx; } }
package org.navalplanner.web.common; import static org.navalplanner.business.i18n.I18nHelper._; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map.Entry; import org.apache.commons.lang.Validate; import org.navalplanner.business.common.IAdHocTransactionService; import org.navalplanner.business.common.IOnTransaction; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.orders.entities.Order; import org.navalplanner.business.orders.entities.TaskSource; import org.navalplanner.business.planner.daos.ITaskSourceDAO; import org.navalplanner.business.planner.entities.Dependency; import org.navalplanner.business.planner.entities.Task; import org.navalplanner.business.planner.entities.TaskElement; import org.navalplanner.business.planner.entities.TaskGroup; import org.navalplanner.business.planner.entities.Dependency.Type; import org.navalplanner.business.planner.entities.TaskElement.IDatesInterceptor; import org.navalplanner.business.resources.daos.IResourceDAO; import org.navalplanner.business.scenarios.daos.IOrderVersionDAO; import org.navalplanner.business.scenarios.daos.IScenarioDAO; import org.navalplanner.business.scenarios.entities.OrderVersion; import org.navalplanner.business.scenarios.entities.Scenario; import org.navalplanner.business.users.daos.IUserDAO; import org.navalplanner.business.users.entities.User; import org.navalplanner.web.planner.TaskElementAdapter; import org.navalplanner.web.users.services.CustomUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.security.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.zkoss.ganttz.adapters.PlannerConfiguration; import org.zkoss.ganttz.data.DependencyType; import org.zkoss.ganttz.data.GanttDiagramGraph; import org.zkoss.ganttz.data.GanttDiagramGraph.IAdapter; import org.zkoss.ganttz.data.GanttDiagramGraph.IDependenciesEnforcerHook; import org.zkoss.ganttz.data.GanttDiagramGraph.IDependenciesEnforcerHookFactory; import org.zkoss.ganttz.data.GanttDiagramGraph.PointType; import org.zkoss.ganttz.data.GanttDiagramGraph.TaskPoint; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.constraint.DateConstraint; import org.zkoss.ganttz.util.LongOperationFeedback; import org.zkoss.ganttz.util.LongOperationFeedback.IBackGroundOperation; import org.zkoss.ganttz.util.LongOperationFeedback.IDesktopUpdate; import org.zkoss.ganttz.util.LongOperationFeedback.IDesktopUpdatesEmitter; import org.zkoss.zk.ui.Desktop; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.util.Clients; /** * Model to manage UI operations from main template. * * @author Manuel Rego Casasnovas <mrego@igalia.com> */ @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class TemplateModel implements ITemplateModel { private static class DependencyWithVisibility { public static DependencyWithVisibility createInvisible( TaskElement source, TaskElement destination, DependencyType type) { return new DependencyWithVisibility(source, destination, type, false); } public static DependencyWithVisibility existent(Dependency each) { return new DependencyWithVisibility(each.getOrigin(), each .getDestination(), toGraphicalType(each.getType()), true); } public static List<Constraint<Date>> getStartConstraintsGiven( Adapter adapter, Set<DependencyWithVisibility> withDependencies) { List<Constraint<Date>> result = new ArrayList<Constraint<Date>>(); for (DependencyWithVisibility each : withDependencies) { TaskElement source = each.getSource(); DependencyType type = each.getGraphicalType(); result.addAll(type.getStartConstraints(source, adapter)); } return result; } public static List<Constraint<Date>> getEndConstraintsGiven( Adapter adapter, Set<DependencyWithVisibility> withDependencies) { List<Constraint<Date>> result = new ArrayList<Constraint<Date>>(); for (DependencyWithVisibility each : withDependencies) { TaskElement source = each.getSource(); DependencyType type = each.getGraphicalType(); result.addAll(type.getEndConstraints(source, adapter)); } return result; } private final TaskElement source; private final TaskElement destination; private final DependencyType type; private final boolean visible; private DependencyWithVisibility(TaskElement source, TaskElement destination, DependencyType type, boolean visible) { Validate.notNull(source); Validate.notNull(destination); Validate.notNull(type); this.source = source; this.destination = destination; this.type = type; this.visible = visible; } public boolean isVisible() { return visible; } public TaskElement getSource() { return source; } public TaskElement getDestination() { return destination; } public DependencyType getGraphicalType() { return type; } private static DependencyType toGraphicalType(Type domainDependencyType) { switch (domainDependencyType) { case END_START: return DependencyType.END_START; case START_START: return DependencyType.START_START; case END_END: return DependencyType.END_END; case START_END: throw new RuntimeException(Dependency.Type.START_END + " graphically it's not supported"); default: throw new RuntimeException("can't handle " + domainDependencyType); } } public PointType getPointType() { return getGraphicalType().getPointModified(); } } private static IDatesInterceptor asIntercerptor( final IDependenciesEnforcerHook hook) { return new IDatesInterceptor() { @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { hook.setStartDate(previousStart, previousLength, newStart); } @Override public void setLengthMilliseconds(long previousLengthMilliseconds, long newLengthMilliseconds) { hook.setLengthMilliseconds(previousLengthMilliseconds, newLengthMilliseconds); } }; } public class Adapter implements IAdapter<TaskElement, DependencyWithVisibility> { private final Scenario scenario; private Adapter(Scenario scenario) { Validate.notNull(scenario); this.scenario = scenario; } @Override public DependencyWithVisibility createInvisibleDependency( TaskElement origin, TaskElement destination, DependencyType type) { return DependencyWithVisibility.createInvisible(origin, destination, type); } @Override public List<TaskElement> getChildren(TaskElement task) { if (!task.isLeaf()) { return task.getChildren(); } else { return new ArrayList<TaskElement>(); } } @Override public List<Constraint<Date>> getEndConstraintsGivenIncoming( Set<DependencyWithVisibility> incoming) { return DependencyWithVisibility.getEndConstraintsGiven(this, incoming); } @Override public Constraint<Date> getCurrentLenghtConstraintFor(TaskElement task) { if (isContainer(task)) { return Constraint.emptyConstraint(); } return DateConstraint.biggerOrEqualThan(this.getEndDateFor(task)); } @Override public Class<DependencyWithVisibility> getDependencyType() { return DependencyWithVisibility.class; } @Override public TaskElement getDestination(DependencyWithVisibility dependency) { return dependency.getDestination(); } @Override public TaskPoint<TaskElement, DependencyWithVisibility> getDestinationPoint( DependencyWithVisibility dependency) { return new TaskPoint<TaskElement, DependencyWithVisibility>(this, dependency.getDestination(), dependency.getPointType()); } @Override public Constraint<Date> getEndDateBiggerThanStartDateConstraintFor( TaskElement task) { return DateConstraint.biggerOrEqualThan(getStartDate(task)); } @Override public Date getEndDateFor(TaskElement task) { return task.getEndDate(); } @Override public Date getSmallestBeginDateFromChildrenFor(TaskElement container) { TaskGroup taskGroup = (TaskGroup) container; return taskGroup.getSmallestStartDateFromChildren(); } @Override public TaskElement getSource(DependencyWithVisibility dependency) { return dependency.getSource(); } @Override public List<Constraint<Date>> getStartConstraintsFor(TaskElement task) { return TaskElementAdapter.getStartConstraintsFor(task); } @Override public List<Constraint<Date>> getStartCosntraintsGiven( Set<DependencyWithVisibility> withDependencies) { return DependencyWithVisibility.getStartConstraintsGiven(this, withDependencies); } @Override public Date getStartDate(TaskElement task) { return task.getStartDate(); } @Override public DependencyType getType(DependencyWithVisibility dependency) { return dependency.getGraphicalType(); } @Override public boolean isContainer(TaskElement task) { return !task.isLeaf() && !task.isMilestone(); } @Override public boolean isVisible(DependencyWithVisibility dependency) { return dependency.isVisible(); } @Override public void registerDependenciesEnforcerHookOn(TaskElement task, IDependenciesEnforcerHookFactory<TaskElement> hookFactory) { IDependenciesEnforcerHook enforcer = hookFactory.create(task); task.setDatesInterceptor(asIntercerptor(enforcer)); } @Override public void setEndDateFor(TaskElement task, Date newEnd) { task.setEndDate(newEnd); } @Override public void setStartDateFor(TaskElement task, Date newStart) { task.moveTo(scenario, newStart); } } @Autowired private IScenarioDAO scenarioDAO; @Autowired private IOrderVersionDAO orderVersionDAO; @Autowired private ITaskSourceDAO taskSourceDAO; @Autowired private IUserDAO userDAO; @Autowired private IResourceDAO resourceDAO; @Autowired private IAdHocTransactionService transactionService; @Override @Transactional(readOnly = true) public List<Scenario> getScenarios() { return scenarioDAO.getAll(); } @Override @Transactional(readOnly = true) public Scenario getScenarioByName(String name) { try { return scenarioDAO.findByName(name); } catch (InstanceNotFoundException e) { return null; } } @Override @Transactional public void setScenario(String loginName, Scenario scenario, IOnFinished onFinish) { Scenario scenarioReloaded = reloadScenario(scenario); associateToUser(scenarioReloaded, findUserByLoginName(loginName)); doReassignations(scenarioReloaded, onFinish); } private Scenario reloadScenario(Scenario scenario) { return scenarioDAO.findExistingEntity(scenario .getId()); } private User findUserByLoginName(String loginName) { try { return userDAO.findByLoginName(loginName); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } } private void associateToUser(Scenario scenario, User user) { user.setLastConnectedScenario(scenario); userDAO.save(user); CustomUser customUser = (CustomUser) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); customUser.setScenario(scenario); } private void doReassignations(final Scenario scenario, IOnFinished onFinish) { if (isOnZKExecution()) { doReassignationsWithFeedback(getDesktop(), scenario, onFinish); } else { doReassignations(scenario, LongOperationFeedback .<IDesktopUpdate> doNothingEmitter()); onFinish.onWithoutErrorFinish(); } } private boolean isOnZKExecution() { Execution current = Executions.getCurrent(); return current != null && current.getDesktop() != null; } private Desktop getDesktop() { Execution current = Executions.getCurrent(); return current.getDesktop(); } private void doReassignationsWithFeedback(Desktop desktop, final Scenario scenario, final IOnFinished onFinish) { IBackGroundOperation<IDesktopUpdate> reassignations = new IBackGroundOperation<IDesktopUpdate>() { @Override public void doOperation( final IDesktopUpdatesEmitter<IDesktopUpdate> desktopUpdateEmitter) { try { transactionService .runOnTransaction(new IOnTransaction<Void>() { @Override public Void execute() { doReassignations(reloadScenario(scenario), desktopUpdateEmitter); return null; } }); } finally { desktopUpdateEmitter.doUpdate(showEnd()); } desktopUpdateEmitter.doUpdate(executeFinish(onFinish)); } }; LongOperationFeedback.progressive(desktop, LongOperationFeedback .withAsyncUpates(reassignations)); } private IDesktopUpdate executeFinish( final IOnFinished onFinish) { return new IDesktopUpdate() { @Override public void doUpdate() { onFinish.onWithoutErrorFinish(); } }; } private void doReassignations(Scenario scenario, IDesktopUpdatesEmitter<IDesktopUpdate> emitter) { List<Entry<Order, OrderVersion>> needingReassignation = scenario .getOrderVersionsNeedingReassignation(); final int total = needingReassignation.size(); if (!needingReassignation.isEmpty()) { emitter.doUpdate(showStart(total)); } int i = 1; for (Entry<Order, OrderVersion> each : needingReassignation) { OrderVersion orderVersion = each.getValue(); Order order = each.getKey(); order.useSchedulingDataFor(scenario); if (order.isScheduled()) { doReassignationsOn(order, orderVersion.getOwnerScenario(), scenario); orderVersion.savingThroughOwner(); orderVersionDAO.save(orderVersion); } emitter.doUpdate(showProgress(total - i)); } } private IDesktopUpdate showStart(final int ordersNumber) { return sendMessage(_("Reassigning {0} orders", ordersNumber)); } private IDesktopUpdate showProgress(int remaining) { return sendMessage(_("{0} orders reassignation remaining", remaining)); } private IDesktopUpdate sendMessage(final String message) { return new IDesktopUpdate() { @Override public void doUpdate() { Clients.showBusy(message, true); } }; } private IDesktopUpdate showEnd() { return new IDesktopUpdate() { @Override public void doUpdate() { Clients.showBusy(null, false); } }; } private void doReassignationsOn(Order order, Scenario from, Scenario to) { copyAssignments(order, from, to); installDependenciesEnforcer(order, new Adapter(to)); doReassignations(order, to); doTheSaving(order); } private void copyAssignments(Order order, Scenario from, Scenario to) { for (Task each : getTasksFrom(order)) { each.copyAssignmentsFromOneScenarioToAnother(from, to); } } private void installDependenciesEnforcer(Order order, Adapter adapter) { GanttDiagramGraph<TaskElement, DependencyWithVisibility> graph = createFor(order, adapter); TaskSource taskSource = order.getTaskSource(); graph.addTopLevel(taskSource.getTask()); for (Dependency each : getAllDependencies(order)) { graph.addWithoutEnforcingConstraints(DependencyWithVisibility .existent(each)); } } private GanttDiagramGraph<TaskElement, DependencyWithVisibility> createFor( Order order, IAdapter<TaskElement, DependencyWithVisibility> adapter) { List<Constraint<Date>> startConstraints = PlannerConfiguration .getStartConstraintsGiven(order.getInitDate()); List<Constraint<Date>> endConstraints = Collections.emptyList(); GanttDiagramGraph<TaskElement, DependencyWithVisibility> result = GanttDiagramGraph .create(adapter, startConstraints, endConstraints, order.getDependenciesConstraintsHavePriority()); return result; } private Set<Dependency> getAllDependencies(Order order) { Set<Dependency> dependencies = new HashSet<Dependency>(); for (TaskElement each : getTaskElementsFrom(order)) { Set<Dependency> dependenciesWithThisOrigin = each .getDependenciesWithThisOrigin(); dependencies.addAll(dependenciesWithThisOrigin); } return dependencies; } private void doReassignations(Order order, Scenario scenario) { for (Task each : getTasksFrom(order)) { each.reassignAllocationsWithNewResources(scenario, resourceDAO); } } private void doTheSaving(Order order) { for (TaskSource each : order.getTaskSourcesFromBottomToTop()) { taskSourceDAO.save(each); } } private List<Task> getTasksFrom(Order order) { List<Task> result = new ArrayList<Task>(); for (TaskElement each : getTaskElementsFrom(order)) { if (each instanceof Task) { result.add((Task) each); } } return result; } private List<TaskElement> getTaskElementsFrom(Order order) { List<TaskElement> result = new ArrayList<TaskElement>(); for (TaskSource each : order.getTaskSourcesFromBottomToTop()) { result.add(each.getTask()); } return result; } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.dao.support; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.log4j.Category; import org.opennms.core.utils.BundleLists; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.dao.GraphDao; import org.opennms.netmgt.model.AdhocGraphType; import org.opennms.netmgt.model.OnmsAttribute; import org.opennms.netmgt.model.OnmsResource; import org.opennms.netmgt.model.PrefabGraph; import org.opennms.netmgt.model.PrefabGraphType; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.ObjectRetrievalFailureException; import org.springframework.util.StringUtils; public class PropertiesGraphDao implements GraphDao { public static final String DEFAULT_GRAPH_LIST_KEY = "reports"; private Map<String, FileReloadContainer<PrefabGraphType>> m_types = new HashMap<String, FileReloadContainer<PrefabGraphType>>(); private HashMap<String, FileReloadContainer<AdhocGraphType>> m_adhocTypes = new HashMap<String, FileReloadContainer<AdhocGraphType>>(); private PrefabGraphTypeCallback m_prefabCallback = new PrefabGraphTypeCallback(); private AdhocGraphTypeCallback m_adhocCallback = new AdhocGraphTypeCallback(); public PropertiesGraphDao(Map<String, File> prefabConfigs, Map<String, File> adhocConfigs) throws IOException { initPrefab(prefabConfigs); initAdhoc(adhocConfigs); } private void initPrefab(Map<String, File> configMap) throws IOException { for (Map.Entry<String, File> configEntry : configMap.entrySet()) { loadProperties(configEntry.getKey(), configEntry.getValue()); } } private void initAdhoc(Map<String, File> configMap) throws IOException { for (Map.Entry<String, File> configEntry : configMap.entrySet()) { loadAdhocProperties(configEntry.getKey(), configEntry.getValue()); } } public PrefabGraphType findByName(String name) { return m_types.get(name).getObject(); } public AdhocGraphType findAdhocByName(String name) { return m_adhocTypes.get(name).getObject(); } public void loadProperties(String type, File file) throws IOException { FileInputStream in = new FileInputStream(file); PrefabGraphType t = createPrefabGraphType(type, in); in.close(); m_types.put(t.getName(), new FileReloadContainer<PrefabGraphType>(t, file, m_prefabCallback)); } public void loadProperties(String type, InputStream in) throws IOException { PrefabGraphType t = createPrefabGraphType(type, in); m_types.put(t.getName(), new FileReloadContainer<PrefabGraphType>(t)); } private PrefabGraphType createPrefabGraphType(String type, InputStream in) throws IOException { Properties properties = new Properties(); properties.load(in); PrefabGraphType t = new PrefabGraphType(); t.setName(type); t.setCommandPrefix(getProperty(properties, "command.prefix")); t.setOutputMimeType(getProperty(properties, "output.mime")); t.setDefaultReport(properties.getProperty("default.report", "none")); t.setReportMap(getPrefabGraphDefinitions(properties)); return t; } public void loadAdhocProperties(String type, File file) throws IOException { FileInputStream in = new FileInputStream(file); AdhocGraphType t = createAdhocGraphType(type, in); in.close(); m_adhocTypes.put(t.getName(), new FileReloadContainer<AdhocGraphType>(t, file, m_adhocCallback)); } public void loadAdhocProperties(String type, InputStream in) throws IOException { AdhocGraphType t = createAdhocGraphType(type, in); m_adhocTypes.put(t.getName(), new FileReloadContainer<AdhocGraphType>(t)); } public AdhocGraphType createAdhocGraphType(String type, InputStream in) throws IOException { Properties properties = new Properties(); properties.load(in); AdhocGraphType t = new AdhocGraphType(); t.setName(type); t.setRrdDirectory(new File(getProperty(properties, "command.input.dir"))); t.setCommandPrefix(getProperty(properties, "command.prefix")); t.setOutputMimeType(getProperty(properties, "output.mime")); t.setTitleTemplate(getProperty(properties, "adhoc.command.title")); t.setDataSourceTemplate(getProperty(properties, "adhoc.command.ds")); t.setGraphLineTemplate(getProperty(properties, "adhoc.command.graphline")); return t; } private Map<String, PrefabGraph> getPrefabGraphDefinitions(Properties properties) { if (properties == null) { throw new IllegalArgumentException("properties cannot be null"); } String listString = getProperty(properties, DEFAULT_GRAPH_LIST_KEY); String[] list = BundleLists.parseBundleList(listString); Map<String, PrefabGraph> map = new LinkedHashMap<String, PrefabGraph>(); for (int i = 0; i < list.length; i++) { String key = list[i]; PrefabGraph graph = makePrefabGraph(key, properties, i); map.put(key, graph); } return map; } private static PrefabGraph makePrefabGraph(String key, Properties props, int order) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } if (props == null) { throw new IllegalArgumentException("props cannot be null"); } String title = getReportProperty(props, key, "name", true); String command = getReportProperty(props, key, "command", true); String columnString = getReportProperty(props, key, "columns", true); String[] columns = BundleLists.parseBundleList(columnString); String externalValuesString = getReportProperty(props, key, "externalValues", false); String[] externalValues; if (externalValuesString == null) { externalValues = new String[0]; } else { externalValues = BundleLists.parseBundleList(externalValuesString); } String[] propertiesValues; String propertiesValuesString = getReportProperty(props, key, "propertiesValues", false); if (propertiesValuesString == null) { propertiesValues = new String[0]; } else { propertiesValues = BundleLists.parseBundleList(propertiesValuesString); } // can be null String[] types; String typesString = getReportProperty(props, key, "type", false); if (typesString == null) { types = new String[0]; } else { types = BundleLists.parseBundleList(typesString); } // can be null String description = getReportProperty(props, key, "description", false); // TODO: Right now a "width" and "height" property is required // in order to get zoom to work properly on non-standard sized // graphs. A more elegant solution would be to parse the // command string and look for --width and --height and set // the following two variables automagically, without having // to rely on a config file. // can be null String graphWidth = getReportProperty(props, key, "width", false); // can be null String graphHeight = getReportProperty(props, key, "height", false); return new PrefabGraph(key, title, columns, command, externalValues, propertiesValues, order, types, description, graphWidth, graphHeight); } private static String getProperty(Properties props, String name) { String property = props.getProperty(name); if (property == null) { throw new DataAccessResourceFailureException("Properties must " + "contain \'" + name + "\' property"); } return property; } private static String getReportProperty(Properties props, String key, String suffix, boolean required) { String propertyName = "report." + key + "." + suffix; String property = props.getProperty(propertyName); if (property == null && required == true) { throw new DataAccessResourceFailureException("Properties for " + "report '" + key + "' must contain \'" + propertyName + "\' property"); } return property; } private Category log() { return ThreadCategory.getInstance(); } private class PrefabGraphTypeCallback implements FileReloadCallback<PrefabGraphType> { public PrefabGraphType reload(PrefabGraphType object, File file) { FileInputStream in; try { in = new FileInputStream(file); } catch (FileNotFoundException e) { log().error("Could not reload configuration file '" + file.getAbsolutePath() + "' due to FileNotFoundException: " + e, e); return null; } PrefabGraphType t; try { t = createPrefabGraphType(object.getName(), in); } catch (IOException e) { log().error("Could not reload configuration file '" + file.getAbsolutePath() + "' due to IOException when reading from file: " + e, e); return null; } catch (DataAccessException e) { log().error("Could not reload configuration file '" + file.getAbsolutePath() + "' due to DataAccessException when reading from " + "file: " + e, e); return null; } try { in.close(); } catch (IOException e) { log().error("Could not reload configuration file '" + file.getAbsolutePath() + "' due to IOException when closing file: " + e, e); return null; } return t; } } public List<PrefabGraph> getAllPrefabGraphs() { LinkedList<PrefabGraph> graphs = new LinkedList<PrefabGraph>(); for (FileReloadContainer<PrefabGraphType> container : m_types.values()) { // for (Map.Entry<String, PrefabGraph> entry : container.getObject().getReportMap().entrySet()) { // graphs.add(entry.getValue()); graphs.addAll(container.getObject().getReportMap().values()); } return graphs; } public PrefabGraph getPrefabGraph(String name) { for (FileReloadContainer<PrefabGraphType> container : m_types.values()) { PrefabGraph graph = container.getObject().getQuery(name); if (graph != null) { return graph; } } throw new ObjectRetrievalFailureException(PrefabGraph.class, name, "Could not find prefabricated graph report with name '" + name + "'", null); } public PrefabGraph[] getPrefabGraphsForResource(OnmsResource resource) { Set<OnmsAttribute> attributes = resource.getAttributes(); // Check if there are no attriutes to graph if (attributes.size() == 0) { log().debug("returning empty graph list for resource " + resource + " because its attribute list is empty"); return new PrefabGraph[0]; } Set<String> availDataSourceList = new HashSet<String>(attributes.size()); for (OnmsAttribute attribute : attributes) { availDataSourceList.add(attribute.getName()); } String resourceType = resource.getResourceType().getName(); List<PrefabGraph> returnList = new LinkedList<PrefabGraph>(); for (PrefabGraph query : getAllPrefabGraphs()) { if (resourceType != null && !query.hasMatchingType(resourceType)) { // if (log().isDebugEnabled()) { // log().debug("skipping " + query.getName() + " because its types \"" + StringUtils.arrayToDelimitedString(query.getTypes(), ", ") + "\" does not match resourceType \"" + resourceType + "\""); continue; } List<String> requiredList = Arrays.asList(query.getColumns()); if (availDataSourceList.containsAll(requiredList)) { // if (log().isDebugEnabled()) { // log().debug("adding " + query.getName() + " to query list"); returnList.add(query); } else { // if (log().isDebugEnabled()) { // log().debug("not adding " + query.getName() + " to query list because the required list of attributes (" + StringUtils.collectionToDelimitedString(requiredList, ", ") + ") is not in the list of attributes on the resource (" + StringUtils.collectionToDelimitedString(availDataSourceList, ", ")+ ")"); } } if (log().isDebugEnabled()) { ArrayList<String> nameList = new ArrayList<String>(returnList.size()); for (PrefabGraph graph : returnList) { nameList.add(graph.getName()); } log().debug("found " + nameList.size() + " prefabricated graphs for resource " + resource + ": " + StringUtils.collectionToDelimitedString(nameList, ", ")); } PrefabGraph[] availQueries = returnList.toArray(new PrefabGraph[returnList.size()]); return availQueries; } private class AdhocGraphTypeCallback implements FileReloadCallback<AdhocGraphType> { public AdhocGraphType reload(AdhocGraphType object, File file) { FileInputStream in = null; try { in = new FileInputStream(file); return createAdhocGraphType(object.getName(), in); } catch (Exception e) { log().error("Could not reload configuration file '" + file.getAbsolutePath() + "' due to: " + e, e); return null; } finally { IOUtils.closeQuietly(in); } } } }
package edu.uncc.parsets.data; import java.awt.event.ActionListener; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.swing.SwingUtilities; import edu.uncc.parsets.ParallelSets; import edu.uncc.parsets.data.old.CSVDataSet; import edu.uncc.parsets.data.old.CSVParser; import edu.uncc.parsets.data.old.DataDimension; import edu.uncc.parsets.gui.MainWindow; import edu.uncc.parsets.util.PSLogging; import edu.uncc.parsets.util.osabstraction.AbstractOS; /** * Encapsulate an SQLite database that stores datasets. This class provides * the means for thread-safe concurrent read and write access to the database. * Any interaction with the database has to go through {@link #createStatement(DBAccess)} * or {@link #prepareStatement(String, DBAccess)}, and release the lock acquired * this way using {@link #releaseReadLock()} or {@link #releaseWriteLock()}. * */ public class LocalDB { /** * Version of the db schema used. This is recorded in the schema_version * entry in the Admin_Settings table, and will allow us to open old dbs * even when the schema changes. */ private static final int SCHEMA_VERSION = 2000; public static final String LOCALDBFILENAME = "local.db"; private static final LocalDB defaultDB; public static final String LAST_VERSION_SEEN_KEY = "last_version_seen"; private static final String DB_SCHEMA_KEY = "schema_version"; private final ReentrantReadWriteLock dbLock = new ReentrantReadWriteLock(); private ArrayList<DataSet> dataSets; private Map<String, List<DataSet>> sections; private Connection db; private List<ActionListener> listeners = new Vector<ActionListener>(); static { defaultDB = new LocalDB(LOCALDBFILENAME); } public static enum DBAccess { FORREADING, FORWRITING } /** * Simple storage class to hold information for {@link LocalDB#writeData(CSVParser, String, List, List)}. * No longer copies the vaues array! */ private static class CubeValues { public int count; public int categoryValues[]; public int key; public CubeValues(int values[], int cubeKey) { count = 1; key = cubeKey; categoryValues = values; } } /** * This is strictly for int arrays of the same size, like use in {@link LocalDB#addLocalDBDataSet(CSVDataSet, CSVParser)} */ private static class IntArrayComparator implements Comparator<int[]> { @Override public int compare(int[] o1, int[] o2) { for (int i = 0; i < o1.length; i++) if (o1[i] != o2[i]) return o1[i]-o2[i]; return 0; } } public LocalDB(String filename) { try { Class.forName("org.sqlite.JDBC"); String dbFileName = null; // PSLogging.logger.fatal("test"); boolean initialized = true; if (ParallelSets.isInstalled()) dbFileName = AbstractOS.getCurrentOS().getLocalDBPath(filename); else { URL dbURL = this.getClass().getResource("/"+filename); if (dbURL == null) { dbFileName = filename; initialized = false; } else dbFileName = (new File(dbURL.toURI())).getAbsolutePath(); } PSLogging.logger.info("Opening local DB file '"+dbFileName+"'"); db = DriverManager.getConnection("jdbc:sqlite:"+dbFileName); if (!initialized) initializeDB(); else { int dbVersion = Integer.parseInt(getSetting(DB_SCHEMA_KEY)); if (dbVersion < SCHEMA_VERSION) migrate1000to2000(); } } catch (ClassNotFoundException e) { PSLogging.logger.fatal("SQLite could not be initialized.", e); } catch (SQLException e) { PSLogging.logger.fatal("Error connecting to local DB.", e); } catch (URISyntaxException e) { PSLogging.logger.fatal("Unable to locate local DB file.", e); } } public static LocalDB getDefaultDB() { return defaultDB; } /** * Acquire a Statement for interacting with the database. This method * acquires a lock, which must be released (using {@link #releaseReadLock()} * or {@link #releaseWriteLock())} when the calling function is done. * * @param accessType the kind of access (reading or writing) the resulting statement will be used for * @return the statement object * @throws SQLException */ public Statement createStatement(DBAccess accessType) throws SQLException { acquireLock(accessType); return db.createStatement(); } private void acquireLock(DBAccess accessType) { if (accessType == DBAccess.FORREADING) dbLock.readLock().lock(); else dbLock.writeLock().lock(); } public void releaseReadLock() { dbLock.readLock().unlock(); } public void releaseWriteLock() { dbLock.writeLock().unlock(); } public PreparedStatement prepareStatement(String statement, DBAccess accessType) throws SQLException { acquireLock(accessType); return db.prepareStatement(statement); } public void initializeDB() { PSLogging.logger.info("Initializing local DB file."); Statement statement; try { statement = createStatement(DBAccess.FORWRITING); ResultSet rs = statement.executeQuery("select name from sqlite_master where type=\"table\";"); // make list of tables first, as dropping invalidates query result List<String> dropTables = new ArrayList<String>(); while (rs.next()) dropTables.add(rs.getString(1)); for (String tableName : dropTables) statement.executeUpdate("drop table "+tableName+";"); statement.execute("begin transaction;"); statement.execute("create table Admin_Settings (key TEXT PRIMARY KEY, value TEXT);"); statement.execute("insert into Admin_Settings values ('creator', '"+MainWindow.WINDOWTITLE+"');"); statement.execute("insert into Admin_Settings values ('"+DB_SCHEMA_KEY+"', '"+SCHEMA_VERSION+"');"); statement.execute("insert into Admin_Settings values ('"+LAST_VERSION_SEEN_KEY+"', '"+ParallelSets.VERSION+"');"); statement.execute("create table Admin_Datasets (name TEXT, handle TEXT PRIMARY KEY, type TEXT, numDimensions INTEGER, numRecords INTEGER, section TEXT, dateAdded TEXT, lastOpened TEXT, dataURL TEXT, source TEXT, srcURL TEXT);"); statement.execute("create table Admin_Dimensions (dataSet TEXT, name TEXT, handle TEXT, type TEXT);"); statement.execute("create table Admin_Categories (dataSet TEXT, dimension TEXT, name TEXT, handle TEXT, number INTEGER, count INTEGER);"); statement.execute("create index Admin_Dimensions_Handle on Admin_Dimensions (dataSet);"); statement.execute("create index Admin_Categories_DSHandle on Admin_Categories (dataSet, dimension);"); statement.execute("commit;"); statement.close(); } catch (SQLException e) { PSLogging.logger.error("Error initializing local DB.", e); } finally { releaseWriteLock(); } rescanDB(); } public LocalDBDataSet[] getDataSets() { if (dataSets == null) rescanDB(); LocalDBDataSet ds[] = dataSets.toArray(new LocalDBDataSet[dataSets.size()]); Arrays.sort(ds); return ds; } public DataSet getDataSet(String handle) { for (DataSet ds : dataSets) if (ds.getHandle().equals(handle)) return ds; return null; } public Map<String, List<DataSet>> getSections() { if (sections == null) { if (dataSets == null) rescanDB(); sections = groupIntoSections(dataSets.iterator()); } return sections; } public static Map<String, List<DataSet>> groupIntoSections(Iterator<DataSet> it) { TreeMap<String, List<DataSet>> sections = new TreeMap<String, List<DataSet>>(); while (it.hasNext()) { DataSet ds = it.next(); List<DataSet> list = sections.get(ds.getSection()); if (list == null) { list = new ArrayList<DataSet>(); sections.put(ds.getSection(), list); } list.add(ds); } for (List<DataSet> list : sections.values()) Collections.sort(list); return sections; } /** * Add a listener to be called whenever {@link #rescanDB()} is run. * @param l The listener to be added */ public void addRescanListener(ActionListener l) { listeners.add(l); } public void removeRescanListener(ActionListener l) { listeners.remove(l); } public void rescanDB() { dataSets = new ArrayList<DataSet>(); sections = null; try { Statement stmt = createStatement(DBAccess.FORREADING); ResultSet rs = stmt.executeQuery("select name, handle, numRecords, dataURL, section, source, srcURL from Admin_DataSets;"); while (rs.next()) { LocalDBDataSet ds = new LocalDBDataSet(rs.getString(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), this); dataSets.add(ds); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (ActionListener l : listeners) l.actionPerformed(null); } }); } catch(SQLException e) { PSLogging.logger.error("Error reading list of datasets.", e); } finally { releaseReadLock(); } } public String addLocalDBDataSet(CSVDataSet dataSet, CSVParser parser) { ArrayList<DataDimension> catDims = new ArrayList<DataDimension>(dataSet.getNumDimensions()); ArrayList<DataDimension> numDims = new ArrayList<DataDimension>(dataSet.getNumDimensions()); for (DataDimension d : dataSet) if (d.getDataType() == DataType.categorical) catDims.add(d); else numDims.add(d); PSLogging.logger.info("Storing data set " + dataSet.getName()); PSLogging.logger.info(dataSet.getNumRecords() + " records"); PSLogging.logger.info(catDims.size() + " (categorical) dimensions"); PSLogging.logger.info(numDims.size() + " measures"); // where is map() when I need it? int categories[] = new int[catDims.size()]; int i = 0; for (DataDimension d : catDims) { categories[i] = d.getNumCategories(); i++; } Statement stmt = null; String handle = null; try { stmt = createStatement(DBAccess.FORWRITING); stmt.execute("begin transaction;"); handle = writeAdmin(dataSet, catDims, numDims); writeData(parser, handle, catDims, numDims); stmt.execute("commit;"); } catch (SQLException e) { PSLogging.logger.error("Could not write dataset to local DB.", e); try { stmt.execute("rollback;"); } catch (SQLException e1) { PSLogging.logger.error("Could not roll back changes.", e1); } } finally { releaseWriteLock(); try { stmt.close(); } catch (SQLException e) { PSLogging.logger.warn("Could not release DB statement.", e); } } rescanDB(); PSLogging.logger.info("Done."); return handle; } private String writeAdmin(CSVDataSet dataSet, ArrayList<DataDimension> catDims, ArrayList<DataDimension> numDims) { String dsHandle = null; PreparedStatement dsStmt = null; PreparedStatement dimStmt = null; PreparedStatement catStmt = null; Statement stmt = null; try { dsStmt = db.prepareStatement("insert into Admin_DataSets values (?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'), ?, ?, ?);"); dsStmt.clearBatch(); dsStmt.setString(1, dataSet.getName()); dsHandle = name2handle(dataSet.getName()); dsHandle = makeUniqueHandle(dsHandle, db); dsStmt.setString(2, dsHandle); dsStmt.setString(3, "cube"); dsStmt.setInt(4, dataSet.getNumDimensions()); dsStmt.setInt(5, dataSet.getNumRecords()); dsStmt.setString(6, dataSet.getSection()); dsStmt.setString(7, dataSet.getURL()); dsStmt.setString(8, dataSet.getSource()); dsStmt.setString(9, dataSet.getSourceURL()); dsStmt.addBatch(); dsStmt.executeBatch(); dimStmt = db.prepareStatement("insert into Admin_Dimensions values (?, ?, ?, ?);"); catStmt = db.prepareStatement("insert into Admin_Categories values (?, ?, ?, ?, ?, ?);"); for (DataDimension dim : dataSet) { dimStmt.setString(1, dsHandle); dimStmt.setString(2, dim.getName()); String dimHandle = name2handle(dim.getKey()); dimStmt.setString(3, dimHandle); dimStmt.setString(4, dim.getDataType().toString()); if (dim.getDataType() == DataType.categorical) { for (int catNum = 0; catNum < dim.getNumCategories(); catNum++) { catStmt.setString(1, dsHandle); catStmt.setString(2, dimHandle); catStmt.setString(3, dim.getCategoryName(catNum)); catStmt.setString(4, name2handle(dim.getCategoryName(catNum))); catStmt.setInt(5, catNum+1); catStmt.setInt(6, dim.getOccurrenceCount(dim.getCategoryKey(catNum))); catStmt.addBatch(); } } dimStmt.addBatch(); } dimStmt.executeBatch(); catStmt.executeBatch(); stmt = db.createStatement(); StringBuffer createSB = new StringBuffer("create table "+dsHandle+"_dims (key INTEGER, count INTEGER"); for (DataDimension dim : catDims) { String handle = name2handle(dim.getKey()); createSB.append(", "); createSB.append(handle); createSB.append(" INTEGER"); } createSB.append(");"); stmt.execute(createSB.toString()); if (numDims.size() > 0) { createSB = new StringBuffer("create table "+dsHandle+"_measures (key INTEGER"); for (DataDimension dim : numDims) { createSB.append(", "+name2handle(dim.getKey())); if (dim.getDataType() == DataType.numerical) createSB.append(" REAL"); else createSB.append(" TEXT"); } createSB.append(");"); stmt.execute(createSB.toString()); stmt.execute("create index "+dsHandle+"_measures_key on "+dsHandle+"_measures (key);"); } } catch (SQLException e) { PSLogging.logger.error("Error writing admin data.", e); } finally { try { if (dsStmt != null) dsStmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement 'dsStmt'.", e); } try { if (dimStmt != null) dimStmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement 'dimStmt'.", e); } try { if (catStmt != null) catStmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement 'catStmt'.", e); } try { if (stmt != null) stmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement 'stmt'.", e); } } return dsHandle; } private String makeUniqueHandle(String handle, Connection db) { int num = 0; try { PreparedStatement stmt = db.prepareStatement("select count(*) from Admin_Datasets where handle = ?;"); stmt.setString(1, handle); ResultSet rs = stmt.executeQuery(); while (rs.getInt(1) > 0) { num++; stmt.setString(1, handle+num); rs = stmt.executeQuery(); } stmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error creating unique DB handle.", e); } if (num == 0) return handle; else return handle+num; } public static String name2handle(String name) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < name.length(); i++) { char c = Character.toLowerCase(name.charAt(i)); if (Character.getType(c) == Character.LOWERCASE_LETTER || Character.getType(c) == Character.DECIMAL_DIGIT_NUMBER) sb.append(c); } return sb.toString(); } public boolean containsHandle(String handle) { for (DataSet ds : getDataSets()) { if (ds.getHandle().equals(handle)) return true; } return false; } private void writeData(CSVParser parser, String handle, List<DataDimension> catDims, List<DataDimension> numDims) { CSVDataSet dataSet = parser.getDataSet(); int keyArray[] = new int[catDims.size()]; TreeMap<int[], CubeValues> cubes = new TreeMap<int[], CubeValues>(new IntArrayComparator()); int key = 1; PreparedStatement measureStmt = null; try { if (numDims.size() > 0) { StringBuffer measureSB = new StringBuffer("insert into "+handle+"_measures values (?"); for (int i = 0; i < numDims.size(); i++) measureSB.append(", ?"); measureSB.append(");"); measureStmt = db.prepareStatement(measureSB.toString()); } int recordNum = 0; float record[] = parser.readNextLine(); while (record != null) { int catIndex = 0; int numIndex = 2; for (int column = 0; column < record.length; column++) { if (dataSet.getDimension(column).getDataType() == DataType.categorical) { keyArray[catIndex] = (int) record[column]; catIndex++; } else { measureStmt.setFloat(numIndex, record[column]); numIndex++; } } CubeValues cube = cubes.get(keyArray); if (cube != null) cube.count++; else { int keyArrayCopy[] = Arrays.copyOf(keyArray, keyArray.length); cubes.put(keyArrayCopy, new CubeValues(keyArrayCopy, key)); key++; } recordNum++; if (numDims.size() > 0) { measureStmt.setInt(1, key); measureStmt.addBatch(); if ((recordNum & 0xff) == 0) measureStmt.executeBatch(); } record = parser.readNextLine(); } if (numDims.size() > 0) measureStmt.executeBatch(); } catch (SQLException e) { PSLogging.logger.error("Error writing measures.", e); } finally { try { if (measureStmt != null) measureStmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement 'measureStmt'.", e); } } PSLogging.logger.info(cubes.size()+" cube values"); StringBuffer dimsSB = new StringBuffer("insert into "+handle+"_dims values (?, ?"); for (int i = 0; i < catDims.size(); i++) dimsSB.append(", ?"); dimsSB.append(");"); PreparedStatement dimsStmt = null; try { int numCube = 0; dimsStmt = db.prepareStatement(dimsSB.toString()); for (CubeValues cube : cubes.values()) { dimsStmt.setInt(1, cube.key); dimsStmt.setInt(2, cube.count); for (int i = 0; i < cube.categoryValues.length; i++) dimsStmt.setInt(i+3, cube.categoryValues[i]); numCube++; dimsStmt.addBatch(); if ((numCube & 0xff) == 0) dimsStmt.executeBatch(); } dimsStmt.executeBatch(); } catch (SQLException e) { PSLogging.logger.error("Error writing measures.", e); } finally { try { if (dimsStmt != null) dimsStmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement 'dimsStmt'.", e); } } } protected void deleteFromDB(String dbHandle) { PSLogging.logger.info("Deleting dataset '"+dbHandle+"' from local DB."); try { Statement stmt = db.createStatement(); stmt.execute("begin transaction;"); stmt.execute("delete from Admin_DataSets where handle = '"+dbHandle+"';"); stmt.execute("delete from Admin_Dimensions where dataSet = '"+dbHandle+"';"); stmt.execute("delete from Admin_Categories where dataSet = '"+dbHandle+"';"); stmt.execute("drop table "+dbHandle+"_dims;"); stmt.execute("drop table if exists "+dbHandle+"_measures;"); stmt.execute("commit;"); stmt.execute("vacuum;"); stmt.close(); } catch (SQLException e) { PSLogging.logger.error("Could not delete dataset.", e); } rescanDB(); } public String getSetting(String key) { try { PreparedStatement stmt = prepareStatement("select value from Admin_Settings where key = ?;", DBAccess.FORREADING); stmt.setString(1, key); ResultSet rs = stmt.executeQuery(); String value = rs.getString(1); stmt.close(); return value; } catch (SQLException e) { PSLogging.logger.error("Could not retrieve setting for "+key, e); } finally { releaseReadLock(); } return null; } public void storeSetting(String key, String value) { try { PreparedStatement stmt = prepareStatement("update Admin_Settings set value = ? where key = ?;", DBAccess.FORWRITING); stmt.setString(1, value); stmt.setString(2, key); int rows = stmt.executeUpdate(); if (rows == 0) { stmt.close(); stmt = db.prepareStatement("insert into Admin_Settings values (?, ?);"); stmt.setString(1, value); stmt.setString(2, key); stmt.execute(); } stmt.close(); } catch (Exception e) { PSLogging.logger.error("Could not update setting "+key+" to "+value, e); } finally { releaseWriteLock(); } } /** * Migrate DB schema version 1000 to 2000. * * SQLite does not implement ALTER TABLE DROP COLUMN, so we need to create * a temporary table, copy the values, drop the original, and rename the * temporary table. */ private void migrate1000to2000() { PSLogging.logger.info("Migrating DB from version 1000 to version 2000."); Statement stmt = null; try { stmt = createStatement(DBAccess.FORWRITING); stmt.execute("begin transaction;"); stmt.execute("create table Admin_Dims (dataSet TEXT, name TEXT, handle TEXT, type TEXT);"); stmt.execute("insert into Admin_Dims select dataSet, name, handle, type from Admin_Dimensions;"); stmt.execute("drop table Admin_Dimensions;"); stmt.execute("alter table Admin_Dims rename to Admin_Dimensions;"); stmt.execute("commit;"); releaseWriteLock(); storeSetting(DB_SCHEMA_KEY, "2000"); } catch (SQLException e) { PSLogging.logger.fatal("Could not migrate DB", e); releaseWriteLock(); try { stmt.execute("rollback;"); } catch (SQLException e1) { PSLogging.logger.fatal("Could not roll back changes", e); } } finally { if (stmt != null) try { stmt.close(); } catch (SQLException e) { PSLogging.logger.error("Error closing DB statement.", e); } } } }
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import ca.sfu.cmpt431.facility.Board; import ca.sfu.cmpt431.facility.BoardOperation; import ca.sfu.cmpt431.facility.Comrade; import ca.sfu.cmpt431.facility.Outfits; import ca.sfu.cmpt431.message.Message; import ca.sfu.cmpt431.message.MessageCodeDictionary; import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; import ca.sfu.cmpt431.message.join.JoinRequestMsg; import ca.sfu.cmpt431.message.join.JoinSplitMsg; import ca.sfu.cmpt431.message.leave.LeaveReceiverMsg; import ca.sfu.cmpt431.message.merge.MergeLastMsg; import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; import ca.sfu.cmpt431.message.regular.RegularNextClockMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private ArrayList<Integer> toLeave = new ArrayList<Integer>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; private int phase; private static final int COMPUTE = 0; private static final int ADD = 1; private static final int LEAVE = 2; /* UI widgets */ MainFrame frame = null; InformationPanel infoPanel = null; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { Board b = BoardOperation.LoadFile("Patterns/HerschelLoop.lg"); System.out.println("UI"); frame = new MainFrame(b, 800, 800); infoPanel = new InformationPanel(); MessageWithIp m; int result = -1; while(true) { if(!Receiver.isEmpty()) { m = Receiver.getNextMessageWithIp(); switch(status) { //waiting for first client case 0: handleNewAddingLeaving(m,1); handlePending(); //send it the outfit regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAddingLeaving(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg if(!newClientSender.isEmpty()){ handlePending(); status = 2; break; } if(waiting4confirm == 0){ //send you a start System.out.println("sending start"); infoPanel.setCycleNum(frame.automataPanel.getCycle()); for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; phase = COMPUTE; } break; //waiting for the client to send the result back //handle new adding or //restart next cycle case 3: if(handleNewAddingLeaving(m,3)) break; if(phase == COMPUTE){ handleNewBoardInfo(m,b,3); if(waiting4confirm!=0){ break; } // Thread.sleep(50); frame.repaint(); infoPanel.setCellNum(frame.automataPanel.getCell()); infoPanel.setLifeNum(frame.automataPanel.getAlive()); infoPanel.setTargetNum("localhost"); phase = LEAVE; // BoardOperation.Print(b); System.out.println("repaint"); } if(phase == LEAVE){ //deal with the confirm //manage the heap if(((Message)m.extracMessage()).getMessageCode()==MessageCodeDictionary.REGULAR_CONFIRM){ // System.out.println("result:"+result); if(result == 1){ int s = regedClientSender.size(); // System.out.println(regedClientSender.get(s-2).id); regedClientSender.get(s-1).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(s-1).sender.close(); regedClientSender.remove(s-1); Comrade c = regedClientSender.get(s-2); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 2){ int s = regedClientSender.size(); // System.out.println(regedClientSender.get(s-2).id); //you can leave now regedClientSender.get(s-2).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); Comrade c = regedClientSender.get(s-1); regedClientSender.remove(s-1); regedClientSender.get(s-2).sender.close(); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 3){ int cid = toLeave.get(0); int index = findClient(cid); int s = regedClientSender.size(); int new_cid = regedClientSender.get(s-1).id; int new_port = regedClientSender.get(s-1).port; String new_ip = regedClientSender.get(s-1).ip; //send your outfit to the last node regedClientSender.get(index).sender.sendMsg(new LeaveReceiverMsg(new_cid, new_port, new_ip)); regedClientSender.get(index).sender.close(); regedClientSender.set(index, regedClientSender.get(s-1)); regedClientSender.remove(s-1); Comrade c = regedClientSender.get(s-2); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 0){ //get the confirm //nothing to do } else{ //error System.out.println("error."); } toLeave.remove(0); } infoPanel.setClientNum(regedClientSender.size()); if((result=handleLeaving())!=-1){ //4, no client now, go to status 0 pls if(result == 4){ toLeave.remove(0); System.out.println("go to status 0"); status = 0; } else{ //wait for a confirm status = 3; } } if(toLeave.isEmpty() && status != 0) phase = ADD; else break; } //handle adding if(handlePending()){ status = 2; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } System.out.println("sending start"); infoPanel.setCycleNum(frame.automataPanel.getCycle()); phase = COMPUTE; } break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAddingLeaving(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding a new client to pending list"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } else if(msg.getMessageCode()==MessageCodeDictionary.REGULAR_BOARD_RETURN){ RegularBoardReturnMsg r = (RegularBoardReturnMsg)msg; if(r.isLeaving){ toLeave.add(msg.getClientId()); System.out.println("client " + toLeave.get(toLeave.size()-1) + " want to leave, pending now"); return false; } } return false; } protected int handleLeaving() throws IOException{ if(toLeave.isEmpty()) return -1; int cid = toLeave.get(0); if(newClientSender.size()!=0){ //ask a new client to replace it immediately //TODO regedClientSender.get(findClient(cid)).sender.sendMsg(new LeaveReceiverMsg(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp)); regedClientSender.get(findClient(cid)).sender.close(); regedClientSender.set(findClient(cid), new Comrade(regedClientSender.size(), newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); newClientSender.remove(0); System.out.println("new adding, replace"); //confirm return 0; } else if(regedClientSender.size()==1){ //there is only one client and no adding //ask him to leave directly regedClientSender.get(0).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(findClient(cid)).sender.close(); regedClientSender.remove(findClient(cid)); System.out.println("only one client, leave directly"); //no confirm, everything done, but you need to wait for a client to start return 4; } else if(isLastPair(cid)!=-1){ //it is the last node, or the pair of last node //ask the last pair merge int s = regedClientSender.size(); int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; System.out.println("pair index:"+pair_index); if(pair_index!=-1 && isLastPair(regedClientSender.get(pair_index).id)!=-1) pair_index = -1; //you pair can not be your neighbour, occurs when there is 2 clients System.out.println("pair index:"+pair_index); int pair_cid = -1; String pair_ip = ""; int pair_port = -1; if(pair_index!=-1){ pair_cid = regedClientSender.get(pair_index).id; pair_ip = regedClientSender.get(pair_index).ip; pair_port = regedClientSender.get(pair_index).port; } System.out.println("last pair handle pending:"+pair_cid+","+cid); regedClientSender.get(regedClientSender.size()-1-isLastPair(cid)).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); //wait for a confirm, still need a LeaveReceiverMsg return isLastPair(cid)+1; //1 if last or 2 if second last } else{ //ask the last node merge first,give it a new pair id //ask the last node to replace int s = regedClientSender.size(); int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; int pair_cid = -1; String pair_ip = ""; int pair_port = -1; if(pair_index!=-1){ pair_cid = regedClientSender.get(pair_index).id; pair_ip = regedClientSender.get(pair_index).ip; pair_port = regedClientSender.get(pair_index).port; } System.out.println("normal merge handle pending(p/u):"+pair_cid+","+cid); regedClientSender.get(regedClientSender.size()-1).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); //wait for a confirm, still need a LeaveReceiverMsg return 3; } } private int findClient(int cid){ for(int i=0; i<regedClientSender.size(); i++){ if(regedClientSender.get(i).id == cid){ return i; } } return -1; } private int isLastPair(int cid){ int s = regedClientSender.size(); if(regedClientSender.get(s-1).id == cid) return 0; else if(regedClientSender.get(s-2).id == cid) return 1; else return -1; } //deal with the pending adding request //manage the heap protected boolean handlePending() throws IOException{ //you can add at most N new clients in a cycle, N is the number of all clients existing before if(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level //c is the pair int mode; if((((int)(Math.log(2*cid+1)/Math.log(2)))%2)!=0) mode = MessageCodeDictionary.SPLIT_MODE_HORIZONTAL; else mode = MessageCodeDictionary.SPLIT_MODE_VERTICAL; // System.out.println(cid); // System.out.println((Math.log(2*cid+1)/Math.log(2))%2); // System.out.println("mode"+mode); System.out.println("Sending a split command to "+ c.id+", new client id: "+cid+", split mode: "+(mode==0?"vertical":"horizontal")); // System.out.println("send JoinSplitMsg"); // System.out.println(newClientSender.get(0).hostIp); c.sender.sendMsg(new JoinSplitMsg(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, mode)); regedClientSender.remove(0); regedClientSender.add(c); regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); waiting4confirm++; } else{ regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); //regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); } //remove the pending one newClientSender.remove(0); System.out.println("register a new client"); infoPanel.setClientNum(regedClientSender.size()); return true; } return false; } protected void handleNewBoardInfo(MessageWithIp m, Board b, int nextStatus){ waiting4confirm // System.out.println("getting a result"); if(waiting4confirm==0) status = nextStatus; RegularBoardReturnMsg r = (RegularBoardReturnMsg)m.extracMessage(); BoardOperation.Merge(b, r.board, r.top, r.left); // b = (Board)m.extracMessage(); } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm // System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
import javax.crypto.SecretKey; import javax.crypto.KeyGenerator; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.KeyStoreException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import javax.crypto.Cipher; import java.io.FileReader; import java.io.FileWriter; import java.util.Properties; public class EncryptFiles { public static void main(String[] args) throws NoSuchAlgorithmException, IOException, CertificateException, KeyStoreException, GeneralSecurityException { FileReader propertyFile = new FileReader(args[0]); Properties p1 = new Properties(); p1.load(propertyFile); EncryptFiles encFiles = new EncryptFiles(); encFiles.setKeyAlias(p1.getProperty("sli.encryption.keyAlias")); encFiles.setKeyLocation(p1.getProperty("sli.encryption.keyLocation")); encFiles.setKeyStorePass(p1.getProperty("sli.encryption.keyStorePass")); encFiles.setPropertyFileLocation(p1 .getProperty("sli.encryption.properties.files.location")); encFiles.setPropertyFiles(p1 .getProperty("sli.encryption.properties.files")); encFiles.init(); } /* * Generate Key and Encrypt property files */ public void init() throws NoSuchAlgorithmException, IOException, CertificateException, KeyStoreException, GeneralSecurityException { try { loadKeyStore(); System.out.println("Loading Key File..."); System.out.println("Begining Encryption of Files..."); boolean filesEncrypted = encryptFiles(); if (!filesEncrypted) { System.out.println("No Files found for Encryption..."); } else { System.out.println("Completed Encryption of Files..."); } } catch (FileNotFoundException fne) { System.out .println("Could not load specified keystore file exiting..."); } catch (NullPointerException npe) { System.out .println("Check key.properties, and ensure all property key has values..."); } } protected void loadKeyStore() throws NoSuchAlgorithmException, IOException, CertificateException, KeyStoreException { // Initalise KeyStore with password password = new KeyStore.PasswordProtection(getKeyStorePass() .toCharArray()); File keyfile = new File(getKeyLocation()); if (getKeyLocation() != null && !"".equals(getKeyLocation()) && getKeyAlias() != null && !"".equals(getKeyAlias()) && getKeyStorePass() != null && !"".equals(getKeyStorePass()) && getPropertyFileLocation() != null && !"".equals(getPropertyFileLocation()) && getPropertyFiles() != null && !"".equals(getPropertyFiles())) { // Check if the keystore file exists. if (keyfile.exists()) { // Load Keystore if the keystore file exists FileInputStream fis = new FileInputStream(getKeyLocation()); ks = KeyStore.getInstance("JCEKS"); ks.load(fis, getKeyStorePass().toCharArray()); fis.close(); } else { throw new FileNotFoundException(); } } else { throw new NullPointerException(); } } /* * Method:saveKey(String alias, SecretKey mykey) Save a key with alias * "alias" and key "mykey". */ protected void saveKey(String alias, SecretKey mykey) throws KeyStoreException { KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(mykey); ks.setEntry(alias, skEntry, password); } /* * Method:storekey() Write the key entry to the keystore file. */ protected void storekey() throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException { java.io.FileOutputStream fos = new java.io.FileOutputStream( getKeyLocation()); ks.store(fos, getKeyStorePass().toCharArray()); fos.close(); } protected boolean encryptFiles() throws NoSuchAlgorithmException, IOException, CertificateException, KeyStoreException, GeneralSecurityException { // Load the KeyStore object if the file exists FileInputStream fis = new FileInputStream(getKeyLocation()); ks = KeyStore.getInstance("JCEKS"); ks.load(fis, getKeyStorePass().toCharArray()); fis.close(); String propertyFiles[] = getPropertyFiles().split(","); System.out.println("property files list is ..." + propertyFiles[0]); if (propertyFiles.length >= 1 && propertyFiles[0] != null && !"".equals(propertyFiles[0])) { for (int i = 0; i < propertyFiles.length; i++) { try{ FileReader propertyFile = new FileReader( getPropertyFileLocation() + "/" + propertyFiles[i]); FileWriter encryptedPropertyFile = new FileWriter( getPropertyFileLocation() + "/" + propertyFiles[i] + ".encrypted"); Properties p1 = new Properties(); p1.load(propertyFile); String apiClient = p1.getProperty("api.client"); String apiServerUrl = p1.getProperty("api.server.url"); String securityServerUrl = p1 .getProperty("security.server.url"); String oauthClientId = p1.getProperty("oauth.client.id"); String oauthClientSecret = p1 .getProperty("oauth.client.secret"); String oauthRedirect = p1.getProperty("oauth.redirect"); String encryptedClientId = encrypt(oauthClientId); String encryptedClientSecret = encrypt(oauthClientSecret); /* * System.out.println("encrypted text is...." + * encryptedClientId); * System.out.println("encrypted text is...." + * encryptedClientSecret); */ Properties p2 = new Properties(); p2.put("api.client", apiClient); p2.put("api.server.url", apiServerUrl); p2.put("security.server.url", securityServerUrl); p2.put("oauth.client.id", encryptedClientId); p2.put("oauth.client.secret", encryptedClientSecret); p2.put("oauth.redirect", oauthRedirect); p2.store(encryptedPropertyFile, ""); System.out.println("Encrypted [" + propertyFiles[i] + "] to [" + propertyFiles[i] + ".encrypted" + "]"); }catch(Exception e){ e.printStackTrace(); } } return true; } else { return false; } } /* * Method:getkey(String alias) Get key from keystore with the given alias */ public Key getkey(String alias) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException { Key k = ks.getKey(alias, getKeyStorePass().toCharArray()); return k; } public String encrypt(String value) throws GeneralSecurityException, IOException { // get key Key mykey = getkey(getKeyAlias()); // Create a cipher object and use the generated key to initialize it Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, mykey); byte[] encrypted = cipher.doFinal(value.getBytes()); return byteArrayToHexString(encrypted); } public String decrypt(String message) throws GeneralSecurityException, IOException { // get key Key mykey = getkey(getKeyAlias()); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, mykey); byte[] decrypted = cipher.doFinal(hexStringToByteArray(message)); return new String(decrypted); } private static String byteArrayToHexString(byte[] b) { StringBuffer sb = new StringBuffer(b.length * 2); for (int i = 0; i < b.length; i++) { int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toUpperCase(); } private static byte[] hexStringToByteArray(String s) { byte[] b = new byte[s.length() / 2]; for (int i = 0; i < b.length; i++) { int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte) v; } return b; } public String getKeyStorePass() { return keyStorePass; } public void setKeyStorePass(String keyStorePass) { this.keyStorePass = keyStorePass; } public String getKeyAlias() { return keyAlias; } public void setKeyAlias(String keyAlias) { this.keyAlias = keyAlias; } public String getKeyLocation() { return keyLocation; } public void setKeyLocation(String keyLocation) { this.keyLocation = keyLocation; } public String getPropertyFileLocation() { return propertyFileLocation; } public void setPropertyFileLocation(String propertyFileLocation) { this.propertyFileLocation = propertyFileLocation; } public String getPropertyFiles() { return propertyFiles; } public void setPropertyFiles(String propertyFiles) { this.propertyFiles = propertyFiles; } private String propertyFileLocation; private String propertyFiles; private String keyStorePass; private String keyAlias; private String keyLocation; KeyStore ks; KeyStore.PasswordProtection password; }
package avis; import avis.models.*; import exception.*; import java.util.HashMap; import java.util.LinkedList; public class SocialNetwork { private LinkedList<Item> items; // private LinkedList<Member> members; private HashMap<String, Member> members; /** * Initialise un <i>SocialNetwok</i>. */ public SocialNetwork() { this.items = new LinkedList<Item>(); this.members = new HashMap<String, Member>(); } /** * Obtenir le nombre de membres du <i>SocialNetwork</i>. * * @return le nombre de membres. */ public int nbMembers() { return members.size(); } /** * Obtenir le nombre de films du <i>SocialNetwork</i>. * * @return le nombre de films. */ public int nbFilms() { return countItems(Film.class); } /** * Obtenir le nombre de livres du <i>SocialNetwork</i>. * * @return le nombre de livres. */ public int nbBooks() { return countItems(Book.class); } public void addMember(String pseudo, String password, String profil) throws BadEntry, MemberAlreadyExists { Member m = new Member(pseudo, password, profil); String genericPseudo = pseudo.trim().toLowerCase(); if (members.containsKey(genericPseudo)) { throw new MemberAlreadyExists(); } this.members.put(genericPseudo, m); } public void addItemFilm(String pseudo, String password, String titre, String genre, String realisateur, String scenariste, int duree) throws BadEntry, NotMember, ItemFilmAlreadyExists { findMatchingMember(pseudo, password); Film film = new Film(titre, genre, realisateur, scenariste, duree); for (Item item : items) { if (item.getTitle().trim().toLowerCase().equals(titre.trim().toLowerCase()) && item instanceof Film) { throw new ItemFilmAlreadyExists(); } } this.items.add(film); } public void addItemBook(String pseudo, String password, String titre, String genre, String auteur, int nbPages) throws BadEntry, NotMember, ItemBookAlreadyExists { findMatchingMember(pseudo, password); Book book = new Book(titre, genre, auteur, nbPages); for (Item item : items) { if (item.getTitle().trim().toLowerCase().equals(titre.trim().toLowerCase()) && item instanceof Book) { throw new ItemBookAlreadyExists(); } } this.items.add(book); } public LinkedList<String> consultItems(String nom) throws BadEntry { if (!Item.titleIsValid(nom)) { throw new BadEntry("Title does not meet the requirements."); } LinkedList<String> itemsStrings = new LinkedList<String>(); for (Item item : items) { if (item.getTitle().trim().toLowerCase().equals(nom.trim().toLowerCase())) { itemsStrings.add(item.toString()); } } return itemsStrings; } public float reviewItemFilm(String pseudo, String password, String titre, float note, String commentaire) throws BadEntry, NotMember, NotItem { return reviewItem(Film.class, pseudo, password, titre, note, commentaire); } public float reviewItemBook(String pseudo, String password, String titre, float note, String commentaire) throws BadEntry, NotMember, NotItem { return reviewItem(Book.class, pseudo, password, titre, note, commentaire); } private float reviewItem(Class<?> klass, String pseudo, String password, String titre, float note, String commentaire) throws BadEntry, NotMember, NotItem { Item item = findMatchingItem(klass, titre); Member member = findMatchingMember(pseudo, password); Review review = member.findReview(klass, titre); if (review == null) { review = new Review(item, member, commentaire, note); member.addReview(review); item.addReview(review); } else { review.update(commentaire, note); } return item.getRating(); } private Item findMatchingItem(Class<?> klass, String title) throws NotItem, BadEntry { Item item = null; if (!Item.titleIsValid(title)) { throw new BadEntry("Item title does not meet the requirements."); } for (Item it : items) { if ((it.getTitle().trim().toLowerCase().equals(title.trim().toLowerCase())) && (klass.isInstance(it))) { item = it; break; } } if (item == null) { throw new NotItem("Item not found."); } return item; } private Member findMatchingMember(String pseudo, String password) throws NotMember, BadEntry { if (!(Member.pseudoIsValid(pseudo) && Member.passwordIsValid(password))) { throw new BadEntry("Pseudo and/or password does not meet the requirements."); } Member member = null; if ((member = members.get(pseudo.trim().toLowerCase())) != null) { if (!member.checkCredentials(pseudo, password)) { throw new NotMember("Invalid credentials."); } } else { throw new NotMember("Invalid credentials."); } return member; } private int countItems(Class<?> klass) { int count = 0; for (Item item : items) { if (klass.isInstance(item)) { count++; } } return count; } public String toString() { String output = ""; output += "SocialNetwork" + "\n"; output += nbMembers() + " members" + "\n"; output += nbBooks() + " books" + "\n"; output += nbFilms() + " films" + "\n"; return output; } }
package edu.teco.dnd.network; import io.netty.bootstrap.ChannelFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.DatagramChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.AttributeKey; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.GenericFutureListener; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.nio.charset.Charset; import java.util.AbstractMap; import java.util.AbstractMap.SimpleEntry; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import edu.teco.dnd.eclipse.Activator; import edu.teco.dnd.eclipse.prefs.PreferencesNetwork; import edu.teco.dnd.network.codecs.DatagramPacketWrapper; import edu.teco.dnd.network.codecs.GsonCodec; import edu.teco.dnd.network.codecs.MessageAdapter; import edu.teco.dnd.network.messages.BeaconMessage; import edu.teco.dnd.network.messages.BeaconMessageDeserializer; import edu.teco.dnd.network.messages.Message; import edu.teco.dnd.util.InetSocketAddressAdapter; public class UDPMulticastBeacon { /** * The logger for this class. */ private static final Logger LOGGER = LogManager.getLogger(UDPMulticastBeacon.class); /** * The default interval to send beacons at. */ public static final long DEFAULT_INTERVAL = 5; /** * The unit for {@link #DEFAULT_INTERVAL}. */ public static final TimeUnit DEFAULT_INTERVAL_UNIT = TimeUnit.SECONDS; /** * The Charset that will be used. */ public static final Charset CHARSET = Charset.forName("UTF-8"); /** * Factory for new channels. */ private final UDPMulticastChannelFactory channelFactory; /** * Stores all channels that are used for sending and receiving multicasts. Maps from interface and multicast address * to channel. */ private final Map<Entry<NetworkInterface, InetSocketAddress>, DatagramChannel> channels = new HashMap<Map.Entry<NetworkInterface, InetSocketAddress>, DatagramChannel>(); /** * Is set to true if the beacon should shut down. */ private boolean shutdown = false; /** * Lock used for synchronizing access to {@link #channels} and {@link #shutdown}. */ private final ReadWriteLock channelLock = new ReentrantReadWriteLock(); private final Condition shutdownCondition = channelLock.writeLock().newCondition(); private final Future<Void> shutdownFuture = new ShutdownFuture(); /** * The listeners that will be informed when a beacon is received. */ private final Set<BeaconListener> listeners = new HashSet<BeaconListener>(); /** * Lock used for synchronizing access to {@link #listeners}. */ private final ReadWriteLock listenersLock = new ReentrantReadWriteLock(); /** * The beacon to send. */ private final AtomicReference<BeaconMessage> beacon; /** * Creates a new UDPMulticastBeacon. * * @param factory * a ChannelFactory * @param group * the EventLoopGroup to use for channels and the timer * @param executor * the executor for application code and a timer for regularly sending the beacon * @param uuid * the UUID to announce * @param interval * the interval at which to send beacons * @param unit * the unit for interval */ public UDPMulticastBeacon(final ChannelFactory<? extends DatagramChannel> factory, final EventLoopGroup group, final EventExecutorGroup executor, final UUID uuid, final long interval, final TimeUnit unit) { beacon = new AtomicReference<BeaconMessage>(new BeaconMessage(uuid, Collections.<InetSocketAddress> emptyList())); executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { sendBeacon(); } }, 0, interval, unit); final MessageAdapter messageAdapter = new MessageAdapter(); messageAdapter.addMessageType(BeaconMessage.class); final GsonCodec gsonCodec = new GsonCodec(Message.class); gsonCodec.registerTypeAdapter(Message.class, messageAdapter); gsonCodec.registerTypeAdapter(InetSocketAddress.class, new InetSocketAddressAdapter()); gsonCodec.registerTypeAdapter(BeaconMessage.class, new BeaconMessageDeserializer()); this.channelFactory = new UDPMulticastChannelFactory(factory, group, new ChannelInitializer<DatagramChannel>() { private final DatagramPacketWrapper datagramPacketWrapper = new DatagramPacketWrapper(); private final StringEncoder stringEncoder = new StringEncoder(); private final StringDecoder stringDecoder = new StringDecoder(); private final ChannelHandler beaconHandler = new BeaconHandler(); @Override protected void initChannel(final DatagramChannel channel) { channel.pipeline().addLast(datagramPacketWrapper).addLast(stringEncoder).addLast(stringDecoder) .addLast(gsonCodec).addLast(executor, beaconHandler); // Move TARGET_ADDRESS from channel context to handler context channel.pipeline().context(DatagramPacketWrapper.class).attr(DatagramPacketWrapper.TARGET_ADDRESS) .set(channel.attr(DatagramPacketWrapper.TARGET_ADDRESS).getAndRemove()); } }); } /** * Creates a new UDPMulticastBeacon. Beacons will be send at intervals defined by the value set in the network * Preferences, the default interval is {@link #DEFAULT_INTERVAL}. The time unit is given by and * {@link #DEFAULT_INTERVAL_UNIT}. * * @param factory * a ChannelFactory * @param group * the EventLoopGroup to use for channels and the timer * @param executor * the executor for application code and a timer for regularly sending the beacon * @param uuid * the UUID to announce */ public UDPMulticastBeacon(final ChannelFactory<? extends DatagramChannel> factory, final EventLoopGroup group, final EventExecutorGroup executor, final UUID uuid) { this(factory, group, executor, uuid, Activator.getDefault().getPreferenceStore() .getInt(PreferencesNetwork.BEACON_INTERVAL), DEFAULT_INTERVAL_UNIT); } /** * Adds an address to the list of multicast addresses that are used to send multicast packages. The first package * will be send as soon as the next timer update is done. * * @param inf * the interface to send with. Must not be null. * @param address * the multicast address to use for sending. Must not be null, must be resolved and must be a multicast * address. */ public void addAddress(final NetworkInterface inf, final InetSocketAddress address) { final Entry<NetworkInterface, InetSocketAddress> key = new AbstractMap.SimpleEntry<NetworkInterface, InetSocketAddress>(inf, address); channelLock.readLock().lock(); try { if (shutdown || channels.containsKey(key)) { return; } } finally { channelLock.readLock().unlock(); } final Map<AttributeKey<?>, Object> attrs = new HashMap<AttributeKey<?>, Object>(); attrs.put(DatagramPacketWrapper.TARGET_ADDRESS, address); ChannelFuture future = null; channelLock.writeLock().lock(); try { if (shutdown || channels.containsKey(key)) { return; } future = channelFactory.bind(inf, address, attrs); channels.put(key, (DatagramChannel) future.channel()); } finally { channelLock.writeLock().unlock(); } future.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { LOGGER.debug("bind {} failed"); future.channel().close(); } } }); future.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { channelLock.writeLock().lock(); try { if (future.channel().equals(channels.get(key))) { channels.remove(key); } } finally { channelLock.writeLock().unlock(); } channelLock.writeLock().lock(); try { shutdownCondition.signalAll(); } finally { channelLock.writeLock().unlock(); } } }); } /** * Adds an address to the list of multicast addresses that are used to send multicast packages. The address will be * used with all interfaces. The first package will be send as soon as the next timer update is done. * * @param address * the multicast address to use for sending. Must not be null, must be resolved and must be a multicast * address. * @throws SocketException * if an I/O error occurs */ public void addAddress(final InetSocketAddress address) throws SocketException { LOGGER.entry(address); channelLock.writeLock().lock(); try { for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces .hasMoreElements();) { final NetworkInterface inf = interfaces.nextElement(); LOGGER.trace("adding address {} for interface {}", address, inf); addAddress(inf, address); } } finally { channelLock.writeLock().unlock(); } LOGGER.exit(); } /** * Removes an address from the list of addresses that should be used. The address will only be removed from the * given interface. If the interface/address combination is not in use nothing is done. * * @param inf * the interface from which the address should be removed * @param address * the address that should be removed */ public void removeAddress(final NetworkInterface inf, final InetSocketAddress address) { LOGGER.entry(inf, address); final Entry<NetworkInterface, InetSocketAddress> key = new SimpleEntry<NetworkInterface, InetSocketAddress>(inf, address); Channel channel = null; channelLock.readLock().lock(); try { channel = channels.get(key); } finally { channelLock.readLock().unlock(); } if (channel != null) { channel.close(); } LOGGER.exit(); } /** * Removes an address from the list of addresses that should be used. The address will be removed from all * interfaces. If the addresses is missing on some interfaces nothing is done for these interfaces. * * @param address * the address that should be removed * @throws SocketException * if an I/O error occurs */ public void removeAddress(final InetSocketAddress address) throws SocketException { LOGGER.entry(address); channelLock.writeLock().lock(); try { for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces .hasMoreElements();) { final NetworkInterface interf = interfaces.nextElement(); LOGGER.trace("removing address {} from {}", address, interf); removeAddress(interf, address); } } finally { channelLock.writeLock().unlock(); } LOGGER.exit(); } /** * Adds a listener. * * @param listener * the listener to add */ public void addListener(final BeaconListener listener) { listenersLock.writeLock().lock(); try { listeners.add(listener); } finally { listenersLock.writeLock().unlock(); } } /** * Removes a listener. If the listener wasn't added before, nothing is done. * * @param listener * the listener to remove */ public void removeListener(final BeaconListener listener) { listenersLock.writeLock().lock(); try { listeners.remove(listener); } finally { listenersLock.writeLock().unlock(); } } /** * Sets the addresses that will be sent with the beacon. * * @param addresses * the addresses to send with the beacon */ public void setAnnounceAddresses(final List<InetSocketAddress> addresses) { final BeaconMessage newBeacon = new BeaconMessage(beacon.get().getUUID(), addresses); LOGGER.debug("doing lazy set on beacon to {}", newBeacon); beacon.lazySet(newBeacon); } /** * Sends a beacon. This will be automatically called at a fixed interval. */ public void sendBeacon() { final BeaconMessage msg = beacon.get(); channelLock.readLock().lock(); try { for (final DatagramChannel channel : channels.values()) { if (channel.isActive()) { LOGGER.trace("trying to send on {}", channel); channel.writeAndFlush(msg).addListener( new GenericFutureListener<io.netty.util.concurrent.Future<Void>>() { @Override public void operationComplete(io.netty.util.concurrent.Future<Void> future) throws Exception { LOGGER.trace(future); } }); } } } finally { channelLock.readLock().unlock(); } } /** * Closes all channels and stops this UDPMulticastBeacon from creating new ones. */ public void shutdown() { LOGGER.entry(); channelLock.readLock().lock(); try { if (shutdown) { LOGGER.exit(); return; } } finally { channelLock.readLock().unlock(); } channelLock.writeLock().lock(); try { shutdown = true; for (final Channel channel : channels.values()) { channel.close(); } } finally { channelLock.writeLock().unlock(); } LOGGER.exit(); } /** * Returns true if this UDPMulticastBeacon is shutting down or has finished shutting down. This is basically whether * or not {@link #shutdown()} has been called. * * @return true if this UDPMulticastBeacon is shutting down or has finished shutting down */ public boolean isShuttingDown() { LOGGER.entry(); channelLock.readLock().lock(); try { LOGGER.exit(shutdown); return shutdown; } finally { channelLock.readLock().unlock(); } } /** * Returns true if this UDPMulticastBeacon has finished shutting down. * * @return true if this UDPMulticastBeacon has finished shutting down */ public boolean isShutDown() { LOGGER.entry(); channelLock.readLock().lock(); try { if (!shutdown) { LOGGER.exit(false); return false; } for (final Channel channel : channels.values()) { if (!channel.closeFuture().isDone()) { LOGGER.exit(false); return false; } } } finally { channelLock.readLock().unlock(); } LOGGER.exit(true); return true; } public Future<Void> getShutdownFuture() { return shutdownFuture; } /** * Handles incoming beacons. * * @param beacon * the beacon that was found */ // TODO: maybe find a way to inform listeners about multiple beacons // maybe queue them and empty the queue at a fixed interval (every second or so) private void handleBeacon(final BeaconMessage beacon) { LOGGER.entry(beacon); if (this.beacon.get().getUUID().equals(beacon.getUUID())) { LOGGER.exit(); return; } listenersLock.readLock().lock(); try { for (final BeaconListener listener : listeners) { listener.beaconFound(beacon); } } finally { listenersLock.readLock().unlock(); } LOGGER.exit(); } @Sharable private class BeaconHandler extends SimpleChannelInboundHandler<BeaconMessage> { @Override public void channelRead0(final ChannelHandlerContext ctx, final BeaconMessage msg) { handleBeacon(msg); } }; private class ShutdownFuture implements Future<Void> { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public Void get() throws InterruptedException { channelLock.writeLock().lock(); try { while (!isDone()) { shutdownCondition.await(); } } finally { channelLock.writeLock().unlock(); } return null; } @Override public Void get(final long timeout, final TimeUnit unit) { throw new UnsupportedOperationException(); } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { channelLock.readLock().lock(); try { if (!shutdown) { return false; } for (final Channel channel : channels.values()) { if (!channel.closeFuture().isDone()) { return false; } } } finally { channelLock.readLock().unlock(); } return true; } } }
package org.ops4j.pax.jdbc.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.maven; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.options.MavenUrlReference; import org.osgi.service.jdbc.DataSourceFactory; public class AbstractJdbcTest { MavenUrlReference karafUrl = maven().groupId("org.apache.karaf").artifactId("apache-karaf") .version("3.0.3").type("tar.gz"); MavenUrlReference paxJdbcRepo() { return maven().groupId("org.ops4j.pax.jdbc") .artifactId("pax-jdbc-features").classifier("features").type("xml") .versionAsInProject(); } protected DataSource createDataSource(DataSourceFactory dsf) throws SQLException { assertNotNull(dsf); Properties props = new Properties(); props.setProperty(DataSourceFactory.JDBC_DATABASE_NAME, "test"); props.setProperty(DataSourceFactory.JDBC_USER, "SA"); props.setProperty(DataSourceFactory.JDBC_PASSWORD, ""); return dsf.createDataSource(props); } protected void checkDataSource(DataSource dataSource) throws SQLException { Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); statement .execute("CREATE TABLE PUBLIC.T1 (col1 INTEGER NOT NULL, col2 CHAR(25), PRIMARY KEY (COL1)) "); statement.executeUpdate("insert into t1 (col1, col2) values(101, 'pax-jdbc-h2')"); ResultSet result = statement.executeQuery("select col1 from t1 where col2 = 'pax-jdbc-h2'"); while (result.next()) { assertEquals(101, result.getInt("col1")); } result.close(); statement.execute("DROP TABLE PUBLIC.T1"); statement.close(); connection.close(); } protected Option karafDefaults() { return composite( //KarafDistributionOption.debugConfiguration("5005", true), karafDistributionConfiguration().frameworkUrl(karafUrl) .unpackDirectory(new File("target/exam")).useDeployFolder(false), configureConsole().ignoreLocalConsole().ignoreRemoteShell(), keepRuntimeFolder() ); } }
package cz.metacentrum.perun.rpc.methods; import java.util.HashMap; import java.util.List; import cz.metacentrum.perun.core.api.*; import cz.metacentrum.perun.core.api.exceptions.PerunException; import cz.metacentrum.perun.rpc.ApiCaller; import cz.metacentrum.perun.rpc.ManagerMethod; import cz.metacentrum.perun.core.api.exceptions.RpcException; import cz.metacentrum.perun.rpc.deserializer.Deserializer; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; public enum UsersManagerMethod implements ManagerMethod { /*# * Returns user based on one of the userExtSource. * * @param userExtSource UserExtSource JSON object UserExtSource * @return User User object */ getUserByUserExtSource { @Override public User call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUserByUserExtSource(ac.getSession(), parms.read("userExtSource", UserExtSource.class)); } }, /*# * Returns user by his login in external source and external source. * * @param extSourceName String Ext source name * @param extLogin String Ext source login * @return User User object */ getUserByExtSourceNameAndExtLogin { @Override public User call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUserByExtSourceNameAndExtLogin(ac.getSession(), parms.readString("extSourceName"), parms.readString("extLogin")); } }, /*# * Returns user by its <code>id</code>. * * @param id int User <code>id</code> * @return User User object */ getUserById { @Override public User call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUserById(parms.readInt("id")); } }, /*# * Returns all users in Perun. * * @return List<User> All Perun users */ getUsers { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUsers(ac.getSession()); } }, /*# * Returns all specific users in Perun. * * @return List<User> All Perun service users */ getSpecificUsers { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getSpecificUsers(ac.getSession()); } }, /*# * Return all specific users who are owned by the user. * * @param user int User <code>id</code> * @return List<User> Specific users for a user */ getSpecificUsersByUser { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getSpecificUsersByUser(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Return all users who owns the specific user. * * @param specificUser int Specific User <code>id</code> * @return List<User> Users for a service user */ getUsersBySpecificUser { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUsersBySpecificUser(ac.getSession(), ac.getUserById(parms.readInt("specificUser"))); } }, /*# * Add specific user owner (the user). * * @param user int User <code>id</code> * @param specificUser int Specific user <code>id</code> */ addSpecificUserOwner { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().addSpecificUserOwner(ac.getSession(), ac.getUserById(parms.readInt("user")), ac.getUserById(parms.readInt("specificUser"))); return null; } }, /*# * Remove specific user owner (the user). * * @param user int User <code>id</code> * @param specificUser int Specific user <code>id</code> */ removeSpecificUserOwner { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().removeSpecificUserOwner(ac.getSession(), ac.getUserById(parms.readInt("user")), ac.getUserById(parms.readInt("specificUser"))); return null; } }, /*# * Get User to RichUser without attributes. * * @param user int user <code>id</code> * @return RichUser found rich user */ getRichUser { @Override public RichUser call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getRichUser(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Get User to RichUser with attributes. * * @param user int user <code>id</code> * @return RichUser found rich user with attributes */ getRichUserWithAttributes { @Override public RichUser call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getRichUserWithAttributes(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Get All richUsers with or without specificUsers. * * @param includedSpecificUsers boolean if you want to or don't want to get specificUsers too * @return List<RichUser> all rich users without attributes */ getAllRichUsers { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getAllRichUsers(ac.getSession(), parms.readBoolean("includedSpecificUsers")); } }, /*# * Get All richUsers with or without specificUsers. * * @param includedSpecificUsers boolean if you want to or don't want to get specificUsers too * @return List<RichUser> all rich users with attributes */ getAllRichUsersWithAttributes { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getAllRichUsersWithAttributes(ac.getSession(), parms.readBoolean("includedSpecificUsers")); } }, /*# * From Users makes RichUsers without attributes. * * @param users List<RichUser> users to convert * @return List<RichUser> list of rich users */ getRichUsersFromListOfUsers { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().getRichUsersFromListOfUsers(ac.getSession(), parms.readList("users", User.class)); } }, /*# * From Users makes RichUsers with attributes. * * @param users List<RichUser> users to convert * @return List<RichUser> list of richUsers */ getRichUsersFromListOfUsersWithAttributes { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().getRichUsersWithAttributesFromListOfUsers(ac.getSession(), parms.readList("users", User.class)); } }, /*# * Returns all RichUsers with attributes who are not member of any VO. * * @return List<RichUser> list of richUsers who are not member of any VO */ getRichUsersWithoutVoAssigned { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getRichUsersWithoutVoAssigned(ac.getSession()); } }, /*# * Get All richUsers with or without specificuSers with selected attributes. * * @param attrsNames List<String> list of attributes name * @param includedSpecificUsers boolean if you want to or don't want to get specificUsers too * @return List<RichUser> list of RichUsers */ /*# * Get All richUsers with or without specificUsers with all included attributes. * * @param includedSpecificUsers boolean if you want to or don't want to get specificUsers too * @return List<RichUser> list of RichUsers */ getRichUsersWithAttributes { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("attrsNames")) { return ac.getUsersManager().getAllRichUsersWithAttributes(ac.getSession(), parms.readBoolean("includedSpecificUsers"), parms.readList("attrsNames", String.class)); } else { return ac.getUsersManager().getAllRichUsersWithAttributes(ac.getSession(), parms.readBoolean("includedSpecificUsers"), null); } } }, /*# * Returns list of RichUsers with attributes who matches the searchString * * @param searchString String searched string * @param attrNames List<String> list of attributes name * @return List<RichUser> list of RichUsers */ findRichUsersWithAttributes { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("attrsNames")) { return ac.getUsersManager().findRichUsersWithAttributes(ac.getSession(), parms.readString("searchString"), parms.readList("attrsNames", String.class)); } else { return ac.getUsersManager().findRichUsersWithAttributes(ac.getSession(), parms.readString("searchString"), null); } } }, /*# * Returns list of RichUsers which are not members of any VO and with selected attributes * * @param attrNames List<String> list of attributes name * @return List<RichUser> list of RichUsers */ getRichUsersWithoutVoWithAttributes { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("attrsNames")) { return ac.getUsersManager().getRichUsersWithoutVoWithAttributes(ac.getSession(), parms.readList("attrsNames", String.class)); } else { return ac.getUsersManager().getRichUsersWithoutVoWithAttributes(ac.getSession(), null); } } }, /*# * Return list of RichUsers who matches the searchString and are not member in specific VO and with selected attributes. * * @param vo VO virtual organization * @param searchString String searched string * @param attrsName List<String> list of attributes name * @return List<RichUser> list of RichUsers */ findRichUsersWithoutSpecificVoWithAttributes { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("attrsNames")) { return ac.getUsersManager().findRichUsersWithoutSpecificVoWithAttributes(ac.getSession(), ac.getVoById(parms.readInt("vo")), parms.readString("searchString"), parms.readList("attrsNames", String.class)); } else { return ac.getUsersManager().findRichUsersWithoutSpecificVoWithAttributes(ac.getSession(), ac.getVoById(parms.readInt("vo")), parms.readString("searchString"), null); } } }, /*# * Deletes a user. User is not deleted, if is member of any VO or is associated with any service identity. * * @param user int User <code>id</code> */ /*# * Deletes a user (force). * Also removes associated members. * * @param user int User <code>id</code> * @param force boolean If true, use force deletion. */ deleteUser { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("force") && parms.readBoolean("force")) { ac.getUsersManager().deleteUser(ac.getSession(), ac.getUserById(parms.readInt("user")), true); } else { ac.getUsersManager().deleteUser(ac.getSession(), ac.getUserById(parms.readInt("user"))); } return null; } }, /*# * Updates users data in DB. * * @param user User JSON object * @return User Updated user */ updateUser { @Override public User call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().updateUser(ac.getSession(), parms.read("user", User.class)); } }, /*# * Updates titles before/after users name * * Titles must be set in User object. * Setting any title to null will remove title from name. * Other user's properties are ignored. * * @param user User JSON object with titles to set * @return User Updated user */ updateNameTitles { @Override public User call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().updateNameTitles(ac.getSession(), parms.read("user", User.class)); } }, /*# * Updates user's userExtSource in DB. * * @param userExtSource UserExtSource JSON object * @return UserExtSource Updated userExtSource */ updateUserExtSource { @Override public UserExtSource call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().updateUserExtSource(ac.getSession(), parms.read("userExtSource", UserExtSource.class)); } }, /*# * Gets list of all user's external sources of the user. * * @param user int User <code>id</code> * @return List<UserExtSource> list of user's external sources */ getUserExtSources { @Override public List<UserExtSource> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUserExtSources(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Adds user's external sources. * @param user int User <code>id</code> * @param userExtSource UserExtSource JSON object * @return UserExtSource Newly added UserExtSource */ addUserExtSource { @Override public UserExtSource call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().addUserExtSource(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.read("userExtSource", UserExtSource.class)); } }, /*# * Remove user's external sources. * @param user int User <code>id</code> * @param userExtSource int UserExtSource <code>id</code> */ removeUserExtSource { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().removeUserExtSource(ac.getSession(), ac.getUserById(parms.readInt("user")), ac.getUserExtSourceById(parms.readInt("userExtSource"))); return null; } }, /*# * Get the user ext source by its id. * * @param userExtSource int UserExtSource <code>id</code> * @return UserExtSource User external source for the id */ getUserExtSourceById { @Override public UserExtSource call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUserExtSourceById(ac.getSession(), parms.readInt("userExtSource")); } }, /*# * Gets user's external source by the user's external login and external source. * * @param extSource ExtSource JSON object * @param extSourceLogin String Login * @return UserExtSource UserExtSource found user's external source */ getUserExtSourceByExtLogin { @Override public UserExtSource call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUserExtSourceByExtLogin(ac.getSession(), parms.read("extSource", ExtSource.class), parms.readString("extSourceLogin")); } }, /*# * Returns user by VO member. * * @param member int Member <code>id</code> * @return User User object */ getUserByMember { @Override public User call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUserByMember(ac.getSession(), ac.getMemberById(parms.readInt("member"))); } }, /*# * Returns list of users who matches the searchString, searching name, email, logins. * * @param searchString String String to search by * @return List<User> Found users */ findUsers { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().findUsers(ac.getSession(), parms.readString("searchString")); } }, /*# * Returns list of RichUsers with attributes who matches the searchString, searching name, email, logins. * * @param searchString String searched string * @return List<RichUser> list of RichUsers */ findRichUsers { @Override public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().findRichUsers(ac.getSession(), parms.readString("searchString")); } }, /*# * Return list of users who matches the searchString, searching name, email and logins * and are not member of specific VO. * * @param vo int VO <code>id</code> * @param searchString String String to search by * @return List<User> Found users */ getUsersWithoutSpecificVo { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUsersWithoutSpecificVo(ac.getSession(), ac.getVoById(parms.readInt("vo")), parms.readString("searchString")); } }, /*# * Returns list of users who matches the searchString. * * @param searchString String String to search by * @return List<User> Found users */ /*# * Returns list of users who matches the parameters. * All parameters must be present, even if empty. * * @param titleBefore String Title before name * @param firstName String First name * @param middleName String Middle name * @param lastName String Last name * @param titleAfter String Title after * @return List<User> Found users */ findUsersByName { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("searchString")) { return ac.getUsersManager().findUsersByName(ac.getSession(), parms.readString("searchString")); } else if (parms.contains("titleBefore") && parms.contains("firstName") && parms.contains("middleName") && parms.contains("lastName") && parms.contains("titleAfter")) { return ac.getUsersManager().findUsersByName(ac.getSession(), parms.readString("titleBefore"), parms.readString("firstName"), parms.readString("middleName"), parms.readString("lastName"), parms.readString("titleAfter")); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "searchString or (titleBefore and firstName and middleName and lastName and titleAfter)"); } } }, /*# * Returns all users who have set the attribute with the value. Searching only def and opt attributes. * * @param attribute Attribute JSON object * @return List<User> Found users */ /*# * Returns all users who have set the attribute with the value. Searching only def and opt attributes. * * @param attributeName String URN of attribute to search by * @param attributeValue Object Value to search by (type of value must match attribute value type) * @return List<User> Found users */ getUsersByAttribute { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("attributeName")) { if (parms.contains("attributeValue")) { String attributeName = parms.readString("attributeName"); Attribute attr = new Attribute(ac.getAttributesManager().getAttributeDefinition(ac.getSession(), attributeName)); if(attr.getType().equals(Integer.class.getName())) { attr.setValue(parms.readInt("attributeValue")); } else if(attr.getType().equals(String.class.getName())) { attr.setValue(parms.readString("attributeValue")); } else if(attr.getType().equals(Boolean.class.getName())) { attr.setValue(parms.readBoolean("attributeValue")); } else if(attr.getType().equals(ArrayList.class.getName())) { attr.setValue(parms.readList("attributeValue", String.class)); } else if(attr.getType().equals(LinkedHashMap.class.getName())) { attr.setValue(parms.read("attributeValue", LinkedHashMap.class)); } else { throw new RpcException(RpcException.Type.CANNOT_DESERIALIZE_VALUE, "attributeValue is not the same type like value of attribute with the attributeName."); } return ac.getUsersManager().getUsersByAttribute(ac.getSession(),attr); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "attributeValue"); } } else if (parms.contains("attribute")) { return ac.getUsersManager().getUsersByAttribute(ac.getSession(), parms.read("attribute", Attribute.class)); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "attribute or (attributeName and attributeValue)"); } } }, /*# * Returns all users who have attribute which have value which contains searchString. * * @param attributeName String URN of attribute to search by * @param attributeValue String Value to search by * @return List<User> Found users */ getUsersByAttributeValue { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { if (parms.contains("attributeName")) { if (parms.contains("attributeValue")) { return ac.getUsersManager().getUsersByAttributeValue(ac.getSession(), parms.readString("attributeName"), parms.readString("attributeValue")); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "attributeValue"); } } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "attributeName"); } } }, /*# * Returns list of VOs, where the user is an Administrator. * * @param user int User <code>id</code> * @return List<Vo> Found VOs */ getVosWhereUserIsAdmin { @Override public List<Vo> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getVosWhereUserIsAdmin(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Returns list of VOs, where the user is a Member. * * @param user int User <code>id</code> * @return List<Vo> Found VOs */ getVosWhereUserIsMember { @Override public List<Vo> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getVosWhereUserIsMember(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Returns list of Groups, where the user is an Administrator. * * @param user int User <code>id</code> * @return List<Group> Found Groups */ getGroupsWhereUserIsAdmin { @Override public List<Group> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getGroupsWhereUserIsAdmin(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Get all resources from the facility which have the user access on. * * @param user int User <code>id</code> * @param facility int Facility <code>id</code> * @return List<Resource> Allowed resources */ /*# * Get all resources which have the user access on. * * @param user int User <code>id</code> * @return List<Resource> Allowed resources */ getAllowedResources { @Override public List<Resource> call(ApiCaller ac, Deserializer parms) throws PerunException { User user = ac.getUserById(parms.readInt("user")); if(parms.contains("facility")) { Facility facility = ac.getFacilityById(parms.readInt("facility")); return ac.getUsersManager().getAllowedResources(ac.getSession(), facility, user); } else { return ac.getUsersManager().getAllowedResources(ac.getSession(), user); } } }, /*# * Get all rich resources which have the user assigned. * * @param user int User <code>id</code> * @return List<RichResource> Assigned rich resources */ getAssignedRichResources { @Override public List<RichResource> call(ApiCaller ac, Deserializer parms) throws PerunException { User user = ac.getUserById(parms.readInt("user")); return ac.getUsersManager().getAssignedRichResources(ac.getSession(), user); } }, /*# * Checks if the login is available in the namespace. * * @param loginNamespace String Namespace * @param login String Login * @exampleResponse 1 * @return int 1: login available, 0: login not available */ isLoginAvailable { @Override public Integer call(ApiCaller ac, Deserializer parms) throws PerunException { if (ac.getUsersManager().isLoginAvailable(ac.getSession(), parms.readString("loginNamespace"), parms.readString("login"))) { return 1; } else { return 0; } } }, /*# * Returns all users who are not member of any VO. * * @return List<User> Found users */ getUsersWithoutVoAssigned { @Override public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUsersWithoutVoAssigned(ac.getSession()); } }, /*# * Adds PERUNADMIN role to the user. * * @param user int User <code>id</code> */ makeUserPerunAdmin { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); User user = ac.getUserById(parms.readInt("user")); ac.getUsersManager().makeUserPerunAdmin(ac.getSession(), user); return null; } }, /*# * Changes user password in defined login-namespace. * * @param login String Users login * @param loginNamespace String Namespace * @param newPassword String New password * @param checkOldPassword boolean Must be false */ /*# * Changes user password in defined login-namespace. * You must send the old password, which will be checked * * @param login String Users login * @param loginNamespace String Namespace * @param oldPassword String Old password which will be checked. * @param newPassword String New password * @param checkOldPassword boolean Must be true */ /*# * Changes user password in defined login-namespace. * * @param user int User <code>id</code> * @param loginNamespace String Namespace * @param newPassword String New password * @param checkOldPassword boolean Must be false */ /*# * Changes user password in defined login-namespace. * You must send the old password, which will be checked * * @param user int User <code>id</code> * @param loginNamespace String Namespace * @param oldPassword String Old password which will be checked. * @param newPassword String New password * @param checkOldPassword boolean Must be true */ changePassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("login")) { String login = parms.readString("login"); if (parms.readBoolean("checkOldPassword")) { ac.getUsersManager().changePassword(ac.getSession(), login, parms.readString("loginNamespace"), parms.readString("oldPassword"), parms.readString("newPassword"), true); } else { ac.getUsersManager().changePassword(ac.getSession(), login, parms.readString("loginNamespace"), parms.readString("oldPassword"), parms.readString("newPassword"), false); } } else { User user = ac.getUserById(parms.readInt("user")); if (parms.readBoolean("checkOldPassword")) { ac.getUsersManager().changePassword(ac.getSession(), user, parms.readString("loginNamespace"), parms.readString("oldPassword"), parms.readString("newPassword"), true); } else { ac.getUsersManager().changePassword(ac.getSession(), user, parms.readString("loginNamespace"), parms.readString("oldPassword"), parms.readString("newPassword"), false); } } return null; } }, /*# * Changes user's password in namespace based on encrypted parameters * * @param i String first encrypted parameter * @param m String second encrypted parameter * @param password String new password */ changeNonAuthzPassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().changeNonAuthzPassword(ac.getSession(), parms.readString("i"), parms.readString("m"), parms.readString("password")); return null; } }, /*# * Creates a password in external authz system. * * @param login String Login * @param namespace String Namespace * @param password String password */ @Deprecated createPassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("user")) { ac.getUsersManager().createPassword(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("namespace"), parms.readString("password")); } else { ac.getUsersManager().createPassword(ac.getSession(), parms.readString("login"), parms.readString("namespace"), parms.readString("password")); } return null; } }, /*# * Reserves a random password in external authz system. User shouldn't be able to log-in (account disabled, password unknown to him). * This is usefull when manager create account for others and later send them password reset request. * * @param user int User <code>id</code> * @param namespace String Namespace */ reserveRandomPassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().reserveRandomPassword(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("namespace")); return null; } }, /*# * Reserves password for a user in specified login-namespace. * * @param user int User <code>id</code> * @param namespace String Namespace * @param password String password */ /*# * Reserves password for a user in specified login-namespace. * * @param login String Login * @param namespace String Namespace * @param password String password */ reservePassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("user")) { ac.getUsersManager().reservePassword(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("namespace"), parms.readString("password")); } else { ac.getUsersManager().reservePassword(ac.getSession(), parms.readString("login"), parms.readString("namespace"), parms.readString("password")); } return null; } }, /*# * Validates password for a user in specified login-namespace. After that, user should be able to log-in * in external authz system using his credentials. * * @param user int User <code>id</code> * @param namespace String Namespace */ /*# * Validates password for a user in specified login-namespace. After that, user should be able to log-in * in external authz system using his credentials. * * @param login String Login * @param namespace String Namespace */ validatePassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("user")) { ac.getUsersManager().validatePassword(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("namespace")); } else { ac.getUsersManager().validatePassword(ac.getSession(), parms.readString("login"), parms.readString("namespace")); } return null; } }, /*# * Validates password for a user in specified login-namespace. After that, user should be able to log-in * in external authz system using his credentials. It also creates UserExtSource and sets some required attributes. * * @param user int User <code>id</code> * @param login String Login * @param namespace String Namespace */ validatePasswordAndSetExtSources { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().validatePasswordAndSetExtSources(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("login"), parms.readString("namespace")); return null; } }, /*# * Set new login in namespace if login is available and user doesn't have login in that namespace. * !! Works only for service/guest users => specific users !! * * @param user int User <code>id</code> * @param login String Login * @param namespace String Namespace */ setLogin { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().setLogin(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("namespace"), parms.readString("login")); return null; } }, /*# * Request to change preferred email address of user. * Validation mail is sent on new address. * * Change is not saved until user validate new email address * by calling validatePreferredEmailChange() method with * proper set of parameters (sent in validation mail). * * @param user int User <code>id</code> * @param email String new email address to set */ requestPreferredEmailChange { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); String referer = parms.getServletRequest().getHeader("Referer"); if (referer == null || referer.isEmpty()) { throw new RpcException(RpcException.Type.MISSING_VALUE, "Missing \"Referer\" header in HTTP request. Please check your browser settings."); } ac.getUsersManager().requestPreferredEmailChange(ac.getSession(), referer, ac.getUserById(parms.readInt("user")), parms.readString("email")); return null; } }, /*# * Validate new preferred email address. * * Request to validate is determined based * on encrypted parameters sent in email notice * by requestPreferredEmailChange() method. * * @param i String encrypted request parameter * @param m String encrypted request parameter * @param u int <code>id</code> of user you want to validate preferred email request * * @return String new validated email address */ validatePreferredEmailChange { @Override public String call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().validatePreferredEmailChange(ac.getSession(), ac.getUserById(parms.readInt("u")), parms.readString("i"), parms.readString("m")); } }, /*# * Return list of email addresses of user, which are * awaiting validation and are inside time window * for validation. * * If there is no preferred email change request pending * or requests are outside time window for validation, * returns empty list. * * @param user int <code>id</code> of user to check * * @return List<String> user's email addresses pending validation */ getPendingPreferredEmailChanges { @Override public List<String> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getPendingPreferredEmailChanges(ac.getSession(), ac.getUserById(parms.readInt("user"))); } }, /*# * Gets count of all users. * @return int Users count */ getUsersCount { @Override public Integer call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getUsersManager().getUsersCount(ac.getSession()); } }, /*# * Creates alternative password in external system. * * @param user int Users <code>id</code> * @param description String Description of a password (e.g. 'mobile phone', 'tablet', ...) * @param loginNamespace String Login namespace * @param password String String representation of password */ createAlternativePassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.getUsersManager().createAlternativePassword(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("description"), parms.readString("loginNamespace"), parms.readString("password")); return null; } }, /*# * Deletes alternative password in external system. * * @param user int Users <code>id</code> * @param loginNamespace String Login namespace * @param passwordId String Password <code>id</code> */ deleteAlternativePassword { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.getUsersManager().deleteAlternativePassword(ac.getSession(), ac.getUserById(parms.readInt("user")), parms.readString("loginNamespace"), parms.readString("passwordId")); return null; } }, /*# * Updates user's userExtSource last access time in DB. We can get information which userExtSource has been used as a last one. * * @param userExtSource int UserExtSource <code>id</code> */ updateUserExtSourceLastAccess { @Override public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getUsersManager().updateUserExtSourceLastAccess(ac.getSession(), ac.getUserExtSourceById(parms.readInt("userExtSource"))); return null; } }, /*# * Generate user account in a backend system associated with login-namespace in Perun. * * This method consumes optional parameters map. Requirements are implementation-dependant * for each login-namespace. * * Returns map with * 1: key=login-namespace attribute urn, value=generated login * 2: rest of opt response attributes... * * @param namespace String * @param parameters Map * * @return Map<String, String> Map of data from backed response * @throws InternalErrorException */ generateAccount { @Override public Map<String, String> call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); return ac.getUsersManager().generateAccount(ac.getSession(), parms.readString("namespace"), parms.read("parameters", HashMap.class)); } }; }
package sk.henrichg.phoneprofiles; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlarmManager; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.WallpaperManager; import android.appwidget.AppWidgetManager; import android.bluetooth.BluetoothAdapter; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.PixelFormat; import android.location.LocationManager; import android.media.AudioManager; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Handler; import android.os.PowerManager; import android.provider.Settings; import android.provider.Settings.Global; import android.service.notification.NotificationListenerService; import android.support.v4.app.NotificationCompat; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.Surface; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.RemoteViews; import com.stericson.RootShell.execution.Command; import com.stericson.RootShell.execution.Shell; import com.stericson.RootTools.RootTools; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Calendar; public class ActivateProfileHelper { private Activity activity; private Context context; private NotificationManager notificationManager; private Handler brightnessHandler; private int networkType = -1; public static boolean lockRefresh = false; public static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj"; // Setting.Global "zen_mode" public static final int ZENMODE_ALL = 0; public static final int ZENMODE_PRIORITY = 1; public static final int ZENMODE_NONE = 2; public static final int ZENMODE_ALARMS = 3; public ActivateProfileHelper() { } public void initialize(Activity a, Context c) { initializeNoNotificationManager(a, c); notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); } public void initializeNoNotificationManager(Activity a, Context c) { activity = a; context = c; } public void setBrightnessHandler(Handler handler) { brightnessHandler = handler; } public void deinitialize() { activity = null; context = null; notificationManager = null; } @SuppressWarnings("deprecation") private void doExecuteForRadios(Profile profile) { try { Thread.sleep(300); } catch (InterruptedException e) { System.out.println(e); } // nahodenie network type if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, context) == GlobalData.PREFERENCE_ALLOWED) { if (profile._deviceNetworkType >= 100) { setPreferredNetworkType(context, profile._deviceNetworkType - 100); try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println(e); } } } // nahodenie mobilnych dat if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == GlobalData.PREFERENCE_ALLOWED) { boolean _isMobileData = isMobileData(context); boolean _setMobileData = false; switch (profile._deviceMobileData) { case 1: if (!_isMobileData) { _isMobileData = true; _setMobileData = true; } break; case 2: if (_isMobileData) { _isMobileData = false; _setMobileData = true; } break; case 3: _isMobileData = !_isMobileData; _setMobileData = true; break; } if (_setMobileData) { setMobileData(context, _isMobileData); try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println(e); } } } // nahodenie WiFi AP boolean canChangeWifi = true; if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP, context) == GlobalData.PREFERENCE_ALLOWED) { WifiApManager wifiApManager = null; try { wifiApManager = new WifiApManager(context); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (wifiApManager != null) { boolean setWifiAPState = false; boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled(); switch (profile._deviceWiFiAP) { case 1: if (!isWifiAPEnabled) { isWifiAPEnabled = true; setWifiAPState = true; canChangeWifi = false; } break; case 2: if (isWifiAPEnabled) { isWifiAPEnabled = false; setWifiAPState = true; canChangeWifi = true; } break; case 3: isWifiAPEnabled = !isWifiAPEnabled; setWifiAPState = true; canChangeWifi = !isWifiAPEnabled; break; } if (setWifiAPState) { wifiApManager.setWifiApState(isWifiAPEnabled); try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println(e); } } } } if (canChangeWifi) { // nahodenie WiFi if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_WIFI, context) == GlobalData.PREFERENCE_ALLOWED) { if (!WifiApManager.isWifiAPEnabled(context)) { // only when wifi AP is not enabled, change wifi WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int wifiState = wifiManager.getWifiState(); boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING)); boolean setWifiState = false; switch (profile._deviceWiFi) { case 1: if (!isWifiEnabled) { isWifiEnabled = true; setWifiState = true; } break; case 2: if (isWifiEnabled) { isWifiEnabled = false; setWifiState = true; } break; case 3: isWifiEnabled = !isWifiEnabled; setWifiState = true; break; } if (setWifiState) { try { wifiManager.setWifiEnabled(isWifiEnabled); } catch (Exception e) { // barla pre security exception INTERACT_ACROSS_USERS - chyba ROM wifiManager.setWifiEnabled(isWifiEnabled); } try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println(e); } } } } } // nahodenie bluetooth if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH, context) == GlobalData.PREFERENCE_ALLOWED) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); boolean isBluetoothEnabled = bluetoothAdapter.isEnabled(); boolean setBluetoothState = false; switch (profile._deviceBluetooth) { case 1 : if (!isBluetoothEnabled) { isBluetoothEnabled = true; setBluetoothState = true; } break; case 2 : if (isBluetoothEnabled) { isBluetoothEnabled = false; setBluetoothState = true; } break; case 3 : isBluetoothEnabled = ! isBluetoothEnabled; setBluetoothState = true; break; } if (setBluetoothState) { if (isBluetoothEnabled) bluetoothAdapter.enable(); else bluetoothAdapter.disable(); } } // nahodenie GPS if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_GPS, context) == GlobalData.PREFERENCE_ALLOWED) { boolean isEnabled; if (android.os.Build.VERSION.SDK_INT < 21) isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER); else { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } switch (profile._deviceGPS) { case 1 : setGPS(context, true); break; case 2 : setGPS(context, false); break; case 3 : if (!isEnabled) { setGPS(context, true); } else if (isEnabled) { setGPS(context, false); } break; } } // nahodenie NFC - len v PPHelper } public void executeForRadios(Profile profile) { boolean _isAirplaneMode = false; boolean _setAirplaneMode = false; if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE, context) == GlobalData.PREFERENCE_ALLOWED) { _isAirplaneMode = isAirplaneMode(context); switch (profile._deviceAirplaneMode) { case 1: if (!_isAirplaneMode) { _isAirplaneMode = true; _setAirplaneMode = true; } break; case 2: if (_isAirplaneMode) { _isAirplaneMode = false; _setAirplaneMode = true; } break; case 3: _isAirplaneMode = !_isAirplaneMode; _setAirplaneMode = true; break; } } if (_setAirplaneMode && _isAirplaneMode) // switch ON airplane mode, set it before executeForRadios setAirplaneMode(context, _isAirplaneMode); doExecuteForRadios(profile); if (_setAirplaneMode && !(_isAirplaneMode)) // switch OFF airplane mode, set if after executeForRadios setAirplaneMode(context, _isAirplaneMode); } private void correctVolume0(AudioManager audioManager, int linkUnlink) { int ringerMode, zenMode; if (linkUnlink == PhoneCallService.LINKMODE_NONE) { ringerMode = GlobalData.getRingerMode(context); zenMode = GlobalData.getZenMode(context); } else { ringerMode = GlobalData.getRingerMode(context); zenMode = GlobalData.getZenMode(context); //ringerMode = RingerModeChangeReceiver.getRingerMode(context, audioManager); } if ((ringerMode == 1) || (ringerMode == 2) || (ringerMode == 4) || ((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) { // any "nonVIBRATE" ringer mode is selected if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) { //Log.e("ActivateProfileHelper","correctVolume0 set ring volume=1"); // actual system ringer mode = vibrate // volume changed it to vibrate //RingerModeChangeReceiver.internalChange = true; audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1); } } } @SuppressLint("NewApi") public void setVolumes(Profile profile, AudioManager audioManager, int linkUnlink) { if (profile.getVolumeRingtoneChange()) { if (linkUnlink == PhoneCallService.LINKMODE_NONE) GlobalData.setRingerVolume(context, profile.getVolumeRingtoneValue()); } if (profile.getVolumeNotificationChange()) { if (linkUnlink == PhoneCallService.LINKMODE_NONE) GlobalData.setNotificationVolume(context, profile.getVolumeNotificationValue()); } int ringerMode = GlobalData.getRingerMode(context); int zenMode = GlobalData.getZenMode(context); // for ringer mode VIBRATE or SILENT (and not for link/unlink volumes) or // for interruption types NONE and ONLY_ALARMS // not set system, ringer, npotification volume // (Android 6 - priority mode = ONLY_ALARMS) if (!( (ringerMode == 3) || ((ringerMode == 4) && (android.os.Build.VERSION.SDK_INT < 21)) || ((ringerMode == 4) && (android.os.Build.VERSION.SDK_INT >= 23)) || ((ringerMode == 5) && ((zenMode == 3) || (zenMode == 4) || (zenMode == 5) || (zenMode == 6))) )) { if (linkUnlink == PhoneCallService.LINKMODE_NONE) { if (profile.getVolumeSystemChange()) { audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, profile.getVolumeSystemValue(), 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue()); correctVolume0(/*profile, */audioManager, linkUnlink); } } TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); int callState = telephony.getCallState(); //if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING)) // && (linkUnlink == PhoneCallService.LINKMODE_NONE)) { if (!GlobalData.applicationUnlinkRingerNotificationVolumes) { if (profile.getVolumeRingtoneChange() || profile.getVolumeSystemChange()) { int volume = GlobalData.getRingerVolume(context); if (volume != -999) { audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume); correctVolume0(/*profile, */audioManager, linkUnlink); } } if (profile.getVolumeNotificationChange() || profile.getVolumeSystemChange()) { int volume = GlobalData.getNotificationVolume(context); if (volume != -999) { audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume); correctVolume0(/*profile, */audioManager, linkUnlink); } } } if (GlobalData.applicationUnlinkRingerNotificationVolumes) { boolean doUnlink = audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL; if (android.os.Build.VERSION.SDK_INT >= 21) { int zm = Settings.Global.getInt(context.getContentResolver(), "zen_mode", ZENMODE_ALL); doUnlink = (zm != ZENMODE_NONE) && (zm != ZENMODE_ALARMS); } //Log.e("ActivateProfileHelper", "setVolumes doUnlink=" + doUnlink); //Log.e("ActivateProfileHelper", "setVolumes ringerMode=" + audioManager.getRingerMode()); //Log.e("ActivateProfileHelper", "setVolumes zenMode=" + Settings.Global.getInt(context.getContentResolver(), "zen_mode", ZENMODE_NONE)); if (doUnlink) { if (linkUnlink == PhoneCallService.LINKMODE_UNLINK) { // for separating ringing and notification // in ringing state ringer volumes must by set // and notification volumes must not by set int volume = GlobalData.getRingerVolume(context); if (volume != -999) { audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue()); audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue()); correctVolume0(/*profile, */audioManager, linkUnlink); } } else if (linkUnlink == PhoneCallService.LINKMODE_LINK) { // for separating ringing and notification // in not ringing state ringer and notification volume must by change //Log.e("ActivateProfileHelper","setVolumes get audio mode="+audioManager.getMode()); int volume = GlobalData.getRingerVolume(context); if (volume != -999) { //Log.e("ActivateProfileHelper","setVolumes set ring volume="+volume); audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue()); } volume = GlobalData.getNotificationVolume(context); if (volume != -999) { //Log.e("ActivateProfileHelper","setVolumes set notification volume="+volume); audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue()); } correctVolume0(/*profile, */audioManager, linkUnlink); } } } } if (linkUnlink == PhoneCallService.LINKMODE_NONE) { if (profile.getVolumeMediaChange()) { audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, profile.getVolumeMediaValue(), 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue()); } if (profile.getVolumeAlarmChange()) { audioManager.setStreamVolume(AudioManager.STREAM_ALARM, profile.getVolumeAlarmValue(), 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue()); } if (profile.getVolumeVoiceChange()) { audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, profile.getVolumeVoiceValue(), 0); //Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue()); } } } public static void setZenMode(Context context, int zenMode, AudioManager audioManager, int ringerMode) { if (android.os.Build.VERSION.SDK_INT >= 21) { int _zenMode = Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1); GlobalData.logE("ActivateProfileHelper.setZenMode", "_zenMode=" + _zenMode); int _ringerMode = audioManager.getRingerMode(); GlobalData.logE("ActivateProfileHelper.setZenMode", "_ringerMode=" + _ringerMode); if (PPNotificationListenerService.isNotificationListenerServiceEnabled(context)) { audioManager.setRingerMode(ringerMode); if (android.os.Build.VERSION.SDK_INT < 23) { try { Thread.sleep(500); } catch (InterruptedException e) { //System.out.println(e); } } if ((zenMode != _zenMode) || (zenMode == ZENMODE_PRIORITY)) { int interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALL; switch (zenMode) { case ZENMODE_ALL: interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALL; break; case ZENMODE_PRIORITY: interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_PRIORITY; break; case ZENMODE_NONE: interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_NONE; break; case ZENMODE_ALARMS: interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALARMS; break; } PPNotificationListenerService.requestInterruptionFilter(context, interruptionFilter); /* if (GlobalData.grantRoot(false) && (GlobalData.settingsBinaryExists())) { String command1 = "settings put global zen_mode " + mode; //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setZenMode", e.getMessage()); } }*/ } } else { switch (zenMode) { case ZENMODE_PRIORITY: audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); try { Thread.sleep(200); } catch (InterruptedException e) { //System.out.println(e); } audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); break; case ZENMODE_ALARMS: audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); try { Thread.sleep(200); } catch (InterruptedException e) { //System.out.println(e); } audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); break; default: audioManager.setRingerMode(ringerMode); } } } else audioManager.setRingerMode(ringerMode); } private void setVibrateWhenRinging(int value) { if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_VIBRATE_WHEN_RINGING, context) == GlobalData.PREFERENCE_ALLOWED) { if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception) Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", value); else { try { Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, value); } catch (Exception ee) { String command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + value; //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); Command command = new Command(0, false, command1); //, command2); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setVibrateWhenRinging", "Error on run su: " + e.toString()); } } } } } private void setNotificationLed(int value) { if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_NOTIFICATION_LED, context) == GlobalData.PREFERENCE_ALLOWED) { if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception) Settings.System.putInt(context.getContentResolver(), "notification_light_pulse", value); else { String command1 = "settings put system " + "notification_light_pulse" + " " + value; //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); Command command = new Command(0, false, command1); //, command2); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setNotificationLed", "Error on run su: " + e.toString()); } } } } @SuppressWarnings("deprecation") public void setRingerMode(Profile profile, AudioManager audioManager, boolean firstCall, int linkUnlink) { int ringerMode; int zenMode; if (linkUnlink == PhoneCallService.LINKMODE_NONE) { if (profile._volumeRingerMode != 0) { GlobalData.setRingerMode(context, profile._volumeRingerMode); if ((profile._volumeRingerMode == 5) && (profile._volumeZenMode != 0)) GlobalData.setZenMode(context, profile._volumeZenMode); } } if (firstCall) return; ringerMode = GlobalData.getRingerMode(context); zenMode = GlobalData.getZenMode(context); if (linkUnlink == PhoneCallService.LINKMODE_NONE) { switch (ringerMode) { case 1: // Ring setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL); //audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); not needed, called from setZenMode try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF); } catch (Exception e) { e.printStackTrace(); } try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); } catch (Exception e) { e.printStackTrace(); } setVibrateWhenRinging(0); break; case 2: // Ring & Vibrate setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL); //audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); not needed, called from setZenMode try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); } catch (Exception e) { e.printStackTrace(); } try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON); } catch (Exception e) { e.printStackTrace(); } setVibrateWhenRinging(1); break; case 3: // Vibrate setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE); //audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); not needed, called from setZenMode try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); } catch (Exception e) { e.printStackTrace(); } try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON); } catch (Exception e) { e.printStackTrace(); } setVibrateWhenRinging(1); break; case 4: // Silent if (android.os.Build.VERSION.SDK_INT >= 23) setZenMode(context, ZENMODE_ALARMS, audioManager, AudioManager.RINGER_MODE_SILENT); else if (android.os.Build.VERSION.SDK_INT >= 21) setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_NORMAL); else { setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_SILENT); try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF); } catch (Exception e) { e.printStackTrace(); } try { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); } catch (Exception e) { e.printStackTrace(); } } setVibrateWhenRinging(0); break; case 5: // Zen mode switch (zenMode) { case 1: setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL); setVibrateWhenRinging(0); break; case 2: setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_NORMAL); setVibrateWhenRinging(0); break; case 3: setZenMode(context, ZENMODE_NONE, audioManager, AudioManager.RINGER_MODE_SILENT); break; case 4: setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE); setVibrateWhenRinging(1); break; case 5: setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_VIBRATE); setVibrateWhenRinging(1); break; case 6: setZenMode(context, ZENMODE_ALARMS, audioManager, AudioManager.RINGER_MODE_SILENT); break; } break; } } } public void executeForWallpaper(Profile profile) { if (profile._deviceWallpaperChange == 1) { DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); display.getMetrics(displayMetrics); int height = displayMetrics.heightPixels; int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmap(profile.getDeviceWallpaperIdentifier(), width, height, context); if (decodedSampleBitmap != null) { // set wallpaper WallpaperManager wallpaperManager = WallpaperManager.getInstance(context); try { wallpaperManager.setBitmap(decodedSampleBitmap); } catch (IOException e) { Log.e("ActivateProfileHelper.executeForWallpaper", "Cannot set wallpaper. Image="+profile.getDeviceWallpaperIdentifier()); } } } } public void executeForRunApplications(Profile profile) { if (profile._deviceRunApplicationChange == 1) { String[] splits = profile._deviceRunApplicationPackageName.split("\\|"); Intent intent; PackageManager packageManager = context.getPackageManager(); for (int i = 0; i < splits.length; i++) { if (!ApplicationsCache.isShortcut(splits[i])) { if (ApplicationsCache.getActivityName(splits[i]).isEmpty()) { intent = packageManager.getLaunchIntentForPackage(splits[i]); if (intent != null) { intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } } else { intent = new Intent(context, LaunchShortcutActivity.class); intent.putExtra(LaunchShortcutActivity.EXTRA_PACKAGE_NAME, ApplicationsCache.getPackageName(splits[i])); intent.putExtra(LaunchShortcutActivity.EXTRA_ACTIVITY_NAME, ApplicationsCache.getActivityName(splits[i])); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } } else { intent = new Intent(context, LaunchShortcutActivity.class); intent.putExtra(LaunchShortcutActivity.EXTRA_PACKAGE_NAME, ApplicationsCache.getPackageName(splits[i])); intent.putExtra(LaunchShortcutActivity.EXTRA_ACTIVITY_NAME, ApplicationsCache.getActivityName(splits[i])); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } } } } public void execute(Profile _profile, boolean _interactive) { // rozdelit zvonenie a notifikacie - zial je to oznacene ako @Hide :-( //Settings.System.putInt(context.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0); final Profile profile = GlobalData.getMappedProfile(_profile, context); final boolean interactive = _interactive; // nahodenie volume a ringer modu // run service for execute volumes Intent volumeServiceIntent = new Intent(context, ExecuteVolumeProfilePrefsService.class); volumeServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id); volumeServiceIntent.putExtra(GlobalData.EXTRA_LINKUNLINK_VOLUMES, PhoneCallService.LINKMODE_NONE); //WakefulIntentService.sendWakefulWork(context, radioServiceIntent); context.startService(volumeServiceIntent); /*AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); // nahodenie ringer modu - aby sa mohli nastavit hlasitosti setRingerMode(profile, audioManager); setVolumes(profile, audioManager); // nahodenie ringer modu - hlasitosti zmenia silent/vibrate setRingerMode(profile, audioManager);*/ // set vibration on touch if (Permissions.checkProfileVibrationOnTouch(context, profile)) { switch (profile._vibrationOnTouch) { case 1: Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1); break; case 2: Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0); break; } } // nahodenie tonov if (Permissions.checkProfileRingtones(context, profile)) { if (profile._soundRingtoneChange == 1) { if (!profile._soundRingtone.isEmpty()) { //Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, profile._soundRingtone); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, Uri.parse(profile._soundRingtone)); } else { // selected is None tone //Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, null); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, null); } } if (profile._soundNotificationChange == 1) { if (!profile._soundNotification.isEmpty()) { //Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, profile._soundNotification); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, Uri.parse(profile._soundNotification)); } else { // selected is None tone //Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, null); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, null); } } if (profile._soundAlarmChange == 1) { if (!profile._soundAlarm.isEmpty()) { //Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, profile._soundAlarm); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, Uri.parse(profile._soundAlarm)); } else { // selected is None tone //Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, null); } } } // nahodenie radio preferences // run service for execute radios Intent radioServiceIntent = new Intent(context, ExecuteRadioProfilePrefsService.class); radioServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id); context.startService(radioServiceIntent); // nahodenie auto-sync boolean _isAutosync = ContentResolver.getMasterSyncAutomatically(); boolean _setAutosync = false; switch (profile._deviceAutosync) { case 1: if (!_isAutosync) { _isAutosync = true; _setAutosync = true; } break; case 2: if (_isAutosync) { _isAutosync = false; _setAutosync = true; } break; case 3: _isAutosync = !_isAutosync; _setAutosync = true; break; } if (_setAutosync) ContentResolver.setMasterSyncAutomatically(_isAutosync); // screen timeout if (Permissions.checkProfileScreenTimeout(context, profile)) { switch (profile._deviceScreenTimeout) { case 1: screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000); break; case 2: screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000); break; case 3: screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000); break; case 4: screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000); break; case 5: screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000); break; case 6: //2147483647 = Integer.MAX_VALUE //18000000 = 5 hours //86400000 = 24 hounrs //43200000 = 12 hours screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000); //18000000); break; case 7: screenTimeoutUnlock(context); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000); break; case 8: screenTimeoutUnlock(context); //if (android.os.Build.VERSION.SDK_INT < 19) // not working in Sony // Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1); //else screenTimeoutLock(context); break; } } // zapnutie/vypnutie lockscreenu boolean setLockscreen = false; switch (profile._deviceKeyguard) { case 1: // enable lockscreen GlobalData.setLockscreenDisabled(context, false); setLockscreen = true; break; case 2: // disable lockscreen GlobalData.setLockscreenDisabled(context, true); setLockscreen = true; break; } if (setLockscreen) { boolean isScreenOn; //if (android.os.Build.VERSION.SDK_INT >= 20) // Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // isScreenOn = display.getState() != Display.STATE_OFF; //else PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); isScreenOn = pm.isScreenOn(); //GlobalData.logE("$$$ ActivateProfileHelper.execute","isScreenOn="+isScreenOn); boolean keyguardShowing = false; KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); if (android.os.Build.VERSION.SDK_INT >= 16) keyguardShowing = kgMgr.isKeyguardLocked(); else keyguardShowing = kgMgr.inKeyguardRestrictedInputMode(); //GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguardShowing="+keyguardShowing); if (isScreenOn && !keyguardShowing) { Intent keyguardService = new Intent(context.getApplicationContext(), KeyguardService.class); context.startService(keyguardService); } } // nahodenie podsvietenia if (Permissions.checkProfileScreenBrightness(context, profile)) { if (profile.getDeviceBrightnessChange()) { if (profile.getDeviceBrightnessAutomatic()) { Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, profile.getDeviceBrightnessManualValue(context)); if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, context) == GlobalData.PREFERENCE_ALLOWED) { if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception) Settings.System.putFloat(context.getContentResolver(), ADAPTIVE_BRIGHTNESS_SETTING_NAME, profile.getDeviceBrightnessAdaptiveValue(context)); else { try { Settings.System.putFloat(context.getContentResolver(), ADAPTIVE_BRIGHTNESS_SETTING_NAME, profile.getDeviceBrightnessAdaptiveValue(context)); } catch (Exception ee) { String command1 = "settings put system " + ADAPTIVE_BRIGHTNESS_SETTING_NAME + " " + Float.toString(profile.getDeviceBrightnessAdaptiveValue(context)); //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); Command command = new Command(0, false, command1); //, command2); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.execute", "Error on run su: " + e.toString()); } } } } } else { Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, profile.getDeviceBrightnessManualValue(context)); } if (brightnessHandler != null) { final Profile __profile = profile; final Context __context = context; brightnessHandler.post(new Runnable() { public void run() { createBrightnessView(__profile, __context); } }); } else createBrightnessView(profile, context); } } // nahodenie rotate if (Permissions.checkProfileAutoRotation(context, profile)) { switch (profile._deviceAutoRotate) { case 1: // set autorotate on Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1); Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0); break; case 2: // set autorotate off // degree 0 Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0); Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0); break; case 3: // set autorotate off // degree 90 Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0); Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90); break; case 4: // set autorotate off // degree 180 Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0); Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180); break; case 5: // set autorotate off // degree 270 Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0); Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270); break; } } // set notification led switch (profile._notificationLed) { case 1: setNotificationLed(1); break; case 2: setNotificationLed(0); break; } // nahodenie pozadia if (Permissions.checkProfileWallpaper(context, profile)) { if (profile._deviceWallpaperChange == 1) { Intent wallpaperServiceIntent = new Intent(context, ExecuteWallpaperProfilePrefsService.class); wallpaperServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id); context.startService(wallpaperServiceIntent); } } // set power save mode if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, context) == GlobalData.PREFERENCE_ALLOWED) { PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean _isPowerSaveMode = false; if (Build.VERSION.SDK_INT >= 21) _isPowerSaveMode = powerManager.isPowerSaveMode(); boolean _setPowerSaveMode = false; switch (profile._devicePowerSaveMode) { case 1: if (!_isPowerSaveMode) { _isPowerSaveMode = true; _setPowerSaveMode = true; } break; case 2: if (_isPowerSaveMode) { _isPowerSaveMode = false; _setPowerSaveMode = true; } break; case 3: _isPowerSaveMode = !_isPowerSaveMode; _setPowerSaveMode = true; break; } if (_setPowerSaveMode) { setPowerSaveMode(_isPowerSaveMode); } } if (interactive) { // preferences, ktore vyzaduju interakciu uzivatela if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, context) == GlobalData.PREFERENCE_ALLOWED) { if (profile._deviceMobileDataPrefs == 1) { final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { activity.startActivity(intent); } catch (Exception e) { final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings"); //intent.addCategory(Intent.ACTION_MAIN); intent.setComponent(componentName); activity.startActivity(intent); } } } //if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_GPS, context)) //{ No check only GPS if (profile._deviceLocationServicePrefs == 1) { final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } if (profile._deviceRunApplicationChange == 1) { Intent runApplicationsServiceIntent = new Intent(context, ExecuteRunApplicationsProfilePrefsService.class); runApplicationsServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id); context.startService(runApplicationsServiceIntent); } } } private static void screenTimeoutLock(Context context) { WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); screenTimeoutUnlock(context); WindowManager.LayoutParams params = new WindowManager.LayoutParams( 1, 1, WindowManager.LayoutParams.TYPE_TOAST, //TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, PixelFormat.TRANSLUCENT ); if (android.os.Build.VERSION.SDK_INT < 17) params.gravity = Gravity.RIGHT | Gravity.TOP; else params.gravity = Gravity.END | Gravity.TOP; GUIData.keepScreenOnView = new BrightnessView(context); windowManager.addView(GUIData.keepScreenOnView, params); } public static void screenTimeoutUnlock(Context context) { if (GUIData.keepScreenOnView != null) { WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); try { windowManager.removeView(GUIData.keepScreenOnView); } catch (Exception e) { } GUIData.keepScreenOnView = null; } GlobalData.logE("@@@ screenTimeoutLock.unlock", "xxx"); } @SuppressLint("RtlHardcoded") private void createBrightnessView(Profile profile, Context context) { //if (context != null) RemoveBrightnessViewBroadcastReceiver.setAlarm(context); WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); if (GUIData.brightneesView != null) { windowManager.removeView(GUIData.brightneesView); GUIData.brightneesView = null; } WindowManager.LayoutParams params = new WindowManager.LayoutParams( 1, 1, WindowManager.LayoutParams.TYPE_TOAST, //TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT ); if (android.os.Build.VERSION.SDK_INT < 17) params.gravity = Gravity.RIGHT | Gravity.TOP; else params.gravity = Gravity.END | Gravity.TOP; if (profile.getDeviceBrightnessAutomatic()) params.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_NONE; else params.screenBrightness = profile.getDeviceBrightnessManualValue(context) / (float) 255; GUIData.brightneesView = new BrightnessView(context); windowManager.addView(GUIData.brightneesView, params); } public static void removeBrightnessView(Context context) { if (GUIData.brightneesView != null) { WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); try { windowManager.removeView(GUIData.brightneesView); } catch (Exception e) { } GUIData.brightneesView = null; } } public void showNotification(Profile profile) { if (lockRefresh) // no refres notification return; if (GlobalData.notificationStatusBar) { // close showed notification //notificationManager.cancel(GlobalData.NOTIFICATION_ID); // vytvorenie intentu na aktivitu, ktora sa otvori na kliknutie na notifikaciu Intent intent = new Intent(context, ActivateProfileActivity.class); // clear all opened activities intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK); // nastavime, ze aktivita sa spusti z notifikacnej listy intent.putExtra(GlobalData.EXTRA_STARTUP_SOURCE, GlobalData.STARTUP_SOURCE_NOTIFICATION); PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); // vytvorenie samotnej notifikacie NotificationCompat.Builder notificationBuilder; RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer); boolean isIconResourceID; String iconIdentifier; String profileName; Bitmap iconBitmap; Bitmap preferencesIndicator; if (profile != null) { isIconResourceID = profile.getIsIconResourceID(); iconIdentifier = profile.getIconIdentifier(); profileName = profile._name; iconBitmap = profile._iconBitmap; preferencesIndicator = profile._preferencesIndicator; } else { isIconResourceID = true; iconIdentifier = GlobalData.PROFILE_ICON_DEFAULT; profileName = context.getResources().getString(R.string.profiles_header_profile_name_no_activated); iconBitmap = null; preferencesIndicator = null; } notificationBuilder = new NotificationCompat.Builder(context) .setContentIntent(pIntent); if (android.os.Build.VERSION.SDK_INT >= 16) { if (GlobalData.notificationShowInStatusBar) notificationBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT); else notificationBuilder.setPriority(NotificationCompat.PRIORITY_MIN); //notificationBuilder.setPriority(Notification.PRIORITY_HIGH); // for heads-up in Android 5.0 } if (android.os.Build.VERSION.SDK_INT >= 21) { notificationBuilder.setCategory(Notification.CATEGORY_STATUS); notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); } notificationBuilder.setTicker(profileName); if (isIconResourceID) { int iconSmallResource; if (iconBitmap != null) { iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName()); notificationBuilder.setSmallIcon(iconSmallResource); contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap); } else { if (GlobalData.notificationStatusBarStyle.equals("0") && (android.os.Build.VERSION.SDK_INT < 21)) { //notificationBuilder.setSmallIcon(0); iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName()); notificationBuilder.setSmallIcon(iconSmallResource); //contentView.setImageViewResource(R.id.notification_activated_profile_icon, 0); contentView.setImageViewResource(R.id.notification_activated_profile_icon, iconSmallResource); } else { //notificationBuilder.setSmallIcon(0); //contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null); iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName()); notificationBuilder.setSmallIcon(iconSmallResource); int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName()); Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource); contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon); } } } else { int iconSmallResource; if (GlobalData.notificationStatusBarStyle.equals("0")) iconSmallResource = R.drawable.ic_profile_default; else iconSmallResource = R.drawable.ic_profile_default_notify; //notificationBuilder.setSmallIcon(0); notificationBuilder.setSmallIcon(iconSmallResource); contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap); } Notification notification = notificationBuilder.build(); if (GlobalData.notificationTextColor.equals("1")) contentView.setTextColor(R.id.notification_activated_profile_name, Color.BLACK); else if (GlobalData.notificationTextColor.equals("2")) contentView.setTextColor(R.id.notification_activated_profile_name, Color.WHITE); contentView.setTextViewText(R.id.notification_activated_profile_name, profileName); //contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, // ProfilePreferencesIndicator.paint(profile, context)); if ((preferencesIndicator != null) && (GlobalData.notificationPrefIndicator)) contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, preferencesIndicator); else contentView.setImageViewResource(R.id.notification_activated_profile_pref_indicator, R.drawable.ic_empty); notification.contentView = contentView; if (GlobalData.notificationStatusBarPermanent) { //notification.flags |= Notification.FLAG_NO_CLEAR; notification.flags |= Notification.FLAG_ONGOING_EVENT; } else { setAlarmForNotificationCancel(); } notificationManager.notify(GlobalData.PROFILE_NOTIFICATION_ID, notification); } else { notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID); } } public void removeNotification() { notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID); } private void setAlarmForNotificationCancel() { if (GlobalData.notificationStatusBarCancel.isEmpty() || GlobalData.notificationStatusBarCancel.equals("0")) return; Intent intent = new Intent(context, NotificationCancelAlarmBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE); Calendar now = Calendar.getInstance(); long time = now.getTimeInMillis() + Integer.valueOf(GlobalData.notificationStatusBarCancel) * 1000; alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); } public void setAlarmForRecreateNotification() { Intent intent = new Intent(context, RecreateNotificationBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE); Calendar now = Calendar.getInstance(); long time = now.getTimeInMillis() + 500; alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); } public void updateWidget() { if (lockRefresh) // no refres widgets return; // icon widget Intent intent = new Intent(context, IconWidgetProvider.class); intent.setAction("android.appwidget.action.APPWIDGET_UPDATE"); int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, IconWidgetProvider.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); context.sendBroadcast(intent); // one row widget Intent intent4 = new Intent(context, OneRowWidgetProvider.class); intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE"); int ids4[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, OneRowWidgetProvider.class)); intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids4); context.sendBroadcast(intent4); // list widget Intent intent2 = new Intent(context, ProfileListWidgetProvider.class); intent2.setAction(ProfileListWidgetProvider.INTENT_REFRESH_LISTWIDGET); int ids2[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, ProfileListWidgetProvider.class)); intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids2); context.sendBroadcast(intent2); // dashclock extension Intent intent3 = new Intent(); intent3.setAction(DashClockBroadcastReceiver.INTENT_REFRESH_DASHCLOCK); context.sendBroadcast(intent3); // activities Intent intent5 = new Intent(); intent5.setAction(RefreshGUIBroadcastReceiver.INTENT_REFRESH_GUI); context.sendBroadcast(intent5); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private boolean isAirplaneMode(Context context) { if (android.os.Build.VERSION.SDK_INT >= 17) return Settings.Global.getInt(context.getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0; else return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0; } private void setAirplaneMode(Context context, boolean mode) { if (android.os.Build.VERSION.SDK_INT >= 17) setAirplaneMode_SDK17(context, mode); else setAirplaneMode_SDK8(context, mode); } private boolean isMobileData(Context context) { if (android.os.Build.VERSION.SDK_INT >= 21) { return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1; } else { final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); try { final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName()); final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled"); getMobileDataEnabledMethod.setAccessible(true); return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager); } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } catch (NoSuchMethodException e) { e.printStackTrace(); return false; } catch (IllegalArgumentException e) { e.printStackTrace(); return false; } catch (IllegalAccessException e) { e.printStackTrace(); return false; } catch (InvocationTargetException e) { e.printStackTrace(); return false; } } /* final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { int netvorkType = networkInfo.getType(); // 0 = mobile, 1 = wifi //String netvorkTypeName = networkInfo.getTypeName(); // "mobile" or "WIFI" boolean connected = networkInfo.isConnected(); // true = active connection //if (netvorkType == 0) //{ // connected into mobile data return connected; //} //else //{ // conected into Wifi // return false; //} } else return false; */ } private void setMobileData(Context context, boolean enable) { if (android.os.Build.VERSION.SDK_INT >= 21) { if (GlobalData.grantRoot(false)) { int state = 0; try { // Get the current state of the mobile network. state = enable ? 1 : 0; // Get the value of the "TRANSACTION_setDataEnabled" field. String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_setDataEnabled"); // Android 5.1+ (API 22) and later. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { SubscriptionManager mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE); // Loop through the subscription list i.e. SIM list. for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) { if (transactionCode != null && transactionCode.length() > 0) { // Get the active subscription ID for a given SIM card. int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId(); // Execute the command via `su` to turn off // mobile network for a subscription service. String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + state; Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su"); } } } } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) { // Android 5.0 (API 21) only. if (transactionCode != null && transactionCode.length() > 0) { // Execute the command via `su` to turn off mobile network. String command1 = "service call phone " + transactionCode + " i32 " + state; Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su"); } } } } catch(Exception e) { e.printStackTrace(); } } } else { final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean OK = false; try { final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName()); final Field iConnectivityManagerField = connectivityManagerClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(connectivityManager); final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager, enable); OK = true; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (!OK) { try { Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(connectivityManager, enable); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } private int getPreferredNetworkType(Context context) { if (GlobalData.grantRoot(false)) { try { // Get the value of the "TRANSACTION_setPreferredNetworkType" field. String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType"); if (transactionCode != null && transactionCode.length() > 0) { String command1 = "service call phone " + transactionCode + " i32"; Command command = new Command(0, false, command1) { @Override public void commandOutput(int id, String line) { super.commandOutput(id, line); String splits[] = line.split(" "); try { networkType = Integer.parseInt(splits[2]); } catch (Exception e) { networkType = -1; } } @Override public void commandTerminated(int id, String reason) { super.commandTerminated(id, reason); } @Override public void commandCompleted(int id, int exitcode) { super.commandCompleted(id, exitcode); } }; try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su"); } } } catch(Exception e) { e.printStackTrace(); } } return networkType; } private void setPreferredNetworkType(Context context, int networkType) { if (GlobalData.grantRoot(false)) { try { // Get the value of the "TRANSACTION_setPreferredNetworkType" field. String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_setPreferredNetworkType"); if (Build.VERSION.SDK_INT >= 23) { SubscriptionManager mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE); // Loop through the subscription list i.e. SIM list. for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) { if (transactionCode != null && transactionCode.length() > 0) { // Get the active subscription ID for a given SIM card. int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId(); String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + networkType; Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su"); } } } } else { if (transactionCode != null && transactionCode.length() > 0) { String command1 = "service call phone " + transactionCode + " i32 " + networkType; Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su"); } } } } catch(Exception e) { e.printStackTrace(); } } } @SuppressWarnings("deprecation") private void setGPS(Context context, boolean enable) { //boolean isEnabled; //int locationMode = -1; //if (android.os.Build.VERSION.SDK_INT < 19) // isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER); /*else { locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1); isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) || (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY); }*/ boolean isEnabled; if (android.os.Build.VERSION.SDK_INT < 21) isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER); else { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } GlobalData.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled); //if(!provider.contains(LocationManager.GPS_PROVIDER) && enable) if ((!isEnabled) && enable) { if (GlobalData.canExploitGPS(context)) { GlobalData.logE("ActivateProfileHelper.setGPS", "exploit"); final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); context.sendBroadcast(poke); } else if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false)) { // zariadenie je rootnute GlobalData.logE("ActivateProfileHelper.setGPS", "rooted"); String command1; //String command2; if (android.os.Build.VERSION.SDK_INT < 23) { String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); String newSet; if (provider == "") newSet = LocationManager.GPS_PROVIDER; else newSet = String.format("%s,%s", provider, LocationManager.GPS_PROVIDER); command1 = "settings put secure location_providers_allowed \"" + newSet + "\""; //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); //command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state true"; Command command = new Command(0, false, command1); //, command2); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString()); } } else { command1 = "settings put secure location_providers_allowed +gps"; Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString()); } } } else { /*GlobalData.logE("ActivateProfileHelper.setGPS", "old method"); try { Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", enable); context.sendBroadcast(intent); } catch (SecurityException e) { e.printStackTrace(); }*/ // for normal apps it is only possible to open the system settings dialog /* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); */ } } else //if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable)) if (isEnabled && (!enable)) { if (GlobalData.canExploitGPS(context)) { GlobalData.logE("ActivateProfileHelper.setGPS", "exploit"); final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); context.sendBroadcast(poke); } else if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false)) { // zariadenie je rootnute GlobalData.logE("ActivateProfileHelper.setGPS", "rooted"); String command1; //String command2; if (android.os.Build.VERSION.SDK_INT < 23) { String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); String[] list = provider.split(","); String newSet = ""; int j = 0; for (int i = 0; i < list.length; i++) { if (!list[i].equals(LocationManager.GPS_PROVIDER)) { if (j > 0) newSet += ","; newSet += list[i]; j++; } } command1 = "settings put secure location_providers_allowed \"" + newSet + "\""; //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); //command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state false"; Command command = new Command(0, false, command1);//, command2); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString()); } } else { command1 = "settings put secure location_providers_allowed -gps"; Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString()); } } } else { //GlobalData.logE("ActivateProfileHelper.setGPS", "old method"); /*try { Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", enable); context.sendBroadcast(intent); } catch (SecurityException e) { e.printStackTrace(); }*/ // for normal apps it is only possible to open the system settings dialog /* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); */ } } } private void setAirplaneMode_SDK17(Context context, boolean mode) { if (GlobalData.grantRoot(false)) { // zariadenie je rootnute String command1; String command2; if (mode) { command1 = "settings put global airplane_mode_on 1"; command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true"; } else { command1 = "settings put global airplane_mode_on 0"; command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false"; } //if (GlobalData.isSELinuxEnforcing()) // command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); // command2 = GlobalData.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP); Command command = new Command(0, false, command1, command2); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su"); } } else { //Log.e("ActivateProfileHelper.setAirplaneMode_SDK17","root NOT granted"); // for normal apps it is only possible to open the system settings dialog /* Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); */ } } @SuppressWarnings("deprecation") private void setAirplaneMode_SDK8(Context context, boolean mode) { Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0); Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); intent.putExtra("state", mode); context.sendBroadcast(intent); } private void setPowerSaveMode(boolean enable) { String command1 = "settings put global low_power " + ((enable) ? 1 : 0); Command command = new Command(0, false, command1); try { RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command); commandWait(command); //RootTools.closeAllShells(); } catch (Exception e) { Log.e("ActivateProfileHelper.setPowerSaveMode", "Error on run su: " + e.toString()); } } private static void commandWait(Command cmd) throws Exception { int waitTill = 50; int waitTillMultiplier = 2; int waitTillLimit = 3200; //7 tries, 6350 msec while (!cmd.isFinished() && waitTill<=waitTillLimit) { synchronized (cmd) { try { if (!cmd.isFinished()) { cmd.wait(waitTill); waitTill *= waitTillMultiplier; } } catch (InterruptedException e) { e.printStackTrace(); } } } if (!cmd.isFinished()){ Log.e("ActivateProfileHelper", "Could not finish root command in " + (waitTill/waitTillMultiplier)); } } public static int getMinimumScreenBrightnessSetting (Context context) { final Resources res = Resources.getSystem(); int id = res.getIdentifier("config_screenBrightnessSettingMinimum", "integer", "android"); // API17+ if (id == 0) id = res.getIdentifier("config_screenBrightnessDim", "integer", "android"); // lower API levels if (id != 0) { try { return res.getInteger(id); } catch (Resources.NotFoundException e) { // ignore } } return 0; } public static int getMaximumScreenBrightnessSetting (Context context) { final Resources res = Resources.getSystem(); final int id = res.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android"); // API17+ if (id != 0) { try { return res.getInteger(id); } catch (Resources.NotFoundException e) { // ignore } } return 255; } }
package com.intellij.codeInsight.daemon.impl; import com.intellij.ProjectTopics; import com.intellij.codeHighlighting.Pass; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.LineMarkerProviders; import com.intellij.codeInsight.daemon.impl.analysis.FileHighlightingSettingListener; import com.intellij.codeInspection.InspectionProfile; import com.intellij.facet.Facet; import com.intellij.facet.FacetManager; import com.intellij.facet.FacetManagerAdapter; import com.intellij.ide.AppLifecycleListener; import com.intellij.ide.PowerSaveMode; import com.intellij.ide.plugins.DynamicPluginListener; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.cl.PluginClassLoader; import com.intellij.ide.scratch.ScratchUtil; import com.intellij.ide.todo.TodoConfiguration; import com.intellij.lang.ExternalLanguageAnnotators; import com.intellij.lang.LanguageAnnotators; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandListener; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorActivityManager; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.actionSystem.DocCommandGroupId; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.EditorEventMulticasterEx; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.impl.DocumentMarkupModel; import com.intellij.openapi.editor.markup.CustomHighlighterRenderer; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileTypes.FileTypeEvent; import com.intellij.openapi.fileTypes.FileTypeListener; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolderEx; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent; import com.intellij.profile.ProfileChangeAdapter; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.ui.AppUIUtil; import com.intellij.util.KeyedLazyInstance; import com.intellij.util.ThreeState; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class DaemonListeners implements Disposable { private static final Logger LOG = Logger.getInstance(DaemonListeners.class); private final Project myProject; private final DaemonCodeAnalyzerImpl myDaemonCodeAnalyzer; private boolean myEscPressed; private volatile boolean cutOperationJustHappened; private final DaemonCodeAnalyzer.DaemonListener myDaemonEventPublisher; private List<Editor> myActiveEditors = Collections.emptyList(); private static final Key<Boolean> DAEMON_INITIALIZED = Key.create("DAEMON_INITIALIZED"); public static DaemonListeners getInstance(Project project) { return project.getComponent(DaemonListeners.class); } public DaemonListeners(@NotNull Project project) { myProject = project; myDaemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(myProject); boolean replaced = ((UserDataHolderEx)myProject).replace(DAEMON_INITIALIZED, null, Boolean.TRUE); if (!replaced) { LOG.error("Daemon listeners already initialized for the project " + myProject); } MessageBus messageBus = myProject.getMessageBus(); myDaemonEventPublisher = messageBus.syncPublisher(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC); if (project.isDefault()) { return; } MessageBusConnection connection = messageBus.connect(); connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() { @Override public void appClosing() { stopDaemon(false, "App closing"); } }); EditorFactory editorFactory = EditorFactory.getInstance(); EditorEventMulticasterEx eventMulticaster = (EditorEventMulticasterEx)editorFactory.getEventMulticaster(); eventMulticaster.addDocumentListener(new DocumentListener() { // clearing highlighters before changing document because change can damage editor highlighters drastically, so we'll clear more than necessary @Override public void beforeDocumentChange(@NotNull DocumentEvent e) { Document document = e.getDocument(); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); Project project = virtualFile == null ? null : ProjectUtil.guessProjectForFile(virtualFile); //no need to stop daemon if something happened in the console or in non-physical document if (!myProject.isDisposed() && ApplicationManager.getApplication().isDispatchThread() && worthBothering(document, project)) { stopDaemon(true, "Document change"); UpdateHighlightersUtil.updateHighlightersByTyping(myProject, e); } } }, this); if (!ApplicationManager.getApplication().isUnitTestMode()) { eventMulticaster.addCaretListener(new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent e) { Editor editor = e.getEditor(); if (EditorActivityManager.getInstance().isVisible(editor) && worthBothering(editor.getDocument(), editor.getProject())) { ApplicationManager.getApplication().invokeLater(() -> { if (!myProject.isDisposed() && EditorActivityManager.getInstance().isVisible(editor)) { IntentionsUI.getInstance(myProject).invalidate(); } }, ModalityState.current(), myProject.getDisposed()); } } }, this); } connection.subscribe(EditorTrackerListener.TOPIC, new EditorTrackerListener() { @Override public void activeEditorsChanged(@NotNull List<Editor> activeEditors) { if (myActiveEditors.equals(activeEditors)) { return; } myActiveEditors = new ArrayList<>(activeEditors); // do not stop daemon if idea loses/gains focus DaemonListeners.this.stopDaemon(true, "Active editor change"); if (ApplicationManager.getApplication().isDispatchThread() && LaterInvocator.isInModalContext()) { // editor appear in modal context, re-enable the daemon myDaemonCodeAnalyzer.setUpdateByTimerEnabled(true); } ErrorStripeUpdateManager errorStripeUpdateManager = ErrorStripeUpdateManager.getInstance(myProject); for (Editor editor : activeEditors) { errorStripeUpdateManager.repaintErrorStripePanel(editor); } } }); editorFactory.addEditorFactoryListener(new EditorFactoryListener() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { if (myProject.isDisposed()) { return; } Editor editor = event.getEditor(); Document document = editor.getDocument(); Project editorProject = editor.getProject(); // worthBothering() checks for getCachedPsiFile, so call getPsiFile here PsiFile file = editorProject == null ? null : PsiDocumentManager.getInstance(editorProject).getPsiFile(document); boolean showing = EditorActivityManager.getInstance().isVisible(editor); boolean worthBothering = worthBothering(document, editorProject); if (!showing || !worthBothering) { LOG.debug("Not worth bothering about editor created for : " + file + " because editor isShowing(): " + showing + "; project is open and file is mine: " + worthBothering); return; } ErrorStripeUpdateManager.getInstance(myProject).repaintErrorStripePanel(editor); } @Override public void editorReleased(@NotNull EditorFactoryEvent event) { myActiveEditors.remove(event.getEditor()); // mem leak after closing last editor otherwise UIUtil.invokeLaterIfNeeded(() -> { IntentionsUI intentionUI = myProject.getServiceIfCreated(IntentionsUI.class); if (intentionUI != null) { intentionUI.invalidate(); } }); } }, this); PsiManager.getInstance(myProject).addPsiTreeChangeListener(new PsiChangeHandler(myProject, connection, this), this); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { @Override public void rootsChanged(@NotNull ModuleRootEvent event) { stopDaemonAndRestartAllFiles("Project roots changed"); } }); connection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() { @Override public void enteredDumbMode() { stopDaemonAndRestartAllFiles("Dumb mode started"); } @Override public void exitDumbMode() { stopDaemonAndRestartAllFiles("Dumb mode finished"); } }); connection.subscribe(PowerSaveMode.TOPIC, () -> stopDaemon(true, "Power save mode change")); connection.subscribe(EditorColorsManager.TOPIC, __ -> stopDaemonAndRestartAllFiles("Editor color scheme changed")); connection.subscribe(CommandListener.TOPIC, new MyCommandListener()); connection.subscribe(ProfileChangeAdapter.TOPIC, new MyProfileChangeListener()); ApplicationManager.getApplication().addApplicationListener(new MyApplicationListener(), project); connection.subscribe(TodoConfiguration.PROPERTY_CHANGE, new MyTodoListener()); connection.subscribe(AnActionListener.TOPIC, new MyAnActionListener()); connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void after(@NotNull List<? extends VFileEvent> events) { boolean isDaemonShouldBeStopped = false; for (VFileEvent event : events) { if (event instanceof VFilePropertyChangeEvent) { VFilePropertyChangeEvent e = (VFilePropertyChangeEvent)event; String propertyName = e.getPropertyName(); if (VirtualFile.PROP_NAME.equals(propertyName)) { fileRenamed(e); } if (!isDaemonShouldBeStopped && !propertyName.equals(PsiTreeChangeEvent.PROP_WRITABLE)) { isDaemonShouldBeStopped = true; } } } if (isDaemonShouldBeStopped) { stopDaemon(true, "Virtual file property change"); } } private void fileRenamed(@NotNull VFilePropertyChangeEvent event) { stopDaemonAndRestartAllFiles("Virtual file name changed"); VirtualFile virtualFile = event.getFile(); PsiFile psiFile = !virtualFile.isValid() ? null : PsiManagerEx.getInstanceEx(myProject).getFileManager().getCachedPsiFile(virtualFile); if (psiFile == null || myDaemonCodeAnalyzer.isHighlightingAvailable(psiFile)) { return; } Document document = FileDocumentManager.getInstance().getCachedDocument(virtualFile); if (document == null) { return; } // highlight markers no more //todo clear all highlights regardless the pass id // Here color scheme required for TextEditorFields, as far as I understand this // code related to standard file editors, which always use Global color scheme, // thus we can pass null here. UpdateHighlightersUtil.setHighlightersToEditor(myProject, document, 0, document.getTextLength(), Collections.emptyList(), null, Pass.UPDATE_ALL); } }); connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() { @Override public void fileTypesChanged(@NotNull FileTypeEvent event) { IntentionsUI.getInstance(project).invalidate(); } }); eventMulticaster.addErrorStripeListener(e -> { RangeHighlighter highlighter = e.getHighlighter(); if (!highlighter.isValid()) return; HighlightInfo info = HighlightInfo.fromRangeHighlighter(highlighter); if (info != null) { GotoNextErrorHandler.navigateToError(myProject, e.getEditor(), info, null); } }, this); LaterInvocator.addModalityStateListener(__ -> { // before showing dialog we are in non-modal context yet, and before closing dialog we are still in modal context boolean inModalContext = Registry.is("ide.perProjectModality") || LaterInvocator.isInModalContext(); stopDaemon(inModalContext, "Modality change. Was modal: " + inModalContext); myDaemonCodeAnalyzer.setUpdateByTimerEnabled(inModalContext); }, this); connection.subscribe(SeverityRegistrar.SEVERITIES_CHANGED_TOPIC, () -> stopDaemonAndRestartAllFiles("Severities changed")); connection.subscribe(FacetManager.FACETS_TOPIC, new FacetManagerAdapter() { @Override public void facetRenamed(@NotNull Facet facet, @NotNull String oldName) { stopDaemonAndRestartAllFiles("facet renamed: " + oldName + " -> " + facet.getName()); } @Override public void facetAdded(@NotNull Facet facet) { stopDaemonAndRestartAllFiles("facet added: " + facet.getName()); } @Override public void facetRemoved(@NotNull Facet facet) { stopDaemonAndRestartAllFiles("facet removed: " + facet.getName()); } @Override public void facetConfigurationChanged(@NotNull Facet facet) { stopDaemonAndRestartAllFiles("facet changed: " + facet.getName()); } }); restartOnExtensionChange(LanguageAnnotators.EP_NAME, "annotators list changed"); restartOnExtensionChange(LineMarkerProviders.EP_NAME, "line marker providers list changed"); restartOnExtensionChange(ExternalLanguageAnnotators.EP_NAME, "external annotators list changed"); connection.subscribe(DynamicPluginListener.TOPIC, new DynamicPluginListener() { @Override public void pluginLoaded(@NotNull IdeaPluginDescriptor pluginDescriptor) { ((PsiModificationTrackerImpl)PsiManager.getInstance(myProject).getModificationTracker()).incCounter(); stopDaemonAndRestartAllFiles("Plugin installed"); } @Override public void beforePluginUnload(@NotNull IdeaPluginDescriptor pluginDescriptor, boolean isUpdate) { ((PsiModificationTrackerImpl)PsiManager.getInstance(myProject).getModificationTracker()).incCounter(); stopDaemonAndRestartAllFiles("Plugin will be uninstalled"); removeHighlightersOnPluginUnload(pluginDescriptor); } }); connection.subscribe(FileHighlightingSettingListener.SETTING_CHANGE, (root, setting) -> WriteAction.run(() -> { PsiFile file = root.getContainingFile(); if (file != null) { // force clearing all PSI caches, including those in WholeFileInspectionFactory ((PsiModificationTrackerImpl)PsiManager.getInstance(myProject).getModificationTracker()).incCounter(); } })); } private <T, U extends KeyedLazyInstance<T>> void restartOnExtensionChange(@NotNull ExtensionPointName<U> name, @NotNull String message) { name.addChangeListener(() -> stopDaemonAndRestartAllFiles(message), this); } private boolean worthBothering(@Nullable Document document, Project project) { if (document == null) { return true; } if (project != null && project != myProject) { return false; } // cached is essential here since we do not want to create PSI file in alien project PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getCachedPsiFile(document); return psiFile != null && psiFile.isPhysical() && psiFile.getOriginalFile() == psiFile; } @Override public void dispose() { stopDaemonAndRestartAllFiles("Project closed"); boolean replaced = ((UserDataHolderEx)myProject).replace(DAEMON_INITIALIZED, Boolean.TRUE, Boolean.FALSE); LOG.assertTrue(replaced, "Daemon listeners already disposed for the project "+myProject); } public static boolean canChangeFileSilently(@NotNull PsiFileSystemItem file) { Project project = file.getProject(); DaemonListeners listeners = getInstance(project); if (listeners == null) return true; if (listeners.cutOperationJustHappened) return false; VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) return false; if (file instanceof PsiCodeFragment) return true; if (ScratchUtil.isScratch(virtualFile)) return listeners.canUndo(virtualFile); if (!ModuleUtilCore.projectContainsFile(project, virtualFile, false)) return false; for (SilentChangeVetoer extension : SilentChangeVetoer.EP_NAME.getExtensionList()) { ThreeState result = extension.canChangeFileSilently(project, virtualFile); if (result != ThreeState.UNSURE) return result.toBoolean(); } return listeners.canUndo(virtualFile); } private boolean canUndo(@NotNull VirtualFile virtualFile) { FileEditor[] editors = FileEditorManager.getInstance(myProject).getEditors(virtualFile); if (editors.length == 0) { return false; } UndoManager undoManager = UndoManager.getInstance(myProject); for (FileEditor editor : editors) { if (undoManager.isUndoAvailable(editor)) { return true; } } return false; } private class MyApplicationListener implements ApplicationListener { @Override public void beforeWriteActionStart(@NotNull Object action) { if (!myDaemonCodeAnalyzer.isRunning()) return; // we'll restart in writeActionFinished() stopDaemon(true, "Write action start"); } @Override public void writeActionFinished(@NotNull Object action) { stopDaemon(true, "Write action finish"); } } private static final class Holder { private static final String myCutActionName = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_CUT).getTemplatePresentation().getText(); } private final class MyCommandListener implements CommandListener { @Override public void commandStarted(@NotNull CommandEvent event) { Document affectedDocument = extractDocumentFromCommand(event); if (!worthBothering(affectedDocument, event.getProject())) { return; } cutOperationJustHappened = Comparing.strEqual(Holder.myCutActionName, event.getCommandName()); if (!myDaemonCodeAnalyzer.isRunning()) return; if (LOG.isDebugEnabled()) { LOG.debug("cancelling code highlighting by command:" + event.getCommand()); } stopDaemon(false, "Command start"); } private @Nullable Document extractDocumentFromCommand(@NotNull CommandEvent event) { Document affectedDocument = event.getDocument(); if (affectedDocument != null) return affectedDocument; Object id = event.getCommandGroupId(); if (id instanceof Document) { affectedDocument = (Document)id; } else if (id instanceof DocCommandGroupId) { affectedDocument = ((DocCommandGroupId)id).getDocument(); } return affectedDocument; } @Override public void commandFinished(@NotNull CommandEvent event) { Document affectedDocument = extractDocumentFromCommand(event); if (!worthBothering(affectedDocument, event.getProject())) { return; } if (myEscPressed) { myEscPressed = false; if (affectedDocument != null) { // prevent Esc key to leave the document in the not-highlighted state if (!myDaemonCodeAnalyzer.getFileStatusMap().allDirtyScopesAreNull(affectedDocument)) { stopDaemon(true, "Command finish"); } } } else if (!myDaemonCodeAnalyzer.isRunning()) { stopDaemon(true, "Command finish"); } } } private final class MyTodoListener implements PropertyChangeListener { @Override public void propertyChange(@NotNull PropertyChangeEvent evt) { if (TodoConfiguration.PROP_TODO_PATTERNS.equals(evt.getPropertyName())) { stopDaemonAndRestartAllFiles("Todo patterns changed"); } else if (TodoConfiguration.PROP_MULTILINE.equals(evt.getPropertyName())) { stopDaemonAndRestartAllFiles("Todo multi-line detection changed"); } } } private class MyProfileChangeListener implements ProfileChangeAdapter { @Override public void profileChanged(InspectionProfile profile) { stopDaemonAndRestartAllFiles("Profile changed"); } @Override public void profileActivated(InspectionProfile oldProfile, @Nullable InspectionProfile profile) { stopDaemonAndRestartAllFiles("Profile activated"); } @Override public void profilesInitialized() { AppUIUtil.invokeLaterIfProjectAlive(myProject, () -> stopDaemonAndRestartAllFiles("Inspection profiles activated")); } } private final class MyAnActionListener implements AnActionListener { private AnAction cachedEscapeAction; @Override public void beforeActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (cachedEscapeAction == null) { myEscPressed = IdeActions.ACTION_EDITOR_ESCAPE.equals(event.getActionManager().getId(action)); if (myEscPressed) { cachedEscapeAction = action; } } else { myEscPressed = cachedEscapeAction == action; } } @Override public void beforeEditorTyping(char c, @NotNull DataContext dataContext) { Editor editor = CommonDataKeys.EDITOR.getData(dataContext); //no need to stop daemon if something happened in the console if (editor != null && !worthBothering(editor.getDocument(), editor.getProject())) { return; } stopDaemon(true, "Editor typing"); } } private void stopDaemon(boolean toRestartAlarm, @NonNls @NotNull String reason) { if (myDaemonCodeAnalyzer.stopProcess(toRestartAlarm, reason)) { myDaemonEventPublisher.daemonCancelEventOccurred(reason); } } private void stopDaemonAndRestartAllFiles(@NotNull String reason) { if (myDaemonCodeAnalyzer.doRestart(reason) && !myProject.isDisposed()) { myDaemonEventPublisher.daemonCancelEventOccurred(reason); } } private void removeHighlightersOnPluginUnload(@NotNull PluginDescriptor pluginDescriptor) { for (FileEditor fileEditor : FileEditorManager.getInstance(myProject).getAllEditors()) { if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); removeHighlightersOnPluginUnload(editor.getMarkupModel(), pluginDescriptor); MarkupModel documentMarkupModel = DocumentMarkupModel.forDocument(editor.getDocument(), myProject, false); if (documentMarkupModel != null) { removeHighlightersOnPluginUnload(documentMarkupModel, pluginDescriptor); } } } } private static void removeHighlightersOnPluginUnload(@NotNull MarkupModel model, @NotNull PluginDescriptor pluginDescriptor) { for (RangeHighlighter highlighter: model.getAllHighlighters()) { if (!(highlighter instanceof RangeHighlighterEx && ((RangeHighlighterEx)highlighter).isPersistent())) { model.removeHighlighter(highlighter); } else if (pluginDescriptor.getPluginClassLoader() instanceof PluginClassLoader) { CustomHighlighterRenderer renderer = highlighter.getCustomRenderer(); if (renderer != null && renderer.getClass().getClassLoader() == pluginDescriptor.getPluginClassLoader()) { model.removeHighlighter(highlighter); } } } } }
package com.intellij.execution.wsl; import com.intellij.openapi.application.Experiments; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public final class WSLCommandLineOptions { private boolean myLaunchWithWslExe = true; private boolean myExecuteCommandInShell = true; private boolean mySudo = false; private String myRemoteWorkingDirectory; private boolean myPassEnvVarsUsingInterop = false; private final List<String> myInitShellCommands = new ArrayList<>(); public boolean isLaunchWithWslExe() { return myLaunchWithWslExe && Experiments.getInstance().isFeatureEnabled("wsl.execute.with.wsl.exe"); } public @NotNull WSLCommandLineOptions setLaunchWithWslExe(boolean launchWithWslExe) { myLaunchWithWslExe = launchWithWslExe; return this; } public boolean isExecuteCommandInShell() { return myExecuteCommandInShell; } /** * Runs "wsl.exe --exec command" (requires launching with wsl.exe): * <pre> * --exec, -e &lt;CommandLine&gt; * Execute the specified command without using the default Linux shell. * </pre> */ public @NotNull WSLCommandLineOptions setExecuteCommandInShell(boolean executeCommandInShell) { myExecuteCommandInShell = executeCommandInShell; return this; } public boolean isSudo() { return mySudo; } public @NotNull WSLCommandLineOptions setSudo(boolean sudo) { mySudo = sudo; return this; } public @Nullable String getRemoteWorkingDirectory() { return myRemoteWorkingDirectory; } /** * @param remoteWorkingDirectory Linux directory (e.g. {@code /home/user/stuff}) to be used as a working directory * when starting a process. * @return this instance */ public @NotNull WSLCommandLineOptions setRemoteWorkingDirectory(@Nullable String remoteWorkingDirectory) { myRemoteWorkingDirectory = remoteWorkingDirectory; if (remoteWorkingDirectory != null && !remoteWorkingDirectory.startsWith("/")) { throw new AssertionError("Linux path was expected, but got " + remoteWorkingDirectory); } return this; } public boolean isPassEnvVarsUsingInterop() { return myPassEnvVarsUsingInterop; } public @NotNull WSLCommandLineOptions setPassEnvVarsUsingInterop(boolean passEnvVarsUsingInterop) { myPassEnvVarsUsingInterop = passEnvVarsUsingInterop; return this; } public @NotNull List<String> getInitShellCommands() { return myInitShellCommands; } /** * Adds an initialize command that is applied only when executing in shell ({@link #isExecuteCommandInShell()} is true). * The initialize command is a linux command that runs before the main command. * If the initialize command fails (exit code != 0), the main command won't run. * For example, it can be used to setup environment before running the app. * * @param initCommand a linux shell command (may contain shell builtin commands) */ public @NotNull WSLCommandLineOptions addInitCommand(@NotNull String initCommand) { myInitShellCommands.add(initCommand); return this; } @Override public String toString() { return "launchWithWslExe=" + myLaunchWithWslExe + ", executeCommandInShell=" + myExecuteCommandInShell + ", sudo=" + mySudo + ", remoteWorkingDirectory='" + myRemoteWorkingDirectory + '\'' + ", passEnvVarsUsingInterop=" + myPassEnvVarsUsingInterop + ", initCommands=" + myInitShellCommands; } }
package org.jetbrains.idea.devkit.inspections; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.lang.jvm.DefaultJvmElementVisitor; import com.intellij.lang.jvm.JvmClass; import com.intellij.lang.jvm.JvmElementVisitor; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.components.BaseComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.MethodReferencesSearch; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.Query; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.devkit.DevKitBundle; import org.jetbrains.idea.devkit.inspections.quickfix.RegisterActionFix; import org.jetbrains.idea.devkit.inspections.quickfix.RegisterComponentFix; import org.jetbrains.idea.devkit.module.PluginModuleType; import org.jetbrains.idea.devkit.util.ComponentType; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.util.Map; import java.util.Objects; import java.util.Set; public class ComponentNotRegisteredInspection extends DevKitJvmInspection { public boolean CHECK_ACTIONS = true; public boolean IGNORE_NON_PUBLIC = true; private static final Logger LOG = Logger.getInstance("org.jetbrains.idea.devkit.inspections.ComponentNotRegisteredInspection"); private static final Map<ComponentType, RegistrationCheckerUtil.RegistrationType> COMPONENT_TYPE_TO_REGISTRATION_TYPE = ContainerUtil.<ComponentType, RegistrationCheckerUtil.RegistrationType>immutableMapBuilder() .put(ComponentType.APPLICATION, RegistrationCheckerUtil.RegistrationType.APPLICATION_COMPONENT) .put(ComponentType.PROJECT, RegistrationCheckerUtil.RegistrationType.PROJECT_COMPONENT) .put(ComponentType.MODULE, RegistrationCheckerUtil.RegistrationType.MODULE_COMPONENT) .build(); @Override @Nullable public JComponent createOptionsPanel() { JPanel jPanel = new JPanel(); jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); final JCheckBox ignoreNonPublic = new JCheckBox( DevKitBundle.message("inspections.component.not.registered.option.ignore.non.public"), IGNORE_NON_PUBLIC); ignoreNonPublic.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { IGNORE_NON_PUBLIC = ignoreNonPublic.isSelected(); } }); final JCheckBox checkJavaActions = new JCheckBox( DevKitBundle.message("inspections.component.not.registered.option.check.actions"), CHECK_ACTIONS); checkJavaActions.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { boolean selected = checkJavaActions.isSelected(); CHECK_ACTIONS = selected; ignoreNonPublic.setEnabled(selected); } }); jPanel.add(checkJavaActions); jPanel.add(ignoreNonPublic); return jPanel; } @Nullable @Override protected JvmElementVisitor<Boolean> buildVisitor(@NotNull Project project, @NotNull HighlightSink sink, boolean isOnTheFly) { return new DefaultJvmElementVisitor<Boolean>() { @Override public Boolean visitClass(@NotNull JvmClass clazz) { PsiElement sourceElement = clazz.getSourceElement(); if (!(sourceElement instanceof PsiClass)) { return null; } checkClass(project, (PsiClass)sourceElement, sink); return false; } }; } private void checkClass(@NotNull Project project, @NotNull PsiClass checkedClass, @NotNull HighlightSink sink) { if (checkedClass.getQualifiedName() == null || checkedClass.getContainingFile().getVirtualFile() == null || checkedClass.hasModifierProperty(PsiModifier.ABSTRACT) || checkedClass.isEnum() || checkedClass.isDeprecated() || PsiUtil.isInnerClass(checkedClass) || !shouldCheckActionClass(checkedClass)) { return; } GlobalSearchScope scope = checkedClass.getResolveScope(); PsiClass actionClass = JavaPsiFacade.getInstance(project).findClass(AnAction.class.getName(), scope); if (actionClass == null) { // stop if action class cannot be found (non-devkit module/project) return; } if (checkedClass.isInheritor(actionClass, true)) { if (!isActionRegistered(checkedClass, project) && canFix(checkedClass)) { LocalQuickFix fix = new RegisterActionFix(org.jetbrains.idea.devkit.util.PsiUtil.createPointer(checkedClass)); sink.highlight(DevKitBundle.message("inspections.component.not.registered.message", DevKitBundle.message("new.menu.action.text")), fix); } // action IS registered, stop here return; } PsiClass baseComponentClass = JavaPsiFacade.getInstance(project).findClass(BaseComponent.class.getName(), scope); if (baseComponentClass == null) { // stop if component class cannot be found (non-devkit module/project) return; } // if directly implements BaseComponent, check that registered as some component if (checkedClass.isInheritor(baseComponentClass, false)) { if (findRegistrationType(checkedClass, RegistrationCheckerUtil.RegistrationType.ALL_COMPONENTS) == null && canFix(checkedClass)) { sink.highlight(DevKitBundle.message("inspections.component.not.registered.message", "Component")); } return; } if (!checkedClass.isInheritor(baseComponentClass, true)) { return; } for (ComponentType componentType : ComponentType.values()) { if (InheritanceUtil.isInheritor(checkedClass, componentType.myClassName) && checkComponentRegistration(checkedClass, sink, componentType)) { return; } } } private static boolean checkComponentRegistration(@NotNull PsiClass checkedClass, @NotNull HighlightSink sink, @NotNull ComponentType componentType) { if (findRegistrationType(checkedClass, COMPONENT_TYPE_TO_REGISTRATION_TYPE.get(componentType)) != null) { return true; } if (!canFix(checkedClass)) { return true; } LocalQuickFix fix = new RegisterComponentFix(componentType, org.jetbrains.idea.devkit.util.PsiUtil.createPointer(checkedClass)); sink.highlight(DevKitBundle.message("inspections.component.not.registered.message", DevKitBundle.message(componentType.myPropertyKey)), fix); return false; } private static PsiClass findRegistrationType(@NotNull PsiClass checkedClass, @NotNull RegistrationCheckerUtil.RegistrationType type) { final Set<PsiClass> types = RegistrationCheckerUtil.getRegistrationTypes(checkedClass, type); return ContainerUtil.getFirstItem(types); } private boolean shouldCheckActionClass(@NotNull PsiClass psiClass) { if (!CHECK_ACTIONS) return false; if (IGNORE_NON_PUBLIC && !psiClass.hasModifierProperty(PsiModifier.PUBLIC)) return false; return true; } private static boolean isActionRegistered(@NotNull PsiClass actionClass, Project project) { final PsiClass registrationType = findRegistrationType(actionClass, RegistrationCheckerUtil.RegistrationType.ACTION); if (registrationType != null) { return true; } if (isTooCostlyToSearch(actionClass, project)) return false; // search code usages: 1) own CTOR calls 2) usage via "new ActionClass()" for (PsiMethod method : actionClass.getConstructors()) { final Query<PsiReference> search = MethodReferencesSearch.search(method); if (search.findFirst() != null) { return true; } } final Query<PsiReference> search = ReferencesSearch.search(actionClass); for (PsiReference reference : search) { if (!(reference instanceof PsiJavaCodeReferenceElement)) continue; final PsiNewExpression newExpression = PsiTreeUtil.getParentOfType(reference.getElement(), PsiNewExpression.class); if (newExpression != null) { final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference(); if (classReference != null && classReference.getQualifiedName().equals(actionClass.getQualifiedName())) { return true; } } } return false; } private static boolean isTooCostlyToSearch(@NotNull PsiClass actionClass, Project project) { final SearchScope useScope = actionClass.getUseScope(); if (!(useScope instanceof GlobalSearchScope)) return false; final PsiSearchHelper.SearchCostResult searchCost = PsiSearchHelper.getInstance(project) .isCheapEnoughToSearch(Objects.requireNonNull(actionClass.getName()), (GlobalSearchScope)useScope, actionClass.getContainingFile(), null); return searchCost == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES; } private static boolean canFix(@NotNull PsiClass psiClass) { Project project = psiClass.getProject(); PsiFile psiFile = psiClass.getContainingFile(); LOG.assertTrue(psiFile != null); Module module = ModuleUtilCore.findModuleForFile(psiFile.getVirtualFile(), project); return PluginModuleType.isPluginModuleOrDependency(module) || module != null && org.jetbrains.idea.devkit.util.PsiUtil.isPluginModule(module); } }
package com.intellij.codeInspection.i18n; import com.intellij.codeInspection.*; import com.intellij.ide.util.PropertiesComponent; import com.intellij.java.i18n.JavaI18nBundle; import com.intellij.lang.Language; import com.intellij.lang.properties.PropertiesBundle; import com.intellij.lang.properties.PropertiesImplUtil; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.references.I18nUtil; import com.intellij.lang.properties.references.I18nizeQuickFixDialog; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.LabeledComponent; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.*; import com.intellij.ui.table.JBTable; import com.intellij.usageView.UsageInfo; import com.intellij.usages.UsageViewPresentation; import com.intellij.usages.impl.UsagePreviewPanel; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.NameUtilCore; import com.intellij.util.text.UniqueNameGenerator; import com.intellij.util.ui.ItemRemovable; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.uast.*; import org.jetbrains.uast.generate.UastCodeGenerationPlugin; import org.jetbrains.uast.generate.UastElementFactory; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; /** * WARNING * Templates are ignored BundleName.message(key, args) is always used instead */ public class I18nizeBatchQuickFix extends I18nizeQuickFix implements BatchQuickFix<CommonProblemDescriptor> { private static final Logger LOG = Logger.getInstance(I18nizeBatchQuickFix.class); @Override public void applyFix(@NotNull Project project, CommonProblemDescriptor @NotNull [] descriptors, @NotNull List<PsiElement> psiElementsToIgnore, @Nullable Runnable refreshViews) { Set<PsiElement> distinct = new HashSet<>(); Map<String, ReplacementBean> keyValuePairs = new LinkedHashMap<>(); UniqueNameGenerator uniqueNameGenerator = new UniqueNameGenerator(); Set<Module> contextModules = new LinkedHashSet<>(); for (CommonProblemDescriptor descriptor : descriptors) { PsiElement psiElement = ((ProblemDescriptor)descriptor).getPsiElement(); ULiteralExpression literalExpression = UastUtils.findContaining(psiElement, ULiteralExpression.class); if (literalExpression != null) { PsiPolyadicExpression concatenation = I18nizeConcatenationQuickFix.getEnclosingLiteralConcatenation(psiElement); if (concatenation == null) { Object val = literalExpression.getValue(); if (distinct.add(psiElement) && val instanceof String) { String value = (String)val; ReplacementBean bean = keyValuePairs.get(value); if (bean != null) { bean.getPsiElements().add(psiElement); bean.getExpressions().add(literalExpression); } else { String key = ObjectUtils.notNull(suggestKeyByPlace(literalExpression), I18nizeQuickFixDialog.suggestUniquePropertyKey(value, null, null)); ArrayList<PsiElement> elements = new ArrayList<>(); elements.add(psiElement); List<UExpression> uExpressions = new ArrayList<>(); uExpressions.add(literalExpression); keyValuePairs.put(value, new ReplacementBean(uniqueNameGenerator.generateUniqueName(key), value, uExpressions, elements, Collections.emptyList())); } ContainerUtil.addIfNotNull(contextModules, ModuleUtilCore.findModuleForPsiElement(psiElement)); } } else if (distinct.add(concatenation)) { ArrayList<PsiExpression> args = new ArrayList<>(); String value = I18nizeConcatenationQuickFix.getValueString(concatenation, args); String key = ObjectUtils.notNull(suggestKeyByPlace(literalExpression), I18nizeQuickFixDialog.suggestUniquePropertyKey(value, null, null)); keyValuePairs.put(value + concatenation.hashCode(), new ReplacementBean(uniqueNameGenerator.generateUniqueName(key), value, Collections.singletonList(UastUtils.findContaining(concatenation, UPolyadicExpression.class)), Collections.singletonList(concatenation), ContainerUtil.map(args, arg -> UastUtils.findContaining(arg, UExpression.class)))); ContainerUtil.addIfNotNull(contextModules, ModuleUtilCore.findModuleForPsiElement(psiElement)); } } } if (keyValuePairs.isEmpty()) return; ArrayList<ReplacementBean> replacements = new ArrayList<>(keyValuePairs.values()); I18NBatchDialog dialog = new I18NBatchDialog(project, replacements, contextModules); if (dialog.showAndGet()) { PropertiesFile propertiesFile = dialog.getPropertiesFile(); Set<PsiFile> files = new HashSet<>(); for (ReplacementBean pair : replacements) { for (PsiElement element : pair.getPsiElements()) { ContainerUtil.addIfNotNull(files, element.getContainingFile()); } } if (files.isEmpty()) { return; } files.add(propertiesFile.getContainingFile()); WriteCommandAction.runWriteCommandAction(project, getFamilyName(), null, () -> { String bundleName = propertiesFile.getVirtualFile().getNameWithoutExtension(); PsiClass[] classesByName = PsiShortNamesCache.getInstance(project).getClassesByName(bundleName, GlobalSearchScope.projectScope(project)); if (classesByName.length == 1) { bundleName = classesByName[0].getQualifiedName(); LOG.assertTrue(bundleName != null, propertiesFile.getName()); } for (ReplacementBean bean : replacements) { JavaI18nUtil.DEFAULT_PROPERTY_CREATION_HANDLER.createProperty(project, Collections.singletonList(propertiesFile), bean.getKey(), bean.getValue(), PsiExpression.EMPTY_ARRAY); List<UExpression> uExpressions = bean.getExpressions(); List<PsiElement> psiElements = bean.getPsiElements(); for (int i = 0; i < psiElements.size(); i++) { PsiElement psiElement = psiElements.get(i); UExpression uExpression = uExpressions.get(i); Language language = psiElement.getLanguage(); UastCodeGenerationPlugin generationPlugin = UastCodeGenerationPlugin.byLanguage(language); if (generationPlugin == null) { LOG.debug("No UAST generation plugin exist for " + language.getDisplayName()); continue; } UastElementFactory pluginElementFactory = generationPlugin.getElementFactory(project); List<UExpression> arguments = new ArrayList<>(); arguments.add(pluginElementFactory.createStringLiteralExpression(bean.getKey(), psiElement)); arguments.addAll(bean.getArgs()); UCallExpression callExpression = pluginElementFactory .createCallExpression(pluginElementFactory.createQualifiedReference(bundleName, uExpression), "message", arguments, null, UastCallKind.METHOD_CALL, psiElement); if (callExpression != null) { generationPlugin.replace(uExpression, callExpression, UCallExpression.class); } else { LOG.debug("Null generated UAST call expression"); } } } }, files.toArray(PsiFile.EMPTY_ARRAY)); } } /** * If expression is passed to ProblemsHolder#registerProblem, suggest inspection.class.name.description key * If expression is returned from getName/getFamilyName of the LocalQuickFix, suggest quick.fix.text/family.name */ @Nullable private static String suggestKeyByPlace(@NotNull UExpression expression) { UElement parent = UastUtils.skipParenthesizedExprUp(expression.getUastParent()); if (parent instanceof UPolyadicExpression) { parent = UastUtils.skipParenthesizedExprUp(parent.getUastParent()); } if (parent == null) return null; UCallExpression callExpression = UastUtils.getUCallExpression(parent); if (callExpression != null) { PsiMethod method = callExpression.resolve(); if (method != null) { if ("registerProblem".equals(method.getName()) && InheritanceUtil.isInheritor(method.getContainingClass(), ProblemsHolder.class.getName())) { PsiClass containingClass = PsiTreeUtil.getParentOfType(callExpression.getSourcePsi(), PsiClass.class); while (containingClass != null) { if (InheritanceUtil.isInheritor(containingClass, InspectionProfileEntry.class.getName())) { String containingClassName = containingClass.getName(); return containingClassName == null ? null : "inspection." + toPropertyName(InspectionProfileEntry.getShortName(containingClassName)) + ".description"; } containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class, true); } } } return null; } final UElement returnStmt = UastUtils.getParentOfType(parent, UReturnExpression.class, false, UCallExpression.class, ULambdaExpression.class); if (returnStmt instanceof UReturnExpression) { UMethod uMethod = UastUtils.getParentOfType(expression, UMethod.class); if (uMethod != null) { UElement uClass = uMethod.getUastParent(); if (uClass instanceof UClass && InheritanceUtil.isInheritor(((UClass)uClass), LocalQuickFix.class.getName())) { String name = ((UClass)uClass).getName(); if (name != null) { if ("getName".equals(uMethod.getName())) { return toPropertyName(name) + ".text"; } if ("getFamilyName".equals(uMethod.getName())) { return toPropertyName(name) + ".family.name"; } } } } } return null; } @NotNull private static String toPropertyName(String name) { return StringUtil.join(NameUtilCore.splitNameIntoWords(name), s -> StringUtil.decapitalize(s), "."); } private static class I18NBatchDialog extends DialogWrapper { private static final @NonNls String LAST_USED_PROPERTIES_FILE = "LAST_USED_PROPERTIES_FILE"; @NotNull private final Project myProject; private final List<ReplacementBean> myKeyValuePairs; private final Set<Module> myContextModules; private JComboBox<String> myPropertiesFile; private UsagePreviewPanel myUsagePreviewPanel; protected I18NBatchDialog(@NotNull Project project, List<ReplacementBean> keyValuePairs, Set<Module> contextModules) { super(project, true); myProject = project; myKeyValuePairs = keyValuePairs; myContextModules = contextModules; setTitle(PropertiesBundle.message("i18nize.dialog.title")); init(); } @Override protected @Nullable String getDimensionServiceKey() { return "i18nInBatch"; } @Nullable @Override protected JComponent createNorthPanel() { List<String> files = I18nUtil.defaultSuggestPropertiesFiles(myProject, myContextModules); myPropertiesFile = new ComboBox<>(ArrayUtil.toStringArray(files)); new ComboboxSpeedSearch(myPropertiesFile); LabeledComponent<JComboBox<String>> component = new LabeledComponent<>(); component.setText(JavaI18nBundle.message("property.file")); component.setComponent(myPropertiesFile); myPropertiesFile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PropertiesFile propertiesFile = getPropertiesFile(); if (propertiesFile != null) { for (int i = 0; i < myKeyValuePairs.size(); i++) { ReplacementBean keyValuePair = myKeyValuePairs.get(i); ReplacementBean updated = new ReplacementBean(I18nizeQuickFixDialog.suggestUniquePropertyKey(keyValuePair.myValue, keyValuePair.myKey, propertiesFile), keyValuePair.myValue, keyValuePair.myExpressions, keyValuePair.myPsiElements, keyValuePair.myArgs); myKeyValuePairs.set(i, updated); } } } }); if (!files.isEmpty()) { myPropertiesFile.setSelectedItem(ObjectUtils.notNull(PropertiesComponent.getInstance(myProject).getValue(LAST_USED_PROPERTIES_FILE), files.get(0))); } return component; } protected PropertiesFile getPropertiesFile() { Object selectedItem = myPropertiesFile.getSelectedItem(); if (selectedItem == null) return null; String path = FileUtil.toSystemIndependentName((String)selectedItem); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); return virtualFile != null ? PropertiesImplUtil.getPropertiesFile(PsiManager.getInstance(myProject).findFile(virtualFile)) : null; } @Nullable @Override protected JComponent createCenterPanel() { Splitter splitter = new JBSplitter(true); myUsagePreviewPanel = new UsagePreviewPanel(myProject, new UsageViewPresentation()); JBTable table = new JBTable(new MyKeyValueModel()); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.putClientProperty("html.disable", Boolean.TRUE); table.setDefaultRenderer(String.class, renderer); table.getSelectionModel().addListSelectionListener(e -> { updateUsagePreview(table); }); splitter.setFirstComponent(ToolbarDecorator.createDecorator(table).setRemoveAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { TableUtil.removeSelectedItems(table); table.repaint(); updateUsagePreview(table); } }).createPanel()); splitter.setSecondComponent(myUsagePreviewPanel); return splitter; } private void updateUsagePreview(JBTable table) { int index = table.getSelectionModel().getLeadSelectionIndex(); if (index != -1) { List<PsiElement> elements = myKeyValuePairs.get(index).getPsiElements(); myUsagePreviewPanel.updateLayout(ContainerUtil.map(elements, element -> new UsageInfo(element.getParent()))); } else { myUsagePreviewPanel.updateLayout(null); } } @Override protected void doOKAction() { PropertiesComponent.getInstance(myProject).setValue(LAST_USED_PROPERTIES_FILE, (String)myPropertiesFile.getSelectedItem()); super.doOKAction(); } @Override protected void dispose() { Disposer.dispose(myUsagePreviewPanel); super.dispose(); } private class MyKeyValueModel extends AbstractTableModel implements ItemRemovable { @Override public int getRowCount() { return myKeyValuePairs.size(); } @Override public String getColumnName(int column) { return column == 0 ? "Key" : "Value"; } @Override public int getColumnCount() { return 2; } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0; } @Override public Object getValueAt(int rowIndex, int columnIndex) { ReplacementBean pair = myKeyValuePairs.get(rowIndex); return columnIndex == 0 ? pair.getKey() : pair.getValue(); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 0) { ReplacementBean bean = myKeyValuePairs.get(rowIndex); myKeyValuePairs.set(rowIndex, new ReplacementBean((String)aValue, bean.getValue(), bean.getExpressions(), bean.getPsiElements(), bean.getArgs())); } } @Override public void removeRow(int idx) { myKeyValuePairs.remove(idx); } } } private static class ReplacementBean { private final String myKey; private final String myValue; private final List<UExpression> myExpressions; private final List<PsiElement> myPsiElements; private final List<UExpression> myArgs; private ReplacementBean(String key, String value, List<UExpression> expression, List<PsiElement> psiElements, List<UExpression> args) { myKey = key; myValue = value; myExpressions = expression; myPsiElements = psiElements; myArgs = args; } public String getKey() { return myKey; } private String getValue() { return myValue; } private List<UExpression> getExpressions() { return myExpressions; } private List<UExpression> getArgs() { return myArgs; } private List<PsiElement> getPsiElements() { return myPsiElements; } } }
package com.kurotkin.automobile; import java.util.Date; public class Car { private Date dateOfProduction; private String typeEngine; private double maxSpeed; private double accelerationTime; private int passengerCapacity; private int numberPassenger; private double currentSpeed; private CarDoor[] carDoors; private CarWheel[] carWheels; public Car(Date dateOfProduction) { if (dateOfProduction.after(new Date())) throw new IllegalArgumentException("Дата выпуска автомобиля из будущего"); this.dateOfProduction = dateOfProduction; } public Car(Date dateOfProduction, String typeEngine, double maxSpeed, double accelerationTime, int passengerCapacity, int numberPassenger, double currentSpeed) { if (dateOfProduction.after(new Date())) throw new IllegalArgumentException("Дата выпуска автомобиля из будущего"); if (maxSpeed < 0.0) throw new IllegalArgumentException("Отрицательная максимальная скорость"); if (accelerationTime < 0.0) throw new IllegalArgumentException("Отрицательное время разгона до 100км/ч"); if (passengerCapacity < 0.0) throw new IllegalArgumentException("Отрицательная пассажировместимость"); if (numberPassenger < 0.0) throw new IllegalArgumentException("Отрицательная количество пассажиров"); if (numberPassenger > passengerCapacity) throw new IllegalArgumentException("Количество пассижиров больше, чем вмещается"); if (currentSpeed < 0.0) throw new IllegalArgumentException("Отрицательная текущая скорость"); this.dateOfProduction = dateOfProduction; this.typeEngine = typeEngine; this.maxSpeed = maxSpeed; this.accelerationTime = accelerationTime; this.passengerCapacity = passengerCapacity; this.numberPassenger = numberPassenger; this.currentSpeed = currentSpeed; } public void changeSpeed(double ps) { if (ps < 0.0 || ps > 100.0) throw new IllegalArgumentException("Ошибка, изменение скорости должно быть 0..100.0% По факту " + ps); else { currentSpeed += (currentSpeed / 100.0 * ps); if (currentSpeed > maxSpeed) currentSpeed = maxSpeed; } } public void putPassenger() { numberPassenger++; if (numberPassenger > passengerCapacity) numberPassenger = passengerCapacity; } public void disPutPassenger() { numberPassenger if (numberPassenger < 0) numberPassenger = 0; } public void disPutAllPassenger() { numberPassenger = 0; } public CarDoor getDoor (int index) { return carDoors[index]; } public CarWheel getWheel (int index) { return carWheels[index]; } public void removeAllWheels(){ ; } // Install the new wheel on the machine X (in addition to the existing ones, that is, if there were 4 wheels, after calling the method with X argument equal to three, the wheel will be 4 + 3 = 7) // Calculate the current maximum speed possible (The speed of the machine is calculated as follows: the maximum speed of the new machine is multiplied by the most worn out wheel in the car.) The maximum speed is 0 if there is not one passenger in the car, since there is no one to drive it) // Output to the console information about the object (all fields and the calculated maximum speed, depending on the integrity of the wheels and the presence of the driver) }
package bat_nav; import java.util.Random; public class Reseau { Plateau plateau; int joueur; int premier_joueur; //client = joueur 1 //serveur = joueur 2 public Reseau(Plateau p) { plateau = p; Random rand = new Random(); premier_joueur = rand.nextInt(2)+1; } public int joueCoup(int x, int y) { //on recoit //0: plouf //ecrire sur le socket int resultat = ...(x, y); //p.joueCoupSurSaGrille(x, y); // c'est fait par l'interface? return resultat; } //socket callback public void recoitCoup() { int x,y; int resultat = p.joueCoupSurMaGrille(x, y); //socket pour renvoyer resultat } }
package beethoven; import java.io.File; import java.io.IOException; import java.util.Iterator; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import com.android.uiautomator.core.UiObject; import com.android.uiautomator.core.UiSelector; import com.android.uiautomator.testrunner.UiAutomatorTestCase; public class Play extends UiAutomatorTestCase { private static final int BLACK = Color.rgb(32, 32, 32); private static final int Y = 700; public void testClassicPro() throws Exception { UiObject tile = new UiObject( new UiSelector() .packageName("com.umonistudio.tile") .className(android.view.View.class)); assertTrue(tile.exists()); X x = new X(50); while (x.hasNext()) { getUiDevice().click(x.next(), Y); } } private class X implements Iterator<Integer> { private final int length; private int count = 0; private Bitmap bmp; private X(int length) { this.length = length; } public boolean hasNext() { return count < length; } public Integer next() { int mod = count % 3; if (mod == 0) { bmp = getBitmap(); } int y = Y - mod * 300; count++; for (int x = 90; x <= 720; x += 180) { int pixel = bmp.getPixel(x, y); if (pixel == BLACK) { return x; } } // Delay until needed. StringBuilder colors = new StringBuilder(); for (int x = 90; x <= 720; x += 180) { int pixel = bmp.getPixel(x, y); colors.append(color(pixel)).append(";"); } throw new AssertionError("No BLACK @ y=" + y + "! " + colors); } public void remove() { throw new UnsupportedOperationException("Not supported!"); } } @SuppressWarnings("deprecation") private Bitmap getBitmap() { File screenshot; try { screenshot = File.createTempFile("beethoven", ".png"); } catch (IOException e) { throw new RuntimeException(e); } screenshot.deleteOnExit(); assertTrue(getUiDevice().takeScreenshot(screenshot, 1, 0)); return new BitmapDrawable(screenshot.getAbsolutePath()).getBitmap(); } private static String color(int pixel) { return '#' + hex(Color.red(pixel)) + hex(Color.green(pixel)) + hex(Color.blue(pixel)); } private static String hex(int color) { String s = Integer.toString(color, 16); if (s.length() == 1) { s = '0' + s; } return s; } }
package fredboat.api; import fredboat.FredBoat; import fredboat.audio.PlayerRegistry; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Spark; import org.eclipse.jetty.server.Server; public class API { static{ int static PORT_SERVER = 1342; } private static final Logger log = LoggerFactory.getLogger(API.class); private static final int PORT = Integer.valueOf(System.getenv(PORT_SERVER)); private API() {} public static void start() { log.info("Igniting Spark API on port: " + PORT); Spark.port(PORT); Spark.get("/stats", (req, res) -> { res.type("application/json"); JSONObject root = new JSONObject(); JSONArray a = new JSONArray(); for(FredBoat fb : FredBoat.getShards()) { JSONObject fbStats = new JSONObject(); fbStats.put("id", fb.getShardInfo().getShardId()); fbStats.put("guilds", fb.getJda().getGuilds().size()); fbStats.put("users", fb.getJda().getUsers().size()); fbStats.put("status", fb.getJda().getStatus()); a.put(fbStats); } JSONObject g = new JSONObject(); g.put("playingPlayers", PlayerRegistry.getPlayingPlayers().size()); g.put("totalPlayers", PlayerRegistry.getRegistry().size()); g.put("distribution", FredBoat.distribution); g.put("guilds", FredBoat.getAllGuilds().size()); g.put("users", FredBoat.getAllUsersAsMap().size()); root.put("shards", a); root.put("global", g); return root; }); } }
package com.samskivert.atlanti.client; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import javax.swing.*; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import com.samskivert.swing.Controller; import com.samskivert.swing.ControllerProvider; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.MultiLineLabel; import com.samskivert.swing.VGroupLayout; import com.samskivert.swing.util.SwingUtil; import com.threerings.media.SafeScrollPane; import com.threerings.media.image.ImageManager; import com.threerings.media.tile.TileManager; import com.threerings.util.MessageBundle; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.client.PlaceView; import com.threerings.toybox.client.ChatPanel; import com.threerings.toybox.client.ToyBoxUI; import com.threerings.toybox.util.ToyBoxContext; import com.samskivert.atlanti.Log; import com.samskivert.atlanti.data.AtlantiCodes; import com.samskivert.atlanti.data.AtlantiTile; import com.samskivert.atlanti.util.PiecenUtil; /** * The top-level user interface component for the game display. */ public class AtlantiPanel extends JPanel implements PlaceView, ControllerProvider, AtlantiCodes { /** A reference to the board that is accessible to the controller. */ public AtlantiBoardView board; /** A reference to our _noplace button. */ public JButton noplace; /** * Constructs a new game display. */ public AtlantiPanel (ToyBoxContext ctx, AtlantiController controller) { // give ourselves a wee bit of a border setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); HGroupLayout gl = new HGroupLayout( HGroupLayout.STRETCH, 10, HGroupLayout.CENTER); gl.setOffAxisPolicy(HGroupLayout.STRETCH); setLayout(gl); // create the board board = new AtlantiBoardView(); board.setOpaque(false); // create a scroll area to contain the board SafeScrollPane scrolly = new SafeScrollPane(board); scrolly.getViewport().setBackground(ToyBoxUI.LIGHT_BLUE); add(scrolly); // create our side panel VGroupLayout sgl = new VGroupLayout(VGroupLayout.STRETCH); sgl.setOffAxisPolicy(VGroupLayout.STRETCH); sgl.setJustification(VGroupLayout.TOP); JPanel sidePanel = new JPanel(sgl); MessageBundle msgs = _ctx.getMessageManager().getBundle(ATLANTI_MESSAGE_BUNDLE); // add a big fat label because we love it! MultiLineLabel vlabel = new MultiLineLabel(msgs.get("m.title")); vlabel.setAntiAliased(true); vlabel.setFont(ToyBoxUI.fancyFont); sidePanel.add(vlabel, VGroupLayout.FIXED); // add a player info view to the side panel sidePanel.add(new JLabel("Scores:"), VGroupLayout.FIXED); sidePanel.add(new PlayerInfoView(), VGroupLayout.FIXED); // add a turn indicator to the side panel sidePanel.add(new JLabel("Current turn:"), VGroupLayout.FIXED); sidePanel.add(new TurnIndicatorView(), VGroupLayout.FIXED); // add a "place nothing" button noplace = new JButton("Place nothing"); noplace.setEnabled(false); noplace.setActionCommand(PLACE_NOTHING); noplace.addActionListener(Controller.DISPATCHER); sidePanel.add(noplace, VGroupLayout.FIXED); // de-opaquify everything before we add the chat box SwingUtil.setOpaque(sidePanel, false); setOpaque(true); setBackground(new Color(0xDAEB9C)); // add a chat box ChatPanel chat = new ChatPanel(ctx); chat.removeSendButton(); sidePanel.add(chat); // add a "back" button JButton back = new JButton( ctx.xlate(ATLANTI_MESSAGE_BUNDLE, "m.back_to_lobby")); back.setActionCommand(BACK_TO_LOBBY); back.addActionListener(Controller.DISPATCHER); sidePanel.add(HGroupLayout.makeButtonBox(HGroupLayout.RIGHT, back), VGroupLayout.FIXED); // add our side panel to the main display add(sidePanel, HGroupLayout.FIXED); // we'll need these later _controller = controller; _ctx = ctx; } // documentation inherited public void addNotify () { super.addNotify(); // we can't create our image manager until we have access to our // containing frame JRootPane rpane = getRootPane(); ImageManager imgr = new ImageManager( _ctx.getToyBoxDirector().getResourceManager(), rpane); TileManager tmgr = new TileManager(imgr); AtlantiTile.setManagers(imgr, tmgr); PiecenUtil.init(tmgr); } // documentation inherited public void willEnterPlace (PlaceObject plobj) { Log.info("Panel entered place."); } // documentation inherited public void didLeavePlace (PlaceObject plobj) { Log.info("Panel left place."); } // documentation inherited public Controller getController () { return _controller; } /** Provides access to needed services. */ protected ToyBoxContext _ctx; /** A reference to our controller that we need to implement the {@link * ControllerProvider} interface. */ protected AtlantiController _controller; }
package no.deichman.services.entity; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.Statement; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import no.deichman.services.entity.kohaadapter.KohaAdapter; import no.deichman.services.entity.repository.InMemoryRepository; import no.deichman.services.uridefaults.BaseURI; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFDataMgr; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static javax.ws.rs.core.Response.Status.CREATED; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import static javax.ws.rs.core.Response.Status.OK; import static no.deichman.services.entity.EntityServiceImplTest.modelForBiblio; import static no.deichman.services.entity.repository.InMemoryRepositoryTest.repositoryWithDataFrom; import static no.deichman.services.testutil.TestJSON.assertValidJSON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class EntityResourceTest { private static final String SOME_WORK_IDENTIFIER = "SOME_WORK_IDENTIFIER"; private EntityResource entityResource; private BaseURI baseURI; @Mock private KohaAdapter mockKohaAdapter; @Before public void setUp() throws Exception { baseURI = BaseURI.local(); EntityServiceImpl service = new EntityServiceImpl(baseURI, new InMemoryRepository(), mockKohaAdapter); entityResource = new EntityResource(baseURI, service); } @Test public void should_have_default_constructor() { assertNotNull(new EntityResource()); } @Test public void get_should_return_a_valid_json_work() { entityResource = new EntityResource(baseURI, new EntityServiceImpl(baseURI, repositoryWithDataFrom("testdata.ttl"), null)); String workId = "work_00001"; Response result = entityResource.get("work", workId); assertNotNull(result); assertEquals(OK.getStatusCode(), result.getStatus()); assertTrue(isValidJSON(result.getEntity().toString())); } @Test(expected = NotFoundException.class) public void get_should_throw_exception_when_work_is_not_found() { String workId = "work_DOES_NOT_EXIST"; entityResource.get("work", workId); } @Test public void create_should_return_201_when_work_created() throws URISyntaxException { String work = createTestWork(SOME_WORK_IDENTIFIER); Response result = entityResource.create("work", work); assertNull(result.getEntity()); assertEquals(CREATED.getStatusCode(), result.getStatus()); } @Test public void create_should_return_location_header_when_work_created() throws URISyntaxException { String work = createTestWork(SOME_WORK_IDENTIFIER); Response result = entityResource.create("work", work); String workURI = baseURI.work(); assertNull(result.getEntity()); assertTrue(Pattern.matches(workURI + "w\\d{12}", result.getHeaderString("Location"))); } @Test public void update_should_return_200_when_work_updated() { String work = createTestWork(SOME_WORK_IDENTIFIER); Response result = entityResource.update("work", work); assertNull(result.getEntity()); assertEquals(OK.getStatusCode(), result.getStatus()); } @Test public void create_should_return_the_new_work() throws URISyntaxException{ String work = createTestWork(SOME_WORK_IDENTIFIER); Response createResponse = entityResource.create("work", work); String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", ""); Response result = entityResource.get("work", workId); assertNotNull(result); assertEquals(CREATED.getStatusCode(), createResponse.getStatus()); assertEquals(OK.getStatusCode(), result.getStatus()); assertTrue(isValidJSON(result.getEntity().toString())); } private String createTestWork(String identifier) { return "{\n" + " \"@context\": {\n" + " \"dcterms\": \"http://purl.org/dc/terms/\",\n" + " \"deichman\": \"http://deichman.no/ontology + " },\n" + " \"@graph\": {\n" + " \"@id\": \"http://deichman.no/work/" + identifier + "\",\n" + " \"@type\": \"deichman:Work\",\n" + " \"dcterms:identifier\": \"" + identifier + "\"\n" + " }\n" + "}"; } @Test public void get_work_items_should_return_list_of_items(){ when(mockKohaAdapter.getBiblio("626460")).thenReturn(modelForBiblio()); entityResource = new EntityResource(baseURI, new EntityServiceImpl(baseURI, repositoryWithDataFrom("testdata.ttl"), mockKohaAdapter)); String workId = "work_TEST_KOHA_ITEMS_LINK"; Response result = entityResource.getWorkItems(workId, "work"); System.out.println(result.getEntity().toString()); assertNotNull(result); assertEquals(OK.getStatusCode(), result.getStatus()); assertTrue(isValidJSON(result.getEntity().toString())); } @Test(expected=NotFoundException.class) public void get_work_items_should_404_on_empty_items_list(){ Response result = entityResource.getWorkItems("DOES_NOT_EXIST", "work"); assertEquals(result.getStatus(), NOT_FOUND.getStatusCode()); } @Test public void patch_with_invalid_data_should_return_status_400() throws Exception { String work = createTestWork(SOME_WORK_IDENTIFIER); Response result = entityResource.create("work", work); String workId = result.getLocation().getPath().substring("/work/".length()); String patchData = "{}"; try { entityResource.patch("work", workId,patchData); fail("HTTP 400 Bad Request"); } catch (BadRequestException bre) { assertEquals("HTTP 400 Bad Request", bre.getMessage()); } } @Test(expected = NotFoundException.class) public void patch_on_a_non_existing_resource_should_return_404() throws Exception { entityResource.patch("work", "a_missing_work1234", "{}"); } @Test(expected=NotFoundException.class) public void delete__non_existing_work_should_raise_not_found_exception(){ entityResource.delete("work", "work_DOES_NOT_EXIST_AND_FAILS"); } @Test public void delete_existing_work_should_return_no_content() throws URISyntaxException{ String work = createTestWork(SOME_WORK_IDENTIFIER); Response createResponse = entityResource.create("work", work); String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", ""); Response response = entityResource.delete("work", workId); assertEquals(response.getStatus(), NO_CONTENT.getStatusCode()); } private static final String A_BIBLIO_ID = "1234"; private String createTestPublicationJSON(String id) { return "{\"@context\": " + "{\"dcterms\": \"http://purl.org/dc/terms/\"," + "\"deichman\": \"http://deichman.no/ontology + "\"@graph\": " + "{\"@id\": \"http://deichman.no/publication/" + id + "\"," + "\"@type\": \"deichman:Publication\"," + "\"dcterms:identifier\":\"" + id + "\"}}"; } @Test public void create_should_return_201_when_publication_created() throws Exception{ when(mockKohaAdapter.getNewBiblio()).thenReturn(A_BIBLIO_ID); Response result = entityResource.create("publication", createTestPublicationJSON("publication_SHOULD_EXIST")); assertNull(result.getEntity()); assertEquals(CREATED.getStatusCode(), result.getStatus()); } @Test public void location_returned_from_create_should_return_the_new_publication() throws Exception{ when(mockKohaAdapter.getNewBiblio()).thenReturn(A_BIBLIO_ID); Response createResponse = entityResource.create("publication", createTestPublicationJSON("publication_SHOULD_EXIST")); String publicationId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/publication/", ""); Response result = entityResource.get("publication", publicationId); assertNotNull(result); assertEquals(CREATED.getStatusCode(), createResponse.getStatus()); assertEquals(OK.getStatusCode(), result.getStatus()); assertTrue(result.getEntity().toString().contains("\"deichman:recordID\"")); assertValidJSON(result.getEntity().toString()); } @Test public void delete_publication_should_return_no_content() throws Exception{ when(mockKohaAdapter.getNewBiblio()).thenReturn(A_BIBLIO_ID); Response createResponse = entityResource.create("publication", createTestPublicationJSON("publication_SHOULD_BE_PATCHABLE")); String publicationId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/publication/", ""); Response response = entityResource.delete("publication", publicationId); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); } @Test public void patch_should_actually_persist_changes() throws Exception { when(mockKohaAdapter.getNewBiblio()).thenReturn(A_BIBLIO_ID); String publication = createTestPublicationJSON("publication_SHOULD_BE_PATCHABLE"); Response result = entityResource.create("publication", publication); String publicationId = result.getLocation().getPath().substring("/publication/".length()); String patchData = "{" + "\"op\": \"add\"," + "\"s\": \"" + result.getLocation().toString() + "\"," + "\"p\": \"http://deichman.no/ontology#color\"," + "\"o\": {" + "\"value\": \"red\"" + "}" + "}"; Response patchResponse = entityResource.patch("publication", publicationId, patchData); Model testModel = ModelFactory.createDefaultModel(); String response = patchResponse.getEntity().toString(); InputStream in = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); RDFDataMgr.read(testModel, in, Lang.JSONLD); Statement s = ResourceFactory.createStatement( ResourceFactory.createResource(result.getLocation().toString()), ResourceFactory.createProperty("http://deichman.no/ontology#color"), ResourceFactory.createPlainLiteral("red")); assertTrue(testModel.contains(s)); } @Test public void work_should_have_language_labels() throws URISyntaxException { String work = "{\n" + " \"@context\": {\n" + " \"rdfs\": \"http://www.w3.org/2000/01/rdf-schema + " \"deichman\": \"http://deichman.no/ontology + " },\n" + " \"@graph\": {\n" + " \"@id\": \"http://deichman.no/publication/work_should_have_language_labels\",\n" + " \"@type\": \"deichman:Work\"\n," + " \"deichman:language\": \"http://lexvo.org/id/iso639-3/eng\"\n" + " }\n" + "}"; Response createResponse = entityResource.create("work", work); String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", ""); Response result = entityResource.get("work", workId); String labelsComparison = "{\n" + " \"@id\" : \"http://lexvo.org/id/iso639-3/eng\",\n" + " \"@type\" : \"http://lexvo.org/ontology#Language\",\n" + " \"rdfs:label\" : {\n" + " \"@language\" : \"no\",\n" + " \"@value\" : \"Engelsk\"\n" + " }\n" + " }"; assertEquals(OK.getStatusCode(), result.getStatus()); assertTrue(result.getEntity().toString().contains(labelsComparison)); } private boolean isValidJSON(final String json) { boolean valid = false; try { final JsonParser parser = new ObjectMapper().getJsonFactory().createJsonParser(json); while (parser.nextToken() != null) { // NOOP } valid = true; } catch (IOException ioe) { ioe.printStackTrace(); } return valid; } }
package no.haktho.json.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.PrePersist; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name="USER_DATA") public class Node implements Serializable{ private static final long serialVersionUID = -1178957056634479706L; @TableGenerator( name="incrementByOne", allocationSize=1, initialValue=0) @Id @Column(name="ID", nullable=false) @GeneratedValue(strategy=GenerationType.TABLE, generator="incrementByOne") private long id; @Column(name="NODE_NAME", nullable=false) String name; double consumption_kwh; double consumption_power; double consumption_kwhd; double pv_power; double pv_kwhd; double pv_kwh; double grid2storage_kwh; double grid2storage_power; double grid2storage_kwhd; double grid2household_kwh; double grid2household_power; double grid2household_kwhd; double pv2storage_kwh; double pv2storage_power; double pv2storage_kwhd; double pv2household_kwh; double pv2household_power; double pv2household_kwhd; double pv2grid_kwh; double pv2grid_power; double pv2grid_kwhd; double storage2grid_kwh; double storage2grid_power; double storage2grid_kwhd; double storage2household_kwh; double storage2household_power; double storage2household_kwhd; long consumption_kwh_time; long consumption_power_time; long consumption_kwhd_time; long pv_power_time; long pv_kwhd_time; long pv_kwh_time; long grid2storage_kwh_time; long grid2storage_power_time; long grid2storage_kwhd_time; long grid2household_kwh_time; long grid2household_power_time; long grid2household_kwhd_time; long pv2storage_kwh_time; long pv2storage_power_time; long pv2storage_kwhd_time; long pv2household_kwh_time; long pv2household_power_time; long pv2household_kwhd_time; long pv2grid_kwh_time; long pv2grid_power_time; long pv2grid_kwhd_time; long storage2grid_kwh_time; long storage2grid_power_time; long storage2grid_kwhd_time; long storage2household_kwh_time; long storage2household_power_time; long storage2household_kwhd_time; @Temporal(TemporalType.TIMESTAMP) private Date timestamp; public Node(){} public Node(String name){ this.name = name; this.consumption_kwh = 0; this.consumption_power = 0; this.consumption_kwhd = 0; this.pv_power = 0; this.pv_kwhd = 0; this.pv_kwh = 0; this.grid2storage_kwh = 0; this.grid2storage_power = 0; this.grid2storage_kwhd = 0; this.grid2household_kwh = 0; this.grid2household_power = 0; this.grid2household_kwhd = 0; this.pv2storage_kwh = 0; this.pv2storage_power = 0; this.pv2storage_kwhd = 0; this.pv2household_kwh = 0; this.pv2household_power = 0; this.pv2household_kwhd = 0; this.pv2grid_kwh = 0; this.pv2grid_power = 0; this.pv2grid_kwhd = 0; this.storage2grid_kwh = 0; this.storage2grid_power = 0; this.storage2grid_kwhd = 0; this.storage2household_kwh = 0; this.storage2household_power = 0; this.storage2household_kwhd = 0; this.consumption_kwh_time= 0; this.consumption_power_time = 0; this.consumption_kwhd_time= 0; this.pv_power_time= 0; this.pv_kwhd_time = 0; this.pv_kwh_time = 0; this.grid2storage_kwh_time = 0; this.grid2storage_power_time = 0; this.grid2storage_kwhd_time = 0; this.grid2household_kwh_time = 0; this.grid2household_power_time = 0; this.grid2household_kwhd_time = 0; this.pv2storage_kwh_time = 0; this.pv2storage_power_time = 0; this.pv2storage_kwhd_time = 0; this.pv2household_kwh_time = 0; this.pv2household_power_time = 0; this.pv2household_kwhd_time = 0; this.pv2grid_kwh_time = 0; this.pv2grid_power_time = 0; this.pv2grid_kwhd_time = 0; this.storage2grid_kwh_time = 0; this.storage2grid_power_time = 0; this.storage2grid_kwhd_time = 0; this.storage2household_kwh_time = 0; this.storage2household_power_time = 0; this.storage2household_kwhd_time = 0; } public long getId(){ return id; } public void setId(long id){ this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setConsumption_kwh(double consumption_kwh) { this.consumption_kwh = consumption_kwh; } public void setConsumption_power(double consumption_power) { this.consumption_power = consumption_power; } public void setConsumption_kwhd(double consumption_kwhd) { this.consumption_kwhd = consumption_kwhd; } public void setPv_power(double pv_power) { this.pv_power = pv_power; } public void setPv_kwhd(double pv_kwhd) { this.pv_kwhd = pv_kwhd; } public void setPv_kwh(double pv_kwh) { this.pv_kwh = pv_kwh; } public double getConsumption_kwh() { return consumption_kwh; } public double getConsumption_power() { return consumption_power; } public double getConsumption_kwhd() { return consumption_kwhd; } public double getPv_power() { return pv_power; } public double getPv_kwhd() { return pv_kwhd; } public double getPv_kwh() { return pv_kwh; } public double getGrid2storage_kwh() { return grid2storage_kwh; } public void setGrid2storage_kwh(double d) { this.grid2storage_kwh = d; } public double getGrid2storage_power() { return grid2storage_power; } public void setGrid2storage_power(double grid2storage_power) { this.grid2storage_power = grid2storage_power; } public double getGrid2storage_kwhd() { return grid2storage_kwhd; } public void setGrid2storage_kwhd(double grid2storage_kwhd) { this.grid2storage_kwhd = grid2storage_kwhd; } public double getGrid2household_kwh() { return grid2household_kwh; } public void setGrid2household_kwh(double grid2household_kwh) { this.grid2household_kwh = grid2household_kwh; } public double getGrid2household_power() { return grid2household_power; } public void setGrid2household_power(double grid2household_power) { this.grid2household_power = grid2household_power; } public double getGrid2household_kwhd() { return grid2household_kwhd; } public void setGrid2household_kwhd(double grid2household_kwhd) { this.grid2household_kwhd = grid2household_kwhd; } public double getPv2storage_kwh() { return pv2storage_kwh; } public void setPv2storage_kwh(double pv2storage_kwh) { this.pv2storage_kwh = pv2storage_kwh; } public double getPv2storage_power() { return pv2storage_power; } public void setPv2storage_power(double pv2storage_power) { this.pv2storage_power = pv2storage_power; } public double getPv2storage_kwhd() { return pv2storage_kwhd; } public void setPv2storage_kwhd(double pv2storage_kwhd) { this.pv2storage_kwhd = pv2storage_kwhd; } public double getPv2household_kwh() { return pv2household_kwh; } public void setPv2household_kwh(double pv2household_kwh) { this.pv2household_kwh = pv2household_kwh; } public double getPv2household_power() { return pv2household_power; } public void setPv2household_power(double pv2household_power) { this.pv2household_power = pv2household_power; } public double getPv2household_kwhd() { return pv2household_kwhd; } public void setPv2household_kwhd(double pv2household_kwhd) { this.pv2household_kwhd = pv2household_kwhd; } public double getPv2grid_kwh() { return pv2grid_kwh; } public void setPv2grid_kwh(double pv2grid_kwh) { this.pv2grid_kwh = pv2grid_kwh; } public double getPv2grid_power() { return pv2grid_power; } public void setPv2grid_power(double pv2grid_power) { this.pv2grid_power = pv2grid_power; } public double getPv2grid_kwhd() { return pv2grid_kwhd; } public void setPv2grid_kwhd(double pv2grid_kwhd) { this.pv2grid_kwhd = pv2grid_kwhd; } public double getStorage2grid_kwh() { return storage2grid_kwh; } public void setStorage2grid_kwh(double storage2grid_kwh) { this.storage2grid_kwh = storage2grid_kwh; } public double getStorage2grid_power() { return storage2grid_power; } public void setStorage2grid_power(double storage2grid_power) { this.storage2grid_power = storage2grid_power; } public double getStorage2grid_kwhd() { return storage2grid_kwhd; } public void setStorage2grid_kwhd(double storage2grid_kwhd) { this.storage2grid_kwhd = storage2grid_kwhd; } public double getStorage2household_kwh() { return storage2household_kwh; } public void setStorage2household_kwh(double storage2household_kwh) { this.storage2household_kwh = storage2household_kwh; } public double getStorage2household_power() { return storage2household_power; } public void setStorage2household_power(double storage2household_power) { this.storage2household_power = storage2household_power; } public double getStorage2household_kwhd() { return storage2household_kwhd; } public void setStorage2household_kwhd(double storage2household_kwhd) { this.storage2household_kwhd = storage2household_kwhd; } public long getConsumption_kwh_time() { return consumption_kwh_time; } public void setConsumption_kwh_time(long consumption_kwh_time) { this.consumption_kwh_time = consumption_kwh_time; } public long getConsumption_power_time() { return consumption_power_time; } public void setConsumption_power_time(long consumption_power_time) { this.consumption_power_time = consumption_power_time; } public long getConsumption_kwhd_time() { return consumption_kwhd_time; } public void setConsumption_kwhd_time(long consumption_kwhd_time) { this.consumption_kwhd_time = consumption_kwhd_time; } public long getPv_power_time() { return pv_power_time; } public void setPv_power_time(long pv_power_time) { this.pv_power_time = pv_power_time; } public long getPv_kwhd_time() { return pv_kwhd_time; } public void setPv_kwhd_time(long pv_kwhd_time) { this.pv_kwhd_time = pv_kwhd_time; } public long getPv_kwh_time() { return pv_kwh_time; } public void setPv_kwh_time(long pv_kwh_time) { this.pv_kwh_time = pv_kwh_time; } public long getGrid2storage_kwh_time() { return grid2storage_kwh_time; } public void setGrid2storage_kwh_time(long grid2storage_kwh_time) { this.grid2storage_kwh_time = grid2storage_kwh_time; } public long getGrid2storage_power_time() { return grid2storage_power_time; } public void setGrid2storage_power_time(long grid2storage_power_time) { this.grid2storage_power_time = grid2storage_power_time; } public long getGrid2storage_kwhd_time() { return grid2storage_kwhd_time; } public void setGrid2storage_kwhd_time(long grid2storage_kwhd_time) { this.grid2storage_kwhd_time = grid2storage_kwhd_time; } public long getGrid2household_kwh_time() { return grid2household_kwh_time; } public void setGrid2household_kwh_time(long grid2household_kwh_time) { this.grid2household_kwh_time = grid2household_kwh_time; } public long getGrid2household_power_time() { return grid2household_power_time; } public void setGrid2household_power_time(long grid2household_power_time) { this.grid2household_power_time = grid2household_power_time; } public long getGrid2household_kwhd_time() { return grid2household_kwhd_time; } public void setGrid2household_kwhd_time(long grid2household_kwhd_time) { this.grid2household_kwhd_time = grid2household_kwhd_time; } public long getPv2storage_kwh_time() { return pv2storage_kwh_time; } public void setPv2storage_kwh_time(long pv2storage_kwh_time) { this.pv2storage_kwh_time = pv2storage_kwh_time; } public long getPv2storage_power_time() { return pv2storage_power_time; } public void setPv2storage_power_time(long pv2storage_power_time) { this.pv2storage_power_time = pv2storage_power_time; } public long getPv2storage_kwhd_time() { return pv2storage_kwhd_time; } public void setPv2storage_kwhd_time(long pv2storage_kwhd_time) { this.pv2storage_kwhd_time = pv2storage_kwhd_time; } public long getPv2household_kwh_time() { return pv2household_kwh_time; } public void setPv2household_kwh_time(long pv2household_kwh_time) { this.pv2household_kwh_time = pv2household_kwh_time; } public long getPv2household_power_time() { return pv2household_power_time; } public void setPv2household_power_time(long pv2household_power_time) { this.pv2household_power_time = pv2household_power_time; } public long getPv2household_kwhd_time() { return pv2household_kwhd_time; } public void setPv2household_kwhd_time(long pv2household_kwhd_time) { this.pv2household_kwhd_time = pv2household_kwhd_time; } public long getPv2grid_kwh_time() { return pv2grid_kwh_time; } public void setPv2grid_kwh_time(long pv2grid_kwh_time) { this.pv2grid_kwh_time = pv2grid_kwh_time; } public long getPv2grid_power_time() { return pv2grid_power_time; } public void setPv2grid_power_time(long pv2grid_power_time) { this.pv2grid_power_time = pv2grid_power_time; } public long getPv2grid_kwhd_time() { return pv2grid_kwhd_time; } public void setPv2grid_kwhd_time(long pv2grid_kwhd_time) { this.pv2grid_kwhd_time = pv2grid_kwhd_time; } public long getStorage2grid_kwh_time() { return storage2grid_kwh_time; } public void setStorage2grid_kwh_time(long storage2grid_kwh_time) { this.storage2grid_kwh_time = storage2grid_kwh_time; } public long getStorage2grid_power_time() { return storage2grid_power_time; } public void setStorage2grid_power_time(long storage2grid_power_time) { this.storage2grid_power_time = storage2grid_power_time; } public long getStorage2grid_kwhd_time() { return storage2grid_kwhd_time; } public void setStorage2grid_kwhd_time(long storage2grid_kwhd_time) { this.storage2grid_kwhd_time = storage2grid_kwhd_time; } public long getStorage2household_kwh_time() { return storage2household_kwh_time; } public void setStorage2household_kwh_time(long storage2household_kwh_time) { this.storage2household_kwh_time = storage2household_kwh_time; } public long getStorage2household_power_time() { return storage2household_power_time; } public void setStorage2household_power_time(long storage2household_power_time) { this.storage2household_power_time = storage2household_power_time; } public long getStorage2household_kwhd_time() { return storage2household_kwhd_time; } public void setStorage2household_kwhd_time(long storage2household_kwhd_time) { this.storage2household_kwhd_time = storage2household_kwhd_time; } @PrePersist protected void onCreate(){ timestamp = new Date(); } }
package com.tinkerpop.rexster.server; import com.codahale.metrics.JmxAttributeGauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.jersey.InstrumentedResourceMethodDispatchAdapter; import com.codahale.metrics.servlets.MetricsServlet; import com.sun.jersey.api.container.filter.LoggingFilter; import com.sun.jersey.api.core.ClassNamesResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider; import com.tinkerpop.rexster.EdgeResource; import com.tinkerpop.rexster.GraphResource; import com.tinkerpop.rexster.IndexResource; import com.tinkerpop.rexster.KeyIndexResource; import com.tinkerpop.rexster.PrefixResource; import com.tinkerpop.rexster.RexsterResource; import com.tinkerpop.rexster.RootResource; import com.tinkerpop.rexster.Tokens; import com.tinkerpop.rexster.VertexResource; import com.tinkerpop.rexster.filter.AbstractSecurityFilter; import com.tinkerpop.rexster.filter.DefaultSecurityFilter; import com.tinkerpop.rexster.filter.HeaderResponseFilter; import com.tinkerpop.rexster.server.metrics.AbstractReporterConfig; import com.tinkerpop.rexster.servlet.DogHouseServlet; import com.tinkerpop.rexster.servlet.EvaluatorServlet; import com.tinkerpop.rexster.servlet.RexsterStaticHttpHandler; import org.apache.commons.configuration.HierarchicalConfiguration; import org.apache.commons.configuration.XMLConfiguration; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.glassfish.grizzly.IOStrategy; import org.glassfish.grizzly.http.server.HttpHandler; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.NetworkListener; import org.glassfish.grizzly.http.server.ServerConfiguration; import org.glassfish.grizzly.servlet.ServletRegistration; import org.glassfish.grizzly.servlet.WebappContext; import org.glassfish.grizzly.threadpool.GrizzlyExecutorService; import org.glassfish.grizzly.threadpool.ThreadPoolConfig; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.ws.rs.core.Context; import java.io.File; public class HttpRexsterServer implements RexsterServer { private static final Logger logger = Logger.getLogger(HttpRexsterServer.class); private RexsterApplication app; private final RexsterProperties properties; private Integer rexsterServerPort; private String rexsterServerHost; private String webRootPath; private String baseUri; private int maxWorkerThreadPoolSize; private int coreWorkerThreadPoolSize; private int maxKernalThreadPoolSize; private int coreKernalThreadPoolSize; private int maxPostSize; private int maxHeaderSize; private int uploadTimeoutMillis; private boolean enableJmx; private String ioStrategy; private final HttpServer httpServer; private boolean debugMode; private boolean enableHttpReporter; private boolean enableDogHouse; private String convertRateTo; private String convertDurationTo; private String securityFilterType; private String defaultCharacterEncoding; private HttpHandler staticHttpHandler = null; private WebappContext wacDogHouse; private WebappContext wacJersey; private WebappContext wacMetrics; private String lastDefaultCharacterEncoding; private String lastSecurityFilterType; private Integer lastRexsterServerPort; private String lastRexsterServerHost; private String lastIoStrategy; private boolean lastEnableJmx; private int lastMaxWorkerThreadPoolSize; private int lastCoreWorkerThreadPoolSize; private int lastMaxKernalThreadPoolSize; private int lastCoreKernalThreadPoolSize; private boolean lastEnableDogHouse; private String lastWebRootPath; private String lastBaseUri; private boolean lastDebugMode; private boolean lastEnableHttpReporter; public HttpRexsterServer(final XMLConfiguration configuration) { this(new RexsterProperties(configuration)); } public HttpRexsterServer(final RexsterProperties properties) { this.properties = properties; this.httpServer = new HttpServer(); updateSettings(properties.getConfiguration()); properties.addListener(new RexsterProperties.RexsterPropertiesListener() { @Override public void propertiesChanged(final XMLConfiguration configuration) { // maintain history of previous settings lastRexsterServerHost = rexsterServerHost; lastRexsterServerPort = rexsterServerPort; lastEnableJmx = enableJmx; lastIoStrategy = ioStrategy; lastMaxWorkerThreadPoolSize = maxWorkerThreadPoolSize; lastCoreWorkerThreadPoolSize = coreWorkerThreadPoolSize; lastMaxKernalThreadPoolSize = maxKernalThreadPoolSize; lastCoreKernalThreadPoolSize = coreKernalThreadPoolSize; lastEnableDogHouse = enableDogHouse; lastWebRootPath = webRootPath; lastBaseUri = baseUri; lastSecurityFilterType = securityFilterType; lastDefaultCharacterEncoding = defaultCharacterEncoding; lastDebugMode = debugMode; lastEnableHttpReporter = enableHttpReporter; updateSettings(configuration); try { reconfigure(app); } catch (Exception ex) { logger.error("Could not modify Rexster configuration. Please restart Rexster to allow changes to be applied.", ex); } } }); } @Override public void stop() throws Exception { this.httpServer.stop(); } @Override public void start(final RexsterApplication application) throws Exception { this.app = application; reconfigure(application); } /** * Reconfigures and starts the server if not already started. */ public void reconfigure(final RexsterApplication application) throws Exception { // Seems to be a bug in WebappContext.undeploy() of grizzly that not only undeploy's the context,but // all the servlet registrations from other contexts as well. hence....it is not possible to undeploy // just a single context with tearing everything down and building it back. unfortunately this means that // a full undeploy and redeploy of all apps installed to the web server need to be removed and put back // on any change. ....either that, or I don't get the undeploy() method and what it's supposed to do if (hasAnythingChanged()) { if (this.wacJersey != null) { this.wacJersey.undeploy(); this.wacJersey = null; } if (this.wacDogHouse != null) { this.wacDogHouse.undeploy(); this.wacDogHouse = null; } if (this.wacMetrics != null) { this.wacMetrics.undeploy(); this.wacMetrics = null; } } deployRestApi(application); deployStaticResourceServer(); deployDogHouse(application); deployMetricsAdmin(application); this.configureNetworkListener(); // the JMX settings below pipe in metrics from Grizzly. if (hasEnableJmxChanged()) { this.httpServer.getServerConfiguration().setJmxEnabled(enableJmx); manageJmxMetrics(application, enableJmx); logger.info(this.enableJmx ? "JMX enabled on HTTP/REST." : "JMX disabled on HTTP/REST."); } if (!this.httpServer.isStarted()) { this.httpServer.start(); } logger.info("Rexster Server running on: [" + baseUri + ":" + rexsterServerPort + "]"); } private void manageJmxMetrics(final RexsterApplication application, final boolean register) throws MalformedObjectNameException { // the JMX settings below pipe in metrics from Grizzly. final MetricRegistry metricRegistry = application.getMetricRegistry(); manageMetricsFromJmx(metricRegistry, register); logger.info(register ? "Registered JMX Metrics." : "Removed JMX Metrics."); } private boolean hasAnythingChanged() { return hasRestConfigurationsChanged() || hasWebRootChanged() || hasEnableDogHouseChanged() || hasBaseUriChanged() || hasEnableHttpReporterChanged(); } private boolean hasWebRootChanged() { return !this.webRootPath.equals(this.lastWebRootPath); } private boolean hasPortHostChanged() { return !this.rexsterServerPort.equals(this.lastRexsterServerPort) || !this.lastRexsterServerHost.equals(this.rexsterServerHost); } private boolean hasEnableJmxChanged() { return this.enableJmx != this.lastEnableJmx; } private boolean hasEnableDogHouseChanged() { return this.enableDogHouse != this.lastEnableDogHouse; } private boolean hasBaseUriChanged() { return !this.baseUri.equals(this.lastBaseUri); } private boolean hasIoStrategyChanged() { return !this.ioStrategy.equals(this.lastIoStrategy); } private boolean hasThreadPoolSizeChanged() { return this.maxKernalThreadPoolSize != lastMaxKernalThreadPoolSize || this.maxWorkerThreadPoolSize != lastMaxWorkerThreadPoolSize || this.coreKernalThreadPoolSize != lastCoreKernalThreadPoolSize || this.coreWorkerThreadPoolSize != this.lastCoreWorkerThreadPoolSize; } private boolean hasRestConfigurationsChanged() { return !this.securityFilterType.equals(this.lastSecurityFilterType) || !this.defaultCharacterEncoding.equals(this.lastDefaultCharacterEncoding) || this.debugMode != lastDebugMode; } private boolean hasEnableHttpReporterChanged() { return this.enableHttpReporter != this.lastEnableHttpReporter; } private void updateSettings(final XMLConfiguration configuration) { this.debugMode = configuration.getBoolean("debug", false); this.enableDogHouse = configuration.getBoolean("http.enable-doghouse", true); this.enableHttpReporter = configuration.getBoolean("http-reporter-enabled", false); this.convertRateTo = configuration.getString("http-reporter-convert", AbstractReporterConfig.DEFAULT_TIME_UNIT.toString()); this.convertDurationTo = configuration.getString("http-reporter-duration", AbstractReporterConfig.DEFAULT_TIME_UNIT.toString()); this.rexsterServerPort = configuration.getInteger("http.server-port", new Integer(RexsterSettings.DEFAULT_HTTP_PORT)); this.rexsterServerHost = configuration.getString("http.server-host", "0.0.0.0"); this.webRootPath = configuration.getString("http.web-root", RexsterSettings.DEFAULT_WEB_ROOT_PATH); this.baseUri = configuration.getString("http.base-uri", RexsterSettings.DEFAULT_BASE_URI); this.coreWorkerThreadPoolSize = configuration.getInt("http.thread-pool.worker.core-size", 8); this.maxWorkerThreadPoolSize = configuration.getInt("http.thread-pool.worker.max-size", 8); this.coreKernalThreadPoolSize = configuration.getInt("http.thread-pool.kernal.core-size", 4); this.maxKernalThreadPoolSize = configuration.getInt("http.thread-pool.kernal.max-size", 4); this.maxPostSize = configuration.getInt("http.max-post-size", 2097152); this.maxHeaderSize = configuration.getInt("http.max-header-size", 8192); this.uploadTimeoutMillis = configuration.getInt("http.upload-timeout-millis", 300000); this.enableJmx = configuration.getBoolean("http.enable-jmx", false); this.ioStrategy = configuration.getString("http.io-strategy", "leader-follower"); this.defaultCharacterEncoding = configuration.getString("http.character-set", "ISO-8859-1"); HierarchicalConfiguration securityConfiguration = null; try { securityConfiguration = configuration.configurationAt(Tokens.REXSTER_SECURITY_AUTH); } catch (IllegalArgumentException iae) { // do nothing...null is cool } securityFilterType = securityConfiguration != null ? securityConfiguration.getString("type") : Tokens.REXSTER_SECURITY_NONE; } private static void manageMetricsFromJmx(final MetricRegistry metricRegistry, final boolean register) throws MalformedObjectNameException { final String jmxObjectMemoryManager = "org.glassfish.grizzly:pp=/gmbal-root/TCPNIOTransport[RexPro],type=HeapMemoryManager,name=MemoryManager"; final String metricGroupMemoryManager = "heap-memory-manager"; final String[] heapMemoryManagerMetrics = new String[] { "pool-allocated-bytes", "pool-released-bytes", "real-allocated-bytes", "total-allocated-bytes" }; manageJmxKeysAsMetric(metricRegistry, jmxObjectMemoryManager, metricGroupMemoryManager, heapMemoryManagerMetrics, register); final String jmxObjectHttpServerFilter = "org.glassfish.grizzly:pp=/gmbal-root/HttpServer[HttpServer]/NetworkListener[NetworkListener[grizzly]],type=HttpServerFilter,name=HttpServerFilter"; final String metricGroupHttpServerFilter = "http-server"; final String[] httpServerManagerMetrics = new String [] { "current-suspended-request-count", "requests-cancelled-count", "requests-completed-count", "requests-received-count", "requests-timed-out-count" }; manageJmxKeysAsMetric(metricRegistry, jmxObjectHttpServerFilter, metricGroupHttpServerFilter, httpServerManagerMetrics, register); final String jmxObjectHttpKeepAlive = "org.glassfish.grizzly:pp=/gmbal-root/HttpServer[HttpServer]/NetworkListener[NetworkListener[grizzly]],type=KeepAlive,name=Keep-Alive"; final String metricGroupHttpKeepAlive = "http-keep-alive"; final String[] httpKeepAliveMetrics = new String [] { "hits-count", "idle-timeout-seconds", "live-connections-count", "max-requests-count", "refuses-count", "timeouts-count" }; manageJmxKeysAsMetric(metricRegistry, jmxObjectHttpKeepAlive, metricGroupHttpKeepAlive, httpKeepAliveMetrics, register); final String jmxObjectNetworkListener = "org.glassfish.grizzly:pp=/gmbal-root/HttpServer[HttpServer],type=NetworkListener,name=NetworkListener[grizzly]"; final String metricGroupNetworkListener = "network-listener"; final String [] networkListenerMetrics = new String[] { "chunking-enabled", "host", "idle-timeout-seconds", "max-http-header-size", "max-pending-bytes", "port" }; manageJmxKeysAsMetric(metricRegistry, jmxObjectNetworkListener, metricGroupNetworkListener, networkListenerMetrics, register); final String jmxObjectTcpNioTransport = "org.glassfish.grizzly:pp=/gmbal-root/HttpServer[HttpServer]/NetworkListener[NetworkListener[grizzly]],type=TCPNIOTransport,name=Transport"; final String metricGroupTcpNioTransport = "tcp-nio-transport"; final String [] tcpNioTransportMetrics = new String[] { "bound-addresses", "bytes-read", "bytes-written", "client-connect-timeout-millis", "io-strategy", "open-connections-count", "read-buffer-size", "selector-threads-count", "server-socket-so-timeout", "total-connections-count", "write-buffer-size" }; manageJmxKeysAsMetric(metricRegistry, jmxObjectTcpNioTransport, metricGroupTcpNioTransport, tcpNioTransportMetrics, register); final String jmxObjectThreadPool = "org.glassfish.grizzly:pp=/gmbal-root/HttpServer[HttpServer]/NetworkListener[NetworkListener[grizzly]]/TCPNIOTransport[Transport],type=ThreadPool,name=ThreadPool"; final String metricGroupThreadPool = "thread-pool"; final String [] threadPoolMetrics = new String[] { "thread-pool-allocated-thread-count", "thread-pool-core-pool-size", "thread-pool-max-num-threads", "thread-pool-queued-task-count", "thread-pool-task-queue-overflow-count", "thread-pool-total-allocated-thread-count", "thread-pool-total-completed-tasks-count", "thread-pool-type" }; manageJmxKeysAsMetric(metricRegistry, jmxObjectThreadPool, metricGroupThreadPool, threadPoolMetrics, register); } private static void manageJmxKeysAsMetric(final MetricRegistry metricRegistry, final String jmxObjectName, final String metricGroup, final String[] metricKeys, final boolean register) throws MalformedObjectNameException { for (String metricKey : metricKeys) { if (register) registerJmxKeyAsMetric(metricRegistry, metricGroup, jmxObjectName, metricKey); else deregisterJmxKeyAsMetric(metricRegistry, metricGroup, metricKey); } } private static void registerJmxKeyAsMetric(final MetricRegistry metricRegistry, final String metricGroup, final String jmxObjectName, final String jmxAttributeName) throws MalformedObjectNameException { metricRegistry.register(MetricRegistry.name("http", "core", metricGroup, jmxAttributeName), new JmxAttributeGauge(new ObjectName(jmxObjectName), jmxAttributeName)); } private static void deregisterJmxKeyAsMetric(final MetricRegistry metricRegistry, final String metricGroup, final String jmxAttributeName) throws MalformedObjectNameException { metricRegistry.remove(MetricRegistry.name("http", "core", metricGroup, jmxAttributeName)); } private void deployRestApi(final RexsterApplication application) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (hasAnythingChanged()) { wacJersey = new WebappContext("jersey", ""); // explicitly load resources so that the "RexsterApplicationProvider" class is not loaded final ResourceConfig rc = constructResourceConfig(); // constructs an injectable for the RexsterApplication instance. This get constructed externally // and is passed into the HttpRexsterServer. The SingletonTypeInjectableProvider is responsible for // pushing that instance into the context. rc.getSingletons().add(new SingletonTypeInjectableProvider<Context, RexsterApplication>( RexsterApplication.class, application) { }); rc.getSingletons().add(new InstrumentedResourceMethodDispatchAdapter(application.getMetricRegistry())); if (this.debugMode) { rc.getContainerRequestFilters().add(new LoggingFilter()); rc.getContainerResponseFilters().add(new LoggingFilter()); } rc.getContainerResponseFilters().add(new HeaderResponseFilter(defaultCharacterEncoding)); if (!securityFilterType.equals(Tokens.REXSTER_SECURITY_NONE)) { if (securityFilterType.equals(Tokens.REXSTER_SECURITY_DEFAULT)) { wacJersey.addContextInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, DefaultSecurityFilter.class.getName()); rc.getContainerRequestFilters().add(new DefaultSecurityFilter()); } else { wacJersey.addContextInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, securityFilterType); final Class clazz = Class.forName(securityFilterType, true, Thread.currentThread().getContextClassLoader()); final AbstractSecurityFilter securityFilter = (AbstractSecurityFilter) clazz.newInstance(); securityFilter.configure(properties.getConfiguration()); rc.getContainerRequestFilters().add(securityFilter); } } final ServletRegistration sg = wacJersey.addServlet("jersey", new ServletContainer(rc));
// FormatTools.java package loci.formats; import java.awt.image.BufferedImage; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Hashtable; /** A utility class for format reader and writer implementations. */ public final class FormatTools { // -- Constants -- /** Identifies the <i>INT8</i> data type used to store pixel values. */ public static final int INT8 = 0; /** Identifies the <i>UINT8</i> data type used to store pixel values. */ public static final int UINT8 = 1; /** Identifies the <i>INT16</i> data type used to store pixel values. */ public static final int INT16 = 2; /** Identifies the <i>UINT16</i> data type used to store pixel values. */ public static final int UINT16 = 3; /** Identifies the <i>INT32</i> data type used to store pixel values. */ public static final int INT32 = 4; /** Identifies the <i>UINT32</i> data type used to store pixel values. */ public static final int UINT32 = 5; /** Identifies the <i>FLOAT</i> data type used to store pixel values. */ public static final int FLOAT = 6; /** Identifies the <i>DOUBLE</i> data type used to store pixel values. */ public static final int DOUBLE = 7; /** Human readable pixel type. */ private static String[] pixelTypes; static { pixelTypes = new String[8]; pixelTypes[INT8] = "int8"; pixelTypes[UINT8] = "uint8"; pixelTypes[INT16] = "int16"; pixelTypes[UINT16] = "uint16"; pixelTypes[INT32] = "int32"; pixelTypes[UINT32] = "uint32"; pixelTypes[FLOAT] = "float"; pixelTypes[DOUBLE] = "double"; } // -- Constructor -- private FormatTools() { } // -- Utility methods -- /** * A utility method for test reading a file from the command line, * and displaying the results in a simple display. */ public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean omexml = false; boolean ignoreColors = false; boolean normalize = false; boolean fastBlit = false; int start = 0; int end = Integer.MAX_VALUE; int series = 0; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-nocolors")) ignoreColors = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatReader.setDebug(true); else if (args[i].equals("-level")) { try { FormatReader.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-map")) map = args[++i]; else System.out.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else System.out.println("Ignoring unknown argument: " + args[i]); } } } if (FormatReader.debug) { System.out.println("Debugging at level " + FormatReader.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String format = reader.getFormat(); String[] s = { "To test read a file in " + format + " format, run:", " java " + className + " [-nopix] [-nometa] [-thumbs] [-merge]", " [-stitch] [-separate] [-nocolors] [-omexml] [-normalize] [-fast]", " [-debug] [-range start end] [-series num] [-map id] file", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -nocolors: ignore color lookup tables, if present", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -map: specify file on disk to which name should be mapped", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) System.out.println(s[i]); return false; } if (map != null) Location.mapId(id, map); if (omexml) { try { Class c = Class.forName("loci.formats.ome.OMEXMLMetadataStore"); MetadataStore ms = (MetadataStore) c.newInstance(); reader.setMetadataStore(ms); } catch (Throwable t) { // NB: error messages for missing OME-Java are printed later } } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; System.out.print("Checking file format "); System.out.println("[" + ir.getFormat(id) + "]"); } else { // verify format System.out.print("Checking " + reader.getFormat() + " format "); System.out.println(reader.isThisType(id) ? "[yes]" : "[no]"); } if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); reader.setColorTableIgnored(ignoreColors); reader.setNormalized(normalize); reader.setMetadataFiltered(true); if (!normalize && reader.getPixelType(id) == FLOAT) { throw new FormatException("Sorry, unnormalized floating point " + "data is not supported. Please use the '-normalize' option."); } // read basic metadata System.out.println(); System.out.println("Reading core metadata"); System.out.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) System.out.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(id); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { System.out.println( "************ Warning: invalid used files list ************"); } if (used == null) { System.out.println("Used files = null"); } else if (used.length == 0) { System.out.println("Used files = []"); } else if (used.length > 1) { System.out.println("Used files:"); for (int u=0; u<used.length; u++) System.out.println("\t" + used[u]); } else if (!id.equals(used[0])) { System.out.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(id); System.out.println("Series count = " + seriesCount); for (int j=0; j<seriesCount; j++) { reader.setSeries(id, j); // read basic metadata for series int imageCount = reader.getImageCount(id); boolean rgb = reader.isRGB(id); int rgbChanCount = reader.getRGBChannelCount(id); boolean interleaved = reader.isInterleaved(id); int sizeX = reader.getSizeX(id); int sizeY = reader.getSizeY(id); int sizeZ = reader.getSizeZ(id); int sizeC = reader.getSizeC(id); int effSizeC = reader.getEffectiveSizeC(id); int sizeT = reader.getSizeT(id); int thumbSizeX = reader.getThumbSizeX(id); int thumbSizeY = reader.getThumbSizeY(id); boolean little = reader.isLittleEndian(id); String dimOrder = reader.getDimensionOrder(id); boolean orderCertain = reader.isOrderCertain(id); int pixelType = reader.getPixelType(id); // output basic metadata for series System.out.println("Series System.out.println("\tImage count = " + imageCount); System.out.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) System.out.print(" (merged)"); else if (separate) System.out.print(" (separated)"); if (rgb != (rgbChanCount != 1)) { System.out.println("\t************ Warning: RGB mismatch ************"); } System.out.println(); System.out.println("\tInterleaved = " + interleaved); System.out.println("\tWidth = " + sizeX); System.out.println("\tHeight = " + sizeY); System.out.println("\tSizeZ = " + sizeZ); System.out.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { System.out.print(" (effectively " + effSizeC + ")"); } System.out.println(); System.out.println("\tSizeT = " + sizeT); if (imageCount != sizeZ * effSizeC * sizeT) { System.out.println("\t************ Warning: ZCT mismatch ************"); } System.out.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); System.out.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); System.out.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); System.out.println("\tPixel type = " + getPixelTypeString(pixelType)); if (doMeta) { System.out.println("\t int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(id, indices[i]); indices2[i] = reader.getIndex(id, zct[i][0], zct[i][1], zct[i][2]); System.out.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { System.out.println(" [mismatch: " + indices2[i] + "]"); } else System.out.println(); } } } reader.setSeries(id, series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(id); // read pixels if (pixels) { System.out.println(); System.out.print("Reading" + s + " pixel data "); long s1 = System.currentTimeMillis(); int num = reader.getImageCount(id); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; System.out.print("(" + start + "-" + end + ") "); long e1 = System.currentTimeMillis(); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(id, i) : reader.openImage(id, i); } else { int x = reader.getSizeX(id); int y = reader.getSizeY(id); byte[] b = thumbs ? reader.openThumbBytes(id, i) : reader.openBytes(id, i); Object pix = DataTools.makeDataArray(b, getBytesPerPixel(reader.getPixelType(id)), reader.getPixelType(id) == FLOAT, reader.isLittleEndian(id)); images[i - start] = ImageTools.makeImage(ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = ImageTools.getPixelType(images[i - start]); if (pixType != pixelType && !fastBlit) { if (!mismatch) { System.out.println(); mismatch = true; } System.out.println("\tPlane #" + i + ": pixel type mismatch: " + getPixelTypeString(pixType) + "/" + getPixelTypeString(pixelType)); } else { mismatch = false; System.out.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) System.out.print(" "); System.out.println("[done]"); // output timing results float sec = (e2 - s1) / 1000f; float avg = (float) (e2 - s2) / images.length; long initial = e1 - s1; System.out.println(sec + "s elapsed (" + avg + "ms per image, " + initial + "ms overhead)"); // display pixels in image viewer ImageViewer viewer = new ImageViewer(); viewer.setImages(id, reader, images); viewer.setVisible(true); } // read format-specific metadata table if (doMeta) { System.out.println(); System.out.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(id); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { System.out.print(keys[i] + ": "); System.out.println(reader.getMetadataValue(id, keys[i])); } } // output OME-XML if (omexml) { System.out.println(); System.out.println("Generating OME-XML"); MetadataStore ms = reader.getMetadataStore(id); if (ms.getClass().getName().equals( "loci.formats.ome.OMEXMLMetadataStore")) { try { Method m = ms.getClass().getMethod("dumpXML", (Class[]) null); System.out.println(m.invoke(ms, (Object[]) null)); System.out.println(); } catch (Throwable t) { System.out.println("Error generating OME-XML:"); t.printStackTrace(); } } else { System.out.println("OME-Java library not found; no OME-XML available"); } } return true; } // -- Dimensional positions -- /** * Gets the rasterized index corresponding * to the given Z, C and T coordinates. */ public static int getIndex(IFormatReader reader, String id, int z, int c, int t) throws FormatException, IOException { String order = reader.getDimensionOrder(id); int zSize = reader.getSizeZ(id); int cSize = reader.getEffectiveSizeC(id); int tSize = reader.getSizeT(id); int num = reader.getImageCount(id); return getIndex(order, zSize, cSize, tSize, num, z, c, t); } /** * Gets the rasterized index corresponding * to the given Z, C and T coordinates. */ public static int getIndex(String order, int zSize, int cSize, int tSize, int num, int z, int c, int t) throws FormatException, IOException { // check DimensionOrder if (order == null) throw new FormatException("Dimension order is null"); if (!order.startsWith("XY")) { throw new FormatException("Invalid dimension order: " + order); } int iz = order.indexOf("Z") - 2; int ic = order.indexOf("C") - 2; int it = order.indexOf("T") - 2; if (iz < 0 || iz > 2 || ic < 0 || ic > 2 || it < 0 || it > 2) { throw new FormatException("Invalid dimension order: " + order); } // check SizeZ if (zSize <= 0) throw new FormatException("Invalid Z size: " + zSize); if (z < 0 || z >= zSize) { throw new FormatException("Invalid Z index: " + z + "/" + zSize); } // check SizeC if (cSize <= 0) throw new FormatException("Invalid C size: " + cSize); if (c < 0 || c >= cSize) { throw new FormatException("Invalid C index: " + c + "/" + cSize); } // check SizeT if (tSize <= 0) throw new FormatException("Invalid T size: " + tSize); if (t < 0 || t >= tSize) { throw new FormatException("Invalid T index: " + t + "/" + tSize); } // check image count if (num <= 0) throw new FormatException("Invalid image count: " + num); if (num != zSize * cSize * tSize) { // if this happens, there is probably a bug in metadata population -- // either one of the ZCT sizes, or the total number of images -- // or else the input file is invalid throw new FormatException("ZCT size vs image count mismatch (sizeZ=" + zSize + ", sizeC=" + cSize + ", sizeT=" + tSize + ", total=" + num + ")"); } // assign rasterization order int v0 = iz == 0 ? z : (ic == 0 ? c : t); int v1 = iz == 1 ? z : (ic == 1 ? c : t); int v2 = iz == 2 ? z : (ic == 2 ? c : t); int len0 = iz == 0 ? zSize : (ic == 0 ? cSize : tSize); int len1 = iz == 1 ? zSize : (ic == 1 ? cSize : tSize); int len2 = iz == 2 ? zSize : (ic == 2 ? cSize : tSize); return v0 + v1 * len0 + v2 * len0 * len1; } /** * Gets the Z, C and T coordinates corresponding * to the given rasterized index value. */ public static int[] getZCTCoords(IFormatReader reader, String id, int index) throws FormatException, IOException { String order = reader.getDimensionOrder(id); int zSize = reader.getSizeZ(id); int cSize = reader.getEffectiveSizeC(id); int tSize = reader.getSizeT(id); int num = reader.getImageCount(id); return getZCTCoords(order, zSize, cSize, tSize, num, index); } /** * Gets the Z, C and T coordinates corresponding to the given rasterized * index value. */ public static int[] getZCTCoords(String order, int zSize, int cSize, int tSize, int num, int index) throws FormatException, IOException { // check DimensionOrder if (order == null) throw new FormatException("Dimension order is null"); if (!order.startsWith("XY")) { throw new FormatException("Invalid dimension order: " + order); } int iz = order.indexOf("Z") - 2; int ic = order.indexOf("C") - 2; int it = order.indexOf("T") - 2; if (iz < 0 || iz > 2 || ic < 0 || ic > 2 || it < 0 || it > 2) { throw new FormatException("Invalid dimension order: " + order); } // check SizeZ if (zSize <= 0) throw new FormatException("Invalid Z size: " + zSize); // check SizeC if (cSize <= 0) throw new FormatException("Invalid C size: " + cSize); // check SizeT if (tSize <= 0) throw new FormatException("Invalid T size: " + tSize); // check image count if (num <= 0) throw new FormatException("Invalid image count: " + num); if (num != zSize * cSize * tSize) { // if this happens, there is probably a bug in metadata population -- // either one of the ZCT sizes, or the total number of images -- // or else the input file is invalid throw new FormatException("ZCT size vs image count mismatch (sizeZ=" + zSize + ", sizeC=" + cSize + ", sizeT=" + tSize + ", total=" + num + ")"); } if (index < 0 || index >= num) { throw new FormatException("Invalid image index: " + index + "/" + num); } // assign rasterization order int len0 = iz == 0 ? zSize : (ic == 0 ? cSize : tSize); int len1 = iz == 1 ? zSize : (ic == 1 ? cSize : tSize); //int len2 = iz == 2 ? sizeZ : (ic == 2 ? sizeC : sizeT); int v0 = index % len0; int v1 = index / len0 % len1; int v2 = index / len0 / len1; int z = iz == 0 ? v0 : (iz == 1 ? v1 : v2); int c = ic == 0 ? v0 : (ic == 1 ? v1 : v2); int t = it == 0 ? v0 : (it == 1 ? v1 : v2); return new int[] {z, c, t}; } /** * Computes a unique 1-D index corresponding to the multidimensional * position given in the pos array, using the specified lengths array * as the maximum value at each positional dimension. */ public static int positionToRaster(int[] lengths, int[] pos) { int[] offsets = new int[lengths.length]; if (offsets.length > 0) offsets[0] = 1; for (int i=1; i<offsets.length; i++) { offsets[i] = offsets[i - 1] * lengths[i - 1]; } int raster = 0; for (int i=0; i<pos.length; i++) raster += offsets[i] * pos[i]; return raster; } /** * Computes a unique 3-D position corresponding to the given raster * value, using the specified lengths array as the maximum value at * each positional dimension. */ public static int[] rasterToPosition(int[] lengths, int raster) { int[] offsets = new int[lengths.length]; if (offsets.length > 0) offsets[0] = 1; for (int i=1; i<offsets.length; i++) { offsets[i] = offsets[i - 1] * lengths[i - 1]; } int[] pos = new int[lengths.length]; for (int i=0; i<pos.length; i++) { int q = i < pos.length - 1 ? raster % offsets[i + 1] : raster; pos[i] = q / offsets[i]; raster -= q; } return pos; } /** * Computes the number of raster values for a positional array * with the given lengths. */ public static int getRasterLength(int[] lengths) { int len = 1; for (int i=0; i<lengths.length; i++) len *= lengths[i]; return len; } // -- Pixel types -- /** * Takes a string value and maps it to one of the pixel type enumerations. * @param pixelTypeAsString the pixel type as a string. * @return type enumeration value for use with class constants. */ public static int pixelTypeFromString(String pixelTypeAsString) { String lowercaseTypeAsString = pixelTypeAsString.toLowerCase(); for (int i = 0; i < pixelTypes.length; i++) { if (pixelTypes[i].equals(lowercaseTypeAsString)) return i; } throw new RuntimeException("Unknown type: '" + pixelTypeAsString + "'"); } /** * Takes a pixel type value and gets a corresponding string representation. * @param pixelType the pixel type. * @return string value for human-readable output. */ public static String getPixelTypeString(int pixelType) { return pixelType < 0 || pixelType >= pixelTypes.length ? "unknown (" + pixelType + ")" : pixelTypes[pixelType]; } /** * Retrieves how many bytes per pixel the current plane or section has. * @param type the pixel type as retrieved from * {@link IFormatReader#getPixelType(String)}. * @return the number of bytes per pixel. * @see IFormatReader#getPixelType(String) */ public static int getBytesPerPixel(int type) { switch (type) { case INT8: case UINT8: return 1; case INT16: case UINT16: return 2; case INT32: case UINT32: case FLOAT: return 4; case DOUBLE: return 8; } throw new RuntimeException("Unknown type with id: '" + type + "'"); } }
package org.ister.nerlo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.apache.commons.cli.*; /** * Main class. * * We should read node spec from command line and/or conf file. * * @author ingo */ public class Main { private final String[] args; private final String pwd = System.getProperty("user.dir"); private String sname = "jnode"; private String cookie = "123456"; private String peer = "shell"; private String propf = pwd + "/properties"; private static JNode NODE = null; private static Properties PROPERTIES = null; private static final String VERSION = "0.0.1-alpha"; private static final String NAME = "nerlo"; private Main(String[] args) { this.args = args; } /** * Run the program. * * @throws Exception */ public void run() throws Exception { parseOptions(this.args); initProps(this.propf); NODE = JNode.getInstance(cookie, sname, peer); NODE.run(); } private void parseOptions(String[] args) { CommandLineParser parser = new GnuParser(); try { Options options = getOptions(); CommandLine line = parser.parse( options, args ); processCommandLine(line, options); } catch( ParseException e ) { System.out.println( "Parsing command line failed. Reason: " + e.getMessage() ); } } private void processCommandLine(CommandLine line, Options options) { if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); printBanner(); formatter.printHelp(NAME + " [options]", options); System.exit(0); } if (line.hasOption("version")) { printBanner(); System.exit(0); } if (line.hasOption("sname")) { this.sname = line.getOptionValue("sname"); } if (line.hasOption("cookie")) { this.cookie = line.getOptionValue("cookie"); } if (line.hasOption("peer")) { this.peer = line.getOptionValue("peer"); } if (line.hasOption("ps")) { this.propf = line.getOptionValue("ps"); } } private void printBanner() { System.out.println(NAME + " version " + VERSION); } @SuppressWarnings("static-access") private Options getOptions() { Option help = new Option("help", "print this message"); Option version = new Option("version", "print the version information and exit"); Option sname = OptionBuilder.withArgName("sname") .hasArg() .withDescription("give short name of Java node") .create("sname"); Option cookie = OptionBuilder.withArgName("cookie") .hasArg() .withDescription("Erlang cookie") .create("cookie"); Option peer = OptionBuilder.withArgName("peer") .hasArg() .withDescription("give short name of Erlang node") .create("peer"); Option propf = OptionBuilder.withArgName("properties") .hasArg() .withDescription("give path to properties file") .create("ps"); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(sname); options.addOption(cookie); options.addOption(peer); options.addOption(propf); return options; } private void initProps(String path) throws IOException { Properties PROPERTIES = new Properties(); try { FileInputStream stream = new FileInputStream(path); PROPERTIES.load(stream); stream.close(); } catch (FileNotFoundException e) { System.out.println("ERROR: properties file not found at " + path); } } public static JNode getJNode() throws IllegalStateException { if (NODE == null) { throw new IllegalStateException("JNode not initialized"); } return NODE; } /** * * @param key * @param def * @return */ public static String getProperty(String key, String def) { if (PROPERTIES == null) { throw new IllegalStateException("Properties not initialized"); } return PROPERTIES.getProperty(key, def); } /* MAIN */ /** * Main */ public static void main(String[] args) throws Exception { Main main = new Main(args); main.run(); } }
package org.jasig.portal.i18n; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import org.jasig.portal.PropertiesManager; import org.jasig.portal.security.IPerson; import org.jasig.portal.services.LogService; import org.jasig.portal.utils.CommonUtils; import org.jasig.portal.utils.DocumentFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Manages locales on behalf of a user. * This class currently keeps track of locales at the following levels:<br> * <ol> * <li>User's locale preferences (associated with a user ID)</li> * <li>Browser's locale preferences (from the Accept-Language request header)</li> * <li>Session's locale preferences (set via the portal request parameter uP_locales)</li> * <li>Portal's locale preferences (set in portal.properties)</li> * </ol> * Eventually, this class will also keep track of locale preferences at * the following levels:<br> * <ol> * <li>Layout node's locale preferences</li> * <li>User profile's locale preferences</li> * </ol> * @author Shoji Kajita <a href="mailto:">kajita@itc.nagoya-u.ac.jp</a> * @author Ken Weiner, kweiner@unicon.net * @version $Revision$ */ public class LocaleManager { private IPerson person; private static boolean localeAware = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.i18n.LocaleManager.locale_aware"); private static Locale jvmLocale; private static Locale[] portalLocales; private Locale[] sessionLocales; private Locale[] browserLocales; private Locale[] userLocales; /** * Constructor that associates a locale manager with a user. * @param person the user */ public LocaleManager(IPerson person) { this.person = person; jvmLocale = Locale.getDefault(); if (localeAware) { portalLocales = loadPortalLocales(); try { userLocales = LocaleStoreFactory.getLocaleStoreImpl().getUserLocales(person); } catch (Exception e) { LogService.log(LogService.ERROR, e); } } } /** * Constructor that sets up locales according to * the <code>Accept-Language</code> request header * from a user's browser. * @param person the user * @param acceptLanguage the Accept-Language request header from a user's browser */ public LocaleManager(IPerson person, String acceptLanguage) { this(person); this.browserLocales = parseLocales(acceptLanguage); } // Getters public boolean isLocaleAware() { return localeAware; } public static Locale getJvmLocale() { return jvmLocale; } public static Locale[] getPortalLocales() { return portalLocales; } public Locale[] getBrowserLocales() { return browserLocales; } public Locale[] getUserLocales() { return userLocales; } public Locale[] getSessionLocales() { return sessionLocales; } // Setters public static void setJvmLocale(Locale jvmLocale) { LocaleManager.jvmLocale = jvmLocale; } public static void setPortalLocales(Locale[] portalLocales) { LocaleManager.portalLocales = portalLocales; } public void setBrowserLocales(Locale[] browserLocales) { this.browserLocales = browserLocales; } public void setUserLocales(Locale[] userLocales) { this.userLocales = userLocales; } public void setSessionLocales(Locale[] sessionLocales) { this.sessionLocales = sessionLocales; } /** * Read and parse portal_locales from portal.properties. * portal_locales will be in the form of a comma-separated * list, e.g. en_US,ja_JP,sv_SE */ private Locale[] loadPortalLocales() { String portalLocalesString = PropertiesManager.getProperty("org.jasig.portal.i18n.LocaleManager.portal_locales"); return parseLocales(portalLocalesString); } /** * Produces a sorted list of locales according to locale preferences * obtained from several places. The following priority is given: * session, user, browser, portal, and jvm. * @return the sorted list of locales */ public Locale[] getLocales() { // Need logic to construct ordered locale list. // Consider creating a separate ILocaleResolver // interface to do this work. List locales = new ArrayList(); // Add highest priority locales first addToLocaleList(locales, sessionLocales); addToLocaleList(locales, userLocales); // We will ignore browser locales until we know how to // translate them into proper java.util.Locales //addToLocaleList(locales, browserLocales); addToLocaleList(locales, portalLocales); addToLocaleList(locales, new Locale[] { jvmLocale }); return (Locale[])locales.toArray(new Locale[0]); } /** * Add locales to the locale list if they aren't in there already */ private void addToLocaleList(List localeList, Locale[] locales) { if (locales != null) { for (int i = 0; i < locales.length; i++) { if (locales[i] != null && !localeList.contains(locales[i])) localeList.add(locales[i]); } } } /** * Helper method to produce a <code>java.util.Locale</code> array from * a comma-delimited locale string list, e.g. "en_US,ja_JP" * @param localeStringList the locales to parse * @return an array of locales representing the locale string list */ public static Locale[] parseLocales(String localeStringList) { Locale[] locales = null; if (localeStringList != null) { StringTokenizer st = new StringTokenizer(localeStringList, ","); locales = new Locale[st.countTokens()]; for (int i = 0; st.hasMoreTokens(); i++) { String localeString = st.nextToken().trim(); locales[i] = parseLocale(localeString); } } return locales; } /** * Helper method to produce a <code>java.util.Locale</code> object from * a locale string such as en_US or ja_JP. * @param localeString a locale string such as en_US * @return a java.util.Locale object representing the locale string */ public static Locale parseLocale(String localeString) { String language = null; String country = null; String variant = null; // Sometimes people specify "en-US" instead of "en_US", so // we'll try to clean that up. localeString = CommonUtils.replaceText(localeString, "-", "_"); StringTokenizer st = new StringTokenizer(localeString, "_"); if (st.hasMoreTokens()) { language = st.nextToken(); } if (st.hasMoreTokens()) { country = st.nextToken(); } if (st.hasMoreTokens()) { variant = st.nextToken(); } Locale locale = null; if (variant != null) { locale = new Locale(language, country, variant); } else if (country != null) { locale = new Locale(language, country); } else if (language != null) { // Uncomment the following line // when we can count on JDK 1.4! //locale = new Locale(language); locale = new Locale(language, ""); } return locale; } /** * Constructs a comma-delimited list of locales * that could be parsed back into a Locale * array with parseLocales(String localeStringList). * @param locales the list of locales * @return a string representing the list of locales */ public static String stringValueOf(Locale[] locales) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < locales.length; i++) { Locale locale = locales[i]; sb.append(locale.toString()); if (i < locales.length - 1) { sb.append(","); } } return sb.toString(); } /** * Stores the user locales persistantly. * @param userLocales the user locales preference * @throws Exception */ public void persistUserLocales(Locale[] userLocales) throws Exception { setUserLocales(userLocales); LocaleStoreFactory.getLocaleStoreImpl().updateUserLocales(person, userLocales); } /** * Creates an XML representation of a list of locales. * @param locales the locale list * @return the locale list as XML */ public static Document xmlValueOf(Locale[] locales) { return xmlValueOf(locales, null); } /** * Creates an XML representation of a list of locales. * If a selected locale is supplied, the XML element representing * the selected locale will have an attribute of selected with value * of true. This is helpful when constructing user interfaces that * indicate which locale is selected. * @param locales the locale list * @param selectedLocale a locale that should be selected if it is in the list * @return the locale list as XML */ public static Document xmlValueOf(Locale[] locales, Locale selectedLocale) { Document doc = DocumentFactory.getNewDocument(); // <locales> Element localesE = doc.createElement("locales"); for (int i = 0; i < locales.length; i++) { Element locE = doc.createElement("locale"); locE.setAttribute("displayName", locales[i].getDisplayName(locales[0])); locE.setAttribute("code", locales[i].toString()); // Mark which locale is the user's preference if (selectedLocale != null && selectedLocale.equals(locales[i])) { locE.setAttribute("selected", "true"); } // <language iso2="..." iso3="..." displayName="..."/> Element languageE = doc.createElement("language"); languageE.setAttribute("iso2", locales[i].getLanguage()); try { languageE.setAttribute("iso3", locales[i].getISO3Language()); } catch (Exception e) { // Do nothing } languageE.setAttribute("displayName", locales[i].getDisplayLanguage(locales[0])); locE.appendChild(languageE); // <country iso2="..." iso3="..." displayName="..."/> Element countryE = doc.createElement("country"); countryE.setAttribute("iso2", locales[i].getCountry()); try { countryE.setAttribute("iso3", locales[i].getISO3Country()); } catch (Exception e) { // Do nothing } countryE.setAttribute("displayName", locales[i].getDisplayCountry(locales[0])); locE.appendChild(countryE); // <variant code="..." displayName="..."/> Element variantE = doc.createElement("variant"); variantE.setAttribute("code", locales[i].getVariant()); variantE.setAttribute("displayName", locales[i].getDisplayVariant(locales[0])); locE.appendChild(variantE); localesE.appendChild(locE); } doc.appendChild(localesE); return doc; } public String toString() { StringBuffer sb = new StringBuffer(1024); sb.append("LocaleManager's locales").append("\n"); sb.append(" sb.append("Session locales: "); if (sessionLocales != null) { sb.append(stringValueOf(sessionLocales)); } sb.append("\n"); sb.append("User locales: "); if (userLocales != null) { sb.append(stringValueOf(userLocales)); } sb.append("\n"); sb.append("Browser locales: "); if (browserLocales != null) { sb.append(stringValueOf(browserLocales)); } sb.append("\n"); sb.append("Portal locales: "); if (portalLocales != null) { sb.append(stringValueOf(portalLocales)); } sb.append("\n"); sb.append("JVM locale: "); if (jvmLocale != null) { sb.append(jvmLocale.toString()); } sb.append("\n"); sb.append("Sorted locales: "); Locale[] sortedLocales = getLocales(); if (sortedLocales != null) { sb.append(stringValueOf(sortedLocales)); } sb.append("\n"); return sb.toString(); } }
package org.jfree.data.xy; /** * An extension of the {@link XYDataset} interface that allows an x-interval * and a y-interval to be defined. Note that the x and y values defined * by the parent interface are NOT required to fall within these intervals. * This interface is used to support (among other things) bar plots against * numerical axes. */ public interface IntervalXYDataset extends XYDataset { /** * Returns the lower bound of the x-interval for the specified series and * item. If this lower bound is specified, it should be less than or * equal to the upper bound of the interval (if one is specified). * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The lower bound of the x-interval (<code>null</code> permitted). */ public Number getStartX(int series, int item); /** * Returns the lower bound of the x-interval (as a double primitive) for * the specified series and item. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The lower bound of the x-interval. * * @see #getStartX(int, int) */ public double getStartXValue(int series, int item); /** * Returns the upper bound of the x-interval for the specified series and * item. If this upper bound is specified, it should be greater than or * equal to the lower bound of the interval (if one is specified). * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The upper bound of the x-interval (<code>null</code> permitted). */ public Number getEndX(int series, int item); /** * Returns the upper bound of the x-interval (as a double primitive) for * the specified series and item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The upper bound of the x-interval. * * @see #getEndX(int, int) */ public double getEndXValue(int series, int item); /** * Returns the lower bound of the y-interval for the specified series and * item. If this lower bound is specified, it should be less than or * equal to the upper bound of the interval (if one is specified). * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The lower bound of the y-interval (<code>null</code> permitted). */ public Number getStartY(int series, int item); /** * Returns the lower bound of the y-interval (as a double primitive) for * the specified series and item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The lower bound of the y-interval. * * @see #getStartY(int, int) */ public double getStartYValue(int series, int item); /** * Returns the upper bound of the y-interval for the specified series and * item. If this upper bound is specified, it should be greater than or * equal to the lower bound of the interval (if one is specified). * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The upper bound of the y-interval (<code>null</code> permitted). */ public Number getEndY(int series, int item); /** * Returns the upper bound of the y-interval (as a double primitive) for * the specified series and item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The upper bound of the y-interval. * * @see #getEndY(int, int) */ public double getEndYValue(int series, int item); }
package net.runelite.client.ui.overlay; import com.google.common.annotations.VisibleForTesting; import java.awt.Dimension; import java.awt.Point; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import javax.inject.Inject; import javax.inject.Singleton; import lombok.AccessLevel; import lombok.Getter; import net.runelite.api.MenuAction; import net.runelite.api.events.MenuOptionClicked; import net.runelite.api.widgets.WidgetItem; import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigManager; import net.runelite.client.config.RuneLiteConfig; import net.runelite.client.eventbus.EventBus; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.OverlayMenuClicked; import net.runelite.client.events.PluginChanged; /** * Manages state of all game overlays */ @Singleton public class OverlayManager { public static final String OPTION_CONFIGURE = "Configure"; private static final String OVERLAY_CONFIG_PREFERRED_LOCATION = "_preferredLocation"; private static final String OVERLAY_CONFIG_PREFERRED_POSITION = "_preferredPosition"; private static final String OVERLAY_CONFIG_PREFERRED_SIZE = "_preferredSize"; private static final String RUNELITE_CONFIG_GROUP_NAME = RuneLiteConfig.class.getAnnotation(ConfigGroup.class).value(); @VisibleForTesting static final Comparator<Overlay> OVERLAY_COMPARATOR = (a, b) -> { final OverlayPosition aPos = a.getPreferredPosition() != null ? a.getPreferredPosition() : a.getPosition(); final OverlayPosition bPos = b.getPreferredPosition() != null ? b.getPreferredPosition() : b.getPosition(); if (aPos != bPos) { // This is so non-dynamic overlays render after dynamic // overlays, which are generally in the scene return aPos.compareTo(bPos); } // For dynamic overlays, higher priority means to // draw *later* so it is on top. // For non-dynamic overlays, higher priority means // draw *first* so that they are closer to their // defined position. return aPos == OverlayPosition.DYNAMIC ? a.getPriority().compareTo(b.getPriority()) : b.getPriority().compareTo(a.getPriority()); }; /** * Insertion-order sorted set of overlays * All access to this must be guarded by a lock on this OverlayManager */ @Getter(AccessLevel.PACKAGE) private final List<Overlay> overlays = new ArrayList<>(); @Getter private final List<WidgetItem> itemWidgets = new ArrayList<>(); private final Map<OverlayLayer, List<Overlay>> overlayLayers = new EnumMap<>(OverlayLayer.class); private final ConfigManager configManager; private final EventBus eventBus; @Inject private OverlayManager(final ConfigManager configManager, final EventBus eventBus) { this.configManager = configManager; this.eventBus = eventBus; } @Subscribe public void onPluginChanged(final PluginChanged event) { overlays.forEach(this::loadOverlay); rebuildOverlayLayers(); } @Subscribe public void onMenuOptionClicked(MenuOptionClicked event) { if (event.getMenuAction() != MenuAction.RUNELITE_OVERLAY) { return; } event.consume(); Optional<Overlay> optionalOverlay = overlays.stream().filter(o -> overlays.indexOf(o) == event.getId()).findAny(); if (optionalOverlay.isPresent()) { Overlay overlay = optionalOverlay.get(); List<OverlayMenuEntry> menuEntries = overlay.getMenuEntries(); Optional<OverlayMenuEntry> optionalOverlayMenuEntry = menuEntries.stream() .filter(me -> me.getOption().equals(event.getMenuOption())) .findAny(); if (optionalOverlayMenuEntry.isPresent()) { eventBus.post(new OverlayMenuClicked(optionalOverlayMenuEntry.get(), overlay)); } } } /** * Gets all of the overlays on a layer sorted by priority and position * * @param layer the layer * @return An immutable list of all of the overlays on that layer */ synchronized List<Overlay> getLayer(OverlayLayer layer) { return overlayLayers.get(layer); } /** * Add overlay. * * @param overlay the overlay * @return true if overlay was added */ public synchronized boolean add(final Overlay overlay) { if (overlays.contains(overlay)) { return false; } // Add is always true overlays.add(overlay); loadOverlay(overlay); // WidgetItemOverlays have a reference to the overlay manager in order to get the WidgetItems // for each frame. if (overlay instanceof WidgetItemOverlay) { ((WidgetItemOverlay) overlay).setOverlayManager(this); } rebuildOverlayLayers(); return true; } /** * Remove overlay. * * @param overlay the overlay * @return true if overlay was removed */ public synchronized boolean remove(final Overlay overlay) { final boolean remove = overlays.remove(overlay); if (remove) { rebuildOverlayLayers(); } return remove; } /** * Remove if overlay matches filter * * @param filter the filter * @return true if any overlay was removed */ public synchronized boolean removeIf(Predicate<Overlay> filter) { final boolean removeIf = overlays.removeIf(filter); if (removeIf) { rebuildOverlayLayers(); } return removeIf; } /** * Returns whether an overlay exists which matches the given predicate. * * @param filter Filter predicate function * @return {@code true} if any overlays match the given filter, {@code false} otherwise */ public synchronized boolean anyMatch(Predicate<Overlay> filter) { return overlays.stream().anyMatch(filter); } /** * Clear all overlays */ public synchronized void clear() { overlays.clear(); rebuildOverlayLayers(); } /** * Force save overlay data * * @param overlay overlay to save */ public synchronized void saveOverlay(final Overlay overlay) { saveOverlayPosition(overlay); saveOverlaySize(overlay); saveOverlayLocation(overlay); rebuildOverlayLayers(); } /** * Resets stored overlay position data * * @param overlay overlay to reset */ public synchronized void resetOverlay(final Overlay overlay) { overlay.setPreferredPosition(null); overlay.setPreferredSize(null); overlay.setPreferredLocation(null); saveOverlay(overlay); } private synchronized void rebuildOverlayLayers() { for (OverlayLayer l : OverlayLayer.values()) { overlayLayers.put(l, new ArrayList<>()); } for (final Overlay overlay : overlays) { OverlayLayer layer = overlay.getLayer(); if (overlay.getPreferredLocation() != null && overlay.getPreferredPosition() == null) { // When UNDER_WIDGET overlays are in preferred locations, move to // ABOVE_WIDGETS so that it can draw over interfaces if (layer == OverlayLayer.UNDER_WIDGETS && !(overlay instanceof WidgetOverlay)) { layer = OverlayLayer.ABOVE_WIDGETS; } } overlayLayers.get(layer).add(overlay); } overlayLayers.forEach((layer, value) -> { value.sort(OVERLAY_COMPARATOR); overlayLayers.put(layer, Collections.unmodifiableList(value)); }); } private void loadOverlay(final Overlay overlay) { final Point location = loadOverlayLocation(overlay); overlay.setPreferredLocation(location); final Dimension size = loadOverlaySize(overlay); overlay.setPreferredSize(size); final OverlayPosition position = loadOverlayPosition(overlay); overlay.setPreferredPosition(position); } private void saveOverlayLocation(final Overlay overlay) { final String key = overlay.getName() + OVERLAY_CONFIG_PREFERRED_LOCATION; if (overlay.getPreferredLocation() != null) { configManager.setConfiguration( RUNELITE_CONFIG_GROUP_NAME, key, overlay.getPreferredLocation()); } else { configManager.unsetConfiguration( RUNELITE_CONFIG_GROUP_NAME, key); } } private void saveOverlaySize(final Overlay overlay) { final String key = overlay.getName() + OVERLAY_CONFIG_PREFERRED_SIZE; if (overlay.getPreferredSize() != null) { configManager.setConfiguration( RUNELITE_CONFIG_GROUP_NAME, key, overlay.getPreferredSize()); } else { configManager.unsetConfiguration( RUNELITE_CONFIG_GROUP_NAME, key); } } private void saveOverlayPosition(final Overlay overlay) { final String key = overlay.getName() + OVERLAY_CONFIG_PREFERRED_POSITION; if (overlay.getPreferredPosition() != null) { configManager.setConfiguration( RUNELITE_CONFIG_GROUP_NAME, key, overlay.getPreferredPosition()); } else { configManager.unsetConfiguration( RUNELITE_CONFIG_GROUP_NAME, key); } } private Point loadOverlayLocation(final Overlay overlay) { final String key = overlay.getName() + OVERLAY_CONFIG_PREFERRED_LOCATION; return configManager.getConfiguration(RUNELITE_CONFIG_GROUP_NAME, key, Point.class); } private Dimension loadOverlaySize(final Overlay overlay) { final String key = overlay.getName() + OVERLAY_CONFIG_PREFERRED_SIZE; return configManager.getConfiguration(RUNELITE_CONFIG_GROUP_NAME, key, Dimension.class); } private OverlayPosition loadOverlayPosition(final Overlay overlay) { final String locationKey = overlay.getName() + OVERLAY_CONFIG_PREFERRED_POSITION; return configManager.getConfiguration(RUNELITE_CONFIG_GROUP_NAME, locationKey, OverlayPosition.class); } }
package com.quickblox.sample.chat.managers; import android.os.Bundle; import com.quickblox.chat.QBChatService; import com.quickblox.chat.QBSystemMessagesManager; import com.quickblox.chat.model.QBChatDialog; import com.quickblox.chat.model.QBChatMessage; import com.quickblox.chat.model.QBDialogType; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.sample.chat.utils.chat.ChatHelper; import com.quickblox.sample.chat.utils.qb.QbDialogHolder; import com.quickblox.sample.chat.utils.qb.QbDialogUtils; import com.quickblox.sample.chat.utils.qb.callback.QbEntityCallbackImpl; import com.quickblox.sample.core.utils.Toaster; import com.quickblox.users.model.QBUser; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smackx.muc.DiscussionHistory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; public class DialogsManager { public static final String PROPERTY_OCCUPANTS_IDS = "current_occupant_ids"; public static final String PROPERTY_DIALOG_TYPE = "type"; public static final String PROPERTY_DIALOG_NAME = "room_name"; public static final String PROPERTY_NOTIFICATION_TYPE = "notification_type"; public static final String CREATING_DIALOG = "1"; private Set<ManagingDialogsCallbacks> managingDialogsCallbackListener = new CopyOnWriteArraySet<>(); private boolean isMessageCreatingDialog(QBChatMessage systemMessage) { return CREATING_DIALOG.equals(systemMessage.getProperty(PROPERTY_NOTIFICATION_TYPE)); } private QBChatMessage buildSystemMessageAboutCreatingGroupDialog(QBChatDialog dialog) { QBChatMessage qbChatMessage = new QBChatMessage(); qbChatMessage.setDialogId(dialog.getDialogId()); qbChatMessage.setProperty(PROPERTY_OCCUPANTS_IDS, QbDialogUtils.getOccupantsIdsStringFromList(dialog.getOccupants())); qbChatMessage.setProperty(PROPERTY_DIALOG_TYPE, String.valueOf(dialog.getType().getCode())); qbChatMessage.setProperty(PROPERTY_DIALOG_NAME, String.valueOf(dialog.getName())); qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, CREATING_DIALOG); qbChatMessage.setBody("New Chat Created"); return qbChatMessage; } private QBChatDialog buildChatDialogFromSystemMessage(QBChatMessage qbChatMessage) { QBChatDialog chatDialog = new QBChatDialog(); chatDialog.setDialogId(qbChatMessage.getDialogId()); chatDialog.setOccupantsIds(QbDialogUtils.getOccupantsIdsListFromString((String) qbChatMessage.getProperty(PROPERTY_OCCUPANTS_IDS))); chatDialog.setType(QBDialogType.parseByCode(Integer.parseInt(qbChatMessage.getProperty(PROPERTY_DIALOG_TYPE).toString()))); chatDialog.setName(qbChatMessage.getProperty(PROPERTY_DIALOG_NAME).toString()); chatDialog.setUnreadMessageCount(0); return chatDialog; } public void sendSystemMessageAboutCreatingDialog(QBSystemMessagesManager systemMessagesManager, QBChatDialog dialog) { QBChatMessage systemMessageCreatingDialog = buildSystemMessageAboutCreatingGroupDialog(dialog); try { for (Integer recipientId : dialog.getOccupants()) { if (!recipientId.equals(QBChatService.getInstance().getUser().getId())) { systemMessageCreatingDialog.setRecipientId(recipientId); systemMessagesManager.sendSystemMessage(systemMessageCreatingDialog); } } } catch (SmackException.NotConnectedException e) { e.printStackTrace(); } } private void loadUsersFromDialog(QBChatDialog chatDialog) { ChatHelper.getInstance().getUsersFromDialog(chatDialog, new QbEntityCallbackImpl<ArrayList<QBUser>>()); } public void onGlobalMessageReceived(String dialogId, QBChatMessage chatMessage) { if (chatMessage.isMarkable()) { if (QbDialogHolder.getInstance().hasDialogWithId(dialogId)) { QbDialogHolder.getInstance().updateDialog(dialogId, chatMessage); notifyListenersDialogUpdated(dialogId); } else { ChatHelper.getInstance().getDialogById(dialogId, new QbEntityCallbackImpl<QBChatDialog>() { @Override public void onSuccess(QBChatDialog chatDialog, Bundle bundle) { loadUsersFromDialog(chatDialog); QbDialogHolder.getInstance().addDialog(chatDialog); notifyListenersNewDialogLoaded(chatDialog); } }); } } } public void onSystemMessageReceived(final QBChatMessage systemMessage) { if (isMessageCreatingDialog(systemMessage)) { final QBChatDialog chatDialog = buildChatDialogFromSystemMessage(systemMessage); chatDialog.initForChat(QBChatService.getInstance()); DiscussionHistory history = new DiscussionHistory(); history.setMaxStanzas(0); chatDialog.join(history, new QBEntityCallback() { @Override public void onSuccess(Object o, Bundle bundle) { QbDialogHolder.getInstance().addDialog(chatDialog); notifyListenersDialogCreated(chatDialog); QbDialogHolder.getInstance().updateDialog(chatDialog.getDialogId(), systemMessage); onGlobalMessageReceived(chatDialog.getDialogId(), systemMessage); notifyListenersDialogUpdated(chatDialog.getDialogId()); } @Override public void onError(QBResponseException e) { Toaster.shortToast(e.getMessage()); } }); } } private void notifyListenersDialogCreated(final QBChatDialog chatDialog) { for (ManagingDialogsCallbacks listener : getManagingDialogsCallbackListeners()) { listener.onDialogCreated(chatDialog); } } private void notifyListenersDialogUpdated(final String dialogId) { for (ManagingDialogsCallbacks listener : getManagingDialogsCallbackListeners()) { listener.onDialogUpdated(dialogId); } } private void notifyListenersNewDialogLoaded(final QBChatDialog chatDialog) { for (ManagingDialogsCallbacks listener : getManagingDialogsCallbackListeners()) { listener.onNewDialogLoaded(chatDialog); } } public void addManagingDialogsCallbackListener(ManagingDialogsCallbacks listener) { if (listener != null) { managingDialogsCallbackListener.add(listener); } } public void removeManagingDialogsCallbackListener(ManagingDialogsCallbacks listener) { managingDialogsCallbackListener.remove(listener); } public Collection<ManagingDialogsCallbacks> getManagingDialogsCallbackListeners() { return Collections.unmodifiableCollection(managingDialogsCallbackListener); } public interface ManagingDialogsCallbacks { void onDialogCreated(QBChatDialog chatDialog); void onDialogUpdated(String chatDialog); void onNewDialogLoaded(QBChatDialog chatDialog); } }
package uk.org.taverna.scufl2.api.container; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import uk.org.taverna.scufl2.api.common.AbstractNamed; import uk.org.taverna.scufl2.api.common.Named; import uk.org.taverna.scufl2.api.common.NamedSet; import uk.org.taverna.scufl2.api.common.Root; import uk.org.taverna.scufl2.api.common.Visitor; import uk.org.taverna.scufl2.api.common.WorkflowBean; import uk.org.taverna.scufl2.api.core.Workflow; import uk.org.taverna.scufl2.api.profiles.Profile; import uk.org.taverna.scufl2.ucfpackage.UCFPackage; /** * @author Alan R Williams * */ public class WorkflowBundle extends AbstractNamed implements WorkflowBean, Named, Root { public static final URI WORKFLOW_BUNDLE_ROOT = URI .create("http://ns.taverna.org.uk/2010/workflowBundle/"); public static URI generateIdentifier() { return WORKFLOW_BUNDLE_ROOT.resolve(UUID.randomUUID().toString() + "/"); } private URI sameBaseAs = generateIdentifier(); private NamedSet<Profile> profiles = new NamedSet<Profile>(); private NamedSet<Workflow> workflows = new NamedSet<Workflow>(); private Workflow mainWorkflow; private Profile mainProfile; private UCFPackage resources; @Override public boolean accept(Visitor visitor) { if (visitor.visitEnter(this)) { List<Iterable<? extends WorkflowBean>> children = new ArrayList<Iterable<? extends WorkflowBean>>(); children.add(getWorkflows()); children.add(getProfiles()); outer: for (Iterable<? extends WorkflowBean> it : children) { for (WorkflowBean bean : it) { if (!bean.accept(visitor)) { break outer; } } } } return visitor.visitLeave(this); } public Profile getMainProfile() { return mainProfile; } public Workflow getMainWorkflow() { return mainWorkflow; } public NamedSet<Profile> getProfiles() { return profiles; } public UCFPackage getResources() { if (resources == null) { try { resources = new UCFPackage(); } catch (IOException e) { throw new IllegalStateException( "Can't create new UCF package, no access to tmpdir?", e); } } return resources; } @Override public URI getSameBaseAs() { return sameBaseAs; } public NamedSet<Workflow> getWorkflows() { return workflows; } public void setMainProfile(Profile mainProfile) { if (mainProfile != null) { getProfiles().add(mainProfile); } this.mainProfile = mainProfile; } public void setMainWorkflow(Workflow mainWorkflow) { if (mainWorkflow != null) { getWorkflows().add(mainWorkflow); } this.mainWorkflow = mainWorkflow; } public void setProfiles(Set<Profile> profiles) { this.profiles.clear(); this.profiles.addAll(profiles); } public void setResources(UCFPackage resources) { this.resources = resources; } @Override public void setSameBaseAs(URI sameBaseAs) { this.sameBaseAs = sameBaseAs; } public void setWorkflows(Set<Workflow> workflows) { this.workflows.clear(); this.workflows.addAll(workflows); } @Override public String toString() { final int maxLen = 6; return "TavernaResearchObject [" + "profiles=" + (profiles != null ? toString(profiles, maxLen) : null) + ", mainWorkflow=" + mainWorkflow + "]"; } private String toString(Collection<?> collection, int maxLen) { StringBuilder builder = new StringBuilder(); builder.append("["); int i = 0; for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) { if (i > 0) { builder.append(", "); } builder.append(iterator.next()); } builder.append("]"); return builder.toString(); } }
package com.smartdevicelink.managers.screen; import android.support.annotation.NonNull; import android.util.Log; import com.smartdevicelink.managers.BaseSubManager; import com.smartdevicelink.managers.CompletionListener; import com.smartdevicelink.managers.file.FileManager; import com.smartdevicelink.managers.file.filetypes.SdlArtwork; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.rpc.SetDisplayLayout; import com.smartdevicelink.proxy.rpc.enums.MetadataType; import com.smartdevicelink.proxy.rpc.enums.PredefinedLayout; import com.smartdevicelink.proxy.rpc.enums.TextAlignment; import com.smartdevicelink.util.DebugTool; import java.lang.ref.WeakReference; import java.util.List; /** * <strong>ScreenManager</strong> <br> * * Note: This class must be accessed through the SdlManager. Do not instantiate it by itself. <br> */ public class ScreenManager extends BaseSubManager { private static String TAG = "ScreenManager"; private final WeakReference<FileManager> fileManager; private SoftButtonManager softButtonManager; private TextAndGraphicManager textAndGraphicManager; // Sub manager listener private final CompletionListener subManagerListener = new CompletionListener() { @Override public synchronized void onComplete(boolean success) { if (softButtonManager != null && textAndGraphicManager != null) { if (softButtonManager.getState() == BaseSubManager.READY && textAndGraphicManager.getState() == BaseSubManager.READY) { DebugTool.logInfo("Starting screen manager, all sub managers are in ready state"); transitionToState(READY); } else if (softButtonManager.getState() == BaseSubManager.ERROR && textAndGraphicManager.getState() == BaseSubManager.ERROR) { Log.e(TAG, "ERROR starting screen manager, both sub managers in error state"); transitionToState(ERROR); } else if (textAndGraphicManager.getState() == BaseSubManager.SETTING_UP || softButtonManager.getState() == BaseSubManager.SETTING_UP) { DebugTool.logInfo("SETTING UP screen manager, one sub manager is still setting up"); transitionToState(SETTING_UP); } else { Log.w(TAG, "LIMITED starting screen manager, one sub manager in error state and the other is ready"); transitionToState(LIMITED); } } else { // We should never be here, but somehow one of the sub-sub managers is null Log.e(TAG, "ERROR one of the screen sub managers is null"); transitionToState(ERROR); } } }; public ScreenManager(@NonNull ISdl internalInterface, @NonNull FileManager fileManager) { super(internalInterface); this.fileManager = new WeakReference<>(fileManager); initialize(); } @Override public void start(CompletionListener listener) { super.start(listener); } private void initialize(){ if (fileManager.get() != null) { this.softButtonManager = new SoftButtonManager(internalInterface, fileManager.get()); this.textAndGraphicManager = new TextAndGraphicManager(internalInterface, fileManager.get(), softButtonManager); this.softButtonManager.start(subManagerListener); this.textAndGraphicManager.start(subManagerListener); } } /** * <p>Called when manager is being torn down</p> */ @Override public void dispose() { softButtonManager.dispose(); textAndGraphicManager.dispose(); super.dispose(); } /** * Set the textField1 on the head unit screen * Sending an empty String "" will clear the field * @param textField1 String value represents the textField1 */ public void setTextField1(String textField1) { this.softButtonManager.setCurrentMainField1(textField1); this.textAndGraphicManager.setTextField1(textField1); } /** * Get the current textField1 value * @return a String value represents the current textField1 value */ public String getTextField1() { return this.textAndGraphicManager.getTextField1(); } /** * Set the textField2 on the head unit screen * Sending an empty String "" will clear the field * @param textField2 String value represents the textField1 */ public void setTextField2(String textField2) { this.textAndGraphicManager.setTextField2(textField2); } /** * Get the current textField2 value * @return a String value represents the current textField2 value */ public String getTextField2() { return this.textAndGraphicManager.getTextField2(); } /** * Set the textField3 on the head unit screen * Sending an empty String "" will clear the field * @param textField3 String value represents the textField1 */ public void setTextField3(String textField3) { this.textAndGraphicManager.setTextField3(textField3); } /** * Get the current textField3 value * @return a String value represents the current textField3 value */ public String getTextField3() { return this.textAndGraphicManager.getTextField3(); } /** * Set the textField4 on the head unit screen * Sending an empty String "" will clear the field * @param textField4 String value represents the textField1 */ public void setTextField4(String textField4) { this.textAndGraphicManager.setTextField4(textField4); } /** * Get the current textField4 value * @return a String value represents the current textField4 value */ public String getTextField4() { return this.textAndGraphicManager.getTextField4(); } /** * Set the mediaTrackTextField on the head unit screen * @param mediaTrackTextField String value represents the mediaTrackTextField */ public void setMediaTrackTextField(String mediaTrackTextField) { this.textAndGraphicManager.setMediaTrackTextField(mediaTrackTextField); } /** * Get the current mediaTrackTextField value * @return a String value represents the current mediaTrackTextField */ public String getMediaTrackTextField() { return this.textAndGraphicManager.getMediaTrackTextField(); } /** * Set the primaryGraphic on the head unit screen * @param primaryGraphic an SdlArtwork object represents the primaryGraphic */ public void setPrimaryGraphic(SdlArtwork primaryGraphic) { if (primaryGraphic == null){ primaryGraphic = textAndGraphicManager.getBlankArtwork(); } this.textAndGraphicManager.setPrimaryGraphic(primaryGraphic); } /** * Get the current primaryGraphic value * @return an SdlArtwork object represents the current primaryGraphic */ public SdlArtwork getPrimaryGraphic() { return this.textAndGraphicManager.getPrimaryGraphic(); } /** * Set the secondaryGraphic on the head unit screen * @param secondaryGraphic an SdlArtwork object represents the secondaryGraphic */ public void setSecondaryGraphic(SdlArtwork secondaryGraphic) { if (secondaryGraphic == null){ secondaryGraphic = textAndGraphicManager.getBlankArtwork(); } this.textAndGraphicManager.setSecondaryGraphic(secondaryGraphic); } /** * Get the current secondaryGraphic value * @return an SdlArtwork object represents the current secondaryGraphic */ public SdlArtwork getSecondaryGraphic() { return this.textAndGraphicManager.getSecondaryGraphic(); } /** * Set the alignment for the text fields * @param textAlignment TextAlignment value represents the alignment for the text fields */ public void setTextAlignment(TextAlignment textAlignment) { this.textAndGraphicManager.setTextAlignment(textAlignment); } /** * Get the alignment for the text fields * @return a TextAlignment value represents the alignment for the text fields */ public TextAlignment getTextAlignment() { return this.textAndGraphicManager.getTextAlignment(); } /** * Set the metadata type for the textField1 * @param textField1Type a MetadataType value represents the metadata for textField1 */ public void setTextField1Type(MetadataType textField1Type) { this.textAndGraphicManager.setTextField1Type(textField1Type); } /** * Get the metadata type for textField1 * @return a MetadataType value represents the metadata for textField1 */ public MetadataType getTextField1Type() { return this.textAndGraphicManager.getTextField1Type(); } /** * Set the metadata type for the textField2 * @param textField2Type a MetadataType value represents the metadata for textField2 */ public void setTextField2Type(MetadataType textField2Type) { this.textAndGraphicManager.setTextField2Type(textField2Type); } /** * Get the metadata type for textField2 * @return a MetadataType value represents the metadata for textField2 */ public MetadataType getTextField2Type() { return this.textAndGraphicManager.getTextField2Type(); } /** * Set the metadata type for the textField3 * @param textField3Type a MetadataType value represents the metadata for textField3 */ public void setTextField3Type(MetadataType textField3Type) { this.textAndGraphicManager.setTextField3Type(textField3Type); } /** * Get the metadata type for textField3 * @return a MetadataType value represents the metadata for textField3 */ public MetadataType getTextField3Type() { return this.textAndGraphicManager.getTextField3Type(); } /** * Set the metadata type for the textField4 * @param textField4Type a MetadataType value represents the metadata for textField4 */ public void setTextField4Type(MetadataType textField4Type) { this.textAndGraphicManager.setTextField4Type(textField4Type); } /** * Get the metadata type for textField4 * @return a MetadataType value represents the metadata for textField4 */ public MetadataType getTextField4Type() { return this.textAndGraphicManager.getTextField4Type(); } /** * Set softButtonObjects list and upload the images to the head unit * @param softButtonObjects the list of the SoftButtonObject values that should be displayed on the head unit */ public void setSoftButtonObjects(@NonNull List<SoftButtonObject> softButtonObjects) { softButtonManager.setSoftButtonObjects(softButtonObjects); } /** * Get the soft button objects list * @return a List<SoftButtonObject> */ public List<SoftButtonObject> getSoftButtonObjects() { return softButtonManager.getSoftButtonObjects(); } /** * Get the SoftButtonObject that has the provided name * @param name a String value that represents the name * @return a SoftButtonObject */ public SoftButtonObject getSoftButtonObjectByName(@NonNull String name){ return softButtonManager.getSoftButtonObjectByName(name); } /** * Get the SoftButtonObject that has the provided buttonId * @param buttonId a int value that represents the id of the button * @return a SoftButtonObject */ public SoftButtonObject getSoftButtonObjectById(int buttonId){ return softButtonManager.getSoftButtonObjectById(buttonId); } /** * Begin a multiple updates transaction. The updates will be applied when commit() is called<br> * Note: if we don't use beginTransaction & commit, every update will be sent individually. */ public void beginTransaction(){ softButtonManager.setBatchUpdates(true); textAndGraphicManager.setBatchUpdates(true); } /** * Send the updates that were started after beginning the transaction * @param listener a CompletionListener that has a callback that will be called when the updates are finished */ public void commit(final CompletionListener listener){ softButtonManager.setBatchUpdates(false); softButtonManager.update(new CompletionListener() { boolean updateSuccessful = true; @Override public void onComplete(boolean success) { if (!success){ updateSuccessful = false; } textAndGraphicManager.setBatchUpdates(false); textAndGraphicManager.update(new CompletionListener() { @Override public void onComplete(boolean success) { if (!success){ updateSuccessful = false; } listener.onComplete(updateSuccessful); } }); } }); } }
// This file is part of Serleena. // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package com.kyloth.serleena.view.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.kyloth.serleena.R; import com.kyloth.serleena.presentation.ITrackPresenter; import com.kyloth.serleena.presentation.ITrackView; import com.kyloth.serleena.common.NoTrackCrossingException; import com.kyloth.serleena.sensors.NoActiveTrackException; import com.kyloth.serleena.view.widgets.CompassWidget; import java.util.Locale; import java.util.concurrent.TimeUnit; import static java.lang.Math.abs; public class TrackFragment extends Fragment implements ITrackView, View.OnClickListener { private ITrackPresenter presenter; private TextView trackNameText; private TextView nextCheckpointText; private TextView distanceText; private CompassWidget orientationWidget; private TextView deltaText; private TextView lastPartialText; private int totalCheckpoints; private int nextCheckpoint; /** * Crea un nuovo oggetto TrackFragment. */ public TrackFragment() { /* Null object pattern */ presenter = new ITrackPresenter() { @Override public void advanceCheckpoint() throws NoTrackCrossingException { } @Override public void abortTrack() { } @Override public void resume() { } @Override public void pause() { } }; } /** * Ridefinisce Fragment.onCreateView() */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_track, container, false); orientationWidget = (CompassWidget) v.findViewById(R.id.compass_widget_track); nextCheckpointText = (TextView) v.findViewById(R.id.checkpoint_numbers_text); trackNameText = (TextView) v.findViewById(R.id.track_name_text); distanceText = (TextView) v.findViewById(R.id.distance_text); deltaText = (TextView) v.findViewById(R.id.delta_text); lastPartialText = (TextView) v.findViewById(R.id.last_partial_text); orientationWidget.setOnClickListener(this); return v; } @Override public void attachPresenter(ITrackPresenter presenter) { if (presenter == null) throw new IllegalArgumentException("Illegal null presenter"); this.presenter = presenter; } /** * Pulisce la vista. */ @Override public void clearView() { trackNameText.setText((String) getResources().getText(R.string.track_noActiveTrack)); distanceText.setText(""); orientationWidget.setOrientation(0); clearStats(); clearCheckpoints(); } /** * Imposta l'orientamento necessario all'utente a raggiungere il prossimo * checkpoint. * * @param heading Direzione del prossimo checkpoint in gradi. */ @Override public void setDirection(float heading) { orientationWidget.setOrientation(heading); } /** * Metodo per impostare la distanza dal prossimo checkpoint. * * @param distance Distanza dal prossimo checkpoint */ @Override public void setDistance(int distance) { if (distance < 0) throw new IllegalArgumentException("Illegal negative distance"); distanceText.setText(distance + " m"); } /** * Metodo per impostare il tempo di attraversamento dell'ultimo checkpoint. * * @param seconds Secondi impiegati per raggiungere l'ultimo checkpoint attraversato */ @Override public void setLastPartial(int seconds) { if (seconds < 0) throw new IllegalArgumentException("Illegal negative partial"); int millis = seconds * 1000; String s = String.format(Locale.US, "%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) ); lastPartialText.setText(s); } /** * Metodo per impostare il vantaggio rispetto alla miglior prestazione. * * @param seconds Secondi di scarto dalla miglior prestazione */ @Override public void setDelta(int seconds) { String sign = "+"; if (seconds < 0) { sign = "-"; } seconds = abs(seconds); int millis = seconds * 1000; String s = sign + String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) ); deltaText.setText(s); } @Override public void setCheckpointNo(int n) { if (n <= 0) throw new IllegalArgumentException( "Illegal null or negative checkpoint"); nextCheckpoint = n; if (totalCheckpoints > 0) nextCheckpointText.setText(nextCheckpoint + "/" + totalCheckpoints); } /** * Metodo per impostare il numero totale di checkpoint. * * @param n Numero totale di checkpoint */ @Override public void setTotalCheckpoints(int n) { if (n <= 0) throw new IllegalArgumentException( "Illegal null or negative checkpoint"); totalCheckpoints = n; if (nextCheckpoint > 0) nextCheckpointText.setText(nextCheckpoint + "/" + totalCheckpoints); } /** * ITrackView.displayTrackEnded(). */ @Override public void displayTrackEnded() { nextCheckpointText.setText((String) getResources().getText(R.string.track_finish)); } /** * Implementa ITrackView.setTrackName() * * @param name Nome del Percorso. */ @Override public void setTrackName(String name) { if (name == null) throw new IllegalArgumentException(); trackNameText.setText(name); } /** * Pulisci informazioni sulla vista riguardanti i checkpoint. */ @Override public void clearCheckpoints() { totalCheckpoints = 0; nextCheckpoint = 0; nextCheckpointText.setText(""); } /** * Pulisci informazioni riguardanti i tempi di attraversamento del Percorso. */ @Override public void clearStats() { lastPartialText.setText(""); deltaText.setText(""); } /** * Metodo invocato quando il Fragment viene visualizzato. */ @Override public void onResume() { super.onResume(); presenter.resume(); } /** * Metodo invocato quando il Fragment smette di essere visualizzato. */ @Override public void onPause() { super.onPause(); presenter.pause(); } /** * Ridefinisce Object.toString(). */ @Override public String toString() { return "Percorso"; } @Override public void onClick(View v) { try { presenter.advanceCheckpoint(); } catch (NoTrackCrossingException|NoActiveTrackException e) { } } }
package edu.mit.csail.db.ml.server.storage; import jooq.sqlite.gen.Tables; import jooq.sqlite.gen.tables.records.DataframeRecord; import jooq.sqlite.gen.tables.records.DataframesplitRecord; import jooq.sqlite.gen.tables.records.EventRecord; import jooq.sqlite.gen.tables.records.RandomspliteventRecord; import modeldb.*; import org.jooq.DSLContext; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * This class contains logic for storing and reading information about random split events. * A random split event is when the rows of a DataFrame are randomly divided to create two or more new DataFrames. */ public class RandomSplitEventDao { /** * Store a random split event in the database. * @param rse - The RandomSplitEvent. * @param ctx - The database context. * @return A response indicating that the event has been stored. */ public static RandomSplitEventResponse store(RandomSplitEvent rse, DSLContext ctx) { // Store the old DataFrame. That is, store the DataFrame that was split into pieces. DataframeRecord oldDf = DataFrameDao.store(rse.oldDataFrame, rse.experimentRunId, ctx); // Store the RandomSplitEvent. RandomspliteventRecord rseRec = ctx.newRecord(Tables.RANDOMSPLITEVENT); rseRec.setId(null); rseRec.setInputdataframeid(oldDf.getId()); rseRec.setRandomseed(rse.seed); rseRec.setExperimentrun(rse.experimentRunId); rseRec.store(); // Store an entry in the Event table. EventRecord ev = EventDao.store(rseRec.getId(), "random split", rse.experimentRunId, ctx); // Store a DataFrame for each split. List<DataframeRecord> splitDfs = rse .splitDataFrames .stream() .map(df -> DataFrameDao.store(df, rse.experimentRunId, ctx)) .collect(Collectors.toList()); // Store a DataFrameSplit for each split. IntStream .range(0, rse.splitDataFrames.size()) .forEach(ind -> { DataframesplitRecord splRec = ctx.newRecord(Tables.DATAFRAMESPLIT); splRec.setId(null); splRec.setSpliteventid(rseRec.getId()); splRec.setWeight(rse.weights.get(ind).floatValue()); splRec.setDataframeid(splitDfs.get(ind).getId()); splRec.setExperimentrun(rse.experimentRunId); splRec.store(); splRec.getId(); }); // Store a TransformEvent for each split. This allows us to preserve the ancestor chain of DataFrames. // Each split will derive from the original DataFrame. DataFrame oldDataFrame = rse.oldDataFrame.setId(oldDf.getId()); // We'll use a dummy Transformer. Transformer rseTransformer = new Transformer(-1, "RandomSplitTransformer", ""); // Store the TransformEvent for each split. List<Integer> splitIds = IntStream.range(0, rse.splitDataFrames.size()) .mapToObj(index -> { DataFrame splitDataFrame = rse.splitDataFrames.get(index); TransformEvent te = new TransformEvent( oldDataFrame, splitDataFrame, rseTransformer, Collections.emptyList(), Collections.emptyList(), rse.experimentRunId ); return TransformEventDao.store(te, ctx).newDataFrameId; }) .collect(Collectors.toList()); return new RandomSplitEventResponse(oldDf.getId(), splitIds, ev.getId()); } }
package org.jboss.forge.addon.shell.command; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import org.hamcrest.CoreMatchers; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.projects.ProjectFactory; import org.jboss.forge.addon.shell.test.ShellTest; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.Dependencies; import org.jboss.forge.arquillian.archive.ForgeArchive; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author <a href="ggastald@redhat.com">George Gastaldi</a> */ @RunWith(Arquillian.class) public class LsCommandTest { @Deployment @Dependencies({ @AddonDependency(name = "org.jboss.forge.addon:maven"), @AddonDependency(name = "org.jboss.forge.addon:ui"), @AddonDependency(name = "org.jboss.forge.addon:projects"), @AddonDependency(name = "org.jboss.forge.addon:shell-test-harness"), @AddonDependency(name = "org.jboss.forge.addon:resources"), @AddonDependency(name = "org.jboss.forge.furnace.container:cdi") }) public static ForgeArchive getDeployment() { ForgeArchive archive = ShrinkWrap .create(ForgeArchive.class) .addBeansXML() .addAsAddonDependencies( AddonDependencyEntry.create("org.jboss.forge.addon:maven"), AddonDependencyEntry.create("org.jboss.forge.addon:ui"), AddonDependencyEntry.create("org.jboss.forge.addon:projects"), AddonDependencyEntry.create("org.jboss.forge.addon:shell-test-harness"), AddonDependencyEntry.create("org.jboss.forge.addon:resources"), AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi") ); return archive; } @Inject private ShellTest shellTest; @Inject private ProjectFactory projectFactory; @Test public void testLsCommand() throws Exception { Project project = projectFactory.createTempProject(); String projectPath = project.getRootDirectory().getFullyQualifiedName(); shellTest.execute("cd " + projectPath, 5, TimeUnit.SECONDS); shellTest.execute("touch file.txt", 5, TimeUnit.SECONDS); shellTest.clearScreen(); shellTest.execute("ls *file*", 5, TimeUnit.HOURS); Assert.assertThat(shellTest.getStdOut(), CoreMatchers.containsString("file.txt")); } }
package org.skyve.metadata.view.model.chart; import java.time.Month; import java.time.format.TextStyle; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.skyve.CORE; import org.skyve.impl.util.XMLMetaData; /** * Bucket a DateOnly, DateTime, TimeOnly or Timestamp (or any extension of java.util.Date) * by a TemporalBucketType. * * @author mike */ @XmlTransient public class TemporalBucket implements Bucket { private static final long serialVersionUID = -9134123560010408219L; @XmlType(namespace = XMLMetaData.VIEW_NAMESPACE) public static enum TemporalBucketType { quarter, dayMonthYear, day, month, year, monthYear, hour, hourDay, hourDayMonth, minuteHour, secondMinuteHour } protected TemporalBucketType type = null; public TemporalBucket(TemporalBucketType type) { this.type = type; } @Override public String bizQLExpression(String categoryBinding) { StringBuilder result = new StringBuilder(128); if (TemporalBucketType.quarter.equals(type)) { result.append("case when month(bean.") .append(categoryBinding).append(") <= 3 then 1 when month(bean.") .append(categoryBinding).append(") <= 6 then 2 when month(bean.") .append(categoryBinding).append(") <= 9 then 3 ") .append("else 4 end"); padZero(result); String month = result.toString(); result.setLength(0); result.append("concat(cast(year(bean.").append(categoryBinding); result.append(") as string), '-', ").append(month).append(')'); } else if (TemporalBucketType.dayMonthYear.equals(type)) { result.append("month(bean.").append(categoryBinding).append(')'); padZero(result); String month = result.toString(); result.setLength(0); result.append("day(bean.").append(categoryBinding).append(')'); padZero(result); String day = result.toString(); result.setLength(0); result.append("concat(cast(year(bean.").append(categoryBinding); result.append(") as string), '-', ").append(month); result.append(", '-', ").append(day).append(')'); } else if (TemporalBucketType.day.equals(type)) { result.append("day(bean.").append(categoryBinding).append(')'); } else if (TemporalBucketType.month.equals(type)) { result.append("month(bean.").append(categoryBinding).append(')'); } else if (TemporalBucketType.year.equals(type)) { result.append("year(bean.").append(categoryBinding).append(')'); } else if (TemporalBucketType.monthYear.equals(type)) { result.append("month(bean.").append(categoryBinding).append(')'); padZero(result); String month = result.toString(); result.setLength(0); result.append("concat(cast(year(bean.").append(categoryBinding); result.append(") as string), '-', ").append(month).append(')'); } else if (TemporalBucketType.hour.equals(type)) { result.append("hour(bean.").append(categoryBinding).append(')'); padZero(result); } else if (TemporalBucketType.hourDay.equals(type)) { result.append("day(bean.").append(categoryBinding).append(')'); padZero(result); String day = result.toString(); result.setLength(0); result.append("hour(bean.").append(categoryBinding).append(')'); padZero(result); String hour = result.toString(); result.setLength(0); result.append("concat(").append(day).append(", ' ', ").append(hour).append(')'); } else if (TemporalBucketType.hourDayMonth.equals(type)) { result.append("month(bean.").append(categoryBinding).append(')'); padZero(result); String month = result.toString(); result.setLength(0); result.append("day(bean.").append(categoryBinding).append(')'); padZero(result); String day = result.toString(); result.setLength(0); result.append("hour(bean.").append(categoryBinding).append(')'); padZero(result); String hour = result.toString(); result.setLength(0); result.append("concat(").append(month); result.append(", '-', ").append(day); result.append(", ' ', ").append(hour).append(')'); } else if (TemporalBucketType.minuteHour.equals(type)) { result.append("hour(bean.").append(categoryBinding).append(')'); padZero(result); String hour = result.toString(); result.setLength(0); result.append("minute(bean.").append(categoryBinding).append(')'); padZero(result); String minute = result.toString(); result.setLength(0); result.append("concat(").append(hour).append(", ':', ").append(minute).append(')'); } else if (TemporalBucketType.secondMinuteHour.equals(type)) { result.append("hour(bean.").append(categoryBinding).append(')'); padZero(result); String hour = result.toString(); result.setLength(0); result.append("minute(bean.").append(categoryBinding).append(')'); padZero(result); String minute = result.toString(); result.setLength(0); result.append("second(bean.").append(categoryBinding).append(')'); padZero(result); String second = result.toString(); result.setLength(0); result.append("concat(").append(hour).append(", ':', "); result.append(minute).append(", ':', ").append(second).append(')'); } return result.toString(); } @Override public String label(Object category) { if (category == null) { return null; } StringBuilder result = new StringBuilder(16); if (TemporalBucketType.quarter.equals(type)) { String[] tokens = category.toString().split("-"); result.append(quarter(Integer.parseInt(tokens[1]))).append(' ').append(tokens[0]); } else if (TemporalBucketType.dayMonthYear.equals(type)) { String[] tokens = category.toString().split("-"); result.append(day(Integer.parseInt(tokens[2]))).append(' '); result.append(month(Integer.parseInt(tokens[1]))).append(' ').append(tokens[0]); } else if (TemporalBucketType.day.equals(type)) { result.append(day(((Number) category).intValue())); } else if (TemporalBucketType.month.equals(type)) { result.append(month(((Number) category).intValue())); } else if (TemporalBucketType.year.equals(type)) { result.append(category); } else if (TemporalBucketType.monthYear.equals(type)) { String[] tokens = category.toString().split("-"); result.append(month(Integer.parseInt(tokens[1]))).append(' ').append(tokens[0]); } else if (TemporalBucketType.hour.equals(type)) { result.append(category).append(":00"); } else if (TemporalBucketType.hourDay.equals(type)) { String[] tokens = category.toString().split("\\s"); result.append(day(Integer.parseInt(tokens[0]))).append(' ').append(tokens[1]).append(":00"); } else if (TemporalBucketType.hourDayMonth.equals(type)) { String[] tokens = category.toString().split("(\\s|-)"); result.append(month(Integer.parseInt(tokens[0]))).append(' '); result.append(day(Integer.parseInt(tokens[1]))).append(' ').append(tokens[2]).append(":00"); } else if (TemporalBucketType.minuteHour.equals(type)) { String[] tokens = category.toString().split(":"); result.append(tokens[0]).append(':').append(tokens[1]); } else if (TemporalBucketType.secondMinuteHour.equals(type)) { String[] tokens = category.toString().split(":"); result.append(tokens[0]).append(':').append(tokens[1]).append(':').append(tokens[2]); } return result.toString(); } private static String day(int day) { if ((day == 1) || (day == 21) || (day == 31)) { return day + "st"; } else if ((day == 2) || (day == 22)) { return day + "nd"; } else if ((day == 3) || (day == 23)) { return day + "rd"; } else { return day + "th"; } } private static String month(int month) { return Month.of(month).getDisplayName(TextStyle.SHORT, CORE.getUser().getLocale()); } private static void padZero(StringBuilder expression) { String string = expression.toString(); expression.insert(0, "case when "); expression.append(" < 10 then concat('0', cast(").append(string); expression.append(" as string)) else concat('', cast(").append(string).append(" as string)) end"); } private static String quarter(int quarter) { return "Q" + quarter; } }
package com.salesmanager.shop.store.api.v1.product; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.salesmanager.core.business.services.catalog.category.CategoryService; import com.salesmanager.core.business.services.catalog.product.ProductService; import com.salesmanager.core.model.catalog.category.Category; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.ProductCriteria; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.model.catalog.product.LightPersistableProduct; import com.salesmanager.shop.model.catalog.product.PersistableProduct; import com.salesmanager.shop.model.catalog.product.ProductPriceRequest; import com.salesmanager.shop.model.catalog.product.ReadableProduct; import com.salesmanager.shop.model.catalog.product.ReadableProductList; import com.salesmanager.shop.model.catalog.product.ReadableProductPrice; import com.salesmanager.shop.model.entity.EntityExists; import com.salesmanager.shop.store.api.exception.ResourceNotFoundException; import com.salesmanager.shop.store.api.exception.UnauthorizedException; import com.salesmanager.shop.store.controller.product.facade.ProductFacade; import com.salesmanager.shop.utils.ImageFilePath; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import springfox.documentation.annotations.ApiIgnore; /** * API to create, read, update and delete a Product API to create Manufacturer * * @author Carl Samson */ @Controller @RequestMapping("/api/v1") @Api(tags = {"Product display and management resource (Product display and Management Api)"}) @SwaggerDefinition(tags = { @Tag(name = "Product management resource", description = "View product, Add product, edit product and delete product") }) public class ProductApi { @Inject private CategoryService categoryService; @Inject private ProductService productService; @Inject private ProductFacade productFacade; @Inject @Qualifier("img") private ImageFilePath imageUtils; private static final Logger LOGGER = LoggerFactory.getLogger(ProductApi.class); @ResponseStatus(HttpStatus.CREATED) @RequestMapping( value = {"/private/product", "/auth/products"},//private for api //auth for user adding products method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody PersistableProduct create( @Valid @RequestBody PersistableProduct product, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) { productFacade.saveProduct(merchantStore, product, language); return product; } @ResponseStatus(HttpStatus.OK) @RequestMapping( value = {"/private/product/{id}", "/auth/product/{id}"}, method = RequestMethod.PUT) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) @ApiOperation(httpMethod = "PUT", value = "Update product", notes = "", produces = "application/json", response = PersistableProduct.class) public @ResponseBody PersistableProduct update( @PathVariable Long id, @Valid @RequestBody PersistableProduct product, @ApiIgnore MerchantStore merchantStore, HttpServletRequest request, HttpServletResponse response) { try { // Make sure we have consistency in this request if(!id.equals(product.getId())) { response.sendError( 400, "Error url id does not match object id"); return null; } PersistableProduct saved = productFacade.saveProduct(merchantStore, product, merchantStore.getDefaultLanguage()); return saved; } catch (Exception e) { LOGGER.error("Error while updating product", e); try { response.sendError(503, "Error while updating product " + e.getMessage()); } catch (Exception ignore) { } return null; } } /** updates price quantity **/ @ResponseStatus(HttpStatus.OK) @PatchMapping( value = "/private/product/{id}", produces = {APPLICATION_JSON_VALUE}) @ApiOperation(httpMethod = "PATCH", value = "Update product inventory", notes = "Updates product inventory", produces = "application/json", response = Void.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") }) public void update( @PathVariable Long id, @Valid @RequestBody LightPersistableProduct product, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { productFacade.update(id, product, merchantStore, language); return; } @ResponseStatus(HttpStatus.OK) @RequestMapping( value = {"/private/product/{id}", "/auth/product/{id}"}, method = RequestMethod.DELETE) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void delete( @PathVariable Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { productFacade.deleteProduct(id, merchantStore); } /** * @RequestMapping( value="/private/{store}/manufacturer", * method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public * PersistableManufacturer createManufacturer(@PathVariable final String * store, @Valid @RequestBody PersistableManufacturer manufacturer, HttpServletRequest request, * HttpServletResponse response) throws Exception { * * <p>try { * * <p>@ApiIgnore MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); * if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } * } * * <p>if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } * * <p>if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); * response.sendError(503, "Merchant store is null for code " + store); return null; } * * <p>PersistableManufacturerPopulator populator = new PersistableManufacturerPopulator(); * populator.setLanguageService(languageService); * * <p>com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer manuf = new * com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer(); * * <p>populator.populate(manufacturer, manuf, merchantStore, merchantStore.getDefaultLanguage()); * * <p>manufacturerService.save(manuf); * * <p>manufacturer.setId(manuf.getId()); * * <p>return manufacturer; * * <p>} catch (Exception e) { LOGGER.error("Error while saving product",e); try { * response.sendError(503, "Error while saving product " + e.getMessage()); } catch (Exception * ignore) { } * * <p>return null; } * * <p>} @RequestMapping( value="/private/{store}/product/optionValue", * method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public * PersistableProductOptionValue createProductOptionValue(@PathVariable final String * store, @Valid @RequestBody PersistableProductOptionValue optionValue, HttpServletRequest * request, HttpServletResponse response) throws Exception { * * <p>try { * * <p>@ApiIgnore MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); * if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } * } * * <p>if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } * * <p>if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); * response.sendError(503, "Merchant store is null for code " + store); return null; } * * <p>PersistableProductOptionValuePopulator populator = new * PersistableProductOptionValuePopulator(); populator.setLanguageService(languageService); * * <p>com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue optValue = new * com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue(); * populator.populate(optionValue, optValue, merchantStore, merchantStore.getDefaultLanguage()); * * <p>productOptionValueService.save(optValue); * * <p>optionValue.setId(optValue.getId()); * * <p>return optionValue; * * <p>} catch (Exception e) { LOGGER.error("Error while saving product option value",e); try { * response.sendError(503, "Error while saving product option value" + e.getMessage()); } catch * (Exception ignore) { } * * <p>return null; } * * <p>} @RequestMapping( value="/private/{store}/product/option", * method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public * PersistableProductOption createProductOption(@PathVariable final String * store, @Valid @RequestBody PersistableProductOption option, HttpServletRequest request, * HttpServletResponse response) throws Exception { * * <p>try { * * <p>@ApiIgnore MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); * if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } * } * * <p>if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } * * <p>if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); * response.sendError(503, "Merchant store is null for code " + store); return null; } * * <p>PersistableProductOptionPopulator populator = new PersistableProductOptionPopulator(); * populator.setLanguageService(languageService); * * <p>com.salesmanager.core.model.catalog.product.attribute.ProductOption opt = new * com.salesmanager.core.model.catalog.product.attribute.ProductOption(); * populator.populate(option, opt, merchantStore, merchantStore.getDefaultLanguage()); * * <p>productOptionService.save(opt); * * <p>option.setId(opt.getId()); * * <p>return option; * * <p>} catch (Exception e) { LOGGER.error("Error while saving product option",e); try { * response.sendError(503, "Error while saving product option" + e.getMessage()); } catch * (Exception ignore) { } * * <p>return null; } } @RequestMapping( value="/private/{store}/product/review", * method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public * PersistableProductReview createProductReview(@PathVariable final String * store, @Valid @RequestBody PersistableProductReview review, HttpServletRequest request, * HttpServletResponse response) throws Exception { * * <p>try { * * <p>@ApiIgnore MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); * if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } * } * * <p>if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } * * <p>if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); * response.sendError(500, "Merchant store is null for code " + store); return null; } * * <p>//rating already exist ProductReview prodReview = * productReviewService.getByProductAndCustomer(review.getProductId(), review.getCustomerId()); * if(prodReview!=null) { response.sendError(500, "A review already exist for this customer and * product"); return null; } * * <p>//rating maximum 5 if(review.getRating()>Constants.MAX_REVIEW_RATING_SCORE) { * response.sendError(503, "Maximum rating score is " + Constants.MAX_REVIEW_RATING_SCORE); return * null; } * * <p>PersistableProductReviewPopulator populator = new PersistableProductReviewPopulator(); * populator.setLanguageService(languageService); populator.setCustomerService(customerService); * populator.setProductService(productService); * * <p>com.salesmanager.core.model.catalog.product.review.ProductReview rev = new * com.salesmanager.core.model.catalog.product.review.ProductReview(); populator.populate(review, * rev, merchantStore, merchantStore.getDefaultLanguage()); * * <p>productReviewService.create(rev); * * <p>review.setId(rev.getId()); * * <p>return review; * * <p>} catch (Exception e) { LOGGER.error("Error while saving product review",e); try { * response.sendError(503, "Error while saving product review" + e.getMessage()); } catch * (Exception ignore) { } * * <p>return null; } } @RequestMapping("/public/products/{store}") @ResponseBody public * ReadableProductList getProducts(@PathVariable String store, HttpServletRequest request, * HttpServletResponse response) throws Exception { */ /** default routine * */ /* @ApiIgnore MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } } if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); response.sendError(503, "Merchant store is null for code " + store); return null; } Language l = merchantStore.getDefaultLanguage(); String lang = l.getCode(); if(!StringUtils.isBlank(request.getParameter(Constants.LANG))) { lang = request.getParameter(Constants.LANG); } */ /** end default routine * */ /* return this.getProducts(0, 10000, store, lang, null, null, request, response); }*/ /** * Filtering product lists based on product attributes ?category=1 &manufacturer=2 &type=... * &lang=en|fr NOT REQUIRED, will use request language &start=0 NOT REQUIRED, can be used for * pagination &count=10 NOT REQUIRED, can be used to limit item count * * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/products", method = RequestMethod.GET) @ResponseBody @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ReadableProductList list( @RequestParam(value = "lang", required = false) String lang, @RequestParam(value = "category", required = false) Long category, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "sku", required = false) String sku, @RequestParam(value = "manufacturer", required = false) Long manufacturer, @RequestParam(value = "optionValues", required = false) List<Long> optionValueIds, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "owner", required = false) Long owner, @RequestParam(value = "page", required = false) Integer page,//current page 0 .. n allowing navigation @RequestParam(value = "count", required = false) Integer count,//count per page @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) throws Exception { ProductCriteria criteria = new ProductCriteria(); //do not use legacy pagination anymore if (lang != null) { criteria.setLanguage(lang); } else { criteria.setLanguage(language.getCode()); } if (!StringUtils.isBlank(status)) { criteria.setStatus(status); } if (category != null) { List<Long> categoryIds = new ArrayList<Long>(); categoryIds.add(category); criteria.setCategoryIds(categoryIds); } if (manufacturer != null) { criteria.setManufacturerId(manufacturer); } if(CollectionUtils.isNotEmpty(optionValueIds)) { criteria.setOptionValueIds(optionValueIds); } if (owner != null) { criteria.setOwnerId(owner); } if (page != null) { criteria.setStartPage(page); } if (count != null) { criteria.setMaxCount(count); } if(!StringUtils.isBlank(name)) { criteria.setProductName(name); } if(!StringUtils.isBlank(sku)) { criteria.setCode(sku); } // TODO // RENTAL add filter by owner // REPOSITORY to use the new filters try { return productFacade.getProductListsByCriterias(merchantStore, language, criteria); } catch (Exception e) { LOGGER.error("Error while filtering products product", e); try { response.sendError(503, "Error while filtering products " + e.getMessage()); } catch (Exception ignore) { } return null; } } /** * API for getting a product * * @param id * @param lang ?lang=fr|en|... * @param response * @return ReadableProduct * @throws Exception * <p>/api/v1/products/123 */ @RequestMapping(value = "/products/{id}", method = RequestMethod.GET) @ApiOperation(httpMethod = "GET", value = "Get a product by id", notes = "For administration and shop purpose. Specifying ?merchant is required otherwise it falls back to DEFAULT") @ApiResponses(value = { @ApiResponse(code = 200, message = "Single product found", response = ReadableProduct.class) }) @ResponseBody @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ReadableProduct get( @PathVariable final Long id, @RequestParam(value = "lang", required = false) String lang, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { ReadableProduct product = productFacade.getProduct(merchantStore, id, language); if (product == null) { response.sendError(404, "Product not fount for id " + id); return null; } return product; } @RequestMapping(value = "/product/{id}/price", method = RequestMethod.POST) @ApiOperation(httpMethod = "POST", value = "Calculate product price with variants", notes = "Product price calculation from variamts") @ApiResponses(value = { @ApiResponse(code = 200, message = "Price calculated", response = ReadableProductPrice.class) }) @ResponseBody @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ReadableProductPrice price( @PathVariable final Long id, @RequestBody ProductPriceRequest variants, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { return productFacade.getProductPrice(id, variants, merchantStore, language); } /** * API for getting a product * * @param friendlyUrl * @param lang ?lang=fr|en * @param response * @return ReadableProduct * @throws Exception * <p>/api/v1/products/123 */ @RequestMapping(value = {"/products/slug/{friendlyUrl}","/products/friendly/{friendlyUrl}"}, method = RequestMethod.GET) @ApiOperation(httpMethod = "GET", value = "Get a product by friendlyUrl (slug)", notes = "For administration and shop purpose. Specifying ?merchant is " + "required otherwise it falls back to DEFAULT") @ApiResponses(value = { @ApiResponse(code = 200, message = "Single product found", response = ReadableProduct.class) }) @ResponseBody @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ReadableProduct getByfriendlyUrl( @PathVariable final String friendlyUrl, @RequestParam(value = "lang", required = false) String lang, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { ReadableProduct product = productFacade.getProductBySeUrl(merchantStore, friendlyUrl, language); if (product == null) { response.sendError(404, "Product not fount for id " + friendlyUrl); return null; } return product; } @ResponseStatus(HttpStatus.OK) @GetMapping(value = {"/private/product/unique"}, produces = MediaType.APPLICATION_JSON_VALUE) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT") }) @ApiOperation(httpMethod = "GET", value = "Check if product code already exists", notes = "", response = EntityExists.class) public ResponseEntity<EntityExists> exists( @RequestParam(value = "code") String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { boolean exists = productFacade.exists(code, merchantStore); return new ResponseEntity<EntityExists>(new EntityExists(exists), HttpStatus.OK); } @ResponseStatus(HttpStatus.CREATED) @RequestMapping( value = { "/private/product/{productId}/category/{categoryId}", "/auth/product/{productId}/category/{categoryId}" }, method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableProduct addProductToCategory( @PathVariable Long productId, @PathVariable Long categoryId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { try { // get the product Product product = productService.getById(productId); if(product == null) { throw new ResourceNotFoundException("Product id [" + productId + "] is not found"); } if(product.getMerchantStore().getId().intValue() != merchantStore.getId().intValue()) { throw new UnauthorizedException("Product id [" + productId + "] does not belong to store [" + merchantStore.getCode() + "]"); } Category category = categoryService.getById(categoryId); if(category == null) { throw new ResourceNotFoundException("Category id [" + categoryId + "] is not found"); } if(category.getMerchantStore().getId().intValue() != merchantStore.getId().intValue()) { throw new UnauthorizedException("Category id [" + categoryId + "] does not belong to store [" + merchantStore.getCode() + "]"); } return productFacade.addProductToCategory(category, product, language); } catch (Exception e) { LOGGER.error("Error while adding product to category", e); try { response.sendError(503, "Error while adding product to category " + e.getMessage()); } catch (Exception ignore) { } return null; } } @ResponseStatus(HttpStatus.OK) @RequestMapping( value = { "/private/product/{productId}/category/{categoryId}", "/auth/product/{productId}/category/{categoryId}" }, method = RequestMethod.DELETE) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableProduct removeProductFromCategory( @PathVariable Long productId, @PathVariable Long categoryId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { try { Product product = productService.getById(productId); if(product == null) { throw new ResourceNotFoundException("Product id [" + productId + "] is not found"); } if(product.getMerchantStore().getId().intValue() != merchantStore.getId().intValue()) { throw new UnauthorizedException("Product id [" + productId + "] does not belong to store [" + merchantStore.getCode() + "]"); } Category category = categoryService.getById(categoryId); if(category == null) { throw new ResourceNotFoundException("Category id [" + categoryId + "] is not found"); } if(category.getMerchantStore().getId().intValue() != merchantStore.getId().intValue()) { throw new UnauthorizedException("Category id [" + categoryId + "] does not belong to store [" + merchantStore.getCode() + "]"); } return productFacade.removeProductFromCategory(category, product, language); } catch (Exception e) { LOGGER.error("Error while removing product from category", e); try { response.sendError(503, "Error while removing product from category " + e.getMessage()); } catch (Exception ignore) { } return null; } } }
package org.apache.jmeter.samplers; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.avalon.framework.configuration.Configuration; import org.apache.jmeter.assertions.AssertionResult; //import org.apache.jorphan.logging.LoggingManager; //import org.apache.log.Logger; /** * This is a nice packaging for the various information returned from taking a * sample of an entry. * * @author mstover? * @version $Revision$ $Date$ */ public class SampleResult implements Serializable { /** * Data type value indicating that the response data is text. * * @see #getDataType * @see #setDataType(java.lang.String) */ public final static String TEXT = "text"; /** * Data type value indicating that the response data is binary. * * @see #getDataType * @see #setDataType(java.lang.String) */ public final static String BINARY = "bin"; /* empty array which can be returned instead of null */ private static final byte [] EMPTY_BA = new byte [0]; private byte[] responseData; private String responseCode; private String label; private String samplerData; private String threadName; private String responseMessage=""; private String responseHeaders=""; // Never return null private String contentType; private String requestHeaders=""; private long timeStamp = 0; private List assertionResults; private List subResults; private String dataType; private boolean success; private Set files; private String dataEncoding; private long time; private boolean stopThread = false; //Should thread terminate? private boolean stopTest = false; //Should test terminate? private final static String TOTAL_TIME = "totalTime"; //transient private static Logger log = LoggingManager.getLoggerForClass(); public void setMarked(String filename) { if (files == null) { files = new HashSet(); } files.add(filename); } public boolean isMarked(String filename) { return files != null && files.contains(filename); } public String getResponseCode() { return responseCode; } public void setResponseCode(String code) { responseCode = code; } public String getResponseMessage() { return responseMessage; } public void setResponseMessage(String msg) { responseMessage = msg; } public String getThreadName() { return threadName; } public void setThreadName(String threadName) { this.threadName = threadName; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public String getSampleLabel() { return label; } public void setSampleLabel(String label) { this.label = label; } public void addAssertionResult(AssertionResult assertResult) { if (assertionResults == null) { assertionResults = new ArrayList(); } assertionResults.add(assertResult); } /** * Gets the assertion results associated with this sample. * * @return an array containing the assertion results for this sample. * Returns null if there are no assertion results. */ public AssertionResult[] getAssertionResults() { if (assertionResults == null) { return null; } return (AssertionResult[]) assertionResults.toArray( new AssertionResult[0]); } public void addSubResult(SampleResult subResult) { if (subResults == null) { subResults = new ArrayList(); } subResults.add(subResult); } /** * Gets the subresults associated with this sample. * * @return an array containing the subresults for this sample. Returns * null if there are no subresults. */ public SampleResult[] getSubResults() { if (subResults == null) { return null; } return (SampleResult[]) subResults.toArray(new SampleResult[0]); } public void configure(Configuration info) { setTime(info.getAttributeAsLong(TOTAL_TIME, 0L)); } /** * Set the time this sample took to occur. */ public void setTime(long t) { time = t; } /** * Sets the responseData attribute of the SampleResult object. * * @param response the new responseData value */ public void setResponseData(byte[] response) { responseData = response; } /** * Gets the responseData attribute of the SampleResult object. * * @return the responseData value */ public byte[] getResponseData() { return responseData; } /** * Convenience method to get responseData as a non-null byte array * * @return the responseData. If responseData is null * then an empty byte array is returned rather than null. * */ public byte [] responseDataAsBA() { return responseData == null ? EMPTY_BA : responseData; } public void setSamplerData(String s) { samplerData = s; } public String getSamplerData() { return samplerData; } /** * Get the time it took this sample to occur. */ public long getTime() { return time; } public boolean isSuccessful() { return success; } public void setDataType(String dataType) { this.dataType = dataType; } public String getDataType() { return dataType; } /** * Sets the successful attribute of the SampleResult object. * * @param success the new successful value */ public void setSuccessful(boolean success) { this.success = success; } /** * Returns the display name. * * @return display name of this sample result */ public String toString() { return getSampleLabel(); } /** * Returns the dataEncoding. */ public String getDataEncoding() { if (dataEncoding != null) { return dataEncoding; } else { return "8859-1"; } } /** * Sets the dataEncoding. * @param dataEncoding the dataEncoding to set */ public void setDataEncoding(String dataEncoding) { this.dataEncoding = dataEncoding; } /** * @return whether to stop the test */ public boolean isStopTest() { return stopTest; } /** * @return whether to stop this thread */ public boolean isStopThread() { return stopThread; } /** * @param b */ public void setStopTest(boolean b) { stopTest = b; } /** * @param b */ public void setStopThread(boolean b) { stopThread = b; } /** * @return the request headers */ public String getRequestHeaders() { return requestHeaders; } /** * @return the response headers */ public String getResponseHeaders() { return responseHeaders; } /** * @param string - request headers */ public void setRequestHeaders(String string) { requestHeaders = string; } /** * @param string - response headers */ public void setResponseHeaders(String string) { responseHeaders = string; } /** * @return the content type - text or bin */ public String getContentType() { return contentType; } /** * @param string */ public void setContentType(String string) { contentType = string; } }
package com.intellij.ide.structureView.newStructureView; import com.intellij.ide.structureView.ModelListener; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.util.treeView.*; import com.intellij.ide.util.treeView.smartTree.SmartTreeStructure; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.util.Alarm; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; final class StructureTreeBuilder extends AbstractTreeBuilder { private final Project myProject; private final StructureViewModel myStructureModel; private final MyCopyPasteListener myCopyPasteListener; private final PsiTreeChangeListener myPsiTreeChangeListener; private final ModelListener myModelListener; private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); public StructureTreeBuilder(Project project, JTree tree, DefaultTreeModel treeModel, AbstractTreeStructure treeStructure, StructureViewModel structureModel) { super( tree, treeModel, treeStructure, null ); myProject = project; myStructureModel = structureModel; myPsiTreeChangeListener = new MyPsiTreeChangeListener(); myModelListener = new ModelListener() { public void onModelChanged() { myUpdater.addSubtreeToUpdate(myRootNode); } }; PsiManager.getInstance(myProject).addPsiTreeChangeListener(myPsiTreeChangeListener); myCopyPasteListener = new MyCopyPasteListener(); CopyPasteManager.getInstance().addContentChangedListener(myCopyPasteListener); initRootNode(); myStructureModel.addModelListener(myModelListener); } public void dispose() { myUpdateAlarm.cancelAllRequests(); PsiManager.getInstance(myProject).removePsiTreeChangeListener(myPsiTreeChangeListener); CopyPasteManager.getInstance().removeContentChangedListener(myCopyPasteListener); myStructureModel.removeModelListener(myModelListener); super.dispose(); } protected boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) { return ((AbstractTreeNode)nodeDescriptor).isAlwaysShowPlus(); } protected boolean isAutoExpandNode(NodeDescriptor nodeDescriptor) { return false; } protected boolean isSmartExpand() { return false; } protected final AbstractTreeUpdater createUpdater(){ return new AbstractTreeUpdater(this) { protected void updateSubtree(DefaultMutableTreeNode node) { if(!myProject.isDisposed()) { super.updateSubtree(node); } } }; } private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter { public MyPsiTreeChangeListener() { } public void childRemoved(PsiTreeChangeEvent event) { PsiElement child = event.getOldChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } public void childAdded(PsiTreeChangeEvent event) { PsiElement child = event.getNewChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } public void childReplaced(PsiTreeChangeEvent event) { PsiElement oldChild = event.getOldChild(); PsiElement newChild = event.getNewChild(); if (oldChild instanceof PsiWhiteSpace && newChild instanceof PsiWhiteSpace) return; //optimization if (oldChild instanceof PsiCodeBlock && newChild instanceof PsiCodeBlock) return; //optimization childrenChanged(); } public void childMoved(PsiTreeChangeEvent event) { childrenChanged(); childrenChanged(); } public void childrenChanged(PsiTreeChangeEvent event) { childrenChanged(); } private void childrenChanged() { myUpdateAlarm.cancelAllRequests(); myUpdateAlarm.addRequest(new Runnable() { public void run() { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); ((SmartTreeStructure)getTreeStructure()).rebuildTree(); myUpdater.addSubtreeToUpdate(myRootNode); } }, 300); } public void propertyChanged(PsiTreeChangeEvent event) { myUpdater.addSubtreeToUpdate(myRootNode); } } private final class MyCopyPasteListener implements CopyPasteManager.ContentChangedListener { public void contentChanged() { myUpdater.addSubtreeToUpdate(myRootNode); } } }
package reflex; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.antlr.runtime.RecognitionException; import org.junit.Test; import reflex.value.ReflexDateValue; public class DateTest extends ResourceBasedTest { @Test public void testDateAdding() throws RecognitionException { String ret = runTestFor("/date/adding.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); } // See RAP-3540 @Test public void testDate() { ReflexDateValue v = new ReflexDateValue("20120804", "BDF"); String s = v.toString(); assertEquals("20120804", s); } @Test public void testDateCreation() throws RecognitionException { String ret = runTestFor("/date/creation.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); } @Test public void testTime() throws RecognitionException { String ret = runTestFor("/time/creation.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); } @Test public void testComparison() throws RecognitionException { String ret = runTestFor("/date/comparison.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); } @Test public void testTimeComparison() throws RecognitionException { String ret = runTestFor("/date/timecomparison.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); } @Test public void yesterday() throws RecognitionException { String[] ret = runTestFor("/date/yesterday.rfx").split("\n"); ZonedDateTime today = ZonedDateTime.now(ZoneId.of("America/Los_Angeles")); ZonedDateTime yesterday = today.minusDays(1); DateTimeFormatter df1 = DateTimeFormatter.ofPattern("yyyyMMdd"); DateTimeFormatter df2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); assertEquals(ret[3], "TODAY2 " + today.format(df2)); assertEquals(ret[2], "TODAY " + today.format(df1)); assertEquals(ret[1], "YESTERDAY2 " + yesterday.format(df2)); assertEquals(ret[0], "YESTERDAY " + yesterday.format(df1)); assertTrue("Test case did not complete successfully", ret[ret.length - 1].endsWith("true")); } @Test public void testEpoch() throws RecognitionException { String ret = runTestFor("/date/epoch.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); ret = runTestFor("/time/epoch.rfx"); assertTrue("Test case did not complete successfully", ret.endsWith("true")); } }
package de.eternity.support.lua; import java.awt.event.KeyEvent; import java.io.File; import java.lang.reflect.Field; import java.nio.file.Path; import java.nio.file.Paths; import org.luaj.vm2.Globals; import org.luaj.vm2.LuaValue; import org.luaj.vm2.lib.jse.JsePlatform; import de.eternity.Game; import de.eternity.gui.Display; import de.eternity.support.lua.functions.GetFps; import de.eternity.support.lua.functions.GetGameData; import de.eternity.support.lua.functions.GetGameMap; import de.eternity.support.lua.functions.GetTextureStorage; import de.eternity.support.lua.functions.IsKeyPressed; import de.eternity.support.lua.functions.LoadAnimation; import de.eternity.support.lua.functions.LoadSound; import de.eternity.support.lua.functions.PollKeyboard; import de.eternity.support.lua.functions.PopGameState; import de.eternity.support.lua.functions.PushGameState; import de.eternity.support.lua.functions.ReadToml; import de.eternity.support.lua.functions.SetWindowTitle; import de.eternity.support.lua.functions.ToGlobalTextureId; import de.eternity.support.lua.functions.UpdateTileAnimations; import de.eternity.util.LuaGameStates; public class EngineLuaEnvironment { private Globals _G = JsePlatform.standardGlobals(); public EngineLuaEnvironment(Display display, Game game, LuaGameStates luaGameStates){ //load all lua scripts in the dedicated folder and sub folders (first root folder, then subfolders (recursive)) loadLuaFolder(new File(Paths.get("res", game.getGameData().getSettings().getLuaScriptsPath()).toAbsolutePath().toString())); //load hard coded key bindings from KeyEvent class Class<KeyEvent> keyEventClass = KeyEvent.class; Field[] fields = keyEventClass.getFields(); for(int i = 0; i < fields.length; i++) if(fields[i].getName().startsWith("VK_")) try { _G.load(fields[i].getName() + " = " + fields[i].getInt(null)).call(); } catch (IllegalArgumentException | IllegalAccessException e) { //this error is not possible e.printStackTrace(); System.exit(-1); } //init game state handling lua functions _G.set("push_game_state", new PushGameState(game, luaGameStates)); _G.set("pop_game_state", new PopGameState(game)); //init keyboard handling lua functions _G.set("poll_keyboard", new PollKeyboard(game.getGameData().getKeyboard())); _G.set("is_key_pressed", new IsKeyPressed(game.getGameData().getKeyboard())); //init game map methods _G.set("get_game_map", new GetGameMap(game.getGameData().getGameMaps())); //init utility methods _G.set("read_toml", new ReadToml(game.getGameData())); _G.set("get_game_data", new GetGameData(game.getGameData())); _G.set("get_fps", new GetFps()); //init graphics methods _G.set("load_animation", new LoadAnimation(game.getGameData())); _G.set("set_window_title", new SetWindowTitle(display)); _G.set("update_tile_animations", new UpdateTileAnimations(game.getGameData().getTileStorage())); _G.set("get_texture_storage", new GetTextureStorage(game.getGameData().getTextureStorage())); _G.set("to_global_texture_id", new ToGlobalTextureId(game.getGameData().getTextureStorage())); //init sound methods _G.set("load_sound", new LoadSound(game.getGameData().getSettings().getSoundPath())); } private void loadLuaFolder(File dir){ String[] subFiles = dir.list(); if(subFiles != null)//test if subFiles exist //files first for(int i = 0; i < subFiles.length; i++) //only .lua files if(subFiles[i].endsWith(".lua")) _G.get("dofile").call(dir.getAbsolutePath() + "/" + subFiles[i]); //folders second for(int i = 0; i < subFiles.length; i++) //only .lua files if(!subFiles[i].endsWith(".lua")){ File subDir = new File(dir.getAbsolutePath() + "/" + subFiles[i]); if(subDir.exists() && subDir.isDirectory()) loadLuaFolder(subDir); } } public void setMethod(String methodName, LuaValue function){ _G.set(methodName, function); } public LuaGameState loadGameState(Path scriptPath){ return new LuaGameState(_G.loadfile(scriptPath.toString()), scriptPath.getFileName().toString().split("\\.")[0]); } }
package de.gurkenlabs.litiengine.util; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; public final class ArrayUtilities { private static final Logger log = Logger.getLogger(ArrayUtilities.class.getName()); private ArrayUtilities() { } public static byte[] arrayConcat(final byte[] firstArray, final byte[] secondArray) { final int aLen = firstArray.length; final int bLen = secondArray.length; final byte[] combinedArray = new byte[aLen + bLen]; System.arraycopy(firstArray, 0, combinedArray, 0, aLen); System.arraycopy(secondArray, 0, combinedArray, aLen, bLen); return combinedArray; } public static int[] getIntegerArray(String commaSeperatedString) { if (commaSeperatedString == null || commaSeperatedString.isEmpty()) { return new int[0]; } final String[] split = commaSeperatedString.split(","); int[] integers = new int[split.length]; if (integers.length == 0) { return integers; } for (int i = 0; i < split.length; i++) { if (split[i] == null || split[i].isEmpty()) { continue; } try { integers[i] = Integer.parseInt(split[i]); } catch (final NumberFormatException e) { log.log(Level.SEVERE, e.getMessage(), e); } } return integers; } public static double[] getDoubleArray(String commaSeperatedString) { if (commaSeperatedString == null || commaSeperatedString.isEmpty()) { return new double[0]; } final String[] split = commaSeperatedString.split(","); double[] doubles = new double[split.length]; if (doubles.length == 0) { return doubles; } for (int i = 0; i < split.length; i++) { if (split[i] == null || split[i].isEmpty()) { continue; } try { doubles[i] = Double.parseDouble(split[i]); } catch (final NumberFormatException e) { log.log(Level.SEVERE, e.getMessage(), e); } } return doubles; } public static String getCommaSeparatedString(int[] arr) { return getCommaSeparatedString(Arrays.stream(arr).boxed().toArray(Integer[]::new)); } public static String getCommaSeparatedString(double[] arr) { return getCommaSeparatedString(Arrays.stream(arr).boxed().toArray(Double[]::new)); } public static <T> String getCommaSeparatedString(List<T> list) { if (list == null || list.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(','); } } return sb.toString(); } public static <T> String getCommaSeparatedString(T[] arr) { return getCommaSeparatedString(Arrays.asList(arr)); } public static <T> T getRandom(T[] arr) { if (arr.length == 0) { return null; } final int randomIndex = new Random().nextInt(arr.length); return arr[randomIndex]; } public static boolean containsArgument(String[] args, String argument) { if (args == null || args.length == 0) { return false; } for (int i = 0; i < args.length; i++) { final String a = args[i]; if (a != null && !a.isEmpty() && a.equalsIgnoreCase(argument)) { return true; } } return false; } /** * Removes the specified deleteItem from the input array and returns a trimmed new array instance without null entries. * The resulting array will have a length -1; * * @param input * The original array * @param deleteItem * The item to delete * @return A new array with the length input.length - 1. */ public static <T> T[] remove(T[] input, T deleteItem) { List<T> result = new ArrayList<>(); for (T item : input) { if (!deleteItem.equals(item)) { result.add(item); } } result.removeAll(Collections.singleton(null)); T[] newArr = (T[]) input.getClass().cast(Array.newInstance(input.getClass().getComponentType(), result.size())); return result.toArray(newArr); } public static int[] toIntegerArray(List<Integer> intList) { Object[] objArray = intList.toArray(); int[] intArray = new int[objArray.length]; for (int i = 0; i < intArray.length; i++) { intArray[i] = (int) objArray[i]; } return intArray; } }
package Models.MelanomaWorkshop.Model2D; import Framework.Extensions.SphericalAgent2D; import Framework.GridsAndAgents.AgentGrid2D; import Framework.GridsAndAgents.GridBase; import Framework.GridsAndAgents.PDEGrid2D; import Framework.Gui.Vis2DOpenGL; import Framework.Utils; import org.lwjgl.Sys; import Framework.Gui.GridVisWindow; import Framework.Gui.Vis2DOpenGL; import Framework.Utils; import java.util.ArrayList; import java.util.Random; import static Framework.Utils.*; // txt reading/writing import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.ListIterator; import java.io.File; class Dish extends AgentGrid2D<Cell> { final static int BLACK=RGB(0,0,0),RED=RGB(1,0,0),GREEN=RGB(0,1,0),YELLOW=RGB(1,1,0),BLUE=RGB(0,0,1), AZUL=RGB(1,0,1); //GLOBAL CONSTANTS double DIVISION_PROB=0.01; double DEATH_PROB=0.0; double[] CELL_RAD={0.5,0.3,0.6,0.3}; double[] MAX_RAD=new double[CELL_RAD.length]; double FRICTION=0.4; double STEADY_STATE_FORCE=0; double MAX_STEADY_STATE_LOOPS=10; double[] DIV_RADIUS=new double[CELL_RAD.length]; double FORCE_EXPONENT=2; double FORCE_SCALER=0.7; double immAttr; // alpha double stromAttr; // beta double[] divProb={0.003,0.0,0.0,0.01}; double[] deathProb={0.0,0.0,0.0,0.0}; // baseline death probability double baseCaDeathProb=deathProb[0]; double productionRate=0.1; double decayRate=0.1; double additDeathProb = 0.5; int initialAntigens=2; double mutationProb=0.1; int vessels_grid_x = 4; int vessels_grid_y = 4; PDEGrid2D diffusible = new PDEGrid2D(xDim, yDim); //Diffusible factor (VEGF,FGF,TGFB) //double MAX_VEL=1000000000; int fusionCt=0; //INTERNAL VARIABLES Random rn=new Random(); ArrayList<Cell> cellScratch=new ArrayList<>(); ArrayList<Cell> cancerCells=new ArrayList<>(); ArrayList<Cell> stromaCells=new ArrayList<>(); ArrayList<Cell> immuneCells=new ArrayList<>(); ArrayList<double[]>BloodVesselsCoord=new ArrayList<>(); double[] Ves1={xDim/10,yDim/10}; double[] Ves2={xDim*3/4,yDim*3/4}; double[] Ves3={xDim/4,yDim*3/4}; double[] Ves4={xDim*3/4,yDim/4}; public ArrayList<double[]> addBloodVessels(int n_vessels_x, int n_vessels_y){ ArrayList<double[]>BloodVesselsCoord=new ArrayList<>(); double dx = xDim / (n_vessels_x+1); double dy = yDim / (n_vessels_y+1); double x=dx; double y=dy; for (int i = 0; i < n_vessels_x; i++) { for (int j = 0; j < n_vessels_y; j++) { double[] Ves = {dx + dx*i, dy+dy*j}; BloodVesselsCoord.add(Ves); } } return BloodVesselsCoord; } public List<String> readCellCoords(String path_to_file){ List<String> lines = new ArrayList<String>(); try { lines = Files.readAllLines(Paths.get(path_to_file)); //for (String line : lines) { //System.out.println(line); } catch(IOException e) { e.printStackTrace(); } return lines; } public void writeCellCoords(String path_to_file){ try { File file = new File(path_to_file); PrintWriter printWriter = new PrintWriter(file); String line = ""; line = "cell_id,type,x,y\n"; printWriter.print(line); int cnt = 0; for (Cell c:this) { int type = c.type; double x = c.Xpt(); double y = c.Ypt(); System.out.println(x); System.out.println(y); System.out.println(type); line = "" + cnt + "," + type + "," + x + "," + y + "\n"; printWriter.print(line); } printWriter.close(); } // end try block catch (Exception e) { System.out.println(e.getClass()); } } double[] divCoordScratch=new double[2]; public Dish(int sideLen,int startingPop,int startingStroma,double startingRadius, String path_to_file){ super(sideLen,sideLen,Cell.class); double[] startCoords=new double[2]; for (int i = 0; i < CELL_RAD.length ; i++) { MAX_RAD[i]=Math.sqrt(2)*CELL_RAD[i]; DIV_RADIUS[i]=CELL_RAD[i]*(2.0/3.0); } BloodVesselsCoord = this.addBloodVessels(this.vessels_grid_x, this.vessels_grid_y); double[] startCoordsStroma={10,10}; // startingStroma=(int)Math.round((xDim*yDim)/10); // int inc=10; // int xStr=0; // while(xStr < xDim) { // xStr=xStr+inc; // int yStr=0; // while(yStr<yDim){ // yStr=yStr+inc; // Cell c=NewAgentPT(xStr,yStr); // c.Init(2); // for (int i = 0; i < startingStroma; i++) { //// Utils.RandomPointInCircle(startingRadius, startCoords, rn); // Cell c=NewAgentPT(Math.round(Math.random()*xDim),Math.round(Math.random()*yDim)); // c.Init(2); if (path_to_file == null) { //INITIALIZE population of cancer and stroma for (int i = 0; i < startingStroma; i++) { // Utils.RandomPointInCircle(startingRadius, startCoords, rn); Cell c = NewAgentPT(Math.random() * xDim, Math.random() * yDim); c.Init(2,0); } for (int i = 0; i < startingPop; i++) { // Utils.RandomPointInCircle(startingRadius, startCoords, rn); Cell c = NewAgentPT(xDim / 2.0, yDim / 2.0); // Cell c=NewAgentPT(startCoords[0]+xDim/2.0,startCoords[1]+yDim/2.0); c.Init(0,initialAntigens); } } else{ // Get cells from cell list List<String> cell_list = readCellCoords(path_to_file); // create seeds for (int i = 2; i < cell_list.size(); i++) { //for (int i = 950; i < 960; i++) { String line = cell_list.get(i); String[] line_array = line.split(","); System.out.println(line); double x = Double.parseDouble(line_array[2]); double y = Double.parseDouble(line_array[3]); int tmp_type = Integer.parseInt(line_array[1]); // RECODE CELL IDS FROM NICOLAS' SCHEME TO INTERNAL int type = 10; switch (tmp_type) { case 1: type = 1; // Immune (1) -> (1) break; case 2: type = 0; // Melanocyte (2) ->(0) break; case 3: type = 2; // STROMA (3) -> (2) break; case 0: type = 10; // type > 9 -> ignore break; } if (x < xDim && y < yDim && type < 10){ System.out.println(" System.out.println(x); System.out.println(y); System.out.println(type); Cell c=NewAgentPT(x*xDim,y*yDim); c.Init(type,initialAntigens); } } } } int SteadyStateMovement(){ int loopCt=0; while(loopCt<MAX_STEADY_STATE_LOOPS) { double maxForce=0; for (Cell c : this) { maxForce=Math.max(maxForce,c.Observe()); } for (Cell c : this) { c.Act(c); } loopCt++; if(maxForce<STEADY_STATE_FORCE){ //System.out.println(loopCt+","+maxForce); break; } } return loopCt; } void immuneArrival(){ int tick= GetTick(); if ((tick % 70)==1){ for (int i = 0; i <BloodVesselsCoord.size() ; i++) { Cell c=NewAgentPT(BloodVesselsCoord.get(i)[0],BloodVesselsCoord.get(i)[1]); c.Init(1,0); //immune } } } void Production() { for (int z=0; z<cancerCells.size();z++) { diffusible.Set(cancerCells.get(z).Xsq(), cancerCells.get(z).Ysq(), diffusible.Get(cancerCells.get(z).Xsq(), cancerCells.get(z).Ysq()) + productionRate); } } void ChemDecay() { for (int x = 0; x < diffusible.xDim; x++) { for (int y = 0; y < diffusible.yDim; y++) { diffusible.Set(x, y, Math.exp(-decayRate)*diffusible.Get(x,y)); } } } void Diffusion(){ //diff.Advection2ndLW(xVels, yVels); for (int i = 0; i < 1; i++) { diffusible.DiffusionADI(1,0); //diffusible.Advection2ndPredCorr(0.1, 0.1); } } void Step(){ //CHEMICALS Diffusion(); Production(); ChemDecay(); //CELLS //division //death //move SteadyStateMovement(); //for (Cell c:this) { // c.Observe(); //for (Cell c:this){ // c.Act(); for (Cell c:this) { c.Step(); } //System.out.println(fusionCt); immuneArrival(); IncTick(); } } class Cell extends SphericalAgent2D<Cell,Dish> { int color; int type; double oldProb; static double[] motility={0.01,0.04,0.006,0.1}; double xVelStart; double yVelStart; double deviation; double maxVelAbs; Cell cc; int immunePotential; int antigenNumber; boolean checkTouch; void Init(int tType,int tAntigenNumber){ radius=G().CELL_RAD[tType]; type=tType; antigenNumber=tAntigenNumber; switch (type) { case 0: G().cancerCells.add(this); //Melanoma cells break; case 1: G().immuneCells.add(this); //Immune cells break; case 2: G().stromaCells.add(this); //stroma cells break; } maxVelAbs=motility[type]; xVelStart=motility[type]*Math.random()-motility[type]/2; yVelStart=motility[type]*Math.random()-motility[type]/2; deviation=motility[type]/2; xVel=0; yVel=0; SetCellColor(); if (type==1){ //immunecells initialize to zero the immune potential immunePotential=0; } } void SetCellColor(){ switch (type) { case 0: color = G().RED; // MELANOMA break; case 1: color = G().AZUL; // IMMUNE break; case 2: color = G().YELLOW; // STROMA break; // case 3: color = G().YELLOW; // STROMA // break; } } double OverlapToForce(double overlap){ if(overlap<0){ return 0; } return Math.pow(G().FORCE_SCALER*overlap,G().FORCE_EXPONENT); //return G().FORCE_SCALER*overlap; } double Observe(){ return SumForces(radius+G().MAX_RAD[type],G().cellScratch,this::OverlapToForce); /* if(ret>G().MAX_VEL){ xVel*=G().MAX_VEL/ret; yVel*=G().MAX_VEL/ret; } return ret; */ } void Act(Cell cv){ double x=cv.xVel+cv.Xpt(); double y=cv.yVel+cv.Ypt(); if(!G().In(x,y)){ cv.Dispose(); removeDeathFromArrayList(cv); return; } //ForceMove(); MoveSafePT(x,y); ApplyFriction(G().FRICTION); } void Step(){ if (this.type==0) { Cell killer = checkTouchingImmuneCells();// returns true if in the circle around a cancer cell founds at least one immune cell if (checkTouch == true) { if (G().rn.nextDouble() < aditDeathProb()) { // if immune cell is present, an additional deathProbab is added Dispose(); removeDeathFromArrayList(this); immuneExhaustion(killer); return; } } } if(G().rn.nextDouble()<G().deathProb[type]){ /// calculate chance of death Dispose(); removeDeathFromArrayList(this); return; } removeImmuneExhausted(this); if(G().rn.nextDouble()<G().divProb[type]){ Cell child=Divide(G().DIV_RADIUS[type],G().divCoordScratch,G().rn); child.Init(this.type,this.antigenNumber); Init(this.type,this.antigenNumber); } moveCell(); // checkOutOfBorder(); } Cell checkTouchingImmuneCells() { checkTouch = false; int[] hood = CircleHood(false, 1); // this circle is centered on the origin, I then need to translate it to the center of my cancer cell (this) for (int j = 0; j < (hood.length / 2); j++) { // replaces the hood arount the cancer cell pos hood[2 * j] = (int) Math.round(hood[2 * j] + this.Xpt()); hood[2 * j + 1] = (int) Math.round(hood[2 * j + 1] + this.Ypt()); } int n = 0;//moves on immune cells while ((n < G().immuneCells.size()) && (checkTouch == false)) { // considers one at time all cc immune cells cc = G().immuneCells.get(n); int ccXpt = (int) Math.round(cc.Xpt()); int ccYpt = (int) Math.round(cc.Ypt()); int j = 0; //counts on hood while ((checkTouch == false) && (j < (hood.length / 2))) { int hoodXpt = hood[2 * j]; int hoodYpt = hood[2 * j + 1]; if ((hoodXpt == ccXpt) && (hoodYpt == ccYpt)) { checkTouch = true; } j = j + 1; } n = n + 1; } return cc; } boolean checkTouchingCancerCells() { boolean checkCanc = false; int[] hood = CircleHood(false, 1); // this circle is centered on the origin, I then need to translate it to the center of my cancer cell (this) for (int j = 0; j < (hood.length / 2); j++) { // replaces the hood arount the cancer cell pos hood[2 * j] = (int) Math.round(hood[2 * j] + this.Xpt()); hood[2 * j + 1] = (int) Math.round(hood[2 * j + 1] + this.Ypt()); } int n = 0;//moves on immune cells while ((n < G().cancerCells.size()) && (checkCanc == false)) { // considers one at time all cc immune cells cc = G().cancerCells.get(n); int ccXpt = (int) Math.round(cc.Xpt()); int ccYpt = (int) Math.round(cc.Ypt()); int j = 0; //counts on hood while ((checkCanc == false) && (j < (hood.length / 2))) { int hoodXpt = hood[2 * j]; int hoodYpt = hood[2 * j + 1]; if ((hoodXpt == ccXpt) && (hoodYpt == ccYpt)) { checkCanc = true; } j = j + 1; } n = n + 1; } return checkCanc; } // for (Cell cc:G().immuneCells) // while((toReturn==false)&&(i <(hood.length/2))) { // if ((hood[2*i]+this.Xpt()==cc.Xpt())&&(hood[2*i+1]+this.Ypt()==cc.Ypt())){ // toReturn=true; // i=i+1; void removeDeathFromArrayList(Cell tthis){ switch (tthis.type) { case 0: G().cancerCells.remove(tthis); // MELANOMA break; case 1: G().immuneCells.remove(tthis); // IMMUNE break; case 2: G().stromaCells.remove(tthis); // STROMA break; // case 3: color = G().YELLOW; // STROMA // break; } } void immuneExhaustion(Cell tkiller){ if (tkiller.type==1){ // considering immune cell tkiller.immunePotential=tkiller.immunePotential+1; } } void removeImmuneExhausted(Cell aImmuneCell){ if ((aImmuneCell.type==1)&&(aImmuneCell.immunePotential>=5)) { aImmuneCell.Dispose(); removeDeathFromArrayList(aImmuneCell); } } double aditDeathProb(){ return (1+Math.tanh(0.0001*antigenNumber))/2; } void moveCell(){ switch (type) { case 0: // cancer cells do not move break; case 1: xVelStart=xVelStart-(deviation/2)+deviation*Math.random(); yVelStart=yVelStart-(deviation/2)+deviation*Math.random(); // double attX = G().diffusible.GradientX(this.Xsq(), this.Ysq()); // double attY = G().diffusible.GradientY(this.Xsq(), this.Ysq()); // this.xVel=2*xVelStart+0.2*attX; // this.yVel=2*yVelStart+0.2*attY; this.xVel=xVelStart-(motility[type]/2)+motility[type]*Math.random(); this.yVel=yVelStart-(motility[type]/2)+motility[type]*Math.random(); limitVel(this); break; case 2: this.xVel=0; //reinitialize to zero this.yVel=0; if(checkTouchingCancerCells()==false) { // execute this just if there is not a cancer cell touching this.xVel = G().diffusible.GradientX(this.Xsq(), this.Ysq()); this.yVel = G().diffusible.GradientY(this.Xsq(), this.Ysq()); limitVel(this); } break; // case 3: color = G().YELLOW; // break; } } // void checkOutOfBorder(){ // if ((this.Xpt()==G().xDim-1)||(this.Xpt()==1)||(this.Ypt()==G().yDim-1)||(this.Ypt()==1)){ // this.Dispose(); void limitVel(Cell tthis){ if (tthis.xVel<-tthis.maxVelAbs){ tthis.xVel=-tthis.maxVelAbs; } else if (tthis.xVel>tthis.maxVelAbs){ tthis.xVel=tthis.maxVelAbs; } if (tthis.yVel<-tthis.maxVelAbs){ tthis.yVel=-tthis.maxVelAbs; } else if (tthis.yVel>tthis.maxVelAbs){ tthis.yVel=tthis.maxVelAbs; } } } public class Model2D { static int SIDE_LEN=70; static int STARTING_POP=20; static int STARTING_STROMA=70; static double STARTING_RADIUS=20; static int TIMESTEPS=4000; static float[] circleCoords=Utils.GenCirclePoints(1,10); public static void main(String[] args) { double[] motility={1,1,1,1}; //TickTimer trt=new TickRateTimer(); Vis2DOpenGL vis=new Vis2DOpenGL("Cell Fusion Visualization", 1000,1000,SIDE_LEN,SIDE_LEN); String path_to_input_file = "Models/MelanomaWorkshop/Model2D/spatial_distribution/stroma_clusters.txt"; //String path_to_output_file = "Models/MelanomaWorkshop/Model2D/spatial_distribution/simulation_output.txt"; //List<String> list = d.initImageFile(path_to_file); Dish d=new Dish(SIDE_LEN,STARTING_POP,STARTING_STROMA, STARTING_RADIUS, null); GridVisWindow win = new GridVisWindow("diffusion", d.xDim, d.yDim, 5); //d.SetCellsColor("red"); for (int i = 0; i < TIMESTEPS; i++) { vis.TickPause(0); win.TickPause(0); d.Step(); DrawCells(vis,d); DrawDiffusible(win,d); //if (i == TIMESTEPS-1){ // d.writeCellCoords( path_to_output_file ); } } static void DrawCells(Vis2DOpenGL vis,Dish d){ vis.Clear(Dish.BLACK); for (int i = 0; i < d.BloodVesselsCoord.size(); i++) { vis.Circle(d.BloodVesselsCoord.get(i)[0], d.BloodVesselsCoord.get(i)[1], 2, d.BLUE); } for (Cell c:d) { //color "cytoplasm" vis.Circle(c.Xpt(),c.Ypt(),c.radius,c.color); } for (Cell c:d) { //color "nucleus" vis.Circle(c.Xpt(),c.Ypt(),c.radius/2.0, Dish.BLUE); } vis.Show(); //vis.ToPNG(path.concat(Integer.toString(i))); } static void DrawDiffusible(GridVisWindow win,Dish d){ for (int x = 0; x < win.xDim; x++) { for (int y = 0; y < win.yDim; y++) { win.SetPix(x, y, HeatMapBRG(d.diffusible.Get(x , y ))); } } } }
package org.anderes.spring.configuration; import java.util.List; import org.anderes.cookbook.domain.RecipeRepository; import org.anderes.cookbook.domain.RecipeRepositoryStub; import org.anderes.cookbook.web.converter.IngredientEntityToIngredientResource; import org.anderes.cookbook.web.converter.IngredientResourceToIngredientEntity; import org.anderes.cookbook.web.converter.RecipeEntityToRecipeResource; import org.anderes.cookbook.web.converter.RecipeResourceToRecipeEntity; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.format.FormatterRegistry; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan(basePackages = { "org.anderes.cookbook.web.rest", "org.anderes.tech" } ) @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new RecipeResourceToRecipeEntity()); registry.addConverter(new RecipeEntityToRecipeResource()); registry.addConverter(new IngredientEntityToIngredientResource()); registry.addConverter(new IngredientResourceToIngredientEntity()); } * Handles HTTP GET requests for '/resources/**' by efficiently * serving up static resources in the '${webappRoot}/resources/' directory */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) {
package ca.ualberta.smaccr.giftcarder; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { public final static String EXTRA_USERNAME= "ca.ualberta.smaccr.giftcarder.USERNAME"; Inventory inv; String username; private ESUserManager userManager; //getter for UI testing public EditText getEtUsername() {return (EditText) findViewById(R.id.enterUsername);} User user = new User(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* user.setUsername("t"); user.setCity("Edmo"); user.setPhone("012-345-6789"); user.setEmail("t@g.c"); UserRegistrationController.getUserList().addUser(user); */ } @Override protected void onStart() { super.onStart(); userManager = new ESUserManager(""); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public void onBackPressed() { //Back button disabled } /** * Called when user presses Register button * * @param view view that is clicked */ public void registerNewUser(View view){ Intent intent = new Intent(this, RegisterActivity.class); startActivity(intent); } /** * Called when user presses Login button. * <p> * Checks to see if user-entered username is an already registered user. If not, it prompts * the user to register. * * @param view view that is clicked */ public void logInUser(View view) { EditText etUsername = (EditText) findViewById(R.id.enterUsername); String username = etUsername.getText().toString().trim(); UserRegistrationController urc = new UserRegistrationController(this); userManager = new ESUserManager(""); // Try to retrieve the data. If no internet, try { if (Validation.hasText(etUsername)) { // Calls GetThreat to check if user is on server Thread thread = new GetThread(username); thread.start(); } } catch (Exception e) { Toast.makeText(this, "Error retrieving data", Toast.LENGTH_SHORT).show(); } } // Get thread to attempt to get user from server by id ->"this is his username" class GetThread extends Thread { private String id; public GetThread(String id) { this.id = id; } @Override public void run() { user = userManager.getUser(id); runOnUiThread(checkUserOnServer); } } private Runnable checkUserOnServer = new Runnable() { public void run() { checkForUserOnServer(user); } }; public void checkForUserOnServer(User user){ UserRegistrationController urc = new UserRegistrationController(this); userManager = new ESUserManager(""); //If the user exist then we start "all activity", and he gets added to singleton, he is only user in the singleton right now if (user != null) { Toast.makeText(this, user.getUsername(), Toast.LENGTH_LONG).show(); urc.addUser(user); String usernameFromServer = user.getUsername(); Intent intent = new Intent(this, AllActivity.class); intent.putExtra(EXTRA_USERNAME, usernameFromServer); startActivity(intent); } else { Toast.makeText(this, "User not found. Register a new account.", Toast.LENGTH_LONG).show(); } } }
package i5.las2peer.services.ocd.algorithms; import i5.las2peer.services.ocd.algorithms.utils.OcdAlgorithmException; import i5.las2peer.services.ocd.graphs.Cover; import i5.las2peer.services.ocd.graphs.CoverCreationType; import i5.las2peer.services.ocd.graphs.CustomGraph; import i5.las2peer.services.ocd.graphs.GraphType; import i5.las2peer.services.ocd.algorithms.utils.MaximalCliqueGraphRepresentation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.lang.Double; import java.lang.Math; import org.la4j.matrix.Matrix; import org.la4j.matrix.dense.Basic2DMatrix; import org.la4j.matrix.sparse.CCSMatrix; import org.la4j.vector.Vector; import org.la4j.vector.Vectors; import org.la4j.vector.dense.BasicVector; import com.sun.corba.se.impl.orbutil.graph.Graph; import y.base.Edge; import y.base.EdgeCursor; import y.base.Node; import y.base.NodeCursor; /** * The original version of the overlapping community detection algorithm introduced in 2020 * by Ping Ji, Shanxin Zhang, Zhiping Zhou. * @author Marlene Damm */ //TODO description of the algorithm public class AntColonyOptimizationAlgorithm implements OcdAlgorithm { private double pheromones; /** * Defines the number of subproblems solved which need to be minimized */ private int subproblems = 2; /** * Number of objective functions used in this algorithm. The proposed algorithm by Ji et al * uses 2 objective functions. So we recommend to this parameter to be 2. */ private int objectFkt = 2; public AntColonyOptimizationAlgorithm() { //todo } /** * Executes the algorithm on a connected graph. * Implementations of this method should allow to be interrupted. * I.e. they should periodically check the thread for interrupts * and throw an InterruptedException if an interrupt was detected. * @param graph An at least weakly connected graph whose community structure will be detected. * @return A cover for the input graph containing the community structure. * @throws OcdAlgorithmException If the execution failed. * @throws InterruptedException If the executing thread was interrupted. */ @Override public Cover detectOverlappingCommunities(CustomGraph graph) throws OcdAlgorithmException, InterruptedException { MaximalCliqueGraphRepresentation maxClq = new MaximalCliqueGraphRepresentation(); maxClq.cliques(graph); //return new Cover(graph, memberships); return new Cover(graph); } protected Matrix linkStrength(CustomGraph graph, HashMap<Integer,HashSet<Node>> maxClq) { int clqNr = maxClq.size(); Matrix lkstrgth = new Basic2DMatrix(clqNr,clqNr); for(int i = 0; i < clqNr; i++) { HashSet<Node> clq1 = maxClq.get(i); double clq1Size = clq1.size(); for(int j = i + 1; j < clqNr; j++) { HashSet<Node> clq2 = maxClq.get(j); double clq2Size = clq2.size(); HashSet<Node> diff12 = new HashSet<Node>(clq1); diff12.removeAll(clq2); double diff12size = diff12.size(); double cdDist1 = 0; for(Node v1: diff12) { for(Node v2: clq2) { cdDist1 += CzechkanowskiDice(graph, v1, v2); } } HashSet<Node> diff21 = new HashSet<Node>(clq2); diff21.removeAll(clq1); double diff21size = diff21.size(); double cdDist2 = 0; for(Node v1: diff21) { for(Node v2: clq1) { cdDist2 += CzechkanowskiDice(graph, v1, v2); } } double lstr = cdDist2/(diff21size*clq1Size)*cdDist1/(diff12size*clq2Size); lstr = Math.sqrt(lstr); lkstrgth.set(i, j, lstr); } } return lkstrgth; } /** * Version of the Czechkanowski Dice Distance * @param graph a graph from which v1 and v2 are taken * @param v1 node which is in a clique * @param v2 node which is not in the same clique as v1 * @return */ protected double CzechkanowskiDice(CustomGraph graph, Node v1, Node v2) { NodeCursor nbors1 = v1.neighbors(); NodeCursor nbors2 = v2.neighbors(); int nbor1size = nbors1.size()/2; int nbor2size = nbors2.size()/2; double olapsize = 0; for(int i = 0 ; i <nbors1.size(); i++) { Node n1 = nbors1.node(); for(int j = 0 ; j <nbors1.size(); j++) { Node n2 = nbors2.node(); if(n2 == n1) { olapsize++; break; } if(nbors2.ok() == true){ nbors2.cyclicNext(); } else { break; } } if(nbors1.ok() == true){ nbors1.cyclicNext(); } else { break; } } double edgeNr = graph.edgeCount()/2; double nodeNr = graph.nodeCount(); double avgDegr = 2*edgeNr/nodeNr; double tmp1 = avgDegr - nbor1size; double tmp2 = avgDegr - nbor2size; double lmbd1 = Double.max(0, tmp1); double lmbd2 = Double.max(0, tmp2); return olapsize/(lmbd1 + nbor1size + lmbd2 + nbor2size); } /** * Returns a log representing the concrete algorithm execution. * @return The log. */ @Override public CoverCreationType getAlgorithmType(){ return CoverCreationType.ANT_COLONY_OPTIMIZATION; } /** * Returns all graph types the algorithm is compatible with. * @return The compatible graph types. * An empty set if the algorithm is not compatible with any type. */ public Set<GraphType> compatibleGraphTypes(){ Set<GraphType> compatibilities = new HashSet<GraphType>(); compatibilities.add(GraphType.ZERO_WEIGHTS); return compatibilities; }; @Override public Map<String,String> getParameters(){ return new HashMap<String, String>(); } @Override public void setParameters(Map<String, String> parameters) throws IllegalArgumentException { } /** * Initialize parameters and convert the graph into a maximal clique graph representation */ protected void initialize() { //todo } protected void constructSolution() { //todo } protected void updateEP() { //todo } protected void updatePheromoneMatrix() { //todo } protected void updateCurrentSolution() { //todo } }
// This file is part of LibRec. // LibRec is free software: you can redistribute it and/or modify // (at your option) any later version. // LibRec is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the package i5.las2peer.services.recommender.librec.rating; import java.util.HashSet; import java.util.List; import com.google.common.cache.LoadingCache; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import i5.las2peer.services.recommender.communities.CommunityDetector; import i5.las2peer.services.recommender.communities.CommunityDetector.CommunityDetectionAlgorithm; import i5.las2peer.services.recommender.graphs.GraphBuilder; import i5.las2peer.services.recommender.graphs.GraphBuilder.SimilarityMeasure; import i5.las2peer.services.recommender.librec.data.Configuration; import i5.las2peer.services.recommender.librec.data.DenseMatrix; import i5.las2peer.services.recommender.librec.data.DenseVector; import i5.las2peer.services.recommender.librec.data.MatrixEntry; import i5.las2peer.services.recommender.librec.data.SparseMatrix; import i5.las2peer.services.recommender.librec.data.SparseVector; import i5.las2peer.services.recommender.librec.data.VectorEntry; import i5.las2peer.services.recommender.librec.util.Logs; import i5.las2peer.services.recommender.librec.util.Strings; /** * Community-aware model based on Yehuda Koren, Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model., KDD 2008. * * @author guoguibing, martin * */ @Configuration("factors, lRate, lRateN, lRateF, lRateC, lRateCN, lRateCF, maxLRate," + " regB, regN, regU, regI, regC, regCN, regCF, iters, boldDriver") public class ComNeighSVDPlusPlus extends BiasedMF { protected DenseMatrix Y, Z , Ocu, Oci; protected DenseMatrix W, C, D; // weighting factors for neighborhood model protected int numUserCommunities; protected int numItemCommunities; protected DenseVector userComBias, itemComBias; protected SparseMatrix userMemberships, itemMemberships; // Community membership matrices for users and items protected SparseMatrix communityRatingsMatrix; // Average ratings given by the members of each community (numUserCommunities x numItems) protected SparseMatrix userCommunitiesRatingsMatrix; // Average ratings given by each user's communities (numUsers x numItems) protected LoadingCache<Integer, List<Integer>> userCommunitiesCache, itemCommunitiesCache, userCommunitiesItemsCache; public ComNeighSVDPlusPlus(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { super(trainMatrix, testMatrix, fold); setAlgoName("ComNeighSVD++"); } @Override protected void initModel() throws Exception { super.initModel(); } @Override protected void buildModel() throws Exception { Y = new DenseMatrix(numItems, numFactors); Y.init(initMean, initStd); Z = new DenseMatrix(numItems, numFactors); Z.init(initMean, initStd); W = new DenseMatrix(numItems, numItems); W.init(initMean, initStd); C = new DenseMatrix(numItems, numItems); C.init(initMean, initStd); userItemsCache = trainMatrix.rowColumnsCache(cacheSpec); itemUsersCache = trainMatrix.columnRowsCache(cacheSpec); D = new DenseMatrix(numItems, numItems); D.init(initMean, initStd); // build the user and item graphs Logs.info("{}{} build user and item graphs ...", new Object[] { algoName, foldInfo }); GraphBuilder gb = new GraphBuilder(); gb.setRatingData(trainMatrix); gb.setK(10); gb.setSimilarityMeasure(SimilarityMeasure.COSINE_SIMILARITY); gb.buildGraphs(); SparseMatrix userMatrix = gb.getUserAdjacencyMatrix(); SparseMatrix itemMatrix = gb.getItemAdjacencyMatrix(); // detect communities Logs.info("{}{} detect communities ...", new Object[] { algoName, foldInfo }); CommunityDetector cd = new CommunityDetector(); switch(cf.getString("cd.algo", "dmid").toLowerCase()){ default: case "walktrap": cd.setAlgorithm(CommunityDetectionAlgorithm.WALKTRAP); cd.setWalktrapParameters(cf.getInt("cd.walktrap.steps", 2)); break; case "dmid": cd.setAlgorithm(CommunityDetectionAlgorithm.DMID); cd.setDmidParameters(cf.getInt("cd.dmid.iter", 1000), cf.getDouble("cd.dmid.prec", 0.001), cf.getDouble("cd.dmid.proficiency", 0.1)); break; case "slpa": cd.setAlgorithm(CommunityDetectionAlgorithm.SLPA); cd.setSlpaParameters(cf.getDouble("cd.slpa.prob", 0.15), cf.getInt("cd.slpa.memory", 100)); break; } cd.setGraph(userMatrix); cd.detectCommunities(); userMemberships = cd.getMemberships(); userCommunitiesCache = userMemberships.rowColumnsCache(cacheSpec); cd.setGraph(itemMatrix); cd.detectCommunities(); itemMemberships = cd.getMemberships(); itemCommunitiesCache = itemMemberships.rowColumnsCache(cacheSpec); numUserCommunities = userMemberships.numColumns(); numItemCommunities = itemMemberships.numColumns(); debugCommunityInfo(); userComBias = new DenseVector(numUserCommunities); userComBias.init(initMean, initStd); itemComBias = new DenseVector(numItemCommunities); itemComBias.init(initMean, initStd); Logs.info("{}{} compute community ratings ...", new Object[] { algoName, foldInfo }); communityRatingsMatrix = getCommunityRatings(); Logs.info("{}{} compute community ratings per user ...", new Object[] { algoName, foldInfo }); userCommunitiesRatingsMatrix = getUserCommunitiesRatings(); userCommunitiesItemsCache = userCommunitiesRatingsMatrix.rowColumnsCache(cacheSpec); Logs.info("{}{} userCommunitiesRatings: Total number of entries: {}, Avg. entries per user: {}", algoName, foldInfo, userCommunitiesRatingsMatrix.size(), (double) userCommunitiesRatingsMatrix.size() / numUsers); Ocu = new DenseMatrix(numUserCommunities, numFactors); Ocu.init(initMean, initStd); Oci = new DenseMatrix(numItemCommunities, numFactors); Oci.init(initMean, initStd); // iteratively learn the model parameters Logs.info("{}{} learn model parameters ...", new Object[] { algoName, foldInfo }); for (int iter = 1; iter <= numIters; iter++) { loss = 0; for (MatrixEntry me : trainMatrix) { int u = me.row(); // user int j = me.column(); // item double ruj = me.get(); double pred = predict(u, j); double euj = ruj - pred; loss += euj * euj; List<Integer> items = userItemsCache.get(u); List<Integer> userCommunities = userCommunitiesCache.get(u); List<Integer> itemCommunities = itemCommunitiesCache.get(j); List<Integer> userCommunitiesItems = userCommunitiesItemsCache.get(u); // items that have been rated by u's community co-members double w = Math.sqrt(items.size()); double cw = Math.sqrt(userCommunitiesItems.size()); // update baseline parameters double bu = userBias.get(u); double sgd = euj - regB * bu; userBias.add(u, lRate * sgd); loss += regB * bu * bu; double bj = itemBias.get(j); sgd = euj - regB * bj; itemBias.add(j, lRate * sgd); loss += regB * bj * bj; for (int cu : userCommunities){ double bc = userComBias.get(cu); sgd = euj * userMemberships.get(u, cu) - regC * bc; userComBias.add(cu, lRateC * sgd); loss += regC * bc * bc; } for (int ci : itemCommunities){ double bc = itemComBias.get(ci); sgd = euj * itemMemberships.get(j, ci) - regC * bc; itemComBias.add(ci, lRateC * sgd); loss += regC * bc * bc; } // update neighborhood model parameters for (int k : items){ // to reduce complexity we can reduce the list of items to the nearest neighbors of item k double ruk = trainMatrix.get(u, k); double buk = getBias(u,k, userCommunities, itemCommunitiesCache.get(k)); double wjk = W.get(j, k); sgd = euj * (ruk - buk) / w - regN * wjk; W.add(j, k, lRateN * sgd); loss += regN * wjk * wjk; double cjk = C.get(j, k); sgd = euj / w - regN * cjk; C.add(j, k, lRateN * sgd); loss += regN * cjk * cjk; } for (int k : userCommunitiesItems){ double djk = D.get(j, k); double rcuk = userCommunitiesRatingsMatrix.get(u, k); double buk = getBias(u,k, userCommunities, itemCommunitiesCache.get(k)); sgd = euj / cw * (rcuk - buk) - regCN * djk; D.add(j, k , lRateCN * sgd); loss += regCN * djk * djk; } // update factor model parameters double[] sum_ys = new double[numFactors]; for (int f = 0; f < numFactors; f++) { double sum_f = 0; for (int k : items) sum_f += Y.get(k, f); sum_ys[f] = w > 0 ? sum_f / w : sum_f; } double[] sum_zs = new double[numFactors]; for (int f = 0; f < numFactors; f++) { double sum_f = 0; for (int k : userCommunitiesItems) sum_f += Z.get(k, f); sum_zs[f] = cw > 0 ? sum_f / cw : sum_f; } double[] sum_ocus = new double[numFactors]; for (int f = 0; f < numFactors; f++) { for (int c : userCommunities) sum_ocus[f] += Ocu.get(c, f) * userMemberships.get(u, c); } double[] sum_ocis = new double[numFactors]; for (int f = 0; f < numFactors; f++) { for (int c : itemCommunities) sum_ocis[f] += Oci.get(c, f) * itemMemberships.get(j, c); } for (int f = 0; f < numFactors; f++) { double puf = P.get(u, f); double qjf = Q.get(j, f); double sgd_puf = euj * (qjf + sum_ocis[f]) - regU * puf; double sgd_qjf = euj * (puf + sum_ocus[f] + sum_ys[f] + sum_zs[f]) - regI * qjf; P.add(u, f, lRate * sgd_puf); Q.add(j, f, lRate * sgd_qjf); loss += regU * puf * puf + regI * qjf * qjf; for (int k : items) { double ykf = Y.get(k, f); double delta_y = euj * (qjf + sum_ocis[f]) / w - regU * ykf; Y.add(k, f, lRate * delta_y); loss += regU * ykf * ykf; } for (int k : userCommunitiesItems){ double zkf = Z.get(k, f); double delta_z = euj * (qjf + sum_ocis[f]) / cw - regCF * zkf; Z.add(k, f, lRateCF * delta_z); loss += regCF * zkf * zkf; } for (int c : userCommunities){ double ocuf = Ocu.get(c, f); double delta_ocu = euj * userMemberships.get(u, c) * (qjf + sum_ocis[f]) - regCF + ocuf; Ocu.add(c, f, lRateCF * delta_ocu); loss += regCF * ocuf * ocuf; } for (int c : itemCommunities){ double ocif = Oci.get(c, f); double delta_oci = euj * itemMemberships.get(j, c) * (puf + sum_ocus[f] + sum_ys[f] + sum_zs[f]) - regCF + ocif; Oci.add(c, f, lRateCF * delta_oci); loss += regCF * ocif * ocif; } } } loss *= 0.5; if (isConverged(iter)) break; }// end of training } @Override protected double predict(int u, int j) throws Exception { List<Integer> items = userItemsCache.get(u); List<Integer> userCommunities = userCommunitiesCache.get(u); List<Integer> itemCommunities = itemCommunitiesCache.get(j); List<Integer> userCommunitiesItems = userCommunitiesItemsCache.get(u); // items that have been rated by u's community co-members double w = Math.sqrt(items.size()); double cw = Math.sqrt(userCommunitiesItems.size()); // used for normalizing over the user's communities // baseline prediction double pred = getBias(u, j, userCommunities, itemCommunities); // neighborhood model prediction for (int k : items){ double buk = getBias(u,k, userCommunities, itemCommunitiesCache.get(k)); double ruk = trainMatrix.get(u, k); double wjk = W.get(j, k); double cjk = C.get(j, k); pred += ((ruk - buk) * wjk + cjk) / w; } for (int k : userCommunitiesItems){ double rcuk = userCommunitiesRatingsMatrix.get(u, k); double buk = getBias(u,k, userCommunities, itemCommunitiesCache.get(k)); double djk = D.get(j, k); pred += (rcuk - buk) * djk / cw; } // factor model prediction DenseVector userFactor = P.row(u); DenseVector itemFactor = Q.row(j); for (int k : items) userFactor.add(Y.row(k).scale(1.0/w)); for (int k : userCommunitiesItems) userFactor.add(Z.row(k).scale(1.0/cw)); for (int c : userCommunities){ userFactor.add(Ocu.row(c).scale(userMemberships.get(u, c))); } for (int c : itemCommunities){ itemFactor.add(Oci.row(c).scale(itemMemberships.get(j, c))); } pred += itemFactor.inner(userFactor); return pred; } private SparseMatrix getCommunityRatings() throws Exception { // Get the average community ratings for each item Table<Integer, Integer, Double> communityRatingsTable = HashBasedTable.create(); for (int community = 0; community < numUserCommunities; community++){ // each user's membership level for the community SparseVector communityUsersVector = userMemberships.column(community); // build set of items that have been rated by members of the community HashSet<Integer> items = new HashSet<Integer> (); for (VectorEntry e : communityUsersVector){ int user = e.index(); List<Integer> userItems = userItemsCache.get(user); for (int item : userItems) items.add(item); } for (int item : items){ // Sum of ratings given by users of the community to item, weighted by the users community membership levels double ratingsSum = 0; // sum of membership levels of the users that have rated the item, used for normalization double membershipsSum = 0; // each user's rating for the item SparseVector itemUsersVector = trainMatrix.column(item); for (VectorEntry e : communityUsersVector){ int user = e.index(); if (itemUsersVector.contains(user)){ double userMembership = communityUsersVector.get(user); double userRating = itemUsersVector.get(user); ratingsSum += userRating * userMembership; membershipsSum += userMembership; } } if (membershipsSum > 0){ double communityRating = ratingsSum / membershipsSum; communityRatingsTable.put(community, item, communityRating); } } } SparseMatrix matrix = new SparseMatrix(numUserCommunities, numItems, communityRatingsTable); Logs.info("{}{} Community Ratings: Number of communities: {}, Avg. number of ratings per community: {}", algoName, foldInfo, matrix.numRows(), matrix.size() / matrix.numRows()); return matrix; } private SparseMatrix getUserCommunitiesRatings() throws Exception { // Get each user's community ratings, i.e. the weighted average rating of the user's communities for each item // The resulting matrix has dimensions numUsers x numItems Table<Integer, Integer, Double> userCommunitiesRatingsTable = HashBasedTable.create(); for (int user = 0; user < numUsers; user++){ List<Integer> userCommunities = userCommunitiesCache.get(user); for (int item = 0; item < numItems; item++){ double ratingsSum = 0; double membershipsSum = 0; for (int community : userCommunities){ double communityRating = communityRatingsMatrix.get(community, item); double userMembership = userMemberships.get(user, community); ratingsSum += communityRating * userMembership; membershipsSum += userMembership; } if (ratingsSum > 0){ double userCommunitiesRating = ratingsSum / membershipsSum; userCommunitiesRatingsTable.put(user, item, userCommunitiesRating); } } } SparseMatrix matrix = new SparseMatrix(numUsers, numItems, userCommunitiesRatingsTable); Logs.info("{}{} User Communities Ratings: Number of users: {}, Avg. number of community ratings per user: {}", algoName, foldInfo, matrix.numRows(), matrix.size() / matrix.numRows()); return matrix; } private double getBias(int u, int j, List<Integer> userCommunities, List<Integer> itemCommunities){ double bias = globalMean + userBias.get(u) + itemBias.get(j); for (int cu : userCommunities){ double bc = userComBias.get(cu); double muc = userMemberships.get(u, cu); // community membership weight bias += bc * muc; } for (int ci : itemCommunities){ double bc = itemComBias.get(ci); double mic = itemMemberships.get(j, ci); // community membership weight bias += bc * mic; } return bias; } private void debugCommunityInfo() { int userMemSize = userMemberships.size(); int itemMemSize = itemMemberships.size(); double upc = (double) userMemSize / numUserCommunities; double cpu = (double) userMemSize / numUsers; double ipc = (double) itemMemSize / numItemCommunities; double cpi = (double) itemMemSize / numItems; Logs.info("{}{} user communites: {}, users per community: {}, communities per user: {}", new Object[] { algoName, foldInfo, numUserCommunities, upc, cpu }); Logs.info("{}{} item communites: {}, items per community: {}, communities per item: {}", new Object[] { algoName, foldInfo, numItemCommunities, ipc, cpi }); } @Override public String toString() { return Strings.toString(new Object[] { numFactors, initLRate, initLRateN, initLRateF, initLRateC, initLRateCN, initLRateCF, maxLRate, regB, regN, regU, regI, regC, regCN, regCF, numIters, isBoldDriver}); } }
package com.ezrol.terry.minecraft.defaultworldgenerator.gui; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import com.ezrol.terry.minecraft.defaultworldgenerator.config.ConfigGeneralSettings; import com.ezrol.terry.minecraft.defaultworldgenerator.config.ConfigurationFile; import com.ezrol.terry.minecraft.defaultworldgenerator.helper.ConfigurationHelper; import com.ezrol.terry.minecraft.defaultworldgenerator.lib.Reference; import net.minecraft.client.gui.GuiCreateWorld; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.world.WorldType; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.GuiConfigEntries; import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; import net.minecraftforge.fml.client.config.IConfigElement; /** Gui for the configuration screen including custom widgets **/ public class ConfigGui extends GuiConfig { protected String CurrentWorldType = ""; public ConfigGui(GuiScreen parent) { super(parent, initList(), Reference.MOD_ID, true, false, I18n.format(Reference.MOD_ID + ".config.gui.title")); CurrentWorldType = ConfigGeneralSettings.generalWorldGenerator; } public static List<IConfigElement> initList() { List<IConfigElement> lst = new ArrayList<IConfigElement>(); Configuration configuration = ConfigurationFile.configuration; Property prop; prop = ConfigurationHelper.getProp(configuration, "Seed", "general"); lst.add(new ConfigElement(prop)); prop = ConfigurationHelper.getProp(configuration, "World Generator", "general"); prop.setConfigEntryClass(WorldTypeEntries.class); lst.add(new ConfigElement(prop)); prop = ConfigurationHelper.getProp(configuration, "CustomizationJson", "general"); prop.setConfigEntryClass(CustomizeButton.class); lst.add(new ConfigElement(prop)); prop = ConfigurationHelper.getProp(configuration, "Lock Worldtype", "general"); lst.add(new ConfigElement(prop)); return lst; } /** class to list the world types **/ public static class WorldTypeEntries extends GuiConfigEntries.SelectValueEntry { public WorldTypeEntries(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) { super(owningScreen, owningEntryList, configElement, getTypeMap()); } /** Get the list of world types to choose between **/ private static Map<Object, String> getTypeMap() { Map m = new ConcurrentSkipListMap<Object, String>(); String s; for (int i = 0; i < WorldType.worldTypes.length; i++) { if (WorldType.worldTypes[i] != null && WorldType.worldTypes[i].getCanBeCreated()) { s = I18n.format("selectWorld.mapType", new Object[0]) + " " + I18n.format(WorldType.worldTypes[i].getTranslateName(), new Object[0]); m.put(WorldType.worldTypes[i].getWorldTypeName(), s); } } return (m); } @Override public void updateValueButtonText() { super.updateValueButtonText(); if (this.owningScreen instanceof ConfigGui) { ((ConfigGui) this.owningScreen).CurrentWorldType = this.currentValue.toString(); } } } /** class for editing the customization string **/ public static class CustomizeButton extends ButtonEntry { protected final String beforeValue; protected Object currentValue; protected ConfigGui ourOwner; public CustomizeButton(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) { super(owningScreen, owningEntryList, configElement); ourOwner = (ConfigGui) owningScreen; beforeValue = configElement.get().toString(); currentValue = configElement.get().toString(); updateValueButtonText(); } @Override public void updateValueButtonText() { this.btnValue.displayString = currentValue.toString(); } @Override public void valueButtonPressed(int slotIndex) { String type = ourOwner.CurrentWorldType; WorldType worldtype = null; for (int i = 0; i < WorldType.worldTypes.length; i++) { if (WorldType.worldTypes[i] != null && WorldType.worldTypes[i].getCanBeCreated()) { if (WorldType.worldTypes[i].getWorldTypeName().equalsIgnoreCase(type)) { worldtype = WorldType.worldTypes[i]; break; } } } if (worldtype == null || worldtype.isCustomizable()) { GuiFakeNewWorld fakegui = new GuiFakeNewWorld(ourOwner, this); fakegui.chunkProviderSettingsJson = currentValue.toString(); worldtype.onCustomizeButton(mc, fakegui); } else { setValueFromChildScreen(""); } } public void setValueFromChildScreen(Object newValue) { if (enabled() && currentValue != null ? !currentValue.equals(newValue) : newValue != null) { currentValue = newValue; updateValueButtonText(); } } @Override public boolean isDefault() { if (configElement.getDefault() != null) return configElement.getDefault().equals(currentValue); else return currentValue == null; } @Override public void setToDefault() { if (enabled()) { this.currentValue = configElement.getDefault().toString(); updateValueButtonText(); } } @Override public boolean isChanged() { if (beforeValue != null) return !beforeValue.equals(currentValue); else return currentValue == null; } @Override public void undoChanges() { if (enabled()) { currentValue = beforeValue; updateValueButtonText(); } } @Override public boolean saveConfigElement() { if (enabled() && isChanged()) { this.configElement.set(currentValue); return configElement.requiresMcRestart(); } return false; } @Override public String getCurrentValue() { return this.currentValue.toString(); } @Override public String[] getCurrentValues() { return new String[] { getCurrentValue() }; } } /** * Class for a fake new world screen.. needed due to how customization is * implemented :/ **/ public static class GuiFakeNewWorld extends GuiCreateWorld { private GuiConfig par; private CustomizeButton btn; public GuiFakeNewWorld(GuiConfig owningScreen, CustomizeButton btn) { super(owningScreen); this.par = owningScreen; this.btn = btn; } @Override public void initGui() { btn.setValueFromChildScreen(this.chunkProviderSettingsJson); this.mc.displayGuiScreen(par); } } }
package com.github.sbugat.problems.chess; import gnu.getopt.Getopt; import java.util.Arrays; /** * Classic N chess queens on a size N chess board * * Time on Intel Q6600 CPU: * 8 9 10 11 12 13 14 15 16 * 0m0.101s 0m0.118s 0m0.118s 0m0.128s 0m0.174s 0m0.506s 0m2.130s 0m15.820s 1m30.699s * * @author Sylvain Bugat * */ public class NQueensProblemCountRecursive { /**Array to mark unused columns*/ private final boolean [] unusedColumns; /**Array to mark unused ascending diagonals * diagonal number = x + y */ private final boolean [] unusedAscendingDiagonals; /**Array to mark unused descending diagonals * diagonal number = x + chess board size - 1 - y*/ private final boolean [] unusedDescendingDiagonals; /**Number of solution counter*/ private long solutionCount; /**Size of the chess board*/ private final int chessboardSize; private final int chessboardSizeMinusOne; public NQueensProblemCountRecursive( final int chessboardSizeArg ) { chessboardSize = chessboardSizeArg; chessboardSizeMinusOne = chessboardSizeArg - 1; unusedColumns = new boolean[ chessboardSizeArg ]; Arrays.fill( unusedColumns, true ); unusedAscendingDiagonals = new boolean[ chessboardSizeArg * 2 - 1 ]; Arrays.fill( unusedAscendingDiagonals, true ); unusedDescendingDiagonals = new boolean[ chessboardSizeArg * 2 - 1 ]; Arrays.fill( unusedDescendingDiagonals, true ); //Start the algorithm at the fisrt line solve(); //End of the algorithm print the total of solution(s) found System.out.println( "Total number of solution(s):" + solutionCount ); } /** * First line to divide by 2 explored tree */ private void solve() { //Test half square of the line for( int x=0 ; x < chessboardSize/2 ; x ++ ){ final int diag1 = x; final int diag2 = x + chessboardSizeMinusOne; unusedColumns[ x ] = false; unusedAscendingDiagonals[ diag1 ] = false; unusedDescendingDiagonals[ diag2 ] = false; //Go on to the second line solve( 1 ); unusedDescendingDiagonals[ diag2 ] = true; unusedAscendingDiagonals[ diag1 ] = true; unusedColumns[ x ] = true; } //Multiply by 2 the solution count for the other half not calculated solutionCount *= 2; //If the cheesboard size is odd, test with a queen on the middle of the first line if( 0 != chessboardSize % 2 ) { final int x=chessboardSize/2; final int diag1 = x; final int diag2 = x + chessboardSizeMinusOne; unusedColumns[ x ] = false; unusedAscendingDiagonals[ diag1 ] = false; unusedDescendingDiagonals[ diag2 ] = false; //Go on to the second line solve( 1 ); unusedDescendingDiagonals[ diag2 ] = true; unusedAscendingDiagonals[ diag1 ] = true; unusedColumns[ x ] = true; } } /** * Solving using recursive method, do a depth-first/back-tracking algorithm * * @param y number of the line stating at 0 */ private void solve(final int y) { // Test all position on the line for (int x = 0; x < chessboardSize; x++) { // if the row is not already blocked by another queen if (unusedColumns[x]) { final int ascDiagonal = x + y; final int descDiagonal = x + chessboardSizeMinusOne - y; // if both diagonals are not already blocked by anothers queens if (unusedAscendingDiagonals[ascDiagonal] && unusedDescendingDiagonals[descDiagonal]) { // Add contraints for this a queen unusedColumns[x] = false; unusedAscendingDiagonals[ascDiagonal] = false; unusedDescendingDiagonals[descDiagonal] = false; // All queens are sets on the chessboard then a solution is found! if (y >= chessboardSizeMinusOne) { solutionCount++; } else { // Go on to the next line solve(y + 1); } // Unadd contraints for this a queen (back-tracking) unusedDescendingDiagonals[descDiagonal] = true; unusedAscendingDiagonals[ascDiagonal] = true; unusedColumns[x] = true; } } } } /** * main program * * @param args */ public static void main( final String args[] ) { final Getopt getOpt = new Getopt( NQueensProblemCountRecursive.class.getSimpleName(), args, ":n:" ); getOpt.setOpterr( false ); //Default chessboard size int chessBoardSize = 8; int c = getOpt.getopt(); while( -1 != c ) { switch(c) { case 'n': try { chessBoardSize = Integer.parseInt( getOpt.getOptarg() ); if( chessBoardSize < 2 ) { System.err.println( "Usage: " + NQueensProblemCountRecursive.class.getSimpleName() + " [-n <size of the chessboard>]" ); System.exit( 1 ); } } catch( final NumberFormatException e ) { System.err.println( "Usage: " + NQueensProblemCountRecursive.class.getSimpleName() + " [-n <size of the chessboard>]" ); System.exit( 1 ); } break; case '?': default: System.err.println( "Usage: " + NQueensProblemCountRecursive.class.getSimpleName() + " [-n <size of the chessboard>]" ); System.exit( 1 ); } c = getOpt.getopt(); } new NQueensProblemCountRecursive( chessBoardSize ); } }