hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e00358634bac9d1caafd9ad0c3da04a3d11c387
8,784
java
Java
src/main/java/it/algos/vaad23/backend/logic/Logic.java
algos-soft/vaadin23
bab529164922d24a14ff4cca67c24cf0114e3458
[ "Unlicense" ]
null
null
null
src/main/java/it/algos/vaad23/backend/logic/Logic.java
algos-soft/vaadin23
bab529164922d24a14ff4cca67c24cf0114e3458
[ "Unlicense" ]
null
null
null
src/main/java/it/algos/vaad23/backend/logic/Logic.java
algos-soft/vaadin23
bab529164922d24a14ff4cca67c24cf0114e3458
[ "Unlicense" ]
null
null
null
43.92
133
0.698884
101
package it.algos.vaad23.backend.logic; import com.vaadin.flow.component.orderedlayout.*; import com.vaadin.flow.router.*; import static it.algos.vaad23.backend.boot.VaadCost.*; import it.algos.vaad23.backend.enumeration.*; import it.algos.vaad23.backend.service.*; import it.algos.vaad23.backend.wrapper.*; import org.springframework.beans.factory.annotation.*; import org.springframework.context.*; /** * Project vaadin23 * Created by Algos * User: gac * Date: ven, 11-mar-2022 * Time: 18:33 * Superclasse astratta delle view xxxList. Contiene la logica comune. <br> * Serve per 'dichiarare' i riferimenti ad altre classi e usarli nelle sottoclassi concrete <br> * I riferimenti sono 'public' per poterli usare con TestUnit <br> * Serve per 'dichiarare' le property e usarle nelle sottoclassi concrete <br> * Le properties sono 'protected' per poterle usare nelle sottoclassi <br> * <p> * Gestione della 'view' di @Route e della 'business logic' <br> * Mantiene lo 'stato' <br> * L' istanza (PROTOTYPE) della sottoclasse concretaq viene creata a ogni chiamata del browser <br> * Eventuali parametri (opzionali) devono essere passati nell'URL <br> */ public abstract class Logic extends VerticalLayout implements HasUrlParameter<String>, BeforeEnterObserver, AfterNavigationObserver { /** * Istanza di una interfaccia SpringBoot <br> * Iniettata automaticamente dal framework SpringBoot con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public ApplicationContext appContext; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // public HtmlService html; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // public ArrayService array; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public AnnotationService annotationService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public ReflectionService reflectionService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public LogService logger; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // public AIMongoService mongo; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public RouteService routeService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // public ClassService classService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public TextService textService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ @Autowired public DateService dateService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // public AVaadinService vaadinService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // public UtilityService utility; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // protected DataProviderService dataService; /** * Istanza unica di una classe @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) di servizio <br> * Iniettata automaticamente dal framework SpringBoot/Vaadin con l'Annotation @Autowired <br> * Disponibile DOPO il ciclo init() del costruttore di questa classe <br> */ // @Autowired // protected AWikiApiService wikiApi; /** * Wrapper di dati recuperati dall'url del browser, obbligatorio per il form <br> */ protected WrapParametro routeParameter; /** * Regola i parametri del browser per una view costruita da @Route <br> * Usato per costruire GenericLogicList e GenericLogicForm <br> * Se c'è solo il primo segmento, routeParameter NON è valido (non serve) <br> * <p> * Chiamato da com.vaadin.flow.router.Router tramite l' interfaccia HasUrlParameter <br> * Chiamato DOPO @PostConstruct ma PRIMA di beforeEnter() <br> * * @param beforeEvent con stringa del browser (bodyTextUTF8) da decodificare: primoSegmento e queryParameters * @param parametroOpzionale (poco usato) eventualmente presente DOPO il primoSegmento dell'URL e DOPO lo slash */ @Override public void setParameter(final BeforeEvent beforeEvent, @OptionalParameter String parametroOpzionale) { //--routeParameter contiene sia il primoSegmento sia multiParametersMap sia singleParameter routeParameter = routeService.estraeParametri(beforeEvent, parametroOpzionale); //--Regola le property indispensabili per gestire questa view //--Se c'è solo il primo segmento, non serve regolare le property (probabilmente perché siamo in una sottoclasse specifica) if (routeParameter != null && routeParameter.getTypeParam() != AETypeParam.segmentOnly) { fixProperty(); } } protected void fixProperty() { if (routeParameter == null && annotationService.getRouteMenuName(this.getClass()).equals(ROUTE_NAME_GENERIC_VIEW)) { // logger.error("Qualcosa non quadra", Logic.class, "fixProperty"); @todo rimettere } // this.entityClazz = null; // this.entityBean = null; // this.entityBeanPrevID = VUOTA; // this.entityBeanNextID = VUOTA; // // this.entityService = null; // // this.wikiPageTitle = VUOTA; // // this.wikiModuloTitle = VUOTA; // // this.wikiStatisticheTitle = VUOTA; // this.topLayout = null; // this.bottomLayout = null; } }
3e0035c2736a00fcd317ae3cc86cd3bf65cab346
87
java
Java
droid-smartcontroller/app/src/main/java/it/chiarani/otlsmartcontroller/helpers/RoomTypes.java
Xiryl/OTL
f5f89f6c367769f44ec59770d358200d625d4574
[ "MIT" ]
2
2019-04-17T12:57:23.000Z
2019-05-12T13:47:23.000Z
droid-smartcontroller/app/src/main/java/it/chiarani/otlsmartcontroller/helpers/RoomTypes.java
Xiryl/OTL
f5f89f6c367769f44ec59770d358200d625d4574
[ "MIT" ]
3
2019-02-12T21:04:53.000Z
2021-05-08T01:54:57.000Z
droid-smartcontroller/app/src/main/java/it/chiarani/otlsmartcontroller/helpers/RoomTypes.java
Xiryl/OTL
f5f89f6c367769f44ec59770d358200d625d4574
[ "MIT" ]
1
2019-02-12T20:35:09.000Z
2019-02-12T20:35:09.000Z
14.5
47
0.781609
102
package it.chiarani.otlsmartcontroller.helpers; public enum RoomTypes { KITCHEN }
3e00361ec9e5d767ec375e299a81f654290fe382
725
java
Java
ygb/ygb-account-impl/src/test/java/com/qingbo/ginkgo/ygb/account/repository/AccountLogRepositoryTester.java
hwxiasn/archetypes
6fb990ad85a9d0dc47b8e84fad4cd3eb207f65c2
[ "Apache-2.0" ]
null
null
null
ygb/ygb-account-impl/src/test/java/com/qingbo/ginkgo/ygb/account/repository/AccountLogRepositoryTester.java
hwxiasn/archetypes
6fb990ad85a9d0dc47b8e84fad4cd3eb207f65c2
[ "Apache-2.0" ]
null
null
null
ygb/ygb-account-impl/src/test/java/com/qingbo/ginkgo/ygb/account/repository/AccountLogRepositoryTester.java
hwxiasn/archetypes
6fb990ad85a9d0dc47b8e84fad4cd3eb207f65c2
[ "Apache-2.0" ]
null
null
null
29
104
0.783448
103
package com.qingbo.ginkgo.ygb.account.repository; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.qingbo.ginkgo.ygb.account.entity.AccountLog; public class AccountLogRepositoryTester extends BaseRepositoryTester { @Autowired private AccountLogRepository accountLogRepository; @Test public void deleted() { List<AccountLog> list = accountLogRepository.findByTypeAndTradeIdAndDeletedFalse("IN", 1L); printList(list); } @Test public void findByTypeAndSubAccountLogId() { AccountLog accountLog = accountLogRepository.findByTypeAndSubAccountLogId("IN", 141212170626020010L); System.out.println(accountLog); } }
3e003625a8a1704745f47870b28a14e6741b926c
3,969
java
Java
java-common/src/main/java/fr/univnantes/lina/javautil/CharacterUtil.java
nicolashernandez/dev-star
0ae7d61d92b828c1f288f420b8d531b718c57540
[ "Apache-2.0" ]
5
2017-07-07T08:10:15.000Z
2019-09-10T11:15:52.000Z
java-common/src/main/java/fr/univnantes/lina/javautil/CharacterUtil.java
nicolashernandez/dev-star
0ae7d61d92b828c1f288f420b8d531b718c57540
[ "Apache-2.0" ]
1
2017-07-09T13:54:44.000Z
2017-07-18T09:48:41.000Z
java-common/src/main/java/fr/univnantes/lina/javautil/CharacterUtil.java
nicolashernandez/dev-star
0ae7d61d92b828c1f288f420b8d531b718c57540
[ "Apache-2.0" ]
null
null
null
28.35
115
0.696397
104
/** * * Copyright (C) 2015-20.. Nicolas Hernandez * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package fr.univnantes.lina.javautil; /** * most of the method can be invoked by * * String character = "a"; * method(character.codePointAt(0)); * * @author hernandez * */ public class CharacterUtil { /** * * @param currentCharCodePoint * @param previousCharCodePoint * @return */ static public Boolean areDifferent (int currentCharCodePoint, int previousCharCodePoint) { return ((Character.isLetter(currentCharCodePoint) && !Character.isLetter(previousCharCodePoint)) || (Character.isDigit(currentCharCodePoint) && !Character.isDigit(previousCharCodePoint)) || (isSeparator(currentCharCodePoint) && !isSeparator(previousCharCodePoint)) || (isNotLetterDigitOrSeparator(currentCharCodePoint) && !isNotLetterDigitOrSeparator(previousCharCodePoint))); } /** * is Symbol * @param codePoint * @return */ static public Boolean isNotLetterDigitOrSeparator (int codePoint) { return !(Character.isLetter(codePoint) || Character.isDigit(codePoint) || isSeparator(codePoint)); } /** * * @param codePoint * @return */ static public Boolean isSeparator (int codePoint) { /*if (getVerboseMode()) System.err.println("Debug: reminder Character.LINE_SEPARATOR type>"+Character.LINE_SEPARATOR +"< Character.SPACE_SEPARATOR>"+Character.SPACE_SEPARATOR +"< Character.PARAGRAPH_SEPARATOR>"+Character.PARAGRAPH_SEPARATOR +"< Character.CONTROL>"+Character.CONTROL +"<"); */ return ((Character.getType(codePoint) == Character.LINE_SEPARATOR) || (Character.getType(codePoint) == Character.SPACE_SEPARATOR) || (Character.getType(codePoint) == Character.PARAGRAPH_SEPARATOR) || (Character.getType(codePoint) == Character.CONTROL) ); } /** * * @param codePoint * @return */ static public Boolean isAscii (int codePoint) { return codePoint < 128; } /** String [] vocals = {"a", "e", "i", "o", "u", "y", "A", "E", "I", "O", "U", "Y" }; for (String vocal : vocals) System.out.println(vocal+" : "+vocal.codePointAt(0)); a : 97 e : 101 i : 105 o : 111 u : 117 y : 121 A : 65 E : 69 I : 73 O : 79 U : 85 Y : 89 * **/ static public Boolean isAsciiVocal (int codePoint) { int [] asciiVocalCodepointArray = {65, 69, 73, 79, 85, 89, 97, 101, 105, 111, 117, 121}; int asciiVocalCodepointIndex = 0; Boolean isAsciiVocal = false; while (asciiVocalCodepointIndex < asciiVocalCodepointArray.length && !isAsciiVocal) { if (asciiVocalCodepointArray[asciiVocalCodepointIndex] == codePoint) isAsciiVocal = true; asciiVocalCodepointIndex++; } return isAsciiVocal; } /** * Strong assumption: an alphabetic character which is not an ascii character is assume to be a vocal... * @param codePoint * @return */ static public Boolean isVocal (int codePoint) { if (isAscii(codePoint)) if (isAsciiVocal(codePoint)) return true; else return false; // alphabetic or not if (Character.isAlphabetic(codePoint)) return true; return false; } /** * * @param codePoint * @return */ static public Boolean isPunct (int codePoint) { //TODO return null; } }
3e00383fb6b83bbfe433250b18f5dc17d24f4314
6,316
java
Java
src/test/java/org/asciicerebrum/neocortexengine/mechanics/conditionevaluators/impl/CorrectWeaponForFeatEvaluatorTest.java
asciiCerebrum/neocortexEngine
dda27f24ed1dbd4010523124f5fe11e5e8dee4cf
[ "MIT" ]
3
2016-05-24T03:34:31.000Z
2021-04-09T18:38:11.000Z
src/test/java/org/asciicerebrum/neocortexengine/mechanics/conditionevaluators/impl/CorrectWeaponForFeatEvaluatorTest.java
asciiCerebrum/neocortexEngine
dda27f24ed1dbd4010523124f5fe11e5e8dee4cf
[ "MIT" ]
null
null
null
src/test/java/org/asciicerebrum/neocortexengine/mechanics/conditionevaluators/impl/CorrectWeaponForFeatEvaluatorTest.java
asciiCerebrum/neocortexEngine
dda27f24ed1dbd4010523124f5fe11e5e8dee4cf
[ "MIT" ]
2
2016-03-09T07:50:20.000Z
2020-07-05T02:05:54.000Z
34.326087
91
0.70171
105
package org.asciicerebrum.neocortexengine.mechanics.conditionevaluators.impl; import org.asciicerebrum.neocortexengine.domain.core.particles.UniqueId; import org.asciicerebrum.neocortexengine.domain.game.Armor; import org.asciicerebrum.neocortexengine.domain.game.DndCharacter; import org.asciicerebrum.neocortexengine.domain.game.Weapon; import org.asciicerebrum.neocortexengine.domain.ruleentities.ArmorPrototype; import org.asciicerebrum.neocortexengine.domain.ruleentities.CharacterClass; import org.asciicerebrum.neocortexengine.domain.ruleentities.ClassLevel; import org.asciicerebrum.neocortexengine.domain.ruleentities.Feat; import org.asciicerebrum.neocortexengine.domain.ruleentities.FeatBinding; import org.asciicerebrum.neocortexengine.domain.ruleentities.FeatType; import org.asciicerebrum.neocortexengine.domain.ruleentities.WeaponPrototype; import org.asciicerebrum.neocortexengine.domain.ruleentities.composition.LevelAdvancement; import org.asciicerebrum.neocortexengine.domain.ruleentities.composition.LevelAdvancements; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author species8472 */ public class CorrectWeaponForFeatEvaluatorTest { private CorrectWeaponForFeatEvaluator evaluator; private FeatType featType; public CorrectWeaponForFeatEvaluatorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { this.evaluator = new CorrectWeaponForFeatEvaluator(); this.featType = new FeatType(); this.featType.setUniqueId(new UniqueId("featType")); this.evaluator.setFeatType(this.featType); } @After public void tearDown() { } private void setupFull(final DndCharacter dndCharacter, final Weapon weapon) { final LevelAdvancement lvlAdv = new LevelAdvancement(); final Feat feat = new Feat(); final WeaponPrototype weaponProto = new WeaponPrototype(); final LevelAdvancements lvlAdvs = new LevelAdvancements(); feat.setFeatType(this.featType); feat.setFeatBinding(weaponProto); weapon.setInventoryItemPrototype(weaponProto); lvlAdv.getFeatAdvancements().addFeat(feat); lvlAdvs.add(lvlAdv); final ClassLevel clLvl = new ClassLevel(); final CharacterClass chCl = new CharacterClass(); clLvl.setCharacterClass(chCl); lvlAdv.setClassLevel(clLvl); dndCharacter.setLevelAdvancements(lvlAdvs); } @Test public void evaluateNormalTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Weapon weapon = new Weapon(); weapon.setUniqueId(new UniqueId("weapon")); this.setupFull(dndCharacter, weapon); final boolean result = this.evaluator.evaluate(dndCharacter, weapon); assertTrue(result); } @Test public void evaluateNullWeaponTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Weapon weapon = null; final boolean result = this.evaluator.evaluate(dndCharacter, weapon); assertFalse(result); } @Test public void evaluateNotAWeaponTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Armor armor = new Armor(); armor.setUniqueId(new UniqueId("armor")); final boolean result = this.evaluator.evaluate(dndCharacter, armor); assertFalse(result); } @Test public void evaluateEmptyFeatBindingsTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Weapon weapon = new Weapon(); weapon.setUniqueId(new UniqueId("weapon")); this.setupFull(dndCharacter, weapon); dndCharacter.getLevelAdvancements().iterator().next() .getFeatAdvancements().iterator().next() .setFeatType(new FeatType()); final boolean result = this.evaluator.evaluate(dndCharacter, weapon); assertFalse(result); } @Test public void evaluateWrongFeatBindingsTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Weapon weapon = new Weapon(); weapon.setUniqueId(new UniqueId("weapon")); this.setupFull(dndCharacter, weapon); dndCharacter.getLevelAdvancements().iterator().next() .getFeatAdvancements().iterator().next() .setFeatBinding(new ArmorPrototype()); final boolean result = this.evaluator.evaluate(dndCharacter, weapon); assertFalse(result); } @Test public void evaluateALLFeatBindingsTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Weapon weapon = new Weapon(); weapon.setUniqueId(new UniqueId("weapon")); this.setupFull(dndCharacter, weapon); dndCharacter.getLevelAdvancements().iterator().next() .getFeatAdvancements().iterator().next() .setFeatBinding(FeatBinding.GenericBinding.ALL); final boolean result = this.evaluator.evaluate(dndCharacter, weapon); assertTrue(result); } @Test public void evaluateWrongPrototypeTest() { final DndCharacter dndCharacter = new DndCharacter(); dndCharacter.setUniqueId(new UniqueId("character")); final Weapon weapon = new Weapon(); weapon.setUniqueId(new UniqueId("weapon")); this.setupFull(dndCharacter, weapon); dndCharacter.getLevelAdvancements().iterator().next() .getFeatAdvancements().iterator().next() .setFeatBinding(new WeaponPrototype()); final boolean result = this.evaluator.evaluate(dndCharacter, weapon); assertFalse(result); } }
3e00387cc139121b114a6907264aebf37935f152
7,511
java
Java
src/main/java/dev/jaqobb/weighted_dripleaves/WeightedDripleavesPlugin.java
jaqobb/weighted-dripleaves
143a26286309a1713c660b12122b9a0914f891d4
[ "MIT" ]
null
null
null
src/main/java/dev/jaqobb/weighted_dripleaves/WeightedDripleavesPlugin.java
jaqobb/weighted-dripleaves
143a26286309a1713c660b12122b9a0914f891d4
[ "MIT" ]
null
null
null
src/main/java/dev/jaqobb/weighted_dripleaves/WeightedDripleavesPlugin.java
jaqobb/weighted-dripleaves
143a26286309a1713c660b12122b9a0914f891d4
[ "MIT" ]
null
null
null
44.976048
146
0.641859
106
/* * MIT License * * Copyright (c) 2021 Jakub Zagórski (jaqobb) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.jaqobb.weighted_dripleaves; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.data.type.BigDripleaf; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; public final class WeightedDripleavesPlugin extends JavaPlugin implements Listener { private boolean includeArmor; private boolean includeEquipment; private boolean calculateAllPlayers; private double weightToTriggerDripleaf; private Map<Material, Double> weights; @Override public void onLoad() { this.getLogger().log(Level.INFO, "Loading configuration..."); this.saveDefaultConfig(); this.includeArmor = this.getConfig().getBoolean("include.armor"); this.includeEquipment = this.getConfig().getBoolean("include.equipment"); this.calculateAllPlayers = this.getConfig().getBoolean("calculate-all-players"); this.weightToTriggerDripleaf = this.getConfig().getDouble("weight-to-trigger-dripleaf"); this.weights = new EnumMap<>(Material.class); for (String weightMaterial : this.getConfig().getConfigurationSection("weights").getKeys(false)) { this.weights.put(Material.getMaterial(weightMaterial), this.getConfig().getConfigurationSection("weights").getDouble(weightMaterial)); } this.getServer().getLogger().log(Level.INFO, "Loaded configuration:"); this.getLogger().log(Level.INFO, "* Include armor: " + (this.includeArmor ? "yes" : "no") + "."); this.getLogger().log(Level.INFO, "* Include equipment: " + (this.includeEquipment ? "yes" : "no") + "."); this.getLogger().log(Level.INFO, "* Calculate all players: " + (this.calculateAllPlayers ? "yes" : "no") + "."); this.getLogger().log(Level.INFO, "* Weight to trigger dripleaf: " + this.weightToTriggerDripleaf + "."); this.getLogger().log(Level.INFO, "* Weights: " + this.weights.size() + "."); } @Override public void onEnable() { this.getLogger().log(Level.INFO, "Registering listener..."); this.getServer().getPluginManager().registerEvents(this, this); } @EventHandler public void onBlockPhysics(BlockPhysicsEvent event) { Block block = event.getSourceBlock(); if (block.getType() != Material.BIG_DRIPLEAF) { return; } event.setCancelled(true); BigDripleaf blockData = (BigDripleaf) block.getBlockData(); if (blockData.getTilt() != BigDripleaf.Tilt.UNSTABLE) { return; } Collection<Player> players = this.getPlayersOnBlock(block); if (players.isEmpty()) { return; } double weight = 0.0D; for (Player player : players) { weight += this.calculatePlayerWeight(player); if (!this.calculateAllPlayers) { break; } } if (Double.compare(weight, this.weightToTriggerDripleaf) < 0) { blockData.setTilt(BigDripleaf.Tilt.NONE); block.setBlockData(blockData); } } private Collection<Player> getPlayersOnBlock(Block block) { Collection<Player> players = new ArrayList<>(10); for (Player player : Bukkit.getOnlinePlayers()) { if (this.getCorrectDripleafBlockUnderPlayer(player, player.getLocation(), 0) != null) { players.add(player); } else if (this.getCorrectDripleafBlockUnderPlayer(player, player.getLocation(), 1) != null) { players.add(player); } } return Collections.unmodifiableCollection(players); } private double calculatePlayerWeight(Player player) { double weight = 0.0D; if (this.includeArmor) { for (ItemStack item : player.getInventory().getArmorContents()) { if (item == null) { continue; } if (this.weights.containsKey(item.getType())) { weight += this.weights.get(item.getType()) * item.getAmount(); } } } if (this.includeEquipment) { for (ItemStack item : player.getInventory().getStorageContents()) { if (item == null) { continue; } if (this.weights.containsKey(item.getType())) { weight += this.weights.get(item.getType()) * item.getAmount(); } } } return weight; } private Block getCorrectDripleafBlockUnderPlayer(Player player, Location playerLocation, int depth) { double checkEmpty = 0.0D; double checkWidth = 0.4D; Location[] locations = new Location[9]; locations[0] = playerLocation.clone().add(checkEmpty, -depth, checkEmpty); locations[1] = playerLocation.clone().add(checkWidth, -depth, checkEmpty); locations[2] = playerLocation.clone().add(checkWidth, -depth, checkWidth); locations[3] = playerLocation.clone().add(checkWidth, -depth, -checkWidth); locations[4] = playerLocation.clone().add(-checkWidth, -depth, checkEmpty); locations[5] = playerLocation.clone().add(-checkWidth, -depth, checkWidth); locations[6] = playerLocation.clone().add(-checkWidth, -depth, -checkWidth); locations[7] = playerLocation.clone().add(checkEmpty, -depth, checkWidth); locations[8] = playerLocation.clone().add(checkEmpty, -depth, -checkWidth); for (Location location : locations) { Block locationBlock = location.getBlock(); Material locationBlockType = locationBlock.getType(); if (!locationBlockType.isAir() && locationBlockType.isBlock() && locationBlockType != Material.BIG_DRIPLEAF) { return locationBlock; } } return null; } }
3e0038d4d9ff881e3ce20f9670e457bcb9bad739
592
java
Java
UPAnalysis/src/upAnalysis/summary/summaryBuilder/rs/ParamRS.java
devuxd/Reacher
0a4d658816913170c32456b3ed49980958ae98d6
[ "MIT" ]
1
2019-09-13T20:19:00.000Z
2019-09-13T20:19:00.000Z
UPAnalysis/src/upAnalysis/summary/summaryBuilder/rs/ParamRS.java
devuxd/Reacher
0a4d658816913170c32456b3ed49980958ae98d6
[ "MIT" ]
null
null
null
UPAnalysis/src/upAnalysis/summary/summaryBuilder/rs/ParamRS.java
devuxd/Reacher
0a4d658816913170c32456b3ed49980958ae98d6
[ "MIT" ]
null
null
null
15.578947
46
0.697635
107
package upAnalysis.summary.summaryBuilder.rs; public class ParamRS implements ResolvedSource { private int paramId; private boolean isVarArg; public ParamRS(int paramId, boolean isVarArg) { this.paramId = paramId; this.isVarArg = isVarArg; } public boolean isVarArg() { return isVarArg; } public String toString() { return "P" + paramId; } public boolean equals(Object op) { if (!(op instanceof ParamRS)) return false; ParamRS otherSource = (ParamRS) op; return paramId == otherSource.paramId; } public int hashCode() { return paramId; } }
3e003969a951577292c6ee574e2aed4c6815d3b5
2,811
java
Java
poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java
HasaanA16/poi
1c1bd6e5854c14ab6650e50c9d4540a360ac34a5
[ "Apache-2.0" ]
1,431
2015-01-08T10:48:44.000Z
2022-03-31T07:11:01.000Z
poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java
HasaanA16/poi
1c1bd6e5854c14ab6650e50c9d4540a360ac34a5
[ "Apache-2.0" ]
252
2015-01-19T21:19:03.000Z
2022-03-30T23:54:59.000Z
poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java
HasaanA16/poi
1c1bd6e5854c14ab6650e50c9d4540a360ac34a5
[ "Apache-2.0" ]
715
2015-01-06T02:51:25.000Z
2022-03-21T06:54:46.000Z
34.280488
93
0.654571
108
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** * Tests that InteractiveInfoAtom works properly. */ public class TestInteractiveInfo { // From a real file private final byte[] data_a = { 0x0F, 0, 0xF2-256, 0x0F, 0x18, 0, 0, 0, 0, 0, 0xF3-256, 0x0F, 0x10, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 8, 0, 0, 0 }; @Test void testRecordType() { InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); assertEquals(4082, ii.getRecordType()); } @Test void testGetChildDetails() { InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); InteractiveInfoAtom ia = ii.getInteractiveInfoAtom(); assertEquals(1, ia.getHyperlinkID()); } @Test void testWrite() throws Exception { InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ii.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } // Create A from scratch @Test void testCreate() throws Exception { InteractiveInfo ii = new InteractiveInfo(); InteractiveInfoAtom ia = ii.getInteractiveInfoAtom(); // Set values ia.setHyperlinkID(1); ia.setSoundRef(0); ia.setAction((byte)4); ia.setHyperlinkType((byte)8); // Check it's now the same as a UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ii.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } }
3e003aed2c5a9768bc01c077defb2d921a27a803
19,412
java
Java
deeplinkdispatch-processor/src/main/java/com/airbnb/deeplinkdispatch/DeepLinkProcessor.java
MinceMan/DeepLinkDispatch
6ab057642a6933d665b67fbc70d4874c98e0a763
[ "Apache-2.0" ]
null
null
null
deeplinkdispatch-processor/src/main/java/com/airbnb/deeplinkdispatch/DeepLinkProcessor.java
MinceMan/DeepLinkDispatch
6ab057642a6933d665b67fbc70d4874c98e0a763
[ "Apache-2.0" ]
null
null
null
deeplinkdispatch-processor/src/main/java/com/airbnb/deeplinkdispatch/DeepLinkProcessor.java
MinceMan/DeepLinkDispatch
6ab057642a6933d665b67fbc70d4874c98e0a763
[ "Apache-2.0" ]
null
null
null
44.522936
100
0.658047
109
/* * Copyright (C) 2015 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.deeplinkdispatch; import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; @AutoService(Processor.class) public class DeepLinkProcessor extends AbstractProcessor { private static final ClassName ANDROID_INTENT = ClassName.get("android.content", "Intent"); private static final ClassName ANDROID_CONTEXT = ClassName.get("android.content", "Context"); private static final ClassName ANDROID_URI = ClassName.get("android.net", "Uri"); private static final ClassName DEEPLINKRESULT = ClassName.get("com.airbnb.deeplinkdispatch", "DeepLinkResult"); private Filer filer; private Messager messager; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); } @Override public Set<String> getSupportedAnnotationTypes() { return new HashSet<>( Arrays.asList( DeepLink.class.getCanonicalName(), DeepLinkHandler.class.getCanonicalName())); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { List<DeepLinkAnnotatedElement> deepLinkElements = new ArrayList<>(); Class<DeepLink> deepLinkClass = DeepLink.class; for (Element element : roundEnv.getElementsAnnotatedWith(deepLinkClass)) { ElementKind kind = element.getKind(); if (kind != ElementKind.METHOD && kind != ElementKind.CLASS) { error(element, "Only classes and methods can be annotated with @%s", deepLinkClass.getSimpleName()); } if (kind == ElementKind.METHOD) { Set<Modifier> methodModifiers = element.getModifiers(); if (!methodModifiers.contains(Modifier.STATIC)) { error(element, "Only static methods can be annotated with @%s", deepLinkClass.getSimpleName()); } } String[] deepLinks = element.getAnnotation(deepLinkClass).value(); DeepLinkEntry.Type type = kind == ElementKind.CLASS ? DeepLinkEntry.Type.CLASS : DeepLinkEntry.Type.METHOD; for (String deepLink : deepLinks) { try { deepLinkElements.add(new DeepLinkAnnotatedElement(deepLink, element, type)); } catch (MalformedURLException e) { messager.printMessage(Diagnostic.Kind.ERROR, "Malformed Deep Link URL " + deepLink); } } } boolean hasSpecifiedDeepLinkActivity = !roundEnv.getElementsAnnotatedWith(DeepLinkHandler.class).isEmpty(); if (!deepLinkElements.isEmpty()) { try { generateDeepLinkResult(); generateDeepLinkLoader(deepLinkElements); generateDeepLinkDelegate(); if (!hasSpecifiedDeepLinkActivity) { generateDeepLinkActivity(); } } catch (IOException e) { messager.printMessage(Diagnostic.Kind.ERROR, "Error creating file"); } catch (RuntimeException e) { messager.printMessage(Diagnostic.Kind.ERROR, "Internal error during annotation processing: " + e.getClass().getSimpleName()); } } return true; } private void error(Element e, String msg, Object... args) { messager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args), e); } /** * Generates a DeepLinkResult class for us to use. Must be here because it uses Android's Uri * class and our api is a java lib, not Android */ private void generateDeepLinkResult() throws IOException { TypeSpec deepLinkResult = TypeSpec.classBuilder("DeepLinkResult") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addField(TypeName.BOOLEAN, "successful", Modifier.PRIVATE, Modifier.FINAL) .addField(ANDROID_URI, "uri", Modifier.PRIVATE, Modifier.FINAL) .addField(ClassName.get(String.class), "error", Modifier.PRIVATE, Modifier.FINAL) .addMethod(MethodSpec.constructorBuilder() .addParameter(ParameterSpec.builder(TypeName.BOOLEAN, "successful").build()) .addParameter(ParameterSpec.builder(ANDROID_URI, "uri").build()) .addParameter(ParameterSpec.builder(ClassName.get(String.class), "error") .build()) .addStatement("this.successful = successful") .addStatement("this.uri = uri") .addStatement("this.error = error") .build()) .addMethod(MethodSpec.methodBuilder("isSuccessful") .addModifiers(Modifier.PUBLIC) .addJavadoc("@return whether or not the dispatch was a success.\n") .returns(TypeName.BOOLEAN) .addStatement("return successful") .build()) .addMethod(MethodSpec.methodBuilder("uri") .addModifiers(Modifier.PUBLIC) .addJavadoc("@return this result's uri, or {@code null} if there is none.\n") .returns(ANDROID_URI) .addStatement("return uri") .build()) .addMethod(MethodSpec.methodBuilder("error") .addModifiers(Modifier.PUBLIC) .addJavadoc("@return this result's error message, or {@code null} if there is none.\n") .returns(ClassName.get(String.class)) .addStatement("return error") .build()) .addMethod(MethodSpec.methodBuilder("equals") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(ClassName.get(Object.class), "o") .returns(TypeName.BOOLEAN) .addCode("if (this == o) { return true; }") .addCode("\n") .addCode("if (o == null || getClass() != o.getClass()) { return false; }") .addCode("\n") .addCode("\n") .addCode("DeepLinkResult that = (DeepLinkResult) o;") .addCode("\n") .addCode("\n") .addCode("if (successful != that.successful) { return false; }") .addCode("\n") .addCode("if (uri != null ? !uri.equals(that.uri) : that.uri != null) { return false; " + "}") .addCode("\n") .addCode("return error != null ? error.equals(that.error) " + ": that.error == null;") .build()) .addMethod(MethodSpec.methodBuilder("hashCode") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(TypeName.INT) .addStatement("int result = (successful ? 1 : 0)") .addStatement("result = 31 * result + (uri != null ? uri.hashCode() : 0)") .addStatement("result = 31 * result + (error != null ? error.hashCode() " + ": 0)") .addStatement("return result") .build()) .addMethod(MethodSpec.methodBuilder("toString") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(ClassName.get(String.class)) .addCode("return \"DeepLinkResult{\" +") .addCode("\n") .addCode(" \"successful=\" + successful +") .addCode("\n") .addCode(" \", uri=\" + uri +") .addCode("\n") .addCode(" \", error='\" + error + '\\'' +") .addCode("\n") .addCode(" '}';") .build()) .build(); JavaFile.builder("com.airbnb.deeplinkdispatch", deepLinkResult) .build() .writeTo(filer); } private void generateDeepLinkLoader(List<DeepLinkAnnotatedElement> elements) throws IOException { FieldSpec registry = FieldSpec .builder(ParameterizedTypeName.get(List.class, DeepLinkEntry.class), "registry", Modifier.PRIVATE, Modifier.FINAL) .initializer("new $T<>()", TypeName.get(LinkedList.class)) .build(); MethodSpec.Builder loadMethod = MethodSpec.methodBuilder("load") .returns(void.class); for (DeepLinkAnnotatedElement element : elements) { String type = "DeepLinkEntry.Type." + element.getAnnotationType().toString(); ClassName activity = ClassName.get(element.getActivityElement()); Object method = element.getMethod() == null ? null : element.getMethod(); String uri = element.getUri(); loadMethod.addStatement("registry.add(new DeepLinkEntry($S, $L, $T.class, $S))", uri, type, activity, method); } MethodSpec parseMethod = MethodSpec.methodBuilder("parseUri") .addParameter(String.class, "uri") .returns(DeepLinkEntry.class) .beginControlFlow("for (DeepLinkEntry entry : registry)") .beginControlFlow("if (entry.matches(uri))") .addStatement("return entry") .endControlFlow() .endControlFlow() .addStatement("return null") .build(); TypeSpec deepLinkLoader = TypeSpec.classBuilder("DeepLinkLoader") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addField(registry) .addMethod(loadMethod.build()) .addMethod(parseMethod) .build(); JavaFile.builder("com.airbnb.deeplinkdispatch", deepLinkLoader) .build() .writeTo(filer); } private void generateDeepLinkDelegate() throws IOException { MethodSpec notifyListenerMethod = MethodSpec.methodBuilder("notifyListener") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(void.class) .addParameter(ANDROID_CONTEXT, "context") .addParameter(boolean.class, "isError") .addParameter(ClassName.get("android.net", "Uri"), "uri") .addParameter(String.class, "errorMessage") .addStatement("$T intent = new Intent()", ANDROID_INTENT) .addStatement("intent.setAction($T.ACTION)", DeepLinkHandler.class) .addStatement("intent.putExtra($T.EXTRA_URI, uri.toString())", DeepLinkHandler.class) .addStatement("intent.putExtra($T.EXTRA_SUCCESSFUL, !isError)", DeepLinkHandler.class) .beginControlFlow("if (isError)") .addStatement("intent.putExtra($T.EXTRA_ERROR_MESSAGE, errorMessage)", DeepLinkHandler.class) .endControlFlow() .addStatement("$T.getInstance(context).sendBroadcast(intent)", ClassName.get("android.support.v4.content", "LocalBroadcastManager")) .build(); MethodSpec createResultAndNotifyMethod = MethodSpec.methodBuilder("createResultAndNotify") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(DEEPLINKRESULT) .addParameter(ANDROID_CONTEXT, "context") .addParameter(TypeName.BOOLEAN, "successful", Modifier.FINAL) .addParameter(ANDROID_URI, "uri", Modifier.FINAL) .addParameter(ClassName.get(String.class), "error", Modifier.FINAL) .addStatement("$T result = new $T(successful, uri, error)", DEEPLINKRESULT, DEEPLINKRESULT) .addStatement("notifyListener(context, !successful, uri, error)") .addStatement("return result") .build(); FieldSpec tag = FieldSpec .builder(String.class, "TAG", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("DeepLinkDelegate.class.getSimpleName()") .build(); MethodSpec constructor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("throw new $T($S)", AssertionError.class, "No instances.") .build(); MethodSpec dispatchFromMethod = MethodSpec.methodBuilder("dispatchFrom") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(DEEPLINKRESULT) .addParameter(ClassName.get("android.app", "Activity"), "activity") .beginControlFlow("if (activity == null)") .addStatement("throw new $T($S)", NullPointerException.class, "activity == null") .endControlFlow() .addStatement("$T sourceIntent = activity.getIntent()", ANDROID_INTENT) .addStatement("$T uri = sourceIntent.getData()", ANDROID_URI) .beginControlFlow("if (uri == null)") .addStatement("return createResultAndNotify(activity, false, null, $S)", "No Uri in given activity's intent.") .endControlFlow() .addStatement("DeepLinkLoader loader = new DeepLinkLoader()") .addStatement("loader.load()") .addStatement("String uriString = uri.toString()") .addStatement("DeepLinkEntry entry = loader.parseUri(uriString)") .beginControlFlow("if (entry != null)") .addStatement("DeepLinkUri deepLinkUri = DeepLinkUri.parse(uriString)") .addStatement("$T<String, String> parameterMap = entry.getParameters(uriString)", Map.class) .beginControlFlow("for (String queryParameter : deepLinkUri.queryParameterNames())") .beginControlFlow( "for (String queryParameterValue : deepLinkUri.queryParameterValues(queryParameter))") .beginControlFlow("if (parameterMap.containsKey(queryParameter))") .addStatement( "$T.w(TAG, \"Duplicate parameter name in path and query param: \" + queryParameter)", ClassName.get("android.util", "Log")) .endControlFlow() .addStatement("parameterMap.put(queryParameter, queryParameterValue)") .endControlFlow() .endControlFlow() .addStatement("parameterMap.put(DeepLink.URI, uri.toString())") .beginControlFlow("try") .addStatement("Class<?> c = entry.getActivityClass()") .addStatement("$T newIntent", ANDROID_INTENT) .beginControlFlow("if (entry.getType() == DeepLinkEntry.Type.CLASS)") .addStatement("newIntent = new Intent(activity, c)") .nextControlFlow("else") .addStatement("$T method = c.getMethod(entry.getMethod(), $T.class)", Method.class, ClassName.get("android.content", "Context")) .addStatement("newIntent = (Intent) method.invoke(c, activity)") .endControlFlow() .beginControlFlow("if (newIntent.getAction() == null)") .addStatement("newIntent.setAction(sourceIntent.getAction())") .endControlFlow() .beginControlFlow("if (newIntent.getData() == null)") .addStatement("newIntent.setData(sourceIntent.getData())") .endControlFlow() .addStatement("$T parameters", ClassName.get("android.os", "Bundle")) .beginControlFlow("if (sourceIntent.getExtras() != null)") .addStatement("parameters = new Bundle(sourceIntent.getExtras())") .nextControlFlow("else") .addStatement("parameters = new Bundle()") .endControlFlow() .beginControlFlow( "for (Map.Entry<String, String> parameterEntry : parameterMap.entrySet())") .addStatement("parameters.putString(parameterEntry.getKey(), parameterEntry.getValue())") .endControlFlow() .addStatement("newIntent.putExtras(parameters)") .addStatement("newIntent.putExtra(DeepLink.IS_DEEP_LINK, true)") .beginControlFlow("if (activity.getCallingActivity() != null)") .addStatement("newIntent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT)") .endControlFlow() .addStatement("activity.startActivity(newIntent)") .addStatement("return createResultAndNotify(activity, true, uri, null)") .nextControlFlow("catch (NoSuchMethodException exception)") .addStatement( "return createResultAndNotify(activity, false, uri, \"Deep link to " + "non-existent method: \" + entry.getMethod())") .nextControlFlow("catch (IllegalAccessException exception)") .addStatement( "return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())") .nextControlFlow("catch ($T exception)", InvocationTargetException.class) .addStatement( "return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())") .endControlFlow() .nextControlFlow("else") .addStatement("return createResultAndNotify(activity, false, uri, " + "\"No registered entity to handle deep link: \" + uri.toString())") .endControlFlow() .build(); TypeSpec deepLinkDelegate = TypeSpec.classBuilder("DeepLinkDelegate") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addField(tag) .addMethod(constructor) .addMethod(dispatchFromMethod) .addMethod(createResultAndNotifyMethod) .addMethod(notifyListenerMethod) .build(); JavaFile.builder("com.airbnb.deeplinkdispatch", deepLinkDelegate) .build() .writeTo(filer); } private void generateDeepLinkActivity() throws IOException { MethodSpec onCreateMethod = MethodSpec.methodBuilder("onCreate") .addModifiers(Modifier.PROTECTED) .addAnnotation(Override.class) .returns(void.class) .addParameter(ClassName.get("android.os", "Bundle"), "savedInstanceState") .addStatement("super.onCreate(savedInstanceState)") .addStatement("$T.dispatchFrom(this)", ClassName.get("com.airbnb.deeplinkdispatch", "DeepLinkDelegate")) .addStatement("finish()") .build(); TypeSpec deepLinkActivity = TypeSpec.classBuilder("DeepLinkActivity") .addModifiers(Modifier.PUBLIC) .superclass(ClassName.get("android.app", "Activity")) .addMethod(onCreateMethod) .build(); JavaFile.builder("com.airbnb.deeplinkdispatch", deepLinkActivity) .build() .writeTo(filer); } }
3e003b4a5937bcf7fa79ec0a75b0867bd294ba72
4,431
java
Java
nimrodg-master/src/main/java/au/edu/uq/rcc/nimrodg/master/sig/AuthHeader.java
UQ-RCC/nimrodg
901639deaf28c4fae80916e602473ae54e305559
[ "Apache-2.0" ]
null
null
null
nimrodg-master/src/main/java/au/edu/uq/rcc/nimrodg/master/sig/AuthHeader.java
UQ-RCC/nimrodg
901639deaf28c4fae80916e602473ae54e305559
[ "Apache-2.0" ]
42
2019-01-29T01:42:34.000Z
2021-03-05T03:00:42.000Z
nimrodg-master/src/main/java/au/edu/uq/rcc/nimrodg/master/sig/AuthHeader.java
UQ-RCC/nimrodg
901639deaf28c4fae80916e602473ae54e305559
[ "Apache-2.0" ]
null
null
null
32.343066
420
0.693523
110
/* * Nimrod/G * https://github.com/UQ-RCC/nimrodg * * SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2021 The University of Queensland * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package au.edu.uq.rcc.nimrodg.master.sig; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AuthHeader { private static final Pattern AUTH_HEADER_PATTERN = Pattern.compile("(?<algorithm>NIM1-[\\w-]+)\\s+Credential=(?<credential>(?<accesskey>[\\w]+)\\/(?<timestamp>(?<year>\\d{4})(?<month>\\d{2})(?<day>\\d{2})T(?<hour>\\d{2})(?<minute>\\d{2})(?<second>\\d{2})Z)\\/(?<nonce>\\d+)\\/(?<appid>[\\w]+)),\\s*SignedProperties=(?<properties>[\\w-;]+),\\s*SignedHeaders=(?<headers>[\\w-;]+),\\s+Signature=(?<signature>[a-z0-9]*)$"); public final String algorithm; public final String credential; public final String accessKey; public final String timestampString; public final Instant timestamp; public final long nonce; public final String appid; /** * The set of properties to verify. These are sorted by code-point. */ public final Set<String> signedProperties; /** * The set of headers to verify. These are sorted by code-point. */ public final Set<String> signedHeaders; public final String signature; public final String header; /* This doesn't validate inputs, trust the caller to do it. */ AuthHeader(String algorithm, String credential, String accessKey, String timestampString, Instant timestamp, long nonce, String appid, Set<String> signedProperties, Set<String> signedHeaders, String signature) { this.algorithm = algorithm; this.credential = credential; this.accessKey = accessKey; this.timestampString = timestampString; this.timestamp = timestamp; this.nonce = nonce; this.appid = appid; this.signedProperties = signedProperties; this.signedHeaders = signedHeaders; this.signature = signature; this.header = String.format("%s Credential=%s, SignedProperties=%s, SignedHeaders=%s, Signature=%s", algorithm, credential, String.join(";", signedProperties), String.join(";", signedHeaders), signature ); } @Override public boolean equals(Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; AuthHeader that = (AuthHeader)o; return header.equals(that.header); } @Override public int hashCode() { return header.hashCode(); } @Override public String toString() { return header; } public static AuthHeader parse(String s) { Matcher m = AUTH_HEADER_PATTERN.matcher(s); if(!m.matches()) { return null; } /* Make sure properties and headers are sorted and have no duplicates. */ String[] _props = m.group("properties").split(";"); TreeSet<String> props = new TreeSet<>(Arrays.asList(_props)); if(Arrays.compare(_props, props.stream().toArray(String[]::new)) != 0) { return null; } String[] _headers = m.group("headers").split(";"); TreeSet<String> headers = new TreeSet<>(Arrays.asList(_headers)); if(Arrays.compare(_headers, headers.stream().toArray(String[]::new)) != 0) { return null; } return new AuthHeader( m.group("algorithm"), m.group("credential"), m.group("accesskey"), m.group("timestamp"), OffsetDateTime.of( Integer.parseInt(m.group("year")), Integer.parseInt(m.group("month")), Integer.parseInt(m.group("day")), Integer.parseInt(m.group("hour")), Integer.parseInt(m.group("minute")), Integer.parseInt(m.group("second")), 0, ZoneOffset.UTC ).toInstant(), Long.parseUnsignedLong(m.group("nonce")), m.group("appid"), Collections.unmodifiableSet(props), Collections.unmodifiableSet(headers), m.group("signature") ); } }
3e003bc86cbde478b634bdc2e2bce9059dbdf919
349
java
Java
src/main/java/com/bucketdev/betapp/profilesvc/exception/user/UserNotFoundException.java
BucketDev/betapp-profile-svc
c49d008eda350b3eb113295f2df62d230d454d41
[ "MIT" ]
null
null
null
src/main/java/com/bucketdev/betapp/profilesvc/exception/user/UserNotFoundException.java
BucketDev/betapp-profile-svc
c49d008eda350b3eb113295f2df62d230d454d41
[ "MIT" ]
null
null
null
src/main/java/com/bucketdev/betapp/profilesvc/exception/user/UserNotFoundException.java
BucketDev/betapp-profile-svc
c49d008eda350b3eb113295f2df62d230d454d41
[ "MIT" ]
null
null
null
26.846154
62
0.805158
111
package com.bucketdev.betapp.profilesvc.exception.user; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
3e003d5a61fe741f9288c7d965134143f133daf5
48,122
java
Java
com/planet_ink/coffee_mud/core/database/RoomLoader.java
welterde/ewok
6fce1fd0b8b1164eba79c17252708d3215bd90e9
[ "Apache-2.0" ]
1
2019-02-25T09:33:03.000Z
2019-02-25T09:33:03.000Z
com/planet_ink/coffee_mud/core/database/RoomLoader.java
welterde/ewok
6fce1fd0b8b1164eba79c17252708d3215bd90e9
[ "Apache-2.0" ]
null
null
null
com/planet_ink/coffee_mud/core/database/RoomLoader.java
welterde/ewok
6fce1fd0b8b1164eba79c17252708d3215bd90e9
[ "Apache-2.0" ]
2
2017-08-15T12:28:07.000Z
2021-08-07T05:24:00.000Z
35.96562
134
0.583039
112
package com.planet_ink.coffee_mud.core.database; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.sql.*; import java.util.*; import com.planet_ink.coffee_mud.Libraries.CMCatalog.CataDataImpl; import com.planet_ink.coffee_mud.Libraries.interfaces.*; /* Copyright 2000-2010 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings("unchecked") public class RoomLoader { protected DBConnector DB=null; public RoomLoader(DBConnector newDB) { DB=newDB; } private int recordCount=1; private int currentRecordPos=1; private int updateBreak=1; private final static String zeroes="000000000000"; public Vector DBReadAreaData(String areaID, boolean reportStatus) { DBConnection D=null; Vector areas=new Vector(); try { D=DB.DBFetch(); if(reportStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Counting Areas"); ResultSet R=D.query("SELECT * FROM CMAREA"+((areaID==null)?"":" WHERE CMAREA='"+areaID+"'")); recordCount=DB.getRecordCount(D,R); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); while(R.next()) { currentRecordPos=R.getRow(); String areaName=DBConnections.getRes(R,"CMAREA"); String areaType=DBConnections.getRes(R,"CMTYPE"); Area A=CMClass.getAreaType(areaType); if(A==null) A=CMClass.getAreaType("StdArea"); if(A==null) { Log.errOut("Could not create area: "+areaName); continue; } A.setName(areaName); A.setClimateType((int)DBConnections.getLongRes(R,"CMCLIM")); A.setSubOpList(DBConnections.getRes(R,"CMSUBS")); A.setDescription(DBConnections.getRes(R,"CMDESC")); A.setMiscText(DBConnections.getRes(R,"CMROTX")); A.setTechLevel((int)DBConnections.getLongRes(R,"CMTECH")); A.setAreaState(Area.STATE_ACTIVE); if(((currentRecordPos%updateBreak)==0)&&(reportStatus)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Loading Areas ("+currentRecordPos+" of "+recordCount+")"); areas.addElement(A); } DB.DBDone(D); } catch(SQLException sqle) { Log.errOut("Area",sqle); if(D!=null) DB.DBDone(D); return null; } return areas; } protected void addRoom(Vector rooms, Room R) { try { String roomID=R.roomID(); int start=0; int end=rooms.size()-1; int lastStart=0; int lastEnd=rooms.size()-1; int comp=-1; int mid=-1; while(start<=end) { mid=(end+start)/2; comp=((Room)rooms.elementAt(mid)).roomID().compareToIgnoreCase(roomID); if(comp==0) break; else if(comp>0) { lastEnd=end; end=mid-1; } else { lastStart=start; start=mid+1; } } if(comp==0) rooms.setElementAt(R,mid); else { if(mid>=0) for(comp=lastStart;comp<=lastEnd;comp++) if(((Room)rooms.elementAt(comp)).roomID().compareToIgnoreCase(roomID)>0) { rooms.insertElementAt(R,comp); return; } rooms.addElement(R); } } catch(Throwable t){ t.printStackTrace();} } public Room getRoom(Vector rooms, String roomID) { if(rooms.size()==0) return null; int start=0; int end=rooms.size()-1; while(start<=end) { int mid=(end+start)/2; int comp=((Room)rooms.elementAt(mid)).roomID().compareToIgnoreCase(roomID); if(comp==0) return (Room)rooms.elementAt(mid); else if(comp>0) end=mid-1; else start=mid+1; } return null; } public RoomnumberSet DBReadAreaRoomList(String areaName, boolean reportStatus) { RoomnumberSet roomSet=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); DBConnection D=null; try { D=DB.DBFetch(); if(reportStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Fetching roomnums for "+areaName); ResultSet R=D.query("SELECT * FROM CMROOM"+((areaName==null)?"":" WHERE CMAREA='"+areaName+"'")); while(R.next()) roomSet.add(DBConnections.getRes(R,"CMROID")); DB.DBDone(D); } catch(SQLException sqle) { Log.errOut("RoomSet",sqle); if(D!=null) DB.DBDone(D); return null; } return roomSet; } public Vector DBReadRoomData(String singleRoomIDtoLoad, boolean reportStatus) { return DBReadRoomData(singleRoomIDtoLoad,null,reportStatus,null,null); } public Room DBReadRoomObject(String roomIDtoLoad, boolean reportStatus) { DBConnection D=null; try { D=DB.DBFetch(); if(reportStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Counting Rooms"); ResultSet R=D.query("SELECT * FROM CMROOM WHERE CMROID='"+roomIDtoLoad+"'"); recordCount=DB.getRecordCount(D,R); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); String roomID=null; if(R.next()) { currentRecordPos=R.getRow(); roomID=DBConnections.getRes(R,"CMROID"); String localeID=DBConnections.getRes(R,"CMLOID"); //String areaName=DBConnections.getRes(R,"CMAREA"); Room newRoom=CMClass.getLocale(localeID); if(newRoom==null) Log.errOut("Room","Couldn't load room '"+roomID+"', localeID '"+localeID+"'."); else { newRoom.setRoomID(roomID); newRoom.setDisplayText(DBConnections.getRes(R,"CMDESC1")); if(CMProps.getBoolVar(CMProps.SYSTEMB_ROOMDNOCACHE)) newRoom.setDescription(""); else newRoom.setDescription(DBConnections.getRes(R,"CMDESC2")); newRoom.setMiscText(DBConnections.getRes(R,"CMROTX")); } if(((currentRecordPos%updateBreak)==0)&&(reportStatus)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Loading Rooms ("+currentRecordPos+" of "+recordCount+")"); return newRoom; } } catch(SQLException sqle) { Log.errOut("Room",sqle); } finally { if(D!=null) DB.DBDone(D); } return null; } public Vector DBReadRoomData(String singleRoomIDtoLoad, RoomnumberSet roomsToLoad, boolean reportStatus, Vector unknownAreas, RoomnumberSet unloadedRooms) { Vector rooms=new Vector(); DBConnection D=null; try { D=DB.DBFetch(); if(reportStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Counting Rooms"); ResultSet R=D.query("SELECT * FROM CMROOM"+((singleRoomIDtoLoad==null)?"":" WHERE CMROID='"+singleRoomIDtoLoad+"'")); recordCount=DB.getRecordCount(D,R); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); String roomID=null; while(R.next()) { currentRecordPos=R.getRow(); roomID=DBConnections.getRes(R,"CMROID"); if((roomsToLoad!=null)&&(!roomsToLoad.contains(roomID))) continue; String localeID=DBConnections.getRes(R,"CMLOID"); String areaName=DBConnections.getRes(R,"CMAREA"); Area myArea=CMLib.map().getArea(areaName); if(myArea==null) { myArea=(Area)CMClass.getAreaType("StdArea").copyOf(); myArea.setName(areaName); if((unknownAreas!=null) &&(!unknownAreas.contains(areaName))) unknownAreas.addElement(areaName); } myArea.addProperRoomnumber(roomID); if(CMath.bset(myArea.flags(),Area.FLAG_THIN)) { if(unloadedRooms!=null) { if(!unloadedRooms.contains(roomID)) unloadedRooms.add(roomID); continue; } } Room newRoom=CMClass.getLocale(localeID); if(newRoom==null) Log.errOut("Room","Couldn't load room '"+roomID+"', localeID '"+localeID+"'."); else { newRoom.setRoomID(roomID); newRoom.setArea(myArea); newRoom.setDisplayText(DBConnections.getRes(R,"CMDESC1")); if(CMProps.getBoolVar(CMProps.SYSTEMB_ROOMDNOCACHE)) newRoom.setDescription(""); else newRoom.setDescription(DBConnections.getRes(R,"CMDESC2")); newRoom.setMiscText(DBConnections.getRes(R,"CMROTX")); addRoom(rooms,newRoom); } if(((currentRecordPos%updateBreak)==0)&&(reportStatus)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Loading Rooms ("+currentRecordPos+" of "+recordCount+")"); } } catch(SQLException sqle) { Log.errOut("Room",sqle); rooms=null; } finally { if(D!=null) DB.DBDone(D); } return rooms; } public void DBReadRoomExits(String roomID, Vector allRooms, boolean reportStatus) { DBReadRoomExits(roomID,allRooms,reportStatus,null);} public void DBReadRoomExits(String roomID, Vector allRooms, boolean reportStatus, RoomnumberSet unloadedRooms) { DBConnection D=null; // now grab the exits try { D=DB.DBFetch(); if(reportStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Counting Exits"); ResultSet R=D.query("SELECT * FROM CMROEX"+((roomID==null)?"":" WHERE CMROID='"+roomID+"'")); Room thisRoom=null; Room newRoom=null; recordCount=DB.getRecordCount(D,R); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); while(R.next()) { currentRecordPos=R.getRow(); roomID=DBConnections.getRes(R,"CMROID"); int direction=(int)DBConnections.getLongRes(R,"CMDIRE"); thisRoom=getRoom(allRooms,roomID); if(thisRoom==null) { if((unloadedRooms!=null)&&(!unloadedRooms.contains(roomID))) Log.errOut("Room","Couldn't set "+direction+" exit for unknown room '"+roomID+"'"); } else { String exitID=DBConnections.getRes(R,"CMEXID"); String exitMiscText=DBConnections.getResQuietly(R,"CMEXTX"); String nextRoomID=DBConnections.getRes(R,"CMNRID"); newRoom=getRoom(allRooms,nextRoomID); Exit newExit=CMClass.getExit(exitID); if(newRoom==null) { if(((unloadedRooms!=null)&&(unloadedRooms.contains(nextRoomID))) ||(CMath.bset(thisRoom.getArea().flags(),Area.FLAG_THIN))) { newRoom=CMClass.getLocale("ThinRoom"); newRoom.setRoomID(nextRoomID); newRoom.setArea(thisRoom.getArea()); } } if((newExit==null)&&(newRoom==null)) Log.errOut("Room",roomID+":no room&exit to '"+nextRoomID+"', exit type '"+exitID+"', direction: "+direction); else if((direction>255)&&(!(thisRoom instanceof GridLocale))) Log.errOut("Room","Not GridLocale, tried "+direction+" exit for room '"+roomID+"'"); else if((direction>255)&&(newRoom!=null)) { Vector CEs=CMParms.parseSemicolons(exitMiscText.trim(),true); for(int ces=0;ces<CEs.size();ces++) { Vector SCE=CMParms.parse(((String)CEs.elementAt(ces)).trim()); WorldMap.CrossExit CE=new WorldMap.CrossExit(); if(SCE.size()<3) continue; CE.x=CMath.s_int((String)SCE.elementAt(0)); CE.y=CMath.s_int((String)SCE.elementAt(1)); int codeddir=CMath.s_int((String)SCE.elementAt(2)); if(SCE.size()>=4) CE.destRoomID=newRoom.roomID()+(String)SCE.elementAt(3); else CE.destRoomID=newRoom.roomID(); CE.out=(codeddir&256)==256; CE.dir=codeddir&255; ((GridLocale)thisRoom).addOuterExit(CE); if((!CE.out)&&(!(newRoom instanceof GridLocale))) { newRoom.rawDoors()[CE.dir]=thisRoom; newRoom.setRawExit(CE.dir,CMClass.getExit("Open")); } } } else { if(newExit!=null) newExit.setMiscText(exitMiscText); if(direction>=Directions.NUM_DIRECTIONS()) Log.errOut("RoomLoader",CMLib.map().getExtendedRoomID(thisRoom)+" has an invalid direction #"+direction); else { thisRoom.rawDoors()[direction]=newRoom; thisRoom.setRawExit(direction,newExit); } } } if(reportStatus&&((currentRecordPos%updateBreak)==0)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Loading Exits ("+currentRecordPos+" of "+recordCount+")"); } } catch(SQLException sqle) { Log.errOut("Room",sqle); } finally { if(D!=null) DB.DBDone(D); } } public void DBReadAllRooms(RoomnumberSet set) { Vector areas=null; Vector newAreasToCreate=new Vector(); if(set==null) { while(CMLib.map().numAreas()>0)CMLib.map().delArea(CMLib.map().getFirstArea()); areas=DBReadAreaData(null,true); if(areas==null) return; for(int a=0;a<areas.size();a++) CMLib.map().addArea((Area)areas.elementAt(a)); areas.clear(); } RoomnumberSet unloadedRooms=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); Vector rooms=DBReadRoomData(null,set,set==null,newAreasToCreate,unloadedRooms); // handle stray areas for(Enumeration e=newAreasToCreate.elements();e.hasMoreElements();) { String areaName=(String)e.nextElement(); Log.sysOut("Area","Creating unhandled area: "+areaName); Area A=CMClass.getAreaType("StdArea"); A.setName(areaName); DBCreate(A); CMLib.map().addArea(A); for(Enumeration r=rooms.elements();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if(R.getArea().Name().equals(areaName)) R.setArea(A); } } DBReadRoomExits(null,rooms,set==null,unloadedRooms); DBReadContent(null,null,rooms,unloadedRooms,set==null); if(set==null) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Finalizing room data)"); for(Enumeration r=rooms.elements();r.hasMoreElements();) { Room thisRoom=(Room)r.nextElement(); thisRoom.startItemRejuv(); thisRoom.recoverRoomStats(); } if(set==null) for(Enumeration a=CMLib.map().areas();a.hasMoreElements();) ((Area)a.nextElement()).getAreaStats(); } public String DBReadRoomDesc(String roomID) { DBConnection D=null; // now grab the items try { D=DB.DBFetch(); ResultSet R=D.query("SELECT * FROM CMROOM WHERE CMROID='"+roomID+"'"); if(R.next()) { String txt=DBConnections.getRes(R,"CMDESC2"); DB.DBDone(D); return txt; } DB.DBDone(D); } catch(SQLException sqle) { Log.errOut("Room",sqle); if(D!=null) DB.DBDone(D); } return null; } public String DBReadRoomMOBData(String roomID, String mobID) { DBConnection D=null; // now grab the items try { D=DB.DBFetch(); ResultSet R=D.query("SELECT * FROM CMROCH WHERE CMROID='"+roomID+"'"); while(R.next()) { String NUMID=DBConnections.getRes(R,"CMCHNM"); if(NUMID.equalsIgnoreCase(mobID)) { String txt=DBConnections.getRes(R,"CMCHTX"); DB.DBDone(D); return txt; } } DB.DBDone(D); } catch(SQLException sqle) { Log.errOut("Room",sqle); if(D!=null) DB.DBDone(D); } return null; } private void fixItemKeys(Hashtable itemLocs, Hashtable itemNums) { for(Enumeration e=itemLocs.keys();e.hasMoreElements();) { Item keyItem=(Item)e.nextElement(); String location=(String)itemLocs.get(keyItem); Environmental container=(Environmental)itemNums.get(location); if((container instanceof Container)&&(((Container)container).capacity()>0)) keyItem.setContainer((Container)container); else if(container instanceof Rideable) keyItem.setRiding((Rideable)container); else if(container instanceof Item) keyItem.setContainer((Item)container); } } private void fixMOBRides(Hashtable mobRides, Hashtable itemNums) { for(Enumeration e=mobRides.keys();e.hasMoreElements();) { MOB M=(MOB)e.nextElement(); String ride=(String)mobRides.get(M); if(ride!=null) { Environmental E=(Environmental)itemNums.get(ride); if(E!=null) { if(E instanceof Rideable) M.setRiding((Rideable)E); else if(E instanceof MOB) M.setFollowing((MOB)E); } } } } private void fixContentContainers(Hashtable content, Hashtable stuff, String roomID, Room room, boolean debug) { String lastName=null; Hashtable itemLocs=null; Hashtable mobRides=null; if(room != null) for(Enumeration i=content.elements();i.hasMoreElements();) { Environmental E=(Environmental)i.nextElement(); if((debug)&&((lastName==null)||(!lastName.equals(E.Name())))) {lastName=E.Name(); Log.debugOut("RoomLoader","Loading object(s): "+E.Name());} if(E instanceof Item) room.addItem((Item)E); else { ((MOB)E).setStartRoom(room); ((MOB)E).bringToLife(room,true); } } itemLocs=(Hashtable)stuff.get("LOCSFOR"+roomID.toUpperCase()); mobRides=(Hashtable)stuff.get("RIDESFOR"+roomID.toUpperCase()); if(itemLocs!=null) { fixItemKeys(itemLocs,content); if(room!=null) { room.recoverRoomStats(); room.recoverRoomStats(); } } if(mobRides!=null) fixMOBRides(mobRides,content); } public void DBReadCatalogs() { DBReadContent("CATALOG_MOBS",null,null,null,true); DBReadContent("CATALOG_ITEMS",null,null,null,true); } public void DBReadContent(String thisRoomID, Room thisRoom, Vector rooms, RoomnumberSet unloadedRooms, boolean setStatus) { boolean debug=Log.debugChannelOn()&&(CMSecurity.isDebugging("DBROOMPOP")); if(debug||(Log.debugChannelOn()&&(CMSecurity.isDebugging("DBROOMS")))) Log.debugOut("RoomLoader","Reading content of "+((thisRoomID!=null)?thisRoomID:"ALL")); Hashtable stuff=new Hashtable(); Hashtable itemNums=null; Hashtable cataData=null; Hashtable itemLocs=null; Hashtable mobRides=null; boolean catalog=((thisRoomID!=null)&&(thisRoomID.startsWith("CATALOG_"))); DBConnection D=null; // now grab the items try { D=DB.DBFetch(); if(setStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Counting Items"); ResultSet R=D.query("SELECT * FROM CMROIT"+((thisRoomID==null)?"":" WHERE CMROID='"+thisRoomID+"'")); if(setStatus) recordCount=DB.getRecordCount(D,R); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); while(R.next()) { currentRecordPos=R.getRow(); String roomID=DBConnections.getRes(R,"CMROID"); if((unloadedRooms!=null)&&(unloadedRooms.contains(roomID))) continue; itemNums=(Hashtable)stuff.get("NUMSFOR"+roomID.toUpperCase()); if(itemNums==null) { itemNums=new Hashtable(); stuff.put("NUMSFOR"+roomID.toUpperCase(),itemNums); } itemLocs=(Hashtable)stuff.get("LOCSFOR"+roomID.toUpperCase()); if(itemLocs==null) { itemLocs=new Hashtable(); stuff.put("LOCSFOR"+roomID.toUpperCase(),itemLocs); } String itemNum=DBConnections.getRes(R,"CMITNM"); String itemID=DBConnections.getRes(R,"CMITID"); Item newItem=CMClass.getItem(itemID); if(newItem==null) Log.errOut("Room","Couldn't find item '"+itemID+"'"); else { newItem.setDatabaseID(itemNum); itemNums.put(itemNum,newItem); String loc=DBConnections.getResQuietly(R,"CMITLO"); if(loc.length()>0) { Item container=(Item)itemNums.get(loc); if(container!=null) newItem.setContainer(container); else itemLocs.put(newItem,loc); } try { if(catalog) { String text=DBConnections.getResQuietly(R,"CMITTX"); int x=text.lastIndexOf("<CATALOGDATA>"); if((x>0)&&(text.indexOf("</CATALOGDATA>",x)>0)) { cataData=(Hashtable)stuff.get("CATADATAFOR"+roomID.toUpperCase()); if(cataData==null) { cataData=new Hashtable(); stuff.put("CATADATAFOR"+roomID.toUpperCase(),cataData); } cataData.put(itemNum,text.substring(x)); text=text.substring(0,x); } newItem.setMiscText(text); } else newItem.setMiscText(DBConnections.getResQuietly(R,"CMITTX")); newItem.baseEnvStats().setRejuv((int)DBConnections.getLongRes(R,"CMITRE")); newItem.setUsesRemaining((int)DBConnections.getLongRes(R,"CMITUR")); newItem.baseEnvStats().setLevel((int)DBConnections.getLongRes(R,"CMITLV")); newItem.baseEnvStats().setAbility((int)DBConnections.getLongRes(R,"CMITAB")); newItem.baseEnvStats().setHeight((int)DBConnections.getLongRes(R,"CMHEIT")); newItem.recoverEnvStats(); } catch(Exception e) { Log.errOut("RoomLoader",e); itemNums.remove(itemNum);} } if(((currentRecordPos%updateBreak)==0)&&(setStatus)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Loading Items ("+currentRecordPos+" of "+recordCount+")"); } } catch(SQLException sqle) { Log.errOut("Room",sqle); } finally { if(D!=null) DB.DBDone(D); } // now grab the inhabitants try { D=DB.DBFetch(); if(setStatus) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Counting MOBS"); ResultSet R=D.query("SELECT * FROM CMROCH"+((thisRoomID==null)?"":" WHERE CMROID='"+thisRoomID+"'")); if(setStatus) recordCount=DB.getRecordCount(D,R); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); while(R.next()) { currentRecordPos=R.getRow(); String roomID=DBConnections.getRes(R,"CMROID"); if((unloadedRooms!=null)&&(unloadedRooms.contains(roomID))) continue; String NUMID=DBConnections.getRes(R,"CMCHNM"); String MOBID=DBConnections.getRes(R,"CMCHID"); itemNums=(Hashtable)stuff.get("NUMSFOR"+roomID.toUpperCase()); if(itemNums==null) { itemNums=new Hashtable(); stuff.put("NUMSFOR"+roomID.toUpperCase(),itemNums); } mobRides=(Hashtable)stuff.get("RIDESFOR"+roomID.toUpperCase()); if(mobRides==null) { mobRides=new Hashtable(); stuff.put("RIDESFOR"+roomID.toUpperCase(),mobRides); } MOB newMOB=CMClass.getMOB(MOBID); if(newMOB==null) Log.errOut("Room","Couldn't find MOB '"+MOBID+"'"); else { newMOB.setDatabaseID(NUMID); itemNums.put(NUMID,newMOB); if(thisRoom!=null) { newMOB.setStartRoom(thisRoom); newMOB.setLocation(thisRoom); } try { if((CMProps.getBoolVar(CMProps.SYSTEMB_MOBNOCACHE)) &&(!catalog) &&(NUMID.indexOf(MOBID+"@")>=0)) newMOB.setMiscText("%DBID>"+roomID+NUMID.substring(NUMID.indexOf("@"))); else newMOB.setMiscText(DBConnections.getResQuietly(R,"CMCHTX")); newMOB.baseEnvStats().setLevel(((int)DBConnections.getLongRes(R,"CMCHLV"))); newMOB.baseEnvStats().setAbility((int)DBConnections.getLongRes(R,"CMCHAB")); newMOB.baseEnvStats().setRejuv((int)DBConnections.getLongRes(R,"CMCHRE")); String ride=DBConnections.getRes(R,"CMCHRI"); if((ride!=null)&&(ride.length()>0)) mobRides.put(newMOB,ride); newMOB.recoverCharStats(); newMOB.recoverEnvStats(); newMOB.recoverMaxState(); newMOB.resetToMaxState(); } catch(Exception e) { Log.errOut("RoomLoader",e); itemNums.remove(NUMID);} } if(((currentRecordPos%updateBreak)==0)&&(setStatus)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Loading MOBs ("+currentRecordPos+" of "+recordCount+")"); } } catch(SQLException sqle) { Log.errOut("Room",sqle); } finally { if(D!=null) DB.DBDone(D); } if(thisRoom!=null) { rooms=new Vector(); rooms.addElement(thisRoom); } if(rooms!=null) recordCount=rooms.size(); updateBreak=CMath.s_int("1"+zeroes.substring(0,(""+(recordCount/100)).length()-1)); currentRecordPos=0; itemNums=(Hashtable)stuff.get("NUMSFORCATALOG_ITEMS"); cataData=(Hashtable)stuff.get("CATADATAFORCATALOG_ITEMS"); if((itemNums!=null)&&(thisRoomID!=null)&&(thisRoomID.equals("CATALOG_ITEMS"))) { String itemNum; Item I; String data; fixContentContainers(itemNums,stuff,"CATALOG_ITEMS",null,debug); for(Enumeration e=itemNums.keys();e.hasMoreElements();) { itemNum=(String)e.nextElement(); I=(Item)itemNums.get(itemNum); data=(String)((cataData!=null)?cataData.get(itemNum):null); Item oldI=CMLib.catalog().getCatalogItem(I.Name()); if((oldI!=null)&&(I.databaseID().length()>0)&&(!oldI.databaseID().equals(I.databaseID()))) DBDeleteRoomItem("CATALOG_ITEMS", I); else { CMLib.catalog().submitToCatalog(I); if((data!=null)&&(data.length()>0)) { CatalogLibrary.CataData dataI=CMLib.catalog().getCatalogItemData(I.Name()); if(dataI!=null) dataI.build(data); } } } } // load mob catalog itemNums=(Hashtable)stuff.get("NUMSFORCATALOG_MOBS"); cataData=(Hashtable)stuff.get("CATADATAFORCATALOG_MOBS"); if((itemNums!=null)&&(thisRoomID!=null)&&(thisRoomID.equals("CATALOG_MOBS"))) { String itemNum; MOB M; String data; fixContentContainers(itemNums,stuff,"CATALOG_MOBS",null,debug); for(Enumeration e=itemNums.keys();e.hasMoreElements();) { itemNum=(String)e.nextElement(); M=(MOB)itemNums.get(itemNum); data=(String)((cataData!=null)?cataData.get(itemNum):null); MOB oldM=CMLib.catalog().getCatalogMob(M.Name()); if((oldM!=null)&&(M.databaseID().length()>0)&&(!oldM.databaseID().equals(M.databaseID()))) DBDeleteRoomMOB("CATALOG_MOBS", M); else { CMLib.catalog().submitToCatalog(M); if((data!=null)&&(data.length()>0)) { CatalogLibrary.CataData dataM=CMLib.catalog().getCatalogMobData(M.Name()); if(dataM!=null) dataM.build(data); } } } } // now load the rooms if(rooms!=null) for(Enumeration e=rooms.elements();e.hasMoreElements();) { if((((++currentRecordPos)%updateBreak)==0)&&(setStatus)) CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Populating Rooms ("+(currentRecordPos)+" of "+recordCount+")"); Room room=(Room)e.nextElement(); if(debug) Log.debugOut("RoomLoader","Populating room: "+room.roomID()); itemNums=(Hashtable)stuff.get("NUMSFOR"+room.roomID().toUpperCase()); if(itemNums!=null) fixContentContainers(itemNums,stuff,room.roomID(),room,debug); } if(Log.debugChannelOn()&&(CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done reading content of "+((thisRoomID!=null)?thisRoomID:"ALL")); } private Vector DBGetContents(Room room) { if((!room.savable())||(room.amDestroyed())) return new Vector(); Vector contents=new Vector(); for(int i=0;i<room.numItems();i++) { Item thisItem=room.fetchItem(i); if((thisItem!=null)&&(!contents.contains(thisItem))&&thisItem.savable()) contents.addElement(thisItem); } return contents; } protected String getDBCreateItemString(String roomID, Item thisItem) { boolean catalog=((roomID!=null)&&(roomID.startsWith("CATALOG_"))); thisItem.setExpirationDate(0); // saved items won't clear! Environmental container=thisItem.container(); if((container==null) &&(thisItem.riding()!=null) &&(thisItem.riding().savable())) { Room room=CMLib.map().roomLocation(thisItem); if(((room!=null)&&(room.isHere(thisItem.riding()))) ||(CMLib.catalog().isCatalogObj(thisItem.riding()))) container=thisItem.riding(); } String itemID=""+thisItem; thisItem.setDatabaseID(itemID); String text=thisItem.text(); if(catalog) { CatalogLibrary.CataData dataI=CMLib.catalog().getCatalogItemData(thisItem.Name()); if(dataI!=null) text+=dataI.data(); } return "INSERT INTO CMROIT (" +"CMROID, " +"CMITNM, " +"CMITID, " +"CMITLO, " +"CMITTX, " +"CMITRE, " +"CMITUR, " +"CMITLV, " +"CMITAB, " +"CMHEIT" +") values (" +"'"+roomID+"'," +"'"+itemID+"'," +"'"+thisItem.ID()+"'," +"'"+((container!=null)?(""+container):"")+"'," +"'"+text+" '," +thisItem.baseEnvStats().rejuv()+"," +thisItem.usesRemaining()+"," +thisItem.baseEnvStats().level()+"," +thisItem.baseEnvStats().ability()+"," +thisItem.baseEnvStats().height()+")"; } public void DBCreateThisItem(String roomID, Item thisItem) { DB.update(getDBCreateItemString(roomID,thisItem)); } public void DBUpdateTheseItems(Room room, Vector items) { if((!room.savable())||(room.amDestroyed())) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROIT")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Start item update for room "+room.roomID()); Vector statements=new Vector(); statements.addElement("DELETE FROM CMROIT WHERE CMROID='"+room.roomID()+"'"); for(int i=0;i<items.size();i++) { Item thisItem=(Item)items.elementAt(i); statements.addElement(getDBCreateItemString(room.roomID(),thisItem)); } DB.update(CMParms.toStringArray(statements)); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROIT")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Finished items update for room "+room.roomID()); } public void DBUpdateItems(Room room) { if((!room.savable())||(room.amDestroyed())) return; DBUpdateTheseItems(room,DBGetContents(room)); } public void DBUpdateExits(Room room) { if((!room.savable())||(room.amDestroyed())) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROEX")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Starting exit update for room "+room.roomID()); Vector statements=new Vector(); statements.addElement("DELETE FROM CMROEX WHERE CMROID='"+room.roomID()+"'"); for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { Exit thisExit=room.getRawExit(d); Room thisRoom=room.rawDoors()[d]; if(((thisRoom!=null)||(thisExit!=null)) &&((thisRoom==null)||(thisRoom.savable()))) { statements.addElement( "INSERT INTO CMROEX (" +"CMROID, " +"CMDIRE, " +"CMEXID, " +"CMEXTX, " +"CMNRID" +") values (" +"'"+room.roomID()+"'," +d+"," +"'"+((thisExit==null)?" ":thisExit.ID())+"'," +"'"+((thisExit==null)?" ":thisExit.text())+" '," +"'"+((thisRoom==null)?" ":thisRoom.roomID())+"')"); } } if(room instanceof GridLocale) { Vector exits=((GridLocale)room).outerExits(); HashSet done=new HashSet(); int ordinal=0; for(int v=0;v<exits.size();v++) { WorldMap.CrossExit CE=(WorldMap.CrossExit)exits.elementAt(v); Room R=CMLib.map().getRoom(CE.destRoomID); if(R==null) continue; if(R.getGridParent()!=null) R=R.getGridParent(); if((R.savable())&&(!done.contains(R.roomID()))) { done.add(R.roomID()); HashSet oldStrs=new HashSet(); for(int v2=0;v2<exits.size();v2++) { WorldMap.CrossExit CE2=(WorldMap.CrossExit)exits.elementAt(v2); if((CE2.destRoomID.equals(R.roomID()) ||(CE2.destRoomID.startsWith(R.roomID()+"#(")))) { String str=CE2.x+" "+CE2.y+" "+((CE2.out?256:512)|CE2.dir)+" "+CE2.destRoomID.substring(R.roomID().length())+";"; if(!oldStrs.contains(str)) oldStrs.add(str); } } StringBuffer exitStr=new StringBuffer(""); for(Iterator a=oldStrs.iterator();a.hasNext();) exitStr.append((String)a.next()); statements.addElement( "INSERT INTO CMROEX (" +"CMROID, " +"CMDIRE, " +"CMEXID, " +"CMEXTX, " +"CMNRID" +") values (" +"'"+room.roomID()+"'," +(256+(++ordinal))+"," +"'Open'," +"'"+exitStr.toString()+"'," +"'"+R.roomID()+"')"); } } } DB.update(CMParms.toStringArray(statements)); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROEX")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Finished exit update for room "+room.roomID()); } public void DBCreateThisMOB(String roomID, MOB thisMOB) { DB.update(getDBCreateMOBString(roomID,thisMOB)); } public String getDBCreateMOBString(String roomID, MOB thisMOB) { if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Creating mob "+thisMOB.name()+" for room "+roomID); boolean catalog=((roomID!=null)&&(roomID.startsWith("CATALOG_"))); String ride=null; if(thisMOB.riding()!=null) ride=""+thisMOB.riding(); else if(thisMOB.amFollowing()!=null) ride=""+thisMOB.amFollowing(); else ride=""; String mobID=""+thisMOB; thisMOB.setDatabaseID(mobID); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Created mob "+thisMOB.name()+" for room "+roomID); if((CMProps.getBoolVar(CMProps.SYSTEMB_MOBNOCACHE))&&(!catalog)) thisMOB.setMiscText("%DBID>"+roomID+mobID.substring(mobID.indexOf("@"))); return "INSERT INTO CMROCH (" +"CMROID, " +"CMCHNM, " +"CMCHID, " +"CMCHTX, " +"CMCHLV, " +"CMCHAB, " +"CMCHRE, " +"CMCHRI " +") values (" +"'"+roomID+"'," +"'"+mobID+"'," +"'"+CMClass.classID(thisMOB)+"'," +"'"+thisMOB.text()+" '," +thisMOB.baseEnvStats().level()+"," +thisMOB.baseEnvStats().ability()+"," +thisMOB.baseEnvStats().rejuv()+"," +"'"+ride+"'" +")"; } public void DBUpdateTheseMOBs(Room room, Vector mobs) { if((!room.savable())||(room.amDestroyed())) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Updating mobs for room "+room.roomID()); if(mobs==null) mobs=new Vector(); Vector statements=new Vector(); statements.addElement("DELETE FROM CMROCH WHERE CMROID='"+room.roomID()+"'"); for(int m=0;m<mobs.size();m++) { MOB thisMOB=(MOB)mobs.elementAt(m); statements.addElement(getDBCreateMOBString(room.roomID(),thisMOB)); } if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating mobs for room "+room.roomID()); DB.update(CMParms.toStringArray(statements)); } public void DBUpdateMOBs(Room room) { if((!room.savable())||(room.amDestroyed())) return; Vector mobs=new Vector(); for(int m=0;m<room.numInhabitants();m++) { MOB thisMOB=room.fetchInhabitant(m); if((thisMOB!=null)&&(thisMOB.savable())) mobs.addElement(thisMOB); } DBUpdateTheseMOBs(room,mobs); } public void DBUpdateAll(Room room) { if((!room.savable())||(room.amDestroyed())) return; DBUpdateRoom(room); DBUpdateMOBs(room); DBUpdateExits(room); DBUpdateItems(room); } public void DBUpdateRoom(Room room) { if((!room.savable())||(room.amDestroyed())) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROOM")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Start updating room "+room.roomID()); DB.update( "UPDATE CMROOM SET " +"CMLOID='"+CMClass.classID(room)+"'," +"CMAREA='"+room.getArea().Name()+"'," +"CMDESC1='"+room.displayText()+" '," +"CMDESC2='"+room.description()+" '," +"CMROTX='"+room.text()+" '" +"WHERE CMROID='"+room.roomID()+"'"); if(CMProps.getBoolVar(CMProps.SYSTEMB_ROOMDNOCACHE)) room.setDescription(""); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROOM")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating room "+room.roomID()); } public void DBReCreate(Room room, String oldID) { if((!room.savable())||(room.amDestroyed())) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROOM")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Recreating room "+room.roomID()); DB.update( "UPDATE CMROOM SET " +"CMROID='"+room.roomID()+"', " +"CMAREA='"+room.getArea().Name()+"' " +"WHERE CMROID='"+oldID+"'"); if(CMProps.getBoolVar(CMProps.SYSTEMB_MOBNOCACHE)) for(int m=0;m<room.numInhabitants();m++) { MOB M=room.fetchInhabitant(m); if((M!=null)&&(M.savable())) M.setMiscText(M.text()); } DB.update( "UPDATE CMROCH SET " +"CMROID='"+room.roomID()+"' " +"WHERE CMROID='"+oldID+"'"); DB.update( "UPDATE CMROEX SET " +"CMROID='"+room.roomID()+"' " +"WHERE CMROID='"+oldID+"'"); DB.update( "UPDATE CMROEX SET " +"CMNRID='"+room.roomID()+"' " +"WHERE CMNRID='"+oldID+"'"); DB.update( "UPDATE CMROIT SET " +"CMROID='"+room.roomID()+"' " +"WHERE CMROID='"+oldID+"'"); DB.update( "UPDATE CMCHAR SET " +"CMROID='"+room.roomID()+"' " +"WHERE CMROID='"+oldID+"'"); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROOM")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done recreating room "+room.roomID()); } public void DBCreate(Area A) { if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMAREA")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Creating area "+A.name()); if((A==null)||(A.name().length()==0)) { Log.errOut("RoomLoader","Unable to create area "+((A!=null)?A.name():"null")); return; } //CMLib.map().addArea(A); // not sure why I ever toyed with this idea, but apparantly I did. DB.update( "INSERT INTO CMAREA (" +"CMAREA," +"CMTYPE," +"CMCLIM," +"CMSUBS," +"CMDESC," +"CMROTX," +"CMTECH" +") values (" +"'"+A.Name()+"'," +"'"+A.ID()+"'," +""+A.climateType()+"," +"'"+A.getSubOpList()+"'," +"'"+A.description()+" '," +"'"+A.text()+" '," +A.getTechLevel()+")"); A.setAreaState(Area.STATE_ACTIVE); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMAREA")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done creating area "+A.name()); } public void DBUpdate(String keyName,Area A) { if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMAREA")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Updating area "+A.name()); boolean ignoreType=CMSecurity.isDisabled("FATAREAS")||CMSecurity.isDisabled("THINAREAS"); DB.update( "UPDATE CMAREA SET " +"CMAREA='"+A.Name()+"'," +(ignoreType?"":"CMTYPE='"+A.ID()+"',") +"CMCLIM="+A.climateType()+"," +"CMSUBS='"+A.getSubOpList()+"'," +"CMDESC='"+A.description()+" '," +"CMROTX='"+A.text()+" '," +"CMTECH="+A.getTechLevel()+" " +"WHERE CMAREA='"+keyName+"'"); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMAREA")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating area "+A.name()); } public void DBDeleteRoomItem(String roomID, Item item) { String keyName=item.databaseID(); if(keyName.length()==0) keyName=""+item; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROIT")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating item "+item.name()+" in room "+roomID); DB.update( "DELETE FROM CMROIT " +"WHERE CMROID='"+roomID+"' " +"AND CMITNM='"+keyName+"'"); } public void DBUpdateRoomItem(String roomID, Item item) { if((roomID==null)||(!item.savable())||(item.amDestroyed())) return; synchronized(roomID.toUpperCase().intern()) { DBDeleteRoomItem(roomID,item); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROIT")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Continue updating item "+item.name()+" in room "+roomID); DBCreateThisItem(roomID,item); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROIT")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating item "+item.name()+" in room "+roomID); } } public void DBDeleteRoomMOB(String roomID, MOB mob) { String keyName=mob.databaseID(); if(keyName.length()==0) keyName=""+mob; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating mob "+mob.name()+" in room "+roomID); DB.update( "DELETE FROM CMROCH " +"WHERE CMROID='"+roomID+"' " +"AND CMCHNM='"+keyName+"'"); } public void DBUpdateRoomMOB(String roomID, MOB mob) { if((roomID==null)||(!mob.savable())||(mob.amDestroyed())) return; DBDeleteRoomMOB(roomID, mob); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Continue updating mob "+mob.name()+" in room "+roomID); DBCreateThisMOB(roomID,mob); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done updating mob "+mob.name()+" in room "+roomID); } public void DBDelete(Area A) { if(A==null) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMAREA")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Destroying area "+A.name()); A.setAreaState(Area.STATE_STOPPED); DB.update("DELETE FROM CMAREA WHERE CMAREA='"+A.Name()+"'"); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMAREA")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done destroying area "+A.name()+"."); } public void DBCreate(Room room) { if(!room.savable()) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROOM")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Creating new room "+room.roomID()); DB.update( "INSERT INTO CMROOM (" +"CMROID," +"CMLOID," +"CMAREA," +"CMDESC1," +"CMDESC2," +"CMROTX" +") values (" +"'"+room.roomID()+"'," +"'"+CMClass.classID(room)+"'," +"'"+room.getArea().Name()+"'," +"'"+room.displayText()+" '," +"'"+room.description()+" '," +"'"+room.text()+" ')"); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROOM")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done creating new room "+room.roomID()); } public void DBDelete(Room room) { if(!room.savable()) return; if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Destroying room "+room.roomID()); room.destroy(); DB.update("DELETE FROM CMROCH WHERE CMROID='"+room.roomID()+"'"); DB.update("DELETE FROM CMROIT WHERE CMROID='"+room.roomID()+"'"); DB.update("DELETE FROM CMROEX WHERE CMROID='"+room.roomID()+"'"); DB.update("DELETE FROM CMROOM WHERE CMROID='"+room.roomID()+"'"); room.destroy(); if(Log.debugChannelOn()&&(CMSecurity.isDebugging("CMROCH")||CMSecurity.isDebugging("DBROOMS"))) Log.debugOut("RoomLoader","Done gestroying room "+room.roomID()); } }
3e003d7aa9fbe5e94a99f42a35eb4451e6c206eb
2,065
java
Java
SkyControl/SkyControl/src/com/bocekm/skycontrol/mavlink/MavLinkHeartbeat.java
bocekm/SkyControl
158630eab3c70326f83245d038198f359ba09a38
[ "Apache-2.0" ]
null
null
null
SkyControl/SkyControl/src/com/bocekm/skycontrol/mavlink/MavLinkHeartbeat.java
bocekm/SkyControl
158630eab3c70326f83245d038198f359ba09a38
[ "Apache-2.0" ]
null
null
null
SkyControl/SkyControl/src/com/bocekm/skycontrol/mavlink/MavLinkHeartbeat.java
bocekm/SkyControl
158630eab3c70326f83245d038198f359ba09a38
[ "Apache-2.0" ]
null
null
null
37.545455
101
0.715254
113
/* * Copyright (c) 2014, Michal Bocek, All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.bocekm.skycontrol.mavlink; import com.MAVLink.Messages.MAVLinkPacket; import com.MAVLink.Messages.ardupilotmega.msg_heartbeat; import com.MAVLink.Messages.enums.MAV_AUTOPILOT; import com.MAVLink.Messages.enums.MAV_MODE_FLAG; import com.MAVLink.Messages.enums.MAV_STATE; import com.MAVLink.Messages.enums.MAV_TYPE; import com.bocekm.skycontrol.connection.Connection; /** * {@link MavLinkHeartbeat} sends heartbeat messages to a vehicle with specific period. */ public class MavLinkHeartbeat { /** * Heartbeat message to be packed to form a MavLink packet. */ private static final msg_heartbeat sMsg = new msg_heartbeat(); static { sMsg.type = MAV_TYPE.MAV_TYPE_GCS; sMsg.autopilot = MAV_AUTOPILOT.MAV_AUTOPILOT_INVALID; sMsg.base_mode = MAV_MODE_FLAG.MAV_MODE_FLAG_AUTO_ENABLED; sMsg.custom_mode = 0; sMsg.system_status = MAV_STATE.MAV_STATE_ACTIVE; } /** * Heartbeat MavLink packet. After sending into airspace, it's purpose is to check that * autopilot equipped vehicle is present and is responding. */ private static final MAVLinkPacket sMsgPacket = sMsg.pack(); /** * Sends the heartbeat to the air, expecting response if any vehicle is in range. */ public static void sendHeartbeat() { Connection.get().getMavLinkClient().sendMavPacket(sMsgPacket); } }
3e003d9423bc216ca0e9f9a981428dabfcde2afc
2,298
java
Java
src/main/java/org/dynaform/web/demo/XmlEditWidget.java
reinra/dynaform
11a689258a147109469577353141fdb17072ab01
[ "Artistic-2.0" ]
10
2015-03-16T10:35:41.000Z
2021-02-24T14:36:52.000Z
src/main/java/org/dynaform/web/demo/XmlEditWidget.java
reinra/dynaform
11a689258a147109469577353141fdb17072ab01
[ "Artistic-2.0" ]
3
2015-03-13T07:54:14.000Z
2018-04-05T19:12:17.000Z
src/main/java/org/dynaform/web/demo/XmlEditWidget.java
reinra/dynaform
11a689258a147109469577353141fdb17072ab01
[ "Artistic-2.0" ]
16
2015-01-24T14:20:55.000Z
2020-05-29T06:51:31.000Z
28.725
92
0.693211
114
package org.dynaform.web.demo; import org.dynaform.xml.XmlUtil; import org.dynaform.xml.writer.XmlWriter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.araneaframework.uilib.core.BaseUIWidget; import org.araneaframework.uilib.form.FormWidget; import org.araneaframework.uilib.form.control.TextareaControl; import org.araneaframework.uilib.form.data.StringData; public class XmlEditWidget extends BaseUIWidget { private static final Log log = LogFactory.getLog(XmlEditWidget.class); private static final long serialVersionUID = 1L; private final FormWidget form = new FormWidget(); protected void init() throws Exception { setViewSelector("xmlEdit"); form.addElement("xml", "#XML", new TextareaControl(), new StringData(), getXml(), true); addWidget("f", form); } private String getXml() { XmlWriter writer = getContext().getXmlForm().getWriter(); return XmlUtil.writeXml(writer); } private SchemaContext getContext() { return (SchemaContext) getEnvironment().requireEntry(SchemaContext.class); } public void handleEventXsdView() { if (storeData()) getContext().selectSchemaView(); } public void handleEventFormEdit() { if (storeData()) getContext().selectFormEdit(); } public void handleEventMetadataEdit() { if (storeData()) getContext().selectMetadataEdit(); } public void handleEventSave() { if (storeData()) getMessageCtx().showInfoMessage("Data saved successfully."); } public void handleEventReset() { form.setValueByFullName("xml", getXml()); getMessageCtx().showInfoMessage("Data was reset successfully."); } private boolean storeData() { if (form.convertAndValidate()) { String xml = (String) form.getValueByFullName("xml"); try { if (log.isDebugEnabled()) log.debug("Starting to read XML"); XmlUtil.readXml(xml, getContext().getXmlForm().getReader()); if (log.isDebugEnabled()) log.debug("Finished reading XML"); return true; } catch (RuntimeException e) { log.error("Could not read the XML", e); getMessageCtx().showErrorMessage("Could not read the XML, see log for details"); } } return false; } }
3e003ddbffad8f78ce63080d79d373c4740d2796
15,111
java
Java
main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/transactions/sales/InvoiceExpCost.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/transactions/sales/InvoiceExpCost.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/transactions/sales/InvoiceExpCost.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
23.759434
131
0.543908
115
package com.netsuite.webservices.transactions.sales; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import com.netsuite.webservices.platform.core.RecordRef; /** * <p>Java class for InvoiceExpCost complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="InvoiceExpCost"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="apply" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/&gt; * &lt;element name="doc" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/&gt; * &lt;element name="line" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/&gt; * &lt;element name="billedDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/&gt; * &lt;element name="jobDisp" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="employeeDisp" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="categoryDisp" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="memo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="department" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="class" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="location" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="originalAmount" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/&gt; * &lt;element name="amount" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/&gt; * &lt;element name="taxableDisp" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="revRecSchedule" type="{urn:core_2014_2.platform.webservices.netsuite.com}RecordRef" minOccurs="0"/&gt; * &lt;element name="revRecStartDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/&gt; * &lt;element name="revRecEndDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/&gt; * &lt;element name="grossAmt" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/&gt; * &lt;element name="tax1Amt" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/&gt; * &lt;element name="taxCode" type="{urn:core_2014_2.platform.webservices.netsuite.com}RecordRef" minOccurs="0"/&gt; * &lt;element name="taxRate1" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/&gt; * &lt;element name="taxRate2" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "InvoiceExpCost", propOrder = { "apply", "doc", "line", "billedDate", "jobDisp", "employeeDisp", "categoryDisp", "memo", "department", "clazz", "location", "originalAmount", "amount", "taxableDisp", "revRecSchedule", "revRecStartDate", "revRecEndDate", "grossAmt", "tax1Amt", "taxCode", "taxRate1", "taxRate2" }) public class InvoiceExpCost { protected Boolean apply; protected Long doc; protected Long line; @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar billedDate; protected String jobDisp; protected String employeeDisp; protected String categoryDisp; protected String memo; protected String department; @XmlElement(name = "class") protected String clazz; protected String location; protected Double originalAmount; protected Double amount; protected String taxableDisp; protected RecordRef revRecSchedule; @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar revRecStartDate; @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar revRecEndDate; protected Double grossAmt; protected Double tax1Amt; protected RecordRef taxCode; protected Double taxRate1; protected Double taxRate2; /** * Gets the value of the apply property. * * @return * possible object is * {@link Boolean } * */ public Boolean isApply() { return apply; } /** * Sets the value of the apply property. * * @param value * allowed object is * {@link Boolean } * */ public void setApply(Boolean value) { this.apply = value; } /** * Gets the value of the doc property. * * @return * possible object is * {@link Long } * */ public Long getDoc() { return doc; } /** * Sets the value of the doc property. * * @param value * allowed object is * {@link Long } * */ public void setDoc(Long value) { this.doc = value; } /** * Gets the value of the line property. * * @return * possible object is * {@link Long } * */ public Long getLine() { return line; } /** * Sets the value of the line property. * * @param value * allowed object is * {@link Long } * */ public void setLine(Long value) { this.line = value; } /** * Gets the value of the billedDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getBilledDate() { return billedDate; } /** * Sets the value of the billedDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setBilledDate(XMLGregorianCalendar value) { this.billedDate = value; } /** * Gets the value of the jobDisp property. * * @return * possible object is * {@link String } * */ public String getJobDisp() { return jobDisp; } /** * Sets the value of the jobDisp property. * * @param value * allowed object is * {@link String } * */ public void setJobDisp(String value) { this.jobDisp = value; } /** * Gets the value of the employeeDisp property. * * @return * possible object is * {@link String } * */ public String getEmployeeDisp() { return employeeDisp; } /** * Sets the value of the employeeDisp property. * * @param value * allowed object is * {@link String } * */ public void setEmployeeDisp(String value) { this.employeeDisp = value; } /** * Gets the value of the categoryDisp property. * * @return * possible object is * {@link String } * */ public String getCategoryDisp() { return categoryDisp; } /** * Sets the value of the categoryDisp property. * * @param value * allowed object is * {@link String } * */ public void setCategoryDisp(String value) { this.categoryDisp = value; } /** * Gets the value of the memo property. * * @return * possible object is * {@link String } * */ public String getMemo() { return memo; } /** * Sets the value of the memo property. * * @param value * allowed object is * {@link String } * */ public void setMemo(String value) { this.memo = value; } /** * Gets the value of the department property. * * @return * possible object is * {@link String } * */ public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the location property. * * @return * possible object is * {@link String } * */ public String getLocation() { return location; } /** * Sets the value of the location property. * * @param value * allowed object is * {@link String } * */ public void setLocation(String value) { this.location = value; } /** * Gets the value of the originalAmount property. * * @return * possible object is * {@link Double } * */ public Double getOriginalAmount() { return originalAmount; } /** * Sets the value of the originalAmount property. * * @param value * allowed object is * {@link Double } * */ public void setOriginalAmount(Double value) { this.originalAmount = value; } /** * Gets the value of the amount property. * * @return * possible object is * {@link Double } * */ public Double getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link Double } * */ public void setAmount(Double value) { this.amount = value; } /** * Gets the value of the taxableDisp property. * * @return * possible object is * {@link String } * */ public String getTaxableDisp() { return taxableDisp; } /** * Sets the value of the taxableDisp property. * * @param value * allowed object is * {@link String } * */ public void setTaxableDisp(String value) { this.taxableDisp = value; } /** * Gets the value of the revRecSchedule property. * * @return * possible object is * {@link RecordRef } * */ public RecordRef getRevRecSchedule() { return revRecSchedule; } /** * Sets the value of the revRecSchedule property. * * @param value * allowed object is * {@link RecordRef } * */ public void setRevRecSchedule(RecordRef value) { this.revRecSchedule = value; } /** * Gets the value of the revRecStartDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRevRecStartDate() { return revRecStartDate; } /** * Sets the value of the revRecStartDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRevRecStartDate(XMLGregorianCalendar value) { this.revRecStartDate = value; } /** * Gets the value of the revRecEndDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRevRecEndDate() { return revRecEndDate; } /** * Sets the value of the revRecEndDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRevRecEndDate(XMLGregorianCalendar value) { this.revRecEndDate = value; } /** * Gets the value of the grossAmt property. * * @return * possible object is * {@link Double } * */ public Double getGrossAmt() { return grossAmt; } /** * Sets the value of the grossAmt property. * * @param value * allowed object is * {@link Double } * */ public void setGrossAmt(Double value) { this.grossAmt = value; } /** * Gets the value of the tax1Amt property. * * @return * possible object is * {@link Double } * */ public Double getTax1Amt() { return tax1Amt; } /** * Sets the value of the tax1Amt property. * * @param value * allowed object is * {@link Double } * */ public void setTax1Amt(Double value) { this.tax1Amt = value; } /** * Gets the value of the taxCode property. * * @return * possible object is * {@link RecordRef } * */ public RecordRef getTaxCode() { return taxCode; } /** * Sets the value of the taxCode property. * * @param value * allowed object is * {@link RecordRef } * */ public void setTaxCode(RecordRef value) { this.taxCode = value; } /** * Gets the value of the taxRate1 property. * * @return * possible object is * {@link Double } * */ public Double getTaxRate1() { return taxRate1; } /** * Sets the value of the taxRate1 property. * * @param value * allowed object is * {@link Double } * */ public void setTaxRate1(Double value) { this.taxRate1 = value; } /** * Gets the value of the taxRate2 property. * * @return * possible object is * {@link Double } * */ public Double getTaxRate2() { return taxRate2; } /** * Sets the value of the taxRate2 property. * * @param value * allowed object is * {@link Double } * */ public void setTaxRate2(Double value) { this.taxRate2 = value; } }
3e003e0cd2cc4cab765a7445a38dc6d647e42b8b
4,605
java
Java
jetfuel-core/src/main/java/com/eixox/xml/XmlAspectMember.java
EixoX/jetfuel
d9cd30ef28f14f31ea4d57b2c8c25c7cfc4485ca
[ "Apache-2.0" ]
3
2017-07-18T20:02:18.000Z
2019-02-14T19:53:27.000Z
jetfuel-core/src/main/java/com/eixox/xml/XmlAspectMember.java
EixoX/jetfuel
d9cd30ef28f14f31ea4d57b2c8c25c7cfc4485ca
[ "Apache-2.0" ]
3
2017-07-23T01:31:55.000Z
2017-07-23T01:34:30.000Z
jetfuel-core/src/main/java/com/eixox/xml/XmlAspectMember.java
EixoX/jetfuel
d9cd30ef28f14f31ea4d57b2c8c25c7cfc4485ca
[ "Apache-2.0" ]
2
2017-07-28T01:58:50.000Z
2018-11-02T02:44:13.000Z
27.410714
73
0.692291
116
package com.eixox.xml; import java.lang.reflect.Field; import java.util.List; import com.eixox.JetfuelException; import com.eixox.adapters.ArrayAdapter; import com.eixox.adapters.ListAdapter; import com.eixox.reflection.AspectField; /** * A representation of xml aspect member. * * @author Rodrigo Portela * */ public class XmlAspectMember extends AspectField { /** * The xml adapter that will be used to read and write to xml nodes. */ public final XmlAdapter<?> xmlAdapter; /** * Creates a new instance of the xml aspect member. * * @param field * @param annotation */ public XmlAspectMember(Field field, Xml annotation) { super(field); this.xmlAdapter = createXmlAdapter( annotation.name().isEmpty() ? field.getName() : annotation.name(), annotation); } /** * * @param xmlName * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private XmlAdapter<?> createXmlAdapterForCdata(String xmlName) { // An array of CDATA simple elements? if (this.adapter instanceof ArrayAdapter<?>) { ArrayAdapter<?> arrayAdapter = (ArrayAdapter<?>) this.adapter; return new XmlArrayAdapter( xmlName, new XmlCdataAdapter(arrayAdapter.componentAdapter)); } // A list of CDATA simple elements? else if (this.adapter instanceof ListAdapter<?>) { ListAdapter<?> listAdapter = (ListAdapter<?>) this.adapter; return new XmlListAdapter( xmlName, new XmlCdataAdapter(listAdapter.componentAdapter), listAdapter.dataType); } // A direct parser of cdata elements. else return new XmlCdataAdapter(this.adapter); } @SuppressWarnings({ "rawtypes", "unchecked" }) private XmlAdapter<?> createXmlAdapterForElement(String xmlName) { // Simple elements? if (this.adapter != null) { // An array of simple elements. if (this.adapter instanceof ArrayAdapter<?>) { ArrayAdapter<?> arrayAdapter = (ArrayAdapter<?>) this.adapter; return new XmlArrayAdapter( xmlName, new XmlTextAdapter(arrayAdapter.componentAdapter)); } // A list of simple elements. else if (this.adapter instanceof ListAdapter<?>) { ListAdapter<?> listAdapter = (ListAdapter<?>) this.adapter; return listAdapter.componentAdapter != null ? new XmlListAdapter( xmlName, new XmlTextAdapter(listAdapter.componentAdapter), listAdapter.dataType) : new XmlListAdapter( xmlName, XmlAspect.getInstance(field.getGenericType()), listAdapter.dataType); } // A simple element else return new XmlElementAdapter( xmlName, new XmlTextAdapter(this.adapter)); } // Complex elements, no standard adapter was present. else { Class<?> dataType = this.getDataType(); // An array of complex elements. if (dataType.isArray()) return new XmlArrayAdapter( xmlName, XmlAspect.getInstance(dataType.getComponentType())); // A list of complex elements. else if (List.class.isAssignableFrom(dataType)) return new XmlListAdapter( xmlName, XmlAspect.getInstance(field.getGenericType()), dataType); // A simple element else return new XmlElementAdapter( xmlName, XmlAspect.getInstance(dataType)); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private XmlAdapter<?> createXmlAdapterForText(String xmlName) { // An array of simple text elements? if (this.adapter instanceof ArrayAdapter<?>) { ArrayAdapter<?> arrayAdapter = (ArrayAdapter<?>) this.adapter; return new XmlArrayAdapter( xmlName, new XmlTextAdapter(arrayAdapter.componentAdapter)); } // A list of simple text elements? else if (this.adapter instanceof ListAdapter<?>) { ListAdapter<?> listAdapter = (ListAdapter<?>) this.adapter; return new XmlListAdapter( xmlName, new XmlTextAdapter(listAdapter.componentAdapter), listAdapter.dataType); } // A direct parser of text elements. else return new XmlTextAdapter(this.adapter); } @SuppressWarnings({ "unchecked", "rawtypes" }) private XmlAdapter<?> createXmlAdapter(String xmlName, Xml annotation) { switch (annotation.type()) { case ATTRIBUTE: return new XmlAttributeAdapter(xmlName, this.adapter); case CDATA: return createXmlAdapterForCdata(xmlName); case ELEMENT: return createXmlAdapterForElement(xmlName); case TEXT: return createXmlAdapterForText(xmlName); default: throw new JetfuelException("Can't create xml adapters for xml type " + annotation.type() + " on " + field + " in " + field.getDeclaringClass()); } } }
3e003e1fbeda899c7a0fca257e659eab7f23b1c9
8,431
java
Java
icarus2-manifest-api/src/main/java/de/ims/icarus2/model/manifest/api/AnnotationManifest.java
ICARUS-tooling/icarus2-modeling-framework
8bac9b33905fb66fd8a6f5e0973523c8e904adb1
[ "ECL-2.0", "Apache-2.0" ]
1
2019-01-26T04:59:48.000Z
2019-01-26T04:59:48.000Z
icarus2-manifest-api/src/main/java/de/ims/icarus2/model/manifest/api/AnnotationManifest.java
ICARUS-tooling/icarus2-modeling-framework
8bac9b33905fb66fd8a6f5e0973523c8e904adb1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
icarus2-manifest-api/src/main/java/de/ims/icarus2/model/manifest/api/AnnotationManifest.java
ICARUS-tooling/icarus2-modeling-framework
8bac9b33905fb66fd8a6f5e0973523c8e904adb1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
32.007576
100
0.713254
117
/* * ICARUS2 Corpus Modeling Framework * Copyright (C) 2014-2021 Markus Gärtner <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.ims.icarus2.model.manifest.api; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import javax.annotation.Nullable; import de.ims.icarus2.GlobalErrorCode; import de.ims.icarus2.model.manifest.types.ValueType; import de.ims.icarus2.util.access.AccessControl; import de.ims.icarus2.util.access.AccessMode; import de.ims.icarus2.util.access.AccessPolicy; import de.ims.icarus2.util.access.AccessRestriction; import de.ims.icarus2.util.collections.LazyCollection; import de.ims.icarus2.util.data.ContentType; /** * Describes a single annotation within an {@link AnnotationLayerManifest annotation layer}. * Such an annotation is always identified by exactly {@code 1} <i>key</i> that must be unique * within the surrounding layer. In addition an arbitrary number of <i>aliases</i> can be provided. * Unlike an annotation's primary key those alias keys are not required to be unique, but will be * prioritized lower than primary keys during a resolution process. * <p> * TODO outline value sets/ranges/defaults and content-type settings + inheritance! * * @author Markus Gärtner * */ @AccessControl(AccessPolicy.DENY) public interface AnnotationManifest extends MemberManifest<AnnotationManifest>, Embedded { public static final boolean DEFAULT_ALLOW_UNKNOWN_VALUES = false; /** * @see de.ims.icarus2.model.manifest.api.MemberManifest#getManifestType() */ @Override default ManifestType getManifestType() { return ManifestType.ANNOTATION_MANIFEST; } /** * Returns the hosting layer manifest or an empty {@link Optional} if this manifest * is a template. * * @return */ default <M extends AnnotationLayerManifest> Optional<M> getLayerManifest() { return getHost(); } /** * Returns the <i>base-name</i> of the key this manifest * describes. * @return */ @AccessRestriction(AccessMode.READ) Optional<String> getKey(); /** * Returns {@code true} iff the primary key used for this annotation has * been declared locally. * * @return */ boolean isLocalKey(); /** * Applies the given {@code action} to all aliases in this manifest, * including both locally defined and inherited ones. * <p> * This method should first apply the action to inherited aliases * before traversing local ones. * * @param action */ @AccessRestriction(AccessMode.READ) void forEachAlias(Consumer<? super String> action); /** * Returns {@code true} if the given {@code alias} has been declared locally. * * @param alias * @return */ boolean isLocalAlias(String alias); /** * Applies the given {@code action} only to locally defined aliases. * * @param action */ @AccessRestriction(AccessMode.READ) default void forEachLocalAlias(Consumer<? super String> action) { forEachAlias(a -> { if(isLocalAlias(a)) { action.accept(a); } }); } /** * Returns a list of supported aliases that can be used for this * manifest's key. If the key does not have any aliases this method * should return an empty list. * @return */ @AccessRestriction(AccessMode.READ) default List<String> getAliases() { LazyCollection<String> result = LazyCollection.lazyList(); forEachAlias(result); return result.getAsList(); } /** * Returns a list only containing the aliases for this annotation which * have been declared within this very manifest. * If there are no local aliases defined for this manifest the method * should return an empty list. * * @return */ @AccessRestriction(AccessMode.READ) default List<String> getLocalAliases() { LazyCollection<String> result = LazyCollection.lazyList(); forEachLocalAlias(result); return result.getAsList(); } /** * Tells whether or not this annotation accepts values outside the predefined * ones obtainable via the following methods: * <p> * <ul> * <li>{@link #getValueRange()}</li> * <li>{@link #getValueSet()}</li> * </ul> * Note that in the case this method returns {@code false} <i>at least one</i> * of those methods {@code must} return a valid object that describes * the bounds of supported values. * <p> * This is <b>not</b> an inheritable property! * * @return {@code true} if and only if this annotation accepts values outside a * predefined and limited set or range. * @see #getValueRange() * @see #getValueSet() * @see #DEFAULT_ALLOW_UNKNOWN_VALUES */ @AccessRestriction(AccessMode.READ) boolean isAllowUnknownValues(); /** * Returns an object that describes the set of available values for this annotation * by means of a lower and upper bound or an empty {@link Optional} if this annotation is either * unbounded or the values are wrapped into an iterator obtainable via the * {@link #getValueSet()} method. Note that as a convention the {@code ValueRange} * class should only wrap bound objects that implement the {@link Comparable} interface * so that there is an easy way to actually use the bounds provided by the range object. * Since the returned {@code ValueRange} only provides the boundary values, the * {@link #getValueType()} method must be used to determine the type of those bounds. * * @return * @see Comparable */ @AccessRestriction(AccessMode.READ) Optional<ValueRange> getValueRange(); boolean isLocalValueRange(); /** * Returns a new iterator to traverse possible values of this annotation or * an empty {@link Optional} if the set of possible annotations is unbounded. Note that * for very large sets of values (especially numerical), it is far cheaper to * use the {@link #getValueRange()} method and return a {@code ValueRange} * object that describes the collection of supported values by means of an * lower and upper bound, instead of generating an iterator that traverses all * the values one by one. * @return */ @AccessRestriction(AccessMode.READ) Optional<ValueSet> getValueSet(); boolean isLocalValueSet(); /** * Returns the type of this annotation. * * @throws ManifestException of type {@link GlobalErrorCode#ILLEGAL_STATE} * if the value type is not set. */ @AccessRestriction(AccessMode.READ) ValueType getValueType(); boolean isLocalValueType(); /** * For primitive annotation types ({@code int}, {@code float}, etc...) this method * returns the wrapped primitive value that is to be treated as a hint for missing * annotation values. For non-primitive annotations it typically returns * an empty {@link Optional}. * * @return */ @AccessRestriction(AccessMode.READ) Optional<Object> getNoEntryValue(); boolean isLocalNoEntryValue(); /** * For annotations of type {@value ValueType#CUSTOM} this method returns the * required {@code ContentType}. For all other value types, the returned value * is an empty {@link Optional}. * * @return */ @AccessRestriction(AccessMode.READ) Optional<ContentType> getContentType(); boolean isLocalContentType(); // Modification methods AnnotationManifest setKey(String key); AnnotationManifest addAlias(String alias); AnnotationManifest removeAlias(String alias); AnnotationManifest setValueRange(@Nullable ValueRange range); AnnotationManifest setValueSet(@Nullable ValueSet values); AnnotationManifest setValueType(ValueType valueType); AnnotationManifest setContentType(@Nullable ContentType contentType); AnnotationManifest setNoEntryValue(@Nullable Object noEntryValue); AnnotationManifest setAllowUnknownValues(boolean allowUnknownValues); }
3e003e5f2a5cd8a0fe10c7bb43f0cd64c6538939
14,646
java
Java
Stock Screener/src/application/files/Webscraper.java
RollinsonSoftware/Stock-Sort
1ea7d2620760e5258975599f94196e3c9872aef4
[ "MIT" ]
null
null
null
Stock Screener/src/application/files/Webscraper.java
RollinsonSoftware/Stock-Sort
1ea7d2620760e5258975599f94196e3c9872aef4
[ "MIT" ]
null
null
null
Stock Screener/src/application/files/Webscraper.java
RollinsonSoftware/Stock-Sort
1ea7d2620760e5258975599f94196e3c9872aef4
[ "MIT" ]
null
null
null
33.210884
107
0.465383
118
package application.files; import java.io.IOException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Scanner; import java.util.Calendar; import yahoofinance.Stock; import yahoofinance.YahooFinance; import yahoofinance.histquotes.Interval; import yahoofinance.quotes.fx.FxQuote; import yahoofinance.quotes.fx.FxSymbols; import yahoofinance.quotes.stock.StockQuote; import yahoofinance.quotes.stock.StockStats; //Output all stock data to a text file, data must be stored as primitives or strings. // Version 0.1 @SuppressWarnings("unused") public class Webscraper { protected static ArrayList<Stock> watchList = new ArrayList<>(10); protected static PrintWriter outputStream = null; protected static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) throws IOException { //Reading all the ticker symbols from the watch list text file. try { Scanner input = new Scanner(new FileInputStream("watchList.txt")); while (input.hasNextLine()) { String temp; try { temp = input.nextLine(); watchList.add(YahooFinance.get(temp.toUpperCase())); } catch (IOException e) { System.out.println("Ticker Symbol could not be found..."); System.exit(0); } } input.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); System.out.println("\nLoading Defualt values..."); watchList.add(YahooFinance.get("INTC")); watchList.add(YahooFinance.get("NVDA")); watchList.add(YahooFinance.get("MU")); watchList.add(YahooFinance.get("QCOM")); watchList.add(YahooFinance.get("TXN")); watchList.add(YahooFinance.get("MSFT")); watchList.add(YahooFinance.get("AAPL")); watchList.add(YahooFinance.get("IBM")); watchList.add(YahooFinance.get("RTN")); watchList.add(YahooFinance.get("AMD")); watchList.add(YahooFinance.get("BRK-B")); watchList.add(YahooFinance.get("F")); watchList.add(YahooFinance.get("FCAU")); watchList.add(YahooFinance.get("T")); watchList.add(YahooFinance.get("TXN")); watchList.add(YahooFinance.get("CLX")); watchList.add(YahooFinance.get("DUK")); } //Printing the watchList to the console. for(Stock company : watchList) { company.print(); System.out.println(" "); } //Updating the stockData.txt with the current watchList. try { outputStream = new PrintWriter(new FileOutputStream("StockData.txt")); } catch(IOException e) { System.out.println("Output/Input Stream could not be established."); e.printStackTrace(); } for(Stock company : watchList) { StockQuote current = company.getQuote(); StockStats stat = company.getStats(); outputStream.println(company.getName()); //Company name outputStream.println(current.getSymbol()); //Company ticker symbol. if(current.getYearHigh() == null) { outputStream.println(0); } else { outputStream.println(current.getYearHigh().doubleValue()); } if(current.getYearLow() == null) { outputStream.println(0); } else { outputStream.println(current.getYearLow().doubleValue()); } if(current.getOpen() == null) { outputStream.println(0); } else { outputStream.println(current.getOpen().doubleValue()); } if(current.getPreviousClose() == null) { outputStream.println(0); } else { outputStream.println(current.getPreviousClose().doubleValue()); } if(current.getPriceAvg200() == null) { outputStream.println(0); } else { outputStream.println(current.getPriceAvg200().doubleValue()); } if(current.getPriceAvg50() == null) { outputStream.println(0); } else { outputStream.println(current.getPriceAvg50().doubleValue()); } if(current.getVolume() == null) { outputStream.println(0); } else { outputStream.println(current.getVolume().intValue()); } if(stat.getMarketCap() == null) { outputStream.println(0); } else { outputStream.println(stat.getMarketCap().doubleValue()); // Market Cap } if(stat.getRevenue() == null) { outputStream.println(0); } else { outputStream.println(stat.getRevenue().doubleValue()); //Last quarters revenue. } if(stat.getEps() == null) { outputStream.println(0); } else { outputStream.println(stat.getEps().doubleValue()); } if(stat.getEpsEstimateNextQuarter() == null) { outputStream.println(0); } else { outputStream.println(stat.getEpsEstimateNextQuarter().doubleValue()); } if(stat.getEpsEstimateNextYear() == null) { outputStream.println(0); } else { outputStream.println(stat.getEpsEstimateNextYear().doubleValue()); } if(stat.getOneYearTargetPrice() == null) { outputStream.println(0); } else { outputStream.println(stat.getOneYearTargetPrice().doubleValue()); } if(stat.getBookValuePerShare() == null) { outputStream.println(0); } else { outputStream.println(stat.getBookValuePerShare().doubleValue()); } if(stat.getPriceBook() == null) { outputStream.println(0); } else { outputStream.println(stat.getPriceBook().doubleValue()); } } System.out.println("\nAll stock data has been written to the file.\n\n"); outputStream.close(); keyboard.close(); /* //how to get individual stock information. StockStats amdStat = amd.getStats(); double shortRatio = amdStat.getShortRatio().doubleValue(); //Converting a BigDecimal to a primitive. System.out.println("------------------------------"); System.out.println(amd.getName()); System.out.println("Ticker Symbol: " + amdStat.getSymbol()); System.out.println("Market Cap: " + amdStat.getMarketCap()); System.out.println("------------------------------"); //Most of these values are stored as BigDecimals, but can be converted with .doubleValue() System.out.println("One Year Price Target: " + amdStat.getOneYearTargetPrice()); System.out.println("EPS: " + amdStat.getEps()); System.out.println("EPS Current Year: " + amdStat.getEpsEstimateCurrentYear()); System.out.println("EPS Next Quarters Estimate: " + amdStat.getEpsEstimateNextQuarter()); System.out.println("EPS Next Years Estimate: " + amdStat.getEpsEstimateNextYear()); System.out.println("Book Value: " + amdStat.getBookValuePerShare()); System.out.println("Price to Book: " + amdStat.getPriceBook()); System.out.println("Short Ratio: " + (shortRatio * 100) + "%"); //just testing the doubleValue() method. System.out.println("------------------------------"); */ } public static void add(String stock) { //Doesn't check if the stock is already on the watch list. try { outputStream = new PrintWriter(new FileOutputStream("watchList.txt", true)); } catch(IOException e) { System.out.println("Output/Input Stream could not be established."); e.printStackTrace(); } outputStream.println(stock); outputStream.close(); } //Lowell is using for the add button on the watch list tab. protected static void saveStockData() { try { outputStream = new PrintWriter(new FileOutputStream("StockData.txt")); } catch(IOException e) { System.out.println("Output/Input Stream could not be established."); e.printStackTrace(); } for(Stock company : watchList) { StockQuote current = company.getQuote(); StockStats stat = company.getStats(); outputStream.println(company.getName()); //Company name outputStream.println(current.getSymbol()); //Company ticker symbol. if(current.getYearHigh() == null) { outputStream.println(0); } else { outputStream.println(current.getYearHigh().doubleValue()); } if(current.getYearLow() == null) { outputStream.println(0); } else { outputStream.println(current.getYearLow().doubleValue()); } if(current.getOpen() == null) { outputStream.println(0); } else { outputStream.println(current.getOpen().doubleValue()); } if(current.getPreviousClose() == null) { outputStream.println(0); } else { outputStream.println(current.getPreviousClose().doubleValue()); } if(current.getPriceAvg200() == null) { outputStream.println(0); } else { outputStream.println(current.getPriceAvg200().doubleValue()); } if(current.getPriceAvg50() == null) { outputStream.println(0); } else { outputStream.println(current.getPriceAvg50().doubleValue()); } if(current.getVolume() == null) { outputStream.println(0); } else { outputStream.println(current.getVolume().intValue()); } if(stat.getMarketCap() == null) { outputStream.println(0); } else { outputStream.println(stat.getMarketCap().doubleValue()); // Market Cap } if(stat.getRevenue() == null) { outputStream.println(0); } else { outputStream.println(stat.getRevenue().doubleValue()); //Last quarters revenue. } if(stat.getEps() == null) { outputStream.println(0); } else { outputStream.println(stat.getEps().doubleValue()); } if(stat.getEpsEstimateNextQuarter() == null) { outputStream.println(0); } else { outputStream.println(stat.getEpsEstimateNextQuarter().doubleValue()); } if(stat.getEpsEstimateNextYear() == null) { outputStream.println(0); } else { outputStream.println(stat.getEpsEstimateNextYear().doubleValue()); } if(stat.getOneYearTargetPrice() == null) { outputStream.println(0); } else { outputStream.println(stat.getOneYearTargetPrice().doubleValue()); } if(stat.getBookValuePerShare() == null) { outputStream.println(0); } else { outputStream.println(stat.getBookValuePerShare().doubleValue()); } if(stat.getPriceBook() == null) { outputStream.println(0); } else { outputStream.println(stat.getPriceBook().doubleValue()); } } System.out.println("\nAll stock data has been written to the file.\n\n"); outputStream.close(); } }
3e003ee06d18edc83af1ae806d5760481c40f6ce
1,988
java
Java
src/main/java/artifacts/common/item/AntidoteVesselItem.java
BLFiedler/artifacts
8c8a29cb1d120420c564e8adc4e1df2283c97978
[ "MIT" ]
null
null
null
src/main/java/artifacts/common/item/AntidoteVesselItem.java
BLFiedler/artifacts
8c8a29cb1d120420c564e8adc4e1df2283c97978
[ "MIT" ]
null
null
null
src/main/java/artifacts/common/item/AntidoteVesselItem.java
BLFiedler/artifacts
8c8a29cb1d120420c564e8adc4e1df2283c97978
[ "MIT" ]
null
null
null
35.5
167
0.730885
119
package artifacts.common.item; import artifacts.Artifacts; import artifacts.client.render.model.curio.AntidoteVesselModel; import net.minecraft.client.renderer.entity.model.BipedModel; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectInstance; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvents; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import top.theillusivec4.curios.api.SlotContext; import top.theillusivec4.curios.api.type.capability.ICurio; import java.util.HashMap; import java.util.Map; public class AntidoteVesselItem extends CurioItem { private static final ResourceLocation TEXTURE = new ResourceLocation(Artifacts.MODID, "textures/entity/curio/antidote_vessel.png"); @Override public ICurio.SoundInfo getEquipSound(SlotContext slotContext, ItemStack stack) { return new ICurio.SoundInfo(SoundEvents.ITEM_BOTTLE_FILL, 1, 1); } @Override public void curioTick(String identifier, int index, LivingEntity entity, ItemStack stack) { Map<Effect, EffectInstance> effects = new HashMap<>(); entity.getActivePotionMap().forEach((effect, instance) -> { if (!effect.isInstant() && !effect.isBeneficial() && instance.getDuration() > 80) { effects.put(effect, instance); } }); effects.forEach((effect, instance) -> { entity.removeActivePotionEffect(effect); entity.addPotionEffect(new EffectInstance(effect, 80, instance.getAmplifier(), instance.isAmbient(), instance.doesShowParticles(), instance.isShowIcon())); }); } @Override @OnlyIn(Dist.CLIENT) protected BipedModel<LivingEntity> createModel() { return new AntidoteVesselModel(); } @Override protected ResourceLocation getTexture() { return TEXTURE; } }
3e003f3ce341c108e24a382ad07d0a6a1c5c8a64
4,056
java
Java
src/main/java/com/google/devtools/build/lib/query2/aquery/AqueryOptions.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
16,989
2015-09-01T19:57:15.000Z
2022-03-31T23:54:00.000Z
src/main/java/com/google/devtools/build/lib/query2/aquery/AqueryOptions.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
12,562
2015-09-01T09:06:01.000Z
2022-03-31T22:26:20.000Z
src/main/java/com/google/devtools/build/lib/query2/aquery/AqueryOptions.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
3,707
2015-09-02T19:20:01.000Z
2022-03-31T17:06:14.000Z
42.25
100
0.711785
120
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.query2.aquery; import com.google.devtools.build.lib.query2.common.CommonQueryOptions; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionDocumentationCategory; import com.google.devtools.common.options.OptionEffectTag; import com.google.devtools.common.options.OptionMetadataTag; /** Options class for aquery specific query options. */ public class AqueryOptions extends CommonQueryOptions { @Option( name = "output", defaultValue = "text", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "The format in which the aquery results should be printed. Allowed values for aquery " + "are: text, textproto, proto, jsonproto.") public String outputFormat; @Option( name = "include_commandline", defaultValue = "true", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "Includes the content of the action command lines in the output (potentially large).") public boolean includeCommandline; @Option( name = "include_artifacts", defaultValue = "true", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "Includes names of the action inputs and outputs in the output " + "(potentially large).") public boolean includeArtifacts; @Option( name = "include_param_files", defaultValue = "false", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "Include the content of the param files used in the command (potentially large). " + "Note: Enabling this flag will automatically enable the " + "--include_commandline flag.") public boolean includeParamFiles; @Option( name = "skyframe_state", defaultValue = "false", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "Without performing extra analysis, dump the current Action Graph from Skyframe. " + "Note: Specifying a target with --skyframe_state is currently not supported. " + "This flag is only available with --output=proto or --output=textproto.") public boolean queryCurrentSkyframeState; @Option( name = "incompatible_proto_output_v2", defaultValue = "true", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, metadataTags = { OptionMetadataTag.INCOMPATIBLE_CHANGE, OptionMetadataTag.DEPRECATED, }, help = "No-op.") public boolean protoV2; @Option( name = "deduplicate_depsets", defaultValue = "true", documentationCategory = OptionDocumentationCategory.QUERY, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "De-duplicate non-leaf children of a dep_set_of_files in the final proto/textproto/json" + " output. This does not deduplicate depsets that don't share an immediate parent." + " This does not affect the final effective list of input artifacts of the actions.") public boolean deduplicateDepsets; }
3e003fec01e79f23ae84e6e99812d5a59c32f17c
135
java
Java
src/remote_first_test/Hello.java
sw-ksnu/remote_first_test
dcb8abc12e8f84b75524333d09604e7ef1980e84
[ "Apache-2.0" ]
null
null
null
src/remote_first_test/Hello.java
sw-ksnu/remote_first_test
dcb8abc12e8f84b75524333d09604e7ef1980e84
[ "Apache-2.0" ]
null
null
null
src/remote_first_test/Hello.java
sw-ksnu/remote_first_test
dcb8abc12e8f84b75524333d09604e7ef1980e84
[ "Apache-2.0" ]
null
null
null
16.875
41
0.718519
121
package remote_first_test; public class Hello { public static void main(String[] args) { System.out.println("Hello Github!"); } }
3e0040508555658c8f01558715604ec9816ae56d
996
java
Java
sources/com/google/android/gms/internal/ads/zzmy.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/com/google/android/gms/internal/ads/zzmy.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/com/google/android/gms/internal/ads/zzmy.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
21.652174
60
0.59739
122
package com.google.android.gms.internal.ads; import android.support.p001v7.widget.LinearLayoutManager; public class zzmy { /* renamed from: a */ private int f28927a; /* renamed from: a */ public void mo32012a() { this.f28927a = 0; } /* renamed from: b */ public final boolean mo32015b() { return mo32017c(LinearLayoutManager.INVALID_OFFSET); } /* renamed from: c */ public final boolean mo32016c() { return mo32017c(4); } /* renamed from: d */ public final boolean mo32018d() { return mo32017c(1); } /* renamed from: a */ public final void mo32013a(int i) { this.f28927a = i; } /* renamed from: b */ public final void mo32014b(int i) { this.f28927a |= LinearLayoutManager.INVALID_OFFSET; } /* access modifiers changed from: protected */ /* renamed from: c */ public final boolean mo32017c(int i) { return (this.f28927a & i) == i; } }
3e00406ad65decd883a71b3b9f205f158f2d7824
915
java
Java
Programas/java/LIBRO_COMM_BD_JAVA_ejemplos/TCP-Codigo/TCPFicheroServidor.java
felipeescallon/lenguajes_programacion
5b88bf2a95492e799c94e414997365a14db05c05
[ "CC0-1.0" ]
1
2021-07-17T03:43:25.000Z
2021-07-17T03:43:25.000Z
Programas/java/LIBRO_COMM_BD_JAVA_ejemplos/TCP-Codigo/TCPFicheroServidor.java
felipeescallon/lenguajes_programacion
5b88bf2a95492e799c94e414997365a14db05c05
[ "CC0-1.0" ]
null
null
null
Programas/java/LIBRO_COMM_BD_JAVA_ejemplos/TCP-Codigo/TCPFicheroServidor.java
felipeescallon/lenguajes_programacion
5b88bf2a95492e799c94e414997365a14db05c05
[ "CC0-1.0" ]
null
null
null
22.317073
80
0.536612
123
import java.io.*; public class TCPFicheroServidor extends TCPServidor { TCPFicheroServidor(int Puerto) { super(Puerto); } public void Comunicacion (DataInputStream Flujo) { final int TAMANIO_BUFFER = 256; byte buffer[] = new byte[TAMANIO_BUFFER]; int NumBytes=0; try { FileOutputStream FicheroDestino = new FileOutputStream("Salida.txt"); try { do { NumBytes = Flujo.read(buffer); FicheroDestino.write(buffer,0,NumBytes); } while (NumBytes==TAMANIO_BUFFER); FicheroDestino.close(); } catch (IOException e){ System.out.println("Error de entrada/salida"); } } catch (FileNotFoundException e) { System.out.println("Fichero no encontrado"); } } }
3e0041e3f0ea5584b9dd0fc8071674b1d454b815
2,399
java
Java
onmsIntegrationExample1/roadfaultintegration/roadfaultapi/src/main/java/org/opennms/poc/api/roadfaultapi/model/MessageContent.java
gallenc/opennms-integrations-play
2a8c5f2d529520957a910cfdc9ce62633079a07f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
onmsIntegrationExample1/roadfaultintegration/roadfaultapi/src/main/java/org/opennms/poc/api/roadfaultapi/model/MessageContent.java
gallenc/opennms-integrations-play
2a8c5f2d529520957a910cfdc9ce62633079a07f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
onmsIntegrationExample1/roadfaultintegration/roadfaultapi/src/main/java/org/opennms/poc/api/roadfaultapi/model/MessageContent.java
gallenc/opennms-integrations-play
2a8c5f2d529520957a910cfdc9ce62633079a07f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
29.256098
222
0.700709
124
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opennms.poc.api.roadfaultapi.model; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Embeddable; import org.opennms.poc.api.roadfaultapi.dao.ListToJsonConverter; /** * * { * "source": "APM-Checkmk", "equipmentClass": "u_server_cluster", "equipmentReference": "openshift12345", "statusTime": "2020-03-26T10:15:40.857Z", * "statusInformation": [ { "statusName": "AV Program Status", "statusValue": "WARN", "statusAdditionalInfo": "" } ] } * * @author cgallen */ @Embeddable public class MessageContent { String source; String equipmentClass; String equipmentReference; List<StatusInformation> statusInformation; Date statusTime; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getEquipmentClass() { return equipmentClass; } public void setEquipmentClass(String equipmentClass) { this.equipmentClass = equipmentClass; } public String getEquipmentReference() { return equipmentReference; } public void setEquipmentReference(String equipmentReference) { this.equipmentReference = equipmentReference; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") public Date getStatusTime() { return statusTime; } public void setStatusTime(Date statusTime) { this.statusTime = statusTime; } @Column(name = "statuslist") @Convert(converter = ListToJsonConverter.class) public List<StatusInformation> getStatusInformation() { return statusInformation; } public void setStatusInformation(List<StatusInformation> statusInformation) { this.statusInformation = statusInformation; } @Override public String toString() { return "MessageContent{" + "source=" + source + ", equipmentClass=" + equipmentClass + ", equipmentReference=" + equipmentReference + ", statusInformation=" + statusInformation + ", statusTime=" + statusTime + '}'; } }
3e0042c9c4dfb2e3e779242b8371de862a8eeecd
4,320
java
Java
research/query_service/ir/compiler/src/main/java/com/alibaba/graphscope/common/intermediate/ArgUtils.java
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
[ "Apache-2.0" ]
1
2021-12-30T02:55:16.000Z
2021-12-30T02:55:16.000Z
research/query_service/ir/compiler/src/main/java/com/alibaba/graphscope/common/intermediate/ArgUtils.java
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
[ "Apache-2.0" ]
null
null
null
research/query_service/ir/compiler/src/main/java/com/alibaba/graphscope/common/intermediate/ArgUtils.java
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
[ "Apache-2.0" ]
null
null
null
33.488372
96
0.634954
125
/* * Copyright 2020 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.graphscope.common.intermediate; import com.alibaba.graphscope.common.exception.OpArgIllegalException; import com.alibaba.graphscope.common.jna.IrCoreLibrary; import com.alibaba.graphscope.common.jna.type.*; public class ArgUtils { private static IrCoreLibrary irCoreLib = IrCoreLibrary.INSTANCE; private static String LABEL = "~label"; private static String ID = "~id"; private static String LEN = "~len"; public static String PROPERTY_ALL = "~all"; public static FfiConst.ByValue asFfiConst(int id) { return irCoreLib.int32AsConst(id); } public static FfiConst.ByValue asFfiConst(long id) { return irCoreLib.int64AsConst(id); } // "" indicates NONE public static FfiProperty.ByValue asFfiProperty(String property) { if (property.isEmpty()) { return irCoreLib.asNoneKey(); } else if (property.equals(LABEL)) { return irCoreLib.asLabelKey(); } else if (property.equals(ID)) { return irCoreLib.asIdKey(); } else if (property.equals(LEN)) { return irCoreLib.asLenKey(); } else { return irCoreLib.asPropertyKey(irCoreLib.cstrAsNameOrId(property)); } } // "" indicates NONE or HEAD public static FfiNameOrId.ByValue asFfiTag(String tag) { if (tag.isEmpty()) { return irCoreLib.noneNameOrId(); } else { return irCoreLib.cstrAsNameOrId(tag); } } public static FfiNameOrId.ByValue asFfiNoneTag() { return irCoreLib.noneNameOrId(); } public static FfiVariable.ByValue asFfiVar(String tag, String property) { FfiNameOrId.ByValue ffiTag = asFfiTag(tag); FfiProperty.ByValue ffiProperty = asFfiProperty(property); return irCoreLib.asVar(ffiTag, ffiProperty); } public static FfiVariable.ByValue asFfiNoneVar() { return irCoreLib.asNoneVar(); } public static FfiAlias.ByValue asFfiNoneAlias() { FfiNameOrId.ByValue alias = irCoreLib.noneNameOrId(); FfiAlias.ByValue ffiAlias = new FfiAlias.ByValue(); ffiAlias.alias = alias; ffiAlias.isQueryGiven = false; return ffiAlias; } public static FfiAlias.ByValue asFfiAlias(String aliasName, boolean isQueryGiven) { FfiNameOrId.ByValue alias = irCoreLib.cstrAsNameOrId(aliasName); FfiAlias.ByValue ffiAlias = new FfiAlias.ByValue(); ffiAlias.alias = alias; ffiAlias.isQueryGiven = isQueryGiven; return ffiAlias; } public static FfiAggFn.ByValue asFfiAggFn(ArgAggFn aggFn) { FfiAggFn.ByValue ffiAggFn = irCoreLib.initAggFn(aggFn.getAggregate(), aggFn.getAlias()); // todo: add var return ffiAggFn; } public static String propertyName(FfiProperty.ByValue property) { switch (property.opt) { case None: return ""; case Id: return ID; case Label: return LABEL; case Len: return LEN; case Key: return property.key.name; default: throw new OpArgIllegalException( OpArgIllegalException.Cause.INVALID_TYPE, "invalid type"); } } public static String tagName(FfiNameOrId.ByValue tag) { switch (tag.opt) { case None: return ""; case Name: return tag.name; case Id: default: throw new OpArgIllegalException( OpArgIllegalException.Cause.INVALID_TYPE, "invalid type"); } } }
3e0043131f2b6f72ca78d4a41976fbf149327fba
1,914
java
Java
Algorithms_Java_Implementation/src/com/akh/hackerrank/easy/AngryProfessor.java
akhr/java
e3b2f2d47a922bbc24fddddf552a4f543793017e
[ "Apache-2.0" ]
1
2019-07-12T01:35:33.000Z
2019-07-12T01:35:33.000Z
Algorithms_Java_Implementation/src/com/akh/hackerrank/easy/AngryProfessor.java
akhr/java
e3b2f2d47a922bbc24fddddf552a4f543793017e
[ "Apache-2.0" ]
5
2021-12-14T21:00:59.000Z
2022-01-04T16:53:16.000Z
Algorithms_Java_Implementation/src/com/akh/hackerrank/easy/AngryProfessor.java
akhr/java
e3b2f2d47a922bbc24fddddf552a4f543793017e
[ "Apache-2.0" ]
null
null
null
23.341463
186
0.687565
126
/** * */ package com.akh.hackerrank.easy; import java.util.Scanner; /** * @author Akhash Ramamurthy * * Feb 18, 2016 5:03:59 PM * AngryProfessor.java */ public class AngryProfessor { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); //For each test case for(int a0 = 0; a0 < t; a0++){ int n = in.nextInt(); int k = in.nextInt(); int studentsOnTime = 0; int a[] = new int[n]; for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextInt(); if(a[a_i] <= 0) studentsOnTime++; if(studentsOnTime >= k){ System.out.println("NO"); break; } } if(studentsOnTime < k) System.out.println("YES"); } } } /** * A Discrete Mathematics professor has a class of NN students. Frustrated with their lack of discipline, he decides to cancel class if fewer than KK students are present when class starts. Given the arrival time of each student, determine if the class is canceled. Input Format The first line of input contains TT, the number of test cases. Each test case consists of two lines. The first line has two space-separated integers, NN (students in the class) and KK (the cancelation threshold). The second line contains NN space-separated integers (a1,a2,…,aNa1,a2,…,aN) describing the arrival times for each student. Note: Non-positive arrival times (ai≤0ai≤0) indicate the student arrived early or on time; positive arrival times (ai>0ai>0) indicate the student arrived aiai minutes late. Output Format For each test case, print the word YES if the class is canceled or NO if it is not. Constraints 1≤T≤101≤T≤10 1≤N≤10001≤N≤1000 1≤K≤N1≤K≤N −100≤ai≤100,where i∈[1,N]−100≤ai≤100,where i∈[1,N] Note If a student arrives exactly on time (ai=0)(ai=0), the student is considered to have entered before the class started. Sample Input 2 4 3 -1 -3 4 2 4 2 0 -1 2 1 Sample Output YES NO **/
3e0045867d0b2ec9143420e7a8abdc3d6d26cca3
12,165
java
Java
sdk/peering/azure-resourcemanager-peering/src/main/java/com/azure/resourcemanager/peering/implementation/OperationsClientImpl.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/peering/azure-resourcemanager-peering/src/main/java/com/azure/resourcemanager/peering/implementation/OperationsClientImpl.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/peering/azure-resourcemanager-peering/src/main/java/com/azure/resourcemanager/peering/implementation/OperationsClientImpl.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
45.055556
119
0.653432
127
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.peering.implementation; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.peering.fluent.OperationsClient; import com.azure.resourcemanager.peering.fluent.models.OperationInner; import com.azure.resourcemanager.peering.models.OperationListResult; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in OperationsClient. */ public final class OperationsClientImpl implements OperationsClient { private final ClientLogger logger = new ClientLogger(OperationsClientImpl.class); /** The proxy service used to perform REST calls. */ private final OperationsService service; /** The service client containing this operation class. */ private final PeeringManagementClientImpl client; /** * Initializes an instance of OperationsClientImpl. * * @param client the instance of the service client containing this operation class. */ OperationsClientImpl(PeeringManagementClientImpl client) { this.service = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for PeeringManagementClientOperations to be used by the proxy service to * perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "PeeringManagementCli") private interface OperationsService { @Headers({"Content-Type: application/json"}) @Get("/providers/Microsoft.Peering/operations") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<OperationListResult>> list( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<OperationListResult>> listNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Lists all of the available API operations for peering resources. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listSinglePageAsync() { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)) .<PagedResponse<OperationInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists all of the available API operations for peering resources. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listSinglePageAsync(Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists all of the available API operations for peering resources. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<OperationInner> listAsync() { return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); } /** * Lists all of the available API operations for peering resources. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<OperationInner> listAsync(Context context) { return new PagedFlux<>( () -> listSinglePageAsync(context), nextLink -> listNextSinglePageAsync(nextLink, context)); } /** * Lists all of the available API operations for peering resources. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<OperationInner> list() { return new PagedIterable<>(listAsync()); } /** * Lists all of the available API operations for peering resources. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<OperationInner> list(Context context) { return new PagedIterable<>(listAsync(context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<OperationInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the paginated list of peering API operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
3e00465b8134afb74199b4836ceff05c6e48dea7
12,666
java
Java
OgreKit/FindPanelTest/Base.lproj/MyTableDocumentWithCocoaBinding.nib/_MyTableDocumentWithCocoaBinding_EOArchive_English.java
acpassarella/SubEthaEdit
e2a29026144ed9d7944ef14a1f6852cb14a54bf1
[ "MIT" ]
1,240
2018-10-25T21:22:38.000Z
2022-03-26T14:13:52.000Z
OgreKit/FindPanelTest/Base.lproj/MyTableDocumentWithCocoaBinding.nib/_MyTableDocumentWithCocoaBinding_EOArchive_English.java
acpassarella/SubEthaEdit
e2a29026144ed9d7944ef14a1f6852cb14a54bf1
[ "MIT" ]
200
2018-11-21T11:44:57.000Z
2022-03-28T19:51:41.000Z
OgreKit/FindPanelTest/Base.lproj/MyTableDocumentWithCocoaBinding.nib/_MyTableDocumentWithCocoaBinding_EOArchive_English.java
acpassarella/SubEthaEdit
e2a29026144ed9d7944ef14a1f6852cb14a54bf1
[ "MIT" ]
115
2018-11-28T09:49:01.000Z
2022-03-31T03:26:05.000Z
58.638889
213
0.714432
128
// _MyTableDocumentWithCocoaBinding_EOArchive_English.java // Generated by EnterpriseObjects palette at 2004\u5e746\u670818\u65e5\u91d1\u66dc\u65e5 2\u664219\u520648\u79d2Asia/Tokyo import com.webobjects.eoapplication.*; import com.webobjects.eocontrol.*; import com.webobjects.eointerface.*; import com.webobjects.eointerface.swing.*; import com.webobjects.eointerface.swing.EOTable._EOTableColumn; import com.webobjects.foundation.*; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; import javax.swing.text.*; public class _MyTableDocumentWithCocoaBinding_EOArchive_English extends com.webobjects.eoapplication.EOArchive { ArrayController _arrayController0; com.webobjects.eointerface.swing.EOFrame _eoFrame0; com.webobjects.eointerface.swing.EOTable _nsTableView0; com.webobjects.eointerface.swing.EOTable._EOTableColumn _eoTableColumn0, _eoTableColumn1; com.webobjects.eointerface.swing.EOTextField _nsTextField0, _nsTextField1, _nsTextField2, _nsTextField3; com.webobjects.eointerface.swing.EOView _nsBox0, _nsBox1, _nsBox2, _nsBox3; javax.swing.JButton _nsButton0, _nsButton1, _nsButton2; javax.swing.JPanel _nsView0; public _MyTableDocumentWithCocoaBinding_EOArchive_English(Object owner, NSDisposableRegistry registry) { super(owner, registry); } protected void _construct() { Object owner = _owner(); EOArchive._ObjectInstantiationDelegate delegate = (owner instanceof EOArchive._ObjectInstantiationDelegate) ? (EOArchive._ObjectInstantiationDelegate)owner : null; Object replacement; super._construct(); _nsTextField3 = (com.webobjects.eointerface.swing.EOTextField)_registered(new com.webobjects.eointerface.swing.EOTextField(), "NSTextField1"); _nsTextField2 = (com.webobjects.eointerface.swing.EOTextField)_registered(new com.webobjects.eointerface.swing.EOTextField(), "NSTextField21"); _nsTextField1 = (com.webobjects.eointerface.swing.EOTextField)_registered(new com.webobjects.eointerface.swing.EOTextField(), "NSTextField2"); _nsTextField0 = (com.webobjects.eointerface.swing.EOTextField)_registered(new com.webobjects.eointerface.swing.EOTextField(), "NSTextField"); _nsBox3 = (com.webobjects.eointerface.swing.EOView)_registered(new com.webobjects.eointerface.swing.EOView(), ""); _nsBox2 = (com.webobjects.eointerface.swing.EOView)_registered(new com.webobjects.eointerface.swing.EOView(), ""); _nsButton2 = (javax.swing.JButton)_registered(new javax.swing.JButton("Add"), "NSButton1"); _arrayController0 = (ArrayController)_registered(new ArrayController(), "MyArrayController"); _nsButton1 = (javax.swing.JButton)_registered(new javax.swing.JButton("Remove"), "NSButton"); _nsBox1 = (com.webobjects.eointerface.swing.EOView)_registered(new com.webobjects.eointerface.swing.EOView(), "NSView"); _nsBox0 = (com.webobjects.eointerface.swing.EOView)_registered(new com.webobjects.eointerface.swing.EOView(), "NSBox2"); _nsButton0 = (javax.swing.JButton)_registered(new javax.swing.JButton("Dump"), "NSButton"); _eoTableColumn1 = (com.webobjects.eointerface.swing.EOTable._EOTableColumn)_registered(new com.webobjects.eointerface.swing.EOTable._EOTableColumn(), ""); _eoTableColumn0 = (com.webobjects.eointerface.swing.EOTable._EOTableColumn)_registered(new com.webobjects.eointerface.swing.EOTable._EOTableColumn(), ""); if ((delegate != null) && ((replacement = delegate.objectForOutletPath(this, "tableView")) != null)) { _nsTableView0 = (replacement == EOArchive._ObjectInstantiationDelegate.NullObject) ? null : (com.webobjects.eointerface.swing.EOTable)replacement; _replacedObjects.setObjectForKey(replacement, "_nsTableView0"); } else { _nsTableView0 = (com.webobjects.eointerface.swing.EOTable)_registered(new com.webobjects.eointerface.swing.EOTable(), "NSTableView"); } if ((delegate != null) && ((replacement = delegate.objectForOutletPath(this, "window")) != null)) { _eoFrame0 = (replacement == EOArchive._ObjectInstantiationDelegate.NullObject) ? null : (com.webobjects.eointerface.swing.EOFrame)replacement; _replacedObjects.setObjectForKey(replacement, "_eoFrame0"); } else { _eoFrame0 = (com.webobjects.eointerface.swing.EOFrame)_registered(new com.webobjects.eointerface.swing.EOFrame(), "Window"); } _nsView0 = (JPanel)_eoFrame0.getContentPane(); } protected void _awaken() { super._awaken(); _nsButton0.addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_owner(), "dump", _nsButton0), "")); if (_replacedObjects.objectForKey("_eoFrame0") == null) { _connect(_eoFrame0, _owner(), "delegate"); } if (_replacedObjects.objectForKey("_eoFrame0") == null) { _connect(_owner(), _eoFrame0, "window"); } if (_replacedObjects.objectForKey("_nsTableView0") == null) { _connect(_owner(), _nsTableView0, "tableView"); } } protected void _init() { super._init(); _setFontForComponent(_nsTextField3, "Lucida Grande", 13, Font.PLAIN); _nsTextField3.setEditable(true); _nsTextField3.setOpaque(true); _nsTextField3.setText(""); _nsTextField3.setHorizontalAlignment(javax.swing.JTextField.LEFT); _nsTextField3.setSelectable(true); _nsTextField3.setEnabled(true); _setFontForComponent(_nsTextField2, "Lucida Grande", 13, Font.PLAIN); _nsTextField2.setEditable(false); _nsTextField2.setOpaque(false); _nsTextField2.setText("Bar:"); _nsTextField2.setHorizontalAlignment(javax.swing.JTextField.LEFT); _nsTextField2.setSelectable(false); _nsTextField2.setEnabled(true); _nsTextField2.setBorder(null); _setFontForComponent(_nsTextField1, "Lucida Grande", 13, Font.PLAIN); _nsTextField1.setEditable(false); _nsTextField1.setOpaque(false); _nsTextField1.setText("Foo:"); _nsTextField1.setHorizontalAlignment(javax.swing.JTextField.LEFT); _nsTextField1.setSelectable(false); _nsTextField1.setEnabled(true); _nsTextField1.setBorder(null); _setFontForComponent(_nsTextField0, "Lucida Grande", 13, Font.PLAIN); _nsTextField0.setEditable(true); _nsTextField0.setOpaque(true); _nsTextField0.setText(""); _nsTextField0.setHorizontalAlignment(javax.swing.JTextField.LEFT); _nsTextField0.setSelectable(true); _nsTextField0.setEnabled(true); if (!(_nsBox3.getLayout() instanceof EOViewLayout)) { _nsBox3.setLayout(new EOViewLayout()); } _nsTextField0.setSize(319, 22); _nsTextField0.setLocation(49, 14); ((EOViewLayout)_nsBox3.getLayout()).setAutosizingMask(_nsTextField0, EOViewLayout.WidthSizable | EOViewLayout.MinYMargin); _nsBox3.add(_nsTextField0); _nsTextField1.setSize(32, 17); _nsTextField1.setLocation(12, 17); ((EOViewLayout)_nsBox3.getLayout()).setAutosizingMask(_nsTextField1, EOViewLayout.MaxXMargin | EOViewLayout.MinYMargin); _nsBox3.add(_nsTextField1); _nsTextField2.setSize(32, 17); _nsTextField2.setLocation(12, 47); ((EOViewLayout)_nsBox3.getLayout()).setAutosizingMask(_nsTextField2, EOViewLayout.MaxXMargin | EOViewLayout.MinYMargin); _nsBox3.add(_nsTextField2); _nsTextField3.setSize(319, 22); _nsTextField3.setLocation(49, 44); ((EOViewLayout)_nsBox3.getLayout()).setAutosizingMask(_nsTextField3, EOViewLayout.WidthSizable | EOViewLayout.MinYMargin); _nsBox3.add(_nsTextField3); if (!(_nsBox2.getLayout() instanceof EOViewLayout)) { _nsBox2.setLayout(new EOViewLayout()); } _nsBox3.setSize(387, 84); _nsBox3.setLocation(2, 15); ((EOViewLayout)_nsBox2.getLayout()).setAutosizingMask(_nsBox3, EOViewLayout.MinYMargin); _nsBox2.add(_nsBox3); _nsBox2.setBorder(new com.webobjects.eointerface.swing._EODefaultBorder("", true, "Lucida Grande", 11, Font.PLAIN)); _setFontForComponent(_nsButton2, "Lucida Grande", 11, Font.PLAIN); _nsButton2.setMargin(new Insets(0, 2, 0, 2)); _nsButton2.addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_arrayController0, "add", _nsButton2), "")); _nsButton1.addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_arrayController0, "remove", _nsButton1), "")); _setFontForComponent(_nsButton1, "Lucida Grande", 11, Font.PLAIN); _nsButton1.setMargin(new Insets(0, 2, 0, 2)); if (!(_nsBox1.getLayout() instanceof EOViewLayout)) { _nsBox1.setLayout(new EOViewLayout()); } _nsButton1.setSize(61, 22); _nsButton1.setLocation(78, 5); ((EOViewLayout)_nsBox1.getLayout()).setAutosizingMask(_nsButton1, EOViewLayout.MinYMargin); _nsBox1.add(_nsButton1); _nsButton2.setSize(61, 22); _nsButton2.setLocation(12, 5); ((EOViewLayout)_nsBox1.getLayout()).setAutosizingMask(_nsButton2, EOViewLayout.MinYMargin); _nsBox1.add(_nsButton2); if (!(_nsBox0.getLayout() instanceof EOViewLayout)) { _nsBox0.setLayout(new EOViewLayout()); } _nsBox1.setSize(148, 35); _nsBox1.setLocation(2, 15); ((EOViewLayout)_nsBox0.getLayout()).setAutosizingMask(_nsBox1, EOViewLayout.MinYMargin); _nsBox0.add(_nsBox1); _nsBox0.setBorder(new com.webobjects.eointerface.swing._EODefaultBorder("", true, "Lucida Grande", 11, Font.PLAIN)); _setFontForComponent(_nsButton0, "Lucida Grande", 13, Font.PLAIN); _nsButton0.setMargin(new Insets(0, 2, 0, 2)); _eoTableColumn1.setMinWidth(10); _eoTableColumn1.setMaxWidth(1000); _eoTableColumn1.setPreferredWidth(283); _eoTableColumn1.setWidth(283); _eoTableColumn1.setResizable(true); _eoTableColumn1.setHeaderValue("Bar"); if ((_eoTableColumn1.getHeaderRenderer() != null)) { ((DefaultTableCellRenderer)(_eoTableColumn1.getHeaderRenderer())).setHorizontalAlignment(javax.swing.JTextField.LEFT); } _eoTableColumn0.setMinWidth(10); _eoTableColumn0.setMaxWidth(1000); _eoTableColumn0.setPreferredWidth(281); _eoTableColumn0.setWidth(281); _eoTableColumn0.setResizable(true); _eoTableColumn0.setHeaderValue("Foo"); if ((_eoTableColumn0.getHeaderRenderer() != null)) { ((DefaultTableCellRenderer)(_eoTableColumn0.getHeaderRenderer())).setHorizontalAlignment(javax.swing.JTextField.LEFT); } if (_replacedObjects.objectForKey("_nsTableView0") == null) { _nsTableView0.table().addColumn(_eoTableColumn0); _nsTableView0.table().addColumn(_eoTableColumn1); _setFontForComponent(_nsTableView0.table().getTableHeader(), "Lucida Grande", 11, Font.PLAIN); _nsTableView0.table().setRowHeight(20); } if (!(_nsView0.getLayout() instanceof EOViewLayout)) { _nsView0.setLayout(new EOViewLayout()); } _nsTableView0.setSize(587, 357); _nsTableView0.setLocation(-7, -6); ((EOViewLayout)_nsView0.getLayout()).setAutosizingMask(_nsTableView0, EOViewLayout.WidthSizable | EOViewLayout.HeightSizable); _nsView0.add(_nsTableView0); _nsBox0.setSize(152, 52); _nsBox0.setLocation(10, 345); ((EOViewLayout)_nsView0.getLayout()).setAutosizingMask(_nsBox0, EOViewLayout.MaxXMargin | EOViewLayout.MinYMargin); _nsView0.add(_nsBox0); _nsBox2.setSize(391, 101); _nsBox2.setLocation(172, 345); ((EOViewLayout)_nsView0.getLayout()).setAutosizingMask(_nsBox2, EOViewLayout.WidthSizable | EOViewLayout.MinYMargin); _nsView0.add(_nsBox2); _nsButton0.setSize(72, 26); _nsButton0.setLocation(50, 411); ((EOViewLayout)_nsView0.getLayout()).setAutosizingMask(_nsButton0, EOViewLayout.MaxXMargin | EOViewLayout.MinYMargin); _nsView0.add(_nsButton0); if (_replacedObjects.objectForKey("_eoFrame0") == null) { _nsView0.setSize(573, 456); _eoFrame0.setTitle("Window"); _eoFrame0.setLocation(207, 241); _eoFrame0.setSize(573, 456); } } }
3e00484a8d53777328a108ddf6796a0a9afe838c
1,405
java
Java
src/test/java/example/spring/events/c/architecture/before/order/OrderManagementTests.java
izaiasdb/curso-spring-events-deep-dive
6109c57b616410fa328d058f42efb6ec199b1b16
[ "Apache-2.0" ]
35
2020-09-02T17:55:11.000Z
2022-03-01T10:51:07.000Z
src/test/java/example/spring/events/c/architecture/before/order/OrderManagementTests.java
izaiasdb/curso-spring-events-deep-dive
6109c57b616410fa328d058f42efb6ec199b1b16
[ "Apache-2.0" ]
null
null
null
src/test/java/example/spring/events/c/architecture/before/order/OrderManagementTests.java
izaiasdb/curso-spring-events-deep-dive
6109c57b616410fa328d058f42efb6ec199b1b16
[ "Apache-2.0" ]
14
2020-09-02T22:49:10.000Z
2022-01-27T11:26:08.000Z
27.54902
75
0.764413
129
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.spring.events.c.architecture.before.order; import static org.mockito.Mockito.*; import example.spring.events.c.architecture.before.inventory.Inventory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; /** * @author Oliver Drotbohm */ @ExtendWith(MockitoExtension.class) class OrderManagementTests { @InjectMocks OrderManagement orders; @Mock Inventory inventory; @Mock OrderRepository repository; @Test void invokesInventoryOnCompletion() { var order = new Order(); doReturn(order).when(repository).save(order); orders.completeOrder(order); verify(inventory, times(1)).updateInventoryFor(order); } }
3e004984140137176033124022c4e115eb691a27
2,401
java
Java
StoreCheckout/src/test/java/test/point/of/sale/TestDataMigration.java
rigbypc/StoreCheckout
b5f4833d00482bf83d5552ae4095ead79a0f2c61
[ "MIT" ]
4
2019-02-20T06:39:32.000Z
2019-04-27T16:00:37.000Z
StoreCheckout/src/test/java/test/point/of/sale/TestDataMigration.java
rigbypc/StoreCheckout
b5f4833d00482bf83d5552ae4095ead79a0f2c61
[ "MIT" ]
null
null
null
StoreCheckout/src/test/java/test/point/of/sale/TestDataMigration.java
rigbypc/StoreCheckout
b5f4833d00482bf83d5552ae4095ead79a0f2c61
[ "MIT" ]
6
2019-01-16T18:03:37.000Z
2019-04-26T08:48:05.000Z
27.918605
92
0.677634
130
package test.point.of.sale; import static org.junit.Assert.*; import point.of.sale.*; import static org.mockito.Mockito.*; import org.junit.Test; public class TestDataMigration { @Test public void testArrayOnly() { StoreToggles.isEnableArray = true; StoreToggles.isEnableHash = false; StoreToggles.isUnderTest = false; Display display = mock(Display.class); Interac interac = mock(Interac.class); ArrayStorage storage = new ArrayStorage(); storage.put("1", "Milk, 3.99"); Sale sale = new Sale(display, storage, interac); sale.scan("1"); verify(display).showLine("Milk, 3.99"); } @Test public void testDataMigration() { StoreToggles.isEnableArray = true; StoreToggles.isEnableHash = true; StoreToggles.isUnderTest = true; Display display = mock(Display.class); Interac interac = mock(Interac.class); ArrayStorage storage = new ArrayStorage(); storage.testingOnlyHashPut("1", "Milk, 3.99"); storage.testingOnlyHashPut("2", "Beer, 10.99"); //Forklift (mass migration) storage.forklift(); assertEquals(0, storage.checkConsistency()); //Consistency Checking (includes incremental replication) storage.testingOnlyHashPut("3", "Eggs, 4.99"); // 1 inconsistency, because we don't do shadow writing assertEquals(1, storage.checkConsistency()); //0 inconsistent, because we incrementally update assertEquals(0, storage.checkConsistency()); //Shadow writes (writes to old and new datastore) storage.put("4", "Bread, 5.99"); //no inconsistency, because we shadow write to the new datastore assertEquals(0, storage.checkConsistency()); //Shadow reads (checks that old and new datastores return the same value storage.testingOnlyHashPut("5", "Wine, 19.99"); storage.barcode("5"); assertEquals(1, storage.getReadInconsistencies()); //should still only have one read inconsistency as new datastore should be consistent now storage.barcode("5"); assertEquals(1, storage.getReadInconsistencies()); //Read and write from new datastore (get rid of old datastore) storage.put("6", "Cookies, 1.99"); assertEquals("Cookies, 1.99", storage.barcode("6")); Sale sale = new Sale(display, storage, interac); sale.scan("1"); verify(display).showLine("Milk, 3.99"); } }
3e004b5c56dde46c775595172f9a1246f9e53d68
589
java
Java
java/src/org/scs/DirectSolver.java
malickf/scs
ff0ee5b457d062d5aa0f5f2c27c384f9a161a9a2
[ "MIT" ]
25
2017-06-30T15:31:33.000Z
2021-04-21T20:12:18.000Z
java/src/org/scs/DirectSolver.java
malickf/scs
ff0ee5b457d062d5aa0f5f2c27c384f9a161a9a2
[ "MIT" ]
34
2017-06-07T01:18:17.000Z
2021-04-24T09:44:00.000Z
java/src/org/scs/DirectSolver.java
malickf/scs
ff0ee5b457d062d5aa0f5f2c27c384f9a161a9a2
[ "MIT" ]
13
2017-06-07T01:16:09.000Z
2021-06-07T09:12:56.000Z
28.047619
116
0.648557
131
package org.scs; public class DirectSolver implements IConeSolver { static { System.loadLibrary("jscsdir"); // Load native library at runtime } private static native void csolve(AMatrix A, double[] b, double[] c, Cone k, Settings p, Solution s, Info info); private static native String cversion(); private final static String VERSION = cversion(); public void solve(Data d, Cone k, Settings p, Solution sol, Info info) { csolve(d.getA(), d.getB(), d.getC(), k, p, sol, info); } public String version() { return VERSION; } }
3e004c4307c7a9896ea0d8126600b631469c572c
3,203
java
Java
appcore/src/main/java/com/longngohoang/news/appcore/common/coremvp/MVPActivity.java
beyonderVN/NewArtical
ea04c522fcd1cd1cdb48598c64d65429ac1f5fe3
[ "Apache-2.0" ]
null
null
null
appcore/src/main/java/com/longngohoang/news/appcore/common/coremvp/MVPActivity.java
beyonderVN/NewArtical
ea04c522fcd1cd1cdb48598c64d65429ac1f5fe3
[ "Apache-2.0" ]
null
null
null
appcore/src/main/java/com/longngohoang/news/appcore/common/coremvp/MVPActivity.java
beyonderVN/NewArtical
ea04c522fcd1cd1cdb48598c64d65429ac1f5fe3
[ "Apache-2.0" ]
null
null
null
35.197802
106
0.702154
132
/* * Copyright (C) 2016 Appflate.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.longngohoang.news.appcore.common.coremvp; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import java.io.Serializable; public abstract class MVPActivity<M extends Serializable, V extends MVPView, P extends MVPPresenter<V, M>> extends AppCompatActivity implements MVPView { private MVPViewDelegate<M, V, P> mvpDelegate = new MVPViewDelegate<M, V, P>() { @NonNull @Override protected P createPresenter() { return MVPActivity.this.createPresenter(); } @NonNull @Override protected M createPresentationModel() { return MVPActivity.this.createPresentationModel(); } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); performFieldInjection(); mvpDelegate.onCreate(this, savedInstanceState); } @Override protected void onStop() { super.onStop(); mvpDelegate.onStop(); } @Override protected void onDestroy() { super.onDestroy(); mvpDelegate.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mvpDelegate.onSaveInstanceState(outState); } @Override protected void onStart() { super.onStart(); mvpDelegate.onStart((V) this); } /** * Used for performing field injection trough various dependency injection frameworks like * Dagger. The injection is performed just before the #createPresenter() or * #createPresentationModel() methods are called, so you can * have your presenter and/or Presentation Model being injected by Dagger. */ protected abstract void performFieldInjection(); /** * Used for creating the presenter instance, called in #onCreate(Bundle) method. * @return an instance of your Presenter. */ @NonNull protected abstract P createPresenter(); /** * Used to create the Presentation Model that will be attached to your presenter in #onAttach() * method of your presenter. * * NOTE: this will be called only if there is no Presentation Model persisted in your * savedInstanceState! * * You can retrieve the arguments from your Intent's extra and pass it * to your Presentation's model constructor. * @return Presentation Model instance used by your Presenter. */ @NonNull protected abstract M createPresentationModel(); }
3e004d4a5071cc38f670516d48ad7d1113363ccf
6,637
java
Java
src/org/sosy_lab/cpachecker/cpa/bdd/BDDCPA.java
mutilin/cpachecker-ldv
e57bec78f72d408abb4a6812044972324df298d4
[ "ECL-2.0", "Apache-2.0" ]
1
2017-03-10T07:42:29.000Z
2017-03-10T07:42:29.000Z
src/org/sosy_lab/cpachecker/cpa/bdd/BDDCPA.java
mutilin/cpachecker-ldv
e57bec78f72d408abb4a6812044972324df298d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/org/sosy_lab/cpachecker/cpa/bdd/BDDCPA.java
mutilin/cpachecker-ldv
e57bec78f72d408abb4a6812044972324df298d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
34.567708
120
0.771734
133
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.bdd; import java.io.PrintStream; import java.util.Collection; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.configuration.Option; import org.sosy_lab.common.configuration.Options; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cfa.CFA; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.core.CPAcheckerResult.Result; import org.sosy_lab.cpachecker.core.defaults.AutomaticCPAFactory; import org.sosy_lab.cpachecker.core.defaults.DelegateAbstractDomain; import org.sosy_lab.cpachecker.core.defaults.MergeJoinOperator; import org.sosy_lab.cpachecker.core.defaults.MergeSepOperator; import org.sosy_lab.cpachecker.core.defaults.StaticPrecisionAdjustment; import org.sosy_lab.cpachecker.core.defaults.StopSepOperator; import org.sosy_lab.cpachecker.core.defaults.VariableTrackingPrecision; import org.sosy_lab.cpachecker.core.interfaces.AbstractDomain; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.CPAFactory; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysisWithBAM; import org.sosy_lab.cpachecker.core.interfaces.MergeOperator; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.core.interfaces.PrecisionAdjustment; import org.sosy_lab.cpachecker.core.interfaces.Reducer; import org.sosy_lab.cpachecker.core.interfaces.StateSpacePartition; import org.sosy_lab.cpachecker.core.interfaces.Statistics; import org.sosy_lab.cpachecker.core.interfaces.StatisticsProvider; import org.sosy_lab.cpachecker.core.interfaces.StopOperator; import org.sosy_lab.cpachecker.core.interfaces.TransferRelation; import org.sosy_lab.cpachecker.core.reachedset.ReachedSet; import org.sosy_lab.cpachecker.util.predicates.bdd.BDDManagerFactory; import org.sosy_lab.cpachecker.util.predicates.regions.NamedRegionManager; import org.sosy_lab.cpachecker.util.predicates.regions.RegionManager; @Options(prefix="cpa.bdd") public class BDDCPA implements ConfigurableProgramAnalysisWithBAM, StatisticsProvider { public static CPAFactory factory() { return AutomaticCPAFactory.forType(BDDCPA.class); } private final NamedRegionManager manager; private final BitvectorManager bvmgr; private final PredicateManager predmgr; private final AbstractDomain abstractDomain; private VariableTrackingPrecision precision; private final MergeOperator mergeOperator; private final StopOperator stopOperator; private final BDDTransferRelation transferRelation; private final BDDReducer reducer; private final ShutdownNotifier shutdownNotifier; private final Configuration config; private final LogManager logger; private final CFA cfa; @Option(secure=true, description="mergeType") private String merge = "join"; private BDDCPA(CFA pCfa, Configuration pConfig, LogManager pLogger, ShutdownNotifier pShutdownNotifier) throws InvalidConfigurationException { pConfig.inject(this); config = pConfig; logger = pLogger; cfa = pCfa; shutdownNotifier = pShutdownNotifier; RegionManager rmgr = new BDDManagerFactory(config, logger).createRegionManager(); abstractDomain = DelegateAbstractDomain.<BDDState>getInstance(); stopOperator = new StopSepOperator(abstractDomain); mergeOperator = (merge.equals("sep")) ? MergeSepOperator.getInstance() : new MergeJoinOperator(abstractDomain); precision = VariableTrackingPrecision.createStaticPrecision(config, cfa.getVarClassification(), getClass()); manager = new NamedRegionManager(rmgr); bvmgr = new BitvectorManager(rmgr); predmgr = new PredicateManager(config, manager, cfa); transferRelation = new BDDTransferRelation(manager, bvmgr, predmgr, logger, config, cfa); reducer = new BDDReducer(manager, predmgr); } public void injectRefinablePrecision() throws InvalidConfigurationException { precision = VariableTrackingPrecision.createRefineablePrecision(config, precision); } public NamedRegionManager getManager() { return manager; } @Override public AbstractDomain getAbstractDomain() { return abstractDomain; } @Override public MergeOperator getMergeOperator() { return mergeOperator; } @Override public StopOperator getStopOperator() { return stopOperator; } @Override public TransferRelation getTransferRelation() { return transferRelation; } @Override public AbstractState getInitialState(CFANode pNode, StateSpacePartition pPartition) { return new BDDState(manager, bvmgr, manager.makeTrue()); } @Override public Precision getInitialPrecision(CFANode pNode, StateSpacePartition pPartition) { return precision; } @Override public PrecisionAdjustment getPrecisionAdjustment() { return StaticPrecisionAdjustment.getInstance(); } @Override public void collectStatistics(Collection<Statistics> statsCollection) { statsCollection.add(new Statistics() { @Override public void printStatistics(PrintStream out, Result result, ReachedSet reached) { transferRelation.printStatistics(out); } @Override public String getName() { return "BDDCPA"; } }); } @Override public Reducer getReducer() { return reducer; } public Configuration getConfiguration() { return config; } public LogManager getLogger() { return logger; } public CFA getCFA() { return cfa; } public ShutdownNotifier getShutdownNotifier() { return shutdownNotifier; } }
3e004d8b0713e7902e6bfc82263a54de2e895c22
1,489
java
Java
src/main/com/skocur/chromerunner/LogWindow.java
oleitao/ChromeRunner
965f623c6ebc398a5b989b984c1b14edab708a89
[ "Apache-2.0" ]
11
2019-05-08T17:29:40.000Z
2021-08-09T19:46:42.000Z
src/main/com/skocur/chromerunner/LogWindow.java
oleitao/ChromeRunner
965f623c6ebc398a5b989b984c1b14edab708a89
[ "Apache-2.0" ]
1
2021-09-17T22:30:16.000Z
2021-09-17T22:30:16.000Z
src/main/com/skocur/chromerunner/LogWindow.java
oleitao/ChromeRunner
965f623c6ebc398a5b989b984c1b14edab708a89
[ "Apache-2.0" ]
1
2022-01-30T18:47:17.000Z
2022-01-30T18:47:17.000Z
25.237288
74
0.648086
134
package com.skocur.chromerunner; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.stage.Screen; import javafx.stage.Stage; public class LogWindow { private static StringBuilder stringBuilder = new StringBuilder(); private static Label label = new Label(); private static boolean isRun = false; public static void run() { if (!isRun) { isRun = true; setWindow(); } } private static void setWindow() { int initialWidth = 300; int initialHeight= 800; Stage stage = new Stage(); stage.setTitle("Log Window"); stage.setMaxWidth(initialWidth); stage.setMaxHeight(initialHeight); Rectangle2D stageBounds = Screen.getPrimary().getVisualBounds(); stage.setX(stageBounds.getWidth() - initialWidth); stage.setY(0); VBox box = new VBox(); box.setSpacing(10); ObservableList list = box.getChildren(); list.addAll(label); Scene scene = new Scene(box, initialWidth, initialHeight); stage.setScene(scene); stage.show(); } public static void addLog(String log) { stringBuilder.append(log); stringBuilder.append("\n"); Platform.runLater(() -> label.setText(stringBuilder.toString()) ); } }
3e004e0adca79e1b4b00b6f1bfa9ca9395656719
3,662
java
Java
java/debugger/impl/src/com/intellij/debugger/memory/component/InstancesTracker.java
erdi/intellij-community
dda25a8a4e6375c6d964cb0197e5c387d585ea9e
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
java/debugger/impl/src/com/intellij/debugger/memory/component/InstancesTracker.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
java/debugger/impl/src/com/intellij/debugger/memory/component/InstancesTracker.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
1
2019-07-18T16:50:52.000Z
2019-07-18T16:50:52.000Z
31.843478
140
0.758056
135
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.memory.component; import com.intellij.debugger.memory.event.InstancesTrackerListener; import com.intellij.debugger.memory.tracking.TrackingType; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.util.EventDispatcher; import com.intellij.util.xmlb.annotations.XCollection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @State(name = "InstancesTracker", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) public class InstancesTracker extends AbstractProjectComponent implements PersistentStateComponent<InstancesTracker.MyState> { private final EventDispatcher<InstancesTrackerListener> myDispatcher = EventDispatcher.create(InstancesTrackerListener.class); private MyState myState = new MyState(); public InstancesTracker(Project project) { super(project); } public static InstancesTracker getInstance(@NotNull Project project) { return project.getComponent(InstancesTracker.class); } public boolean isTracked(@NotNull String className) { return myState.classes.containsKey(className); } public boolean isBackgroundTrackingEnabled() { return myState.isBackgroundTrackingEnabled; } @Nullable public TrackingType getTrackingType(@NotNull String className) { return myState.classes.getOrDefault(className, null); } @NotNull public Map<String, TrackingType> getTrackedClasses() { return new HashMap<>(myState.classes); } public void add(@NotNull String name, @NotNull TrackingType type) { if (type.equals(myState.classes.getOrDefault(name, null))) { return; } myState.classes.put(name, type); myDispatcher.getMulticaster().classChanged(name, type); } public void remove(@NotNull String name) { TrackingType removed = myState.classes.remove(name); if (removed != null) { myDispatcher.getMulticaster().classRemoved(name); } } public void addTrackerListener(@NotNull InstancesTrackerListener listener) { myDispatcher.addListener(listener); } public void addTrackerListener(@NotNull InstancesTrackerListener listener, @NotNull Disposable parentDisposable) { myDispatcher.addListener(listener, parentDisposable); } public void removeTrackerListener(@NotNull InstancesTrackerListener listener) { myDispatcher.removeListener(listener); } public void setBackgroundTackingEnabled(boolean state) { boolean oldState = myState.isBackgroundTrackingEnabled; if (state != oldState) { myState.isBackgroundTrackingEnabled = state; myDispatcher.getMulticaster().backgroundTrackingValueChanged(state); } } @Nullable @Override public MyState getState() { return new MyState(myState); } @Override public void loadState(@NotNull MyState state) { myState = new MyState(state); } static class MyState { boolean isBackgroundTrackingEnabled = false; @XCollection(elementTypes = {Map.Entry.class}) final Map<String, TrackingType> classes = new ConcurrentHashMap<>(); MyState() { } MyState(@NotNull MyState state) { isBackgroundTrackingEnabled = state.isBackgroundTrackingEnabled; for (Map.Entry<String, TrackingType> classState : state.classes.entrySet()) { classes.put(classState.getKey(), classState.getValue()); } } } }
3e004fa6273e71c4ed098752ce76d80c62862ecf
1,564
java
Java
app/src/main/java/com/zyf/algorithm/test/queue09/ArrayQueue.java
Wendyyan/algorithm
d7d2a039f7d824f9fa73f4449ed092ef3fa4c0b2
[ "Apache-2.0" ]
1
2019-03-21T05:38:34.000Z
2019-03-21T05:38:34.000Z
app/src/main/java/com/zyf/algorithm/test/queue09/ArrayQueue.java
wendyzheng96/algorithm
d7d2a039f7d824f9fa73f4449ed092ef3fa4c0b2
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/zyf/algorithm/test/queue09/ArrayQueue.java
wendyzheng96/algorithm
d7d2a039f7d824f9fa73f4449ed092ef3fa4c0b2
[ "Apache-2.0" ]
null
null
null
20.311688
47
0.459079
136
package com.zyf.algorithm.test.queue09; /** * 使用数组实现队列 */ public class ArrayQueue { private String[] items;//数组 private int n;//数组容量 private int head = 0;//队头下标 private int tail = 0;//队尾下标 public ArrayQueue(int n) { items = new String[n]; this.n = n; } /** * 入队 */ private boolean enqueue(String item) { if (tail == n) {//队列已满 if (head == 0) { return false; } for (int i = head; i < tail; i++) { items[i-head] = items[i]; } tail -= head; head = 0; } items[tail] = item; tail++; return true; } /** * 出队 */ private String dequeue() { if (head == tail) {//队列为空 return null; } String tmp = items[head]; head++; return tmp; } private void printAll() { if (0 == n) return; for (int i = head; i < tail; ++i) { System.out.print(items[i] + " "); } System.out.println(); } public static void main(String[] args) { ArrayQueue queue = new ArrayQueue(5); queue.enqueue("1"); queue.enqueue("2"); queue.enqueue("3"); queue.enqueue("4"); queue.enqueue("5"); queue.printAll(); System.out.println(queue.dequeue()); System.out.println(queue.dequeue()); queue.printAll(); System.out.println(queue.enqueue("6")); queue.printAll(); } }
3e0050935a55b533eba6816bbe2f80d5d567c821
7,287
java
Java
webapp/WEB-INF/src/log/Log.java
google-admin/acre
9453a7691d270190ec04b36fb370ba5d04f0c5e5
[ "Apache-2.0" ]
null
null
null
webapp/WEB-INF/src/log/Log.java
google-admin/acre
9453a7691d270190ec04b36fb370ba5d04f0c5e5
[ "Apache-2.0" ]
null
null
null
webapp/WEB-INF/src/log/Log.java
google-admin/acre
9453a7691d270190ec04b36fb370ba5d04f0c5e5
[ "Apache-2.0" ]
null
null
null
33.122727
94
0.561822
137
package log; // Copyright 2007-2010 Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.mozilla.javascript.Scriptable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.acre.Configuration; import com.google.acre.javascript.JSON; import com.google.acre.javascript.JSONException; public class Log { public static final byte ERROR = 0; public static final byte WARN = 1; public static final byte INFO = 2; public static final byte DEBUG = 3; public static final byte TRACE = 4; public static byte toLevel(String str) { if ("error".equalsIgnoreCase(str)) { return ERROR; } else if ("warn".equalsIgnoreCase(str)) { return WARN; } else if ("info".equalsIgnoreCase(str)) { return INFO; } else if ("debug".equalsIgnoreCase(str)) { return DEBUG; } else if ("trace".equalsIgnoreCase(str)) { return TRACE; } else { throw new RuntimeException("Sorry, don't know how to log '" + str + "' messages"); } } public static String getStringFromException(Exception exception) { if (exception == null) return null; StringWriter stringWriter = null; PrintWriter printWriter = null; try { stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); exception.printStackTrace(printWriter); return stringWriter.toString(); } finally { printWriter.close(); try { stringWriter.close(); } catch (IOException e) { // ignore } } } private Logger _logger; public Log() { this(Configuration.Values.SERVICE_NAME.getValue()); } public Log(String logger_name) { _logger = LoggerFactory.getLogger(logger_name); } public Log(Class<?> clazz) { _logger = LoggerFactory.getLogger(clazz); } /** * Wrapped log methods to make sure that the event and level MDC variables * are properly setup and output */ public void error(String event_name, Object message, Throwable t) { log(event_name, ERROR, message, t); } public void error(String event_name, Object message) { log(event_name, ERROR, message, null); } public void warn(String event_name, Object message) { log(event_name, WARN, message, null); } public void info(String event_name, Object message) { log(event_name, INFO, message, null); } public void debug(String event_name, Object message) { log(event_name, DEBUG, message, null); } public void trace(String event_name, Object message) { log(event_name, TRACE, message, null); } public void log(String event_name, byte level, Object message) { log(event_name, level, message, null); } public void log(String event_name, String level, Object message) { log(event_name, toLevel(level), message, null); } public void syslog4j(String level, String event_name, Object... msgparts) { HashMap<String, String> msg = new HashMap<String, String>(); String key = null; for (Object p : msgparts) { if (key == null) { key = (String)p; continue; } if (p instanceof String) { msg.put(key, (String)p); } else if (p instanceof Scriptable || p instanceof Map || p instanceof List) { try { msg.put(key, JSON.stringify(p)); } catch (JSONException e) { msg.put(key, "[INVALID JSON]"); } } else if (p == null) { msg.put(key, null); } else { msg.put(key, p.toString()); } key = null; } log(event_name, level, msg); } // ---------------------------------------------------------------------- /** * Do the actual logging here by delegating the effort to the log4j modules. * Sets up the various volatile MDC variables which will get passed down to * the logging subsystem. * * @param event_name * the name of the event that is being logged * @param level * the severity level * @param message * the message to be logged * @param throwable any exceptions that are thrown */ private void log(String event_name, byte level, Object msg_obj, Throwable throwable) { String message = "[" + event_name + "] " + stringify(msg_obj); if (throwable != null) { switch (level) { case ERROR : _logger.error(message, throwable); break; case WARN : _logger.warn(message, throwable); break; case INFO : _logger.info(message, throwable); break; case DEBUG : _logger.debug(message, throwable); break; case TRACE : _logger.trace(message, throwable); break; } } else { switch (level) { case ERROR : _logger.error(message); break; case WARN : _logger.warn(message); break; case INFO : _logger.info(message); break; case DEBUG : _logger.debug(message); break; case TRACE : _logger.trace(message); break; } } } private String stringify(Object obj) { if (obj instanceof String) { return (String) obj; } else if (obj instanceof Map) { StringBuilder b = new StringBuilder(); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; Iterator<Map.Entry<String,Object>> i = map.entrySet().iterator(); while(i.hasNext()) { Map.Entry<String,Object> entry = i.next(); String key = entry.getKey(); Object v = entry.getValue(); String value = (v == null) ? "null" : v.toString(); b.append(key); b.append(": "); b.append(value); if (i.hasNext()) b.append(", "); } return b.toString(); } else { return "*** don't know how to serialize " + obj.getClass().getName() + " objects"; } } }
3e0050cce6b9fffbd5436df48bfe0654fa28d70e
2,141
java
Java
teaching/ds-algo-CS2040/k-merge/KMergeBinary.java
plty/nus
3d75b6d1c54022a42edbc15317507ddc988a7231
[ "MIT" ]
null
null
null
teaching/ds-algo-CS2040/k-merge/KMergeBinary.java
plty/nus
3d75b6d1c54022a42edbc15317507ddc988a7231
[ "MIT" ]
null
null
null
teaching/ds-algo-CS2040/k-merge/KMergeBinary.java
plty/nus
3d75b6d1c54022a42edbc15317507ddc988a7231
[ "MIT" ]
null
null
null
32.938462
76
0.554414
138
import java.util.Scanner; import java.util.ArrayList; import java.util.LinkedList; import java.util.PriorityQueue; public class KMergeBinary { /** * merge an array full of sorted LinkedList into a new sorted LinkedList * @param lists the ArrayList of LinkedList */ public static LinkedList<Integer> join(ArrayList<LinkedList<Integer>> lists) { return join(lists, 0, lists.size()); } /** * merge an array of sorted LinkedList from index l to r * into a new sorted LinkedList. * @param lists the ArrayList of LinkedList * @param l left-most index (inclusive) * @param r right-most index (exclusive) */ private static LinkedList<Integer> join( ArrayList<LinkedList<Integer>> lists, int l, int r) { if (r == l) return new LinkedList<>(); if (r - l == 1) return lists.get(l); int piv = (l + r) / 2; return merge(join(lists, l, piv), join(lists, piv, r)); } /** Merge two sorted LinkedList into a new sorted LinkedList. */ public static LinkedList<Integer> merge( LinkedList<Integer> left, LinkedList<Integer> right){ // this is the same as the merging part of mergesort int size = left.size() + right.size(); LinkedList<Integer> result = new LinkedList<>(); left.add(1 << 30); right.add(1 << 30); for (int i = 0; i < size; i++) { if (left.getFirst() < right.getFirst()) { result.add(left.remove()); } else { result.add(right.remove()); } } return result; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int k = in.nextInt(); ArrayList<LinkedList<Integer>> lists = new ArrayList<>(); for (int i = 0; i < k; i++) { lists.add(new LinkedList<>()); int len = in.nextInt(); for (int j = 0; j < len; j++) { lists.get(i).add(in.nextInt()); } } in.close(); System.out.println(join(lists)); } }
3e005119a778650a3a1177cdaa74cd70d909a973
5,598
java
Java
src/main/java/web/OnlineDetect.java
cbdog94/STL
8a49e7f9c494d15a501fa139de962bf1e0a04879
[ "MIT" ]
13
2018-11-20T02:54:38.000Z
2022-02-21T09:55:50.000Z
src/main/java/web/OnlineDetect.java
cbdog94/STL
8a49e7f9c494d15a501fa139de962bf1e0a04879
[ "MIT" ]
1
2022-01-04T12:04:55.000Z
2022-01-04T12:04:55.000Z
src/main/java/web/OnlineDetect.java
cbdog94/STL
8a49e7f9c494d15a501fa139de962bf1e0a04879
[ "MIT" ]
5
2019-01-14T05:38:16.000Z
2021-04-22T07:50:57.000Z
37.32
136
0.618257
139
package web; import algorithm.iBOATDetection; import bean.Cell; import bean.GPS; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.gson.Gson; import hbase.TrajectoryUtil; import org.apache.commons.io.FileUtils; import util.TileSystem; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.*; /** * Online Detect. * * @author Bin Cheng */ public class OnlineDetect extends HttpServlet { private static Set<String> idSet = new HashSet<>(); private static Map<String, GPS> starts = new HashMap<>(); public static Map<String, GPS> ends = new HashMap<>(); public static Map<String, List<Cell>> anomalyCells = new HashMap<>(); public static Map<String, List<List<Cell>>> supportTrajectories = new HashMap<>(); public static Map<String, List<Cell>> adaptiveWindow = new HashMap<>(); public static Map<String, List<List<Cell>>> allTrajectories = new HashMap<>(); public static Map<String, Double> score = new HashMap<>(); public static Map<String, GPS> lastGPS = new HashMap<>(); private static final int FINISHED = 3; private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("online-detection-pool-%d").build(); private ExecutorService threadPool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); if (!idSet.contains(id)) { try { String[] starts = req.getParameter("start").split(","); double startLatitude = Double.parseDouble(starts[0]); double startLongitude = Double.parseDouble(starts[1]); GPS startPoint = new GPS(startLatitude, startLongitude, new Date()); String[] ends = req.getParameter("end").split(","); double endLatitude = Double.parseDouble(ends[0]); double endLongitude = Double.parseDouble(ends[1]); GPS endPoint = new GPS(endLatitude, endLongitude, new Date()); threadPool.execute(() -> initDetect(id, startPoint, endPoint)); web.CommonUtil.response(req, resp, 200, "init"); } catch (Exception e) { e.printStackTrace(); web.CommonUtil.response(req, resp, 500, "Please input correct start and end points!"); } } else { GPS point; try { String[] points = req.getParameter("point").split(","); double latitude = Double.parseDouble(points[0]); double longitude = Double.parseDouble(points[1]); point = new GPS(latitude, longitude, new Date()); } catch (Exception e) { e.printStackTrace(); web.CommonUtil.response(req, resp, 500, "Please input correct point!"); return; } try { iBOATDetection.DetectResult detectResult = iBOATDetection.iBOATOnline(id, point); if (detectResult.code == FINISHED) { finishDetect(id); } web.CommonUtil.response(req, resp, 200, new Gson().toJson(detectResult)); } catch (Exception e) { e.printStackTrace(); web.CommonUtil.response(req, resp, 500, "Detection error!"); } } } private void initDetect(String id, GPS startPoint, GPS endPoint) { idSet.add(id); starts.put(id, startPoint); ends.put(id, endPoint); Cell startCell = TileSystem.gpsToTile(startPoint); Cell endCell = TileSystem.gpsToTile(endPoint); Map<String, List<GPS>> allTrajectoryGPSs = TrajectoryUtil.getAllTrajectoryGPSs(startCell, endCell, "SH"); //write file threadPool.execute(() -> { String root = getServletContext().getRealPath("/"); File file = FileUtils.getFile(root + "detect_" + id + ".json"); String content = new Gson().toJson(web.CommonUtil.multiCompress(new ArrayList<>(allTrajectoryGPSs.values()))); try { FileUtils.write(file, content, false); } catch (IOException e) { e.printStackTrace(); } WebSocketOnline.sendMessage(id, "historyDone"); }); List<List<Cell>> allTrajectoriesList = new ArrayList<>(TrajectoryUtil.getAllTrajectoryCells(startCell, endCell, "SH").values()); anomalyCells.put(id, new ArrayList<>()); adaptiveWindow.put(id, new ArrayList<>()); allTrajectories.put(id, allTrajectoriesList); supportTrajectories.put(id, new ArrayList<>(allTrajectoriesList)); score.put(id, 0.0); lastGPS.put(id, startPoint); WebSocketOnline.sendMessage(id, "initDone"); } private void finishDetect(String id) { idSet.remove(id); starts.remove(id); ends.remove(id); anomalyCells.remove(id); supportTrajectories.remove(id); adaptiveWindow.remove(id); allTrajectories.remove(id); score.remove(id); lastGPS.remove(id); } }
3e00519bbe264c332d1c90108eebd79e0d2b4c56
6,065
java
Java
test/system/src/main/java/io/pravega/test/system/framework/services/kubernetes/BookkeeperK8sService.java
ImiaoChien/pravega
adea10d51a4cf0b1fb1182f2df72cd304e020406
[ "Apache-2.0" ]
1
2020-03-31T09:54:30.000Z
2020-03-31T09:54:30.000Z
test/system/src/main/java/io/pravega/test/system/framework/services/kubernetes/BookkeeperK8sService.java
ImiaoChien/pravega
adea10d51a4cf0b1fb1182f2df72cd304e020406
[ "Apache-2.0" ]
2
2019-01-22T23:57:17.000Z
2019-02-13T05:12:23.000Z
test/system/src/main/java/io/pravega/test/system/framework/services/kubernetes/BookkeeperK8sService.java
ImiaoChien/pravega
adea10d51a4cf0b1fb1182f2df72cd304e020406
[ "Apache-2.0" ]
1
2021-06-03T23:08:32.000Z
2021-06-03T23:08:32.000Z
55.642202
161
0.562407
140
/** * Copyright (c) 2017 Dell Inc., or its subsidiaries. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ package io.pravega.test.system.framework.services.kubernetes; import com.google.common.collect.ImmutableMap; import io.pravega.common.concurrent.Futures; import io.pravega.test.system.framework.TestFrameworkException; import lombok.extern.slf4j.Slf4j; import java.net.URI; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static io.pravega.test.system.framework.TestFrameworkException.Type.RequestFailed; @Slf4j public class BookkeeperK8sService extends AbstractService { private final URI zkUri; private final ImmutableMap<String, String> properties; public BookkeeperK8sService(final String id, final URI zkUri, final ImmutableMap<String, String> properties) { super(id); this.zkUri = zkUri; this.properties = properties; } @Override public void start(boolean wait) { Futures.getAndHandleExceptions(deployPravegaUsingOperator(zkUri, DEFAULT_CONTROLLER_COUNT, DEFAULT_SEGMENTSTORE_COUNT, DEFAULT_BOOKIE_COUNT, properties), t -> new TestFrameworkException(RequestFailed, "Failed to deploy pravega operator/pravega services", t)); if (wait) { Futures.getAndHandleExceptions(k8sClient.waitUntilPodIsRunning(NAMESPACE, "component", BOOKKEEPER_LABEL, DEFAULT_BOOKIE_COUNT), t -> new TestFrameworkException(RequestFailed, "Failed to deploy bookkeeper service, check the operator logs", t)); } } @Override public void stop() { Futures.getAndHandleExceptions(k8sClient.deleteCustomObject(CUSTOM_RESOURCE_GROUP_PRAVEGA, CUSTOM_RESOURCE_VERSION_PRAVEGA, NAMESPACE, CUSTOM_RESOURCE_PLURAL_PRAVEGA, PRAVEGA_ID), t -> new TestFrameworkException(RequestFailed, "Failed to stop pravega", t)); } @Override public boolean isRunning() { return k8sClient.getStatusOfPodWithLabel(NAMESPACE, "component", BOOKKEEPER_LABEL) .thenApply(statuses -> statuses.stream() .filter(podStatus -> podStatus.getContainerStatuses() .stream() .allMatch(st -> st.getState().getRunning() != null)) .count()) .thenApply(runCount -> runCount >= DEFAULT_BOOKIE_COUNT) .exceptionally(t -> { log.warn("Exception observed while checking status of pods {}. Details: {}", BOOKKEEPER_LABEL, t.getMessage()); return false; }).join(); } @Override public List<URI> getServiceDetails() { //fetch the URI. return Futures.getAndHandleExceptions(k8sClient.getStatusOfPodWithLabel(NAMESPACE, "component", BOOKKEEPER_LABEL) .thenApply(statuses -> statuses.stream() .map(s -> URI.create(TCP + s.getPodIP() + ":" + BOOKKEEPER_PORT)) .collect(Collectors.toList())), t -> new TestFrameworkException(RequestFailed, "Failed to fetch ServiceDetails for bookkeeper", t)); } @Override @SuppressWarnings("unchecked") public CompletableFuture<Void> scaleService(int newInstanceCount) { log.info("Scaling Bookkeeper service to {} instances.", newInstanceCount); return k8sClient.getCustomObject(CUSTOM_RESOURCE_GROUP_PRAVEGA, CUSTOM_RESOURCE_VERSION_PRAVEGA, NAMESPACE, CUSTOM_RESOURCE_PLURAL_PRAVEGA, PRAVEGA_ID) .thenCompose(o -> { Map<String, Object> spec = (Map<String, Object>) (((Map<String, Object>) o).get("spec")); Map<String, Object> pravegaSpec = (Map<String, Object>) spec.get("pravega"); Map<String, Object> bookkeeperSpec = (Map<String, Object>) spec.get("bookkeeper"); int currentControllerCount = ((Double) pravegaSpec.get("controllerReplicas")).intValue(); int currentSegmentStoreCount = ((Double) pravegaSpec.get("segmentStoreReplicas")).intValue(); int currentBookkeeperCount = ((Double) bookkeeperSpec.get("replicas")).intValue(); log.debug("Current instance counts : Bookkeeper {} Controller {} SegmentStore {}.", currentBookkeeperCount, currentControllerCount, currentSegmentStoreCount); if (currentBookkeeperCount != newInstanceCount) { return deployPravegaUsingOperator(zkUri, currentControllerCount, currentSegmentStoreCount, newInstanceCount, properties) .thenCompose(v -> k8sClient.waitUntilPodIsRunning(NAMESPACE, "component", BOOKKEEPER_LABEL, newInstanceCount)); } else { return CompletableFuture.completedFuture(null); } }); } }
3e0052706d3773a3dac821a7304809be89d565c5
38,495
java
Java
server/service/src/main/java/esform/wx/Core.java
BWrong/esview
61d64e9e22eb60d175f109528b81d2763dd518c9
[ "MIT" ]
null
null
null
server/service/src/main/java/esform/wx/Core.java
BWrong/esview
61d64e9e22eb60d175f109528b81d2763dd518c9
[ "MIT" ]
null
null
null
server/service/src/main/java/esform/wx/Core.java
BWrong/esview
61d64e9e22eb60d175f109528b81d2763dd518c9
[ "MIT" ]
null
null
null
39.726522
241
0.542538
141
package esform.wx; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import esform.domain.wx.BaseMsg; import esform.enums.*; import esform.enums.param.*; import esform.util.*; import esform.wx.msgHandler.CommonMsgHandler; import esform.wx.msgHandler.IMsgHandlerFace; import org.apache.commons.lang3.StringUtils; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.w3c.dom.Document; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; /** * Created by szj46941 on 2018/2/27. */ public class Core implements LifeCycle { static { System.setProperty("jsse.enableSNIExtension", "false"); // 防止SSL错误 } private static IMsgHandlerFace msgHandler = CommonMsgHandler.getInstance(); int retryCount = 0; private String uuid = null; private Map<String, Object> loginInfo = new HashMap<>(); private boolean alive = false; private String indexUrl; private long lastNormalRetCodeTime; // 最后一次收到正常retcode的时间,秒为单位 private String userName; private String nickName; private List<BaseMsg> msgList = new ArrayList<BaseMsg>(); private List<String> groupIdList = new ArrayList<String>(); // 群ID列表 private List<String> groupNickNameList = new ArrayList<String>(); // 群NickName列表 private int memberCount = 0; private JSONObject userSelf; // 登陆账号自身信息 private List<JSONObject> memberList = new ArrayList<JSONObject>(); // 好友+群聊+公众号+特殊账号 private List<JSONObject> contactList = new ArrayList<JSONObject>();// 好友 private List<JSONObject> groupList = new ArrayList<JSONObject>(); // 群 private Map<String, JSONArray> groupMemberMap = new HashMap<String, JSONArray>(); // 群聊成员字典 private List<JSONObject> publicUsersList = new ArrayList<JSONObject>();// 公众号/服务号 private List<JSONObject> specialUsersList = new ArrayList<JSONObject>();// 特殊账号 private Map<String, JSONObject> userInfoMap = new HashMap<String, JSONObject>(); private boolean useHotReload = false; private String hotReloadDir = "itchat.pkl"; private int receivingRetryCount = 5; public void login(String uuid) { boolean isLogin = false; List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(LoginParaEnum.LOGIN_ICON.key(), LoginParaEnum.LOGIN_ICON.value())); params.add(new BasicNameValuePair(LoginParaEnum.UUID.key(), uuid)); params.add(new BasicNameValuePair(LoginParaEnum.TIP.key(), LoginParaEnum.TIP.value())); long startTime = System.currentTimeMillis(); while (!isLogin) { long millis = System.currentTimeMillis(); if (millis - startTime > 60000) { //循环尝试超过1分钟 break; } params.add(new BasicNameValuePair(LoginParaEnum.R.key(), String.valueOf(millis / 1579L))); params.add(new BasicNameValuePair(LoginParaEnum._.key(), String.valueOf(millis))); String result = HttpClient.get(URLEnum.LOGIN_URL.url(), params, true, null); String status = checkLogin(result); if (ResultEnum.SUCCESS.code().equals(status)) { this.setAlive(true); isLogin = true; processLoginInfo(result); // 处理结果 LogUtil.info("processLoginInfo"); webWxInit(); LogUtil.info("webWxInit"); wxStatusNotify(); LogUtil.info("wxStatusNotify"); startReceiving(); LogUtil.info("startReceiving"); webWxGetContact(); LogUtil.info("webWxGetContact"); WebWxBatchGetContact(); LogUtil.info("WebWxBatchGetContact"); setUserInfo(); LogUtil.info("setUserInfo"); // CheckLoginStatusThread(); handleMsg(); LogUtil.info("handleMsg"); } } } /** * 处理登陆信息 */ public void processLoginInfo(String loginContent) { String regEx = "window.redirect_uri=\"(\\S+)\";"; Matcher matcher = CommonTool.getMatcher(regEx, loginContent); if (matcher.find()) { String originalUrl = matcher.group(1); String url = originalUrl.substring(0, originalUrl.lastIndexOf('/')); // https://wx2.qq.com/cgi-bin/mmwebwx-bin this.getLoginInfo().put("url", url); Map<String, List<String>> possibleUrlMap = this.getPossibleUrlMap(); Iterator<Map.Entry<String, List<String>>> iterator = possibleUrlMap.entrySet().iterator(); Map.Entry<String, List<String>> entry; String fileUrl; String syncUrl; while (iterator.hasNext()) { entry = iterator.next(); String indexUrl = entry.getKey(); fileUrl = "https://" + entry.getValue().get(0) + "/cgi-bin/mmwebwx-bin"; syncUrl = "https://" + entry.getValue().get(1) + "/cgi-bin/mmwebwx-bin"; if (this.getLoginInfo().get("url").toString().contains(indexUrl)) { this.setIndexUrl(indexUrl); this.getLoginInfo().put("fileUrl", fileUrl); this.getLoginInfo().put("syncUrl", syncUrl); break; } } if (this.getLoginInfo().get("fileUrl") == null && this.getLoginInfo().get("syncUrl") == null) { this.getLoginInfo().put("fileUrl", url); this.getLoginInfo().put("syncUrl", url); } this.getLoginInfo().put("deviceid", "e" + String.valueOf(new Random().nextLong()).substring(1, 16)); // 生成15位随机数 this.getLoginInfo().put("BaseRequest", new ArrayList<String>()); String text = HttpClient.get(originalUrl, null, false, null); //add by 默非默 2017-08-01 22:28:09 //如果登录被禁止时,则登录返回的message内容不为空,下面代码则判断登录内容是否为空,不为空则退出程序 String msg = getLoginMessage(text); if (!"".equals(msg)) { System.exit(0); } Document doc = CommonTool.xmlParser(text); if (doc != null) { this.getLoginInfo().put(StorageLoginInfoEnum.S_KEY.key(), doc.getElementsByTagName(StorageLoginInfoEnum.S_KEY.key()).item(0).getFirstChild() .getNodeValue()); this.getLoginInfo().put(StorageLoginInfoEnum.WX_SID.key(), doc.getElementsByTagName(StorageLoginInfoEnum.WX_SID.key()).item(0).getFirstChild() .getNodeValue()); this.getLoginInfo().put(StorageLoginInfoEnum.WX_UIN.key(), doc.getElementsByTagName(StorageLoginInfoEnum.WX_UIN.key()).item(0).getFirstChild() .getNodeValue()); this.getLoginInfo().put(StorageLoginInfoEnum.PASS_TICKET.key(), doc.getElementsByTagName(StorageLoginInfoEnum.PASS_TICKET.key()).item(0).getFirstChild() .getNodeValue()); } } } /** * 解析登录返回的消息,如果成功登录,则message为空 */ private String getLoginMessage(String result) { String[] strArr = result.split("<message>"); String[] rs = strArr[1].split("</message>"); if (rs.length > 1) { return rs[0]; } return ""; } private Map<String, List<String>> getPossibleUrlMap() { Map<String, List<String>> possibleUrlMap = new HashMap<String, List<String>>(); possibleUrlMap.put("wx.qq.com", new ArrayList<String>() { /** * */ private static final long serialVersionUID = 1L; { add("file.wx.qq.com"); add("webpush.wx.qq.com"); } }); possibleUrlMap.put("wx2.qq.com", new ArrayList<String>() { /** * */ private static final long serialVersionUID = 1L; { add("file.wx2.qq.com"); add("webpush.wx2.qq.com"); } }); possibleUrlMap.put("wx8.qq.com", new ArrayList<String>() { /** * */ private static final long serialVersionUID = 1L; { add("file.wx8.qq.com"); add("webpush.wx8.qq.com"); } }); possibleUrlMap.put("web2.wechat.com", new ArrayList<String>() { /** * */ private static final long serialVersionUID = 1L; { add("file.web2.wechat.com"); add("webpush.web2.wechat.com"); } }); possibleUrlMap.put("wechat.com", new ArrayList<String>() { /** * */ private static final long serialVersionUID = 1L; { add("file.web.wechat.com"); add("webpush.web.wechat.com"); } }); return possibleUrlMap; } /** * 检查登陆状态 * * @param result * @return */ public String checkLogin(String result) { String regEx = "window.code=(\\d+)"; Matcher matcher = CommonTool.getMatcher(regEx, result); if (matcher.find()) { return matcher.group(1); } return null; } public String getUUid() throws IOException { List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(UUIDParaEnum.APP_ID.key(), UUIDParaEnum.APP_ID.value())); params.add(new BasicNameValuePair(UUIDParaEnum.FUN.key(), UUIDParaEnum.FUN.value())); params.add(new BasicNameValuePair(UUIDParaEnum.LANG.key(), UUIDParaEnum.LANG.value())); params.add(new BasicNameValuePair(UUIDParaEnum.TIME_STAMP.key(), String.valueOf(System.currentTimeMillis()))); String result = HttpClient.get(URLEnum.UUID_URL.url(), params, false, null); String uuid = null; String regEx = "window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";"; Matcher matcher = CommonTool.getMatcher(regEx, result); if (matcher.find()) { if ((ResultEnum.SUCCESS.code().equals(matcher.group(1)))) { uuid = matcher.group(2); String finalUuid = uuid; ThreadUtil.addTask(() -> { login(finalUuid); }); } } return uuid; } @Override public boolean login() { return false; } public Map<String, Object> getParamMap() { return new HashMap<String, Object>(1) { private static final long serialVersionUID = 1L; { Map<String, String> map = new HashMap<String, String>(); for (BaseParaEnum baseRequest : BaseParaEnum.values()) { map.put(baseRequest.key(), getLoginInfo().get(baseRequest.value()).toString()); } put("BaseRequest", map); } }; } @Override public boolean webWxInit() { this.setAlive(true); this.setLastNormalRetCodeTime(System.currentTimeMillis()); // 组装请求URL和参数 String url = String.format(URLEnum.INIT_URL.url(), getLoginInfo().get(StorageLoginInfoEnum.URL.key()), String.valueOf(System.currentTimeMillis() / 3158L), getLoginInfo().get(StorageLoginInfoEnum.PASS_TICKET.key())); Map<String, Object> paramMap = getParamMap(); // 请求初始化接口 HttpEntity entity = HttpClient.doPost(url, JSON.toJSONString(paramMap)); try { String result = EntityUtils.toString(entity, Consts.UTF_8); JSONObject obj = JSON.parseObject(result); JSONObject user = obj.getJSONObject(StorageLoginInfoEnum.USER.key()); JSONObject syncKey = obj.getJSONObject(StorageLoginInfoEnum.SYNC_KEY_1.key()); getLoginInfo().put(StorageLoginInfoEnum.INVITE_START_COUNT.key(), obj.getInteger(StorageLoginInfoEnum.INVITE_START_COUNT.key())); getLoginInfo().put(StorageLoginInfoEnum.SYNC_KEY_1.key(), syncKey); JSONArray syncArray = syncKey.getJSONArray("List"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < syncArray.size(); i++) { sb.append(syncArray.getJSONObject(i).getString("Key") + "_" + syncArray.getJSONObject(i).getString("Val") + "|"); } // 1_661706053|2_661706420|3_661706415|1000_1494151022| String synckey = sb.toString(); // 1_661706053|2_661706420|3_661706415|1000_1494151022 getLoginInfo().put(StorageLoginInfoEnum.SYNC_KEY_2.key(), synckey.substring(0, synckey.length() - 1));// 1_656161336|2_656161626|3_656161313|11_656159955|13_656120033|201_1492273724|1000_1492265953|1001_1492250432|1004_1491805192 setUserName(user.getString("UserName")); setNickName(user.getString("NickName")); setUserSelf(obj.getJSONObject("User")); String chatSet = obj.getString("ChatSet"); String[] chatSetArray = chatSet.split(","); for (int i = 0; i < chatSetArray.length; i++) { if (chatSetArray[i].indexOf("@@") != -1) { // 更新GroupIdList getGroupIdList().add(chatSetArray[i]); // } } } catch (Exception e) { e.printStackTrace(); return false; } return false; } @Override public boolean wxStatusNotify() { // 组装请求URL和参数 String url = String.format(URLEnum.STATUS_NOTIFY_URL.url(), getLoginInfo().get(StorageLoginInfoEnum.PASS_TICKET.key())); Map<String, Object> paramMap = getParamMap(); paramMap.put(StatusNotifyParaEnum.CODE.para(), StatusNotifyParaEnum.CODE.value()); paramMap.put(StatusNotifyParaEnum.FROM_USERNAME.para(), getUserName()); paramMap.put(StatusNotifyParaEnum.TO_USERNAME.para(), getUserName()); paramMap.put(StatusNotifyParaEnum.CLIENT_MSG_ID.para(), System.currentTimeMillis()); String paramStr = JSON.toJSONString(paramMap); try { HttpEntity entity = HttpClient.doPost(url, paramStr); // EntityUtils.toString(entity, Consts.UTF_8); } catch (Exception e) { e.printStackTrace(); } return false; } @Override public void startReceiving() { ThreadUtil.addTask(() -> { while (isAlive()) { try { Map<String, String> resultMap = syncCheck(); String retcode = resultMap.get("retcode"); String selector = resultMap.get("selector"); if (retcode.equals(RetCodeEnum.UNKNOWN.code())) { // LOG.info(RetCodeEnum.UNKNOWN.type()); } else if (retcode.equals(RetCodeEnum.LOGIN_OUT.code())) { // 退出 // LOG.info(RetCodeEnum.LOGIN_OUT.getType()); break; } else if (retcode.equals(RetCodeEnum.LOGIN_OTHER_WHERE.code())) { // 其它地方登陆 // LOG.info(RetCodeEnum.LOGIN_OTHERWHERE.getType()); // break; } else if (retcode.equals(RetCodeEnum.MOBILE_LOGIN_OUT.code())) { // 移动端退出 // LOG.info(RetCodeEnum.MOBILE_LOGIN_OUT.getType()); // break; } else if (retcode.equals(RetCodeEnum.NORMAL.code())) { setLastNormalRetCodeTime(System.currentTimeMillis()); // 最后收到正常报文时间 JSONObject msgObj = webWxSync(); if (selector.equals("2")) { if (msgObj != null) { try { JSONArray msgList = new JSONArray(); msgList = msgObj.getJSONArray("AddMsgList"); msgList = produceMsg(msgList); for (int j = 0; j < msgList.size(); j++) { BaseMsg baseMsg = JSON.parseObject(JSON.toJSONString(msgList.getJSONObject(j)), BaseMsg.class); getMsgList().add(baseMsg); } } catch (Exception e) { e.printStackTrace(); // LOG.info(e.getMessage()); } } } else if (selector.equals("7")) { webWxSync(); } else if (selector.equals("4")) { continue; } else if (selector.equals("3")) { continue; } else if (selector.equals("6")) { if (msgObj != null) { try { JSONArray msgList = new JSONArray(); msgList = msgObj.getJSONArray("AddMsgList"); JSONArray modContactList = msgObj.getJSONArray("ModContactList"); // 存在删除或者新增的好友信息 msgList = produceMsg(msgList); for (int j = 0; j < msgList.size(); j++) { JSONObject userInfo = modContactList.getJSONObject(j); // 存在主动加好友之后的同步联系人到本地 getContactList().add(userInfo); } } catch (Exception e) { e.printStackTrace(); // LOG.info(e.getMessage()); } } } } else { JSONObject obj = webWxSync(); } } catch (Exception e) { // LOG.info(e.getMessage()); retryCount += 1; if (getReceivingRetryCount() < retryCount) { setAlive(false); } else { try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); // LOG.info(e.getMessage()); } } } } }); } //检查是否有新消息 private Map<String, String> syncCheck() { Map<String, String> resultMap = new HashMap<>(); String url = getLoginInfo().get(StorageLoginInfoEnum.SYNC_URL.key()) + URLEnum.SYNC_CHECK_URL.url(); List<BasicNameValuePair> params = new ArrayList<>(); for (BaseParaEnum baseRequest : BaseParaEnum.values()) { params.add(new BasicNameValuePair(baseRequest.key().toLowerCase(), getLoginInfo().get(baseRequest.value()).toString())); } params.add(new BasicNameValuePair("r", String.valueOf(new Date().getTime()))); params.add(new BasicNameValuePair("synckey", (String) getLoginInfo().get("synckey"))); params.add(new BasicNameValuePair("_", String.valueOf(new Date().getTime()))); try { String result = HttpClient.get(url, params, true, null); if (result == null) { resultMap.put("retcode", "9999"); resultMap.put("selector", "9999"); return resultMap; } String regEx = "window.synccheck=\\{retcode:\"(\\d+)\",selector:\"(\\d+)\"\\}"; Matcher matcher = CommonTool.getMatcher(regEx, result); if (!matcher.find() || matcher.group(1).equals("2")) { // LOG.info(String.format("Unexpected sync check result: %s", text)); } else { resultMap.put("retcode", matcher.group(1)); resultMap.put("selector", matcher.group(2)); } } catch (Exception e) { e.printStackTrace(); } return resultMap; } //同步消息 sync the messages private JSONObject webWxSync() { JSONObject result = null; String url = String.format(URLEnum.WEB_WX_SYNC_URL.url(), getLoginInfo().get(StorageLoginInfoEnum.URL.key()), getLoginInfo().get(StorageLoginInfoEnum.WX_SID.key()), getLoginInfo().get(StorageLoginInfoEnum.S_KEY.key()), getLoginInfo().get(StorageLoginInfoEnum.PASS_TICKET.key())); Map<String, Object> paramMap = getParamMap(); paramMap.put(StorageLoginInfoEnum.SYNC_KEY_1.key(), getLoginInfo().get(StorageLoginInfoEnum.SYNC_KEY_1.key())); paramMap.put("rr", -new Date().getTime() / 1000); String paramStr = JSON.toJSONString(paramMap); try { HttpEntity entity = HttpClient.doPost(url, paramStr); String text = EntityUtils.toString(entity, Consts.UTF_8); JSONObject obj = JSON.parseObject(text); if (obj.getJSONObject("BaseResponse").getInteger("Ret") != 0) { result = null; } else { result = obj; getLoginInfo().put(StorageLoginInfoEnum.SYNC_KEY_1.key(), obj.getJSONObject("SyncCheckKey")); JSONArray syncArray = obj.getJSONObject(StorageLoginInfoEnum.SYNC_KEY_1.key()).getJSONArray("List"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < syncArray.size(); i++) { sb.append(syncArray.getJSONObject(i).getString("Key") + "_" + syncArray.getJSONObject(i).getString("Val") + "|"); } String synckey = sb.toString(); getLoginInfo().put(StorageLoginInfoEnum.SYNC_KEY_2.key(), synckey.substring(0, synckey.length() - 1));// 1_656161336|2_656161626|3_656161313|11_656159955|13_656120033|201_1492273724|1000_1492265953|1001_1492250432|1004_1491805192 } } catch (Exception e) { e.printStackTrace(); // LOG.info(e.getMessage()); } return result; } @Override public void webWxGetContact() { String url = String.format(URLEnum.WEB_WX_GET_CONTACT.url(), getLoginInfo().get(StorageLoginInfoEnum.URL.key())); Map<String, Object> paramMap = getParamMap(); HttpEntity entity = HttpClient.doPost(url, JSON.toJSONString(paramMap)); try { String result = EntityUtils.toString(entity, Consts.UTF_8); JSONObject fullFriendsJsonList = JSON.parseObject(result); // 查看seq是否为0,0表示好友列表已全部获取完毕,若大于0,则表示好友列表未获取完毕,当前的字节数(断点续传) long seq = 0; long currentTime = 0L; List<BasicNameValuePair> params = new ArrayList<>(); if (fullFriendsJsonList.get("Seq") != null) { seq = fullFriendsJsonList.getLong("Seq"); currentTime = new Date().getTime(); } setMemberCount(fullFriendsJsonList.getInteger(StorageLoginInfoEnum.MEMBER_COUNT.key())); JSONArray member = fullFriendsJsonList.getJSONArray(StorageLoginInfoEnum.MEMBER_LIST.key()); // 循环获取seq直到为0,即获取全部好友列表 ==0:好友获取完毕 >0:好友未获取完毕,此时seq为已获取的字节数 while (seq > 0) { // 设置seq传参 params.add(new BasicNameValuePair("r", String.valueOf(currentTime))); params.add(new BasicNameValuePair("seq", String.valueOf(seq))); result = HttpClient.get(url, params, false, null); params.remove(new BasicNameValuePair("r", String.valueOf(currentTime))); params.remove(new BasicNameValuePair("seq", String.valueOf(seq))); fullFriendsJsonList = JSON.parseObject(result); if (fullFriendsJsonList.get("Seq") != null) { seq = fullFriendsJsonList.getLong("Seq"); currentTime = new Date().getTime(); } // 累加好友列表 member.addAll(fullFriendsJsonList.getJSONArray(StorageLoginInfoEnum.MEMBER_LIST.key())); } setMemberCount(member.size()); for (Iterator<?> iterator = member.iterator(); iterator.hasNext(); ) { JSONObject o = (JSONObject) iterator.next(); if ((o.getInteger("VerifyFlag") & 8) != 0) { // 公众号/服务号 getPublicUsersList().add(o); } else if (Config.API_SPECIAL_USER.contains(o.getString("UserName"))) { // 特殊账号 getSpecialUsersList().add(o); } else if (o.getString("UserName").indexOf("@@") != -1) { // 群聊 if (!getGroupIdList().contains(o.getString("UserName"))) { getGroupNickNameList().add(o.getString("NickName")); getGroupIdList().add(o.getString("UserName")); getGroupList().add(o); } } else if (o.getString("UserName").equals(getUserSelf().getString("UserName"))) { // 自己 getContactList().remove(o); } else { // 普通联系人 getContactList().add(o); } } return; } catch (Exception e) { e.printStackTrace(); // LOG.error(e.getMessage(), e); } return; } @Override public boolean WebWxBatchGetContact() { String url = String.format(URLEnum.WEB_WX_BATCH_GET_CONTACT.url(), getLoginInfo().get(StorageLoginInfoEnum.URL.key()), new Date().getTime(), getLoginInfo().get(StorageLoginInfoEnum.PASS_TICKET.key())); Map<String, Object> paramMap = getParamMap(); paramMap.put("Count", getGroupIdList().size()); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (int i = 0; i < getGroupIdList().size(); i++) { HashMap<String, String> map = new HashMap<String, String>(); map.put("UserName", getGroupIdList().get(i)); map.put("EncryChatRoomId", ""); list.add(map); } paramMap.put("List", list); HttpEntity entity = HttpClient.doPost(url, JSON.toJSONString(paramMap)); try { String text = EntityUtils.toString(entity, Consts.UTF_8); JSONObject obj = JSON.parseObject(text); JSONArray contactList = obj.getJSONArray("ContactList"); for (int i = 0; i < contactList.size(); i++) { // 群好友 if (contactList.getJSONObject(i).getString("UserName").indexOf("@@") > -1) { // 群 getGroupNickNameList().add(contactList.getJSONObject(i).getString("NickName")); // 更新群昵称列表 getGroupList().add(contactList.getJSONObject(i)); // 更新群信息(所有)列表 getGroupMemberMap().put(contactList.getJSONObject(i).getString("UserName"), contactList.getJSONObject(i).getJSONArray("MemberList")); // 更新群成员Map } } } catch (Exception e) { e.printStackTrace(); // LOG.info(e.getMessage()); } return false; } @Override public void setUserInfo() { for (JSONObject o : getContactList()) { getUserInfoMap().put(o.getString("NickName"), o); getUserInfoMap().put(o.getString("UserName"), o); } } @Override public void CheckLoginStatusThread() { while (isAlive()) { long t1 = System.currentTimeMillis(); // 秒为单位 if (t1 - getLastNormalRetCodeTime() > 60 * 1000) { // 超过60秒,判为离线 setAlive(false); // LOG.info("微信已离线"); } try { Thread.sleep(10 * 1000); // 休眠10秒 } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 接收消息,放入队列 */ public JSONArray produceMsg(JSONArray msgList) { JSONArray result = new JSONArray(); for (int i = 0; i < msgList.size(); i++) { JSONObject msg = new JSONObject(); JSONObject m = msgList.getJSONObject(i); m.put("groupMsg", false);// 是否是群消息 if (m.getString("FromUserName").contains("@@") || m.getString("ToUserName").contains("@@")) { // 群聊消息 if (m.getString("FromUserName").contains("@@") && !getGroupIdList().contains(m.getString("FromUserName"))) { getGroupIdList().add((m.getString("FromUserName"))); } else if (m.getString("ToUserName").contains("@@") && !getGroupIdList().contains(m.getString("ToUserName"))) { getGroupIdList().add((m.getString("ToUserName"))); } // 群消息与普通消息不同的是在其消息体(Content)中会包含发送者id及":<br/>"消息,这里需要处理一下,去掉多余信息,只保留消息内容 if (m.getString("Content").contains("<br/>")) { String content = m.getString("Content").substring(m.getString("Content").indexOf("<br/>") + 5); m.put("Content", content); m.put("groupMsg", true); } } else { CommonTool.msgFormatter(m, "Content"); } if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_TEXT.getCode())) { // words // 文本消息 if (m.getString("Url").length() != 0) { String regEx = "(.+?\\(.+?\\))"; Matcher matcher = CommonTool.getMatcher(regEx, m.getString("Content")); String data = "Map"; if (matcher.find()) { data = matcher.group(1); } msg.put("Type", "Map"); msg.put("Text", data); } else { msg.put("Type", MsgTypeEnum.TEXT.getType()); msg.put("Text", m.getString("Content")); } m.put("Type", msg.getString("Type")); m.put("Text", msg.getString("Text")); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_IMAGE.getCode()) || m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_EMOTICON.getCode())) { // 图片消息 m.put("Type", MsgTypeEnum.PIC.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_VOICE.getCode())) { // 语音消息 m.put("Type", MsgTypeEnum.VOICE.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_VERIFYMSG.getCode())) {// friends // 好友确认消息 // MessageTools.addFriend(core, userName, 3, ticket); // 确认添加好友 m.put("Type", MsgTypeEnum.VERIFYMSG.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_SHARECARD.getCode())) { // 共享名片 m.put("Type", MsgTypeEnum.NAMECARD.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_VIDEO.getCode()) || m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_MICROVIDEO.getCode())) {// viedo m.put("Type", MsgTypeEnum.VIEDO.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_MEDIA.getCode())) { // 多媒体消息 m.put("Type", MsgTypeEnum.MEDIA.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_STATUSNOTIFY.getCode())) {// phone // init // 微信初始化消息 } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_SYS.getCode())) {// 系统消息 m.put("Type", MsgTypeEnum.SYS.getType()); } else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_RECALLED.getCode())) { // 撤回消息 } else { System.out.println("Useless msg"); // LOG.info("Useless msg"); } System.out.println("收到消息一条,来自: " + m.getString("FromUserName")); result.add(m); } return result; } /** * 消息处理 */ public void handleMsg() { while (true) { if (getMsgList().size() > 0 && getMsgList().get(0).getContent() != null) { if (getMsgList().get(0).getContent().length() > 0) { BaseMsg msg = getMsgList().get(0); if (msg.getType() != null) { try { if (msg.getType().equals(MsgTypeEnum.TEXT.getType())) { String result = msgHandler.textMsgHandle(this, msg); if (StringUtils.isNotEmpty(result)) { BaseMsg baseMsg = getMsgList().get(0); if (!this.getUserName().equals(baseMsg.getFromUserName())) { MessageTools.sendMsgById(this, result, getMsgList().get(0).getFromUserName()); } } } } catch (Exception e) { e.printStackTrace(); } } } getMsgList().remove(0); } try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public void setUuid(String uuid) { this.uuid = uuid; } public boolean isAlive() { return alive; } public void setAlive(boolean alive) { this.alive = alive; } public String getIndexUrl() { return indexUrl; } public void setIndexUrl(String indexUrl) { this.indexUrl = indexUrl; } public Map<String, Object> getLoginInfo() { return loginInfo; } public void setLoginInfo(Map<String, Object> loginInfo) { this.loginInfo = loginInfo; } public String getUuid() { return uuid; } public long getLastNormalRetCodeTime() { return lastNormalRetCodeTime; } public void setLastNormalRetCodeTime(long lastNormalRetCodeTime) { this.lastNormalRetCodeTime = lastNormalRetCodeTime; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public List<BaseMsg> getMsgList() { return msgList; } public void setMsgList(List<BaseMsg> msgList) { this.msgList = msgList; } public JSONObject getUserSelf() { return userSelf; } public void setUserSelf(JSONObject userSelf) { this.userSelf = userSelf; } public List<String> getGroupIdList() { return groupIdList; } public void setGroupIdList(List<String> groupIdList) { this.groupIdList = groupIdList; } public List<String> getGroupNickNameList() { return groupNickNameList; } public void setGroupNickNameList(List<String> groupNickNameList) { this.groupNickNameList = groupNickNameList; } public int getRetryCount() { return retryCount; } public void setRetryCount(int retryCount) { this.retryCount = retryCount; } public int getMemberCount() { return memberCount; } public void setMemberCount(int memberCount) { this.memberCount = memberCount; } public List<JSONObject> getMemberList() { return memberList; } public void setMemberList(List<JSONObject> memberList) { this.memberList = memberList; } public List<JSONObject> getContactList() { return contactList; } public void setContactList(List<JSONObject> contactList) { this.contactList = contactList; } public List<JSONObject> getGroupList() { return groupList; } public void setGroupList(List<JSONObject> groupList) { this.groupList = groupList; } public Map<String, JSONArray> getGroupMemberMap() { return groupMemberMap; } public void setGroupMemberMap(Map<String, JSONArray> groupMemberMap) { this.groupMemberMap = groupMemberMap; } public List<JSONObject> getPublicUsersList() { return publicUsersList; } public void setPublicUsersList(List<JSONObject> publicUsersList) { this.publicUsersList = publicUsersList; } public List<JSONObject> getSpecialUsersList() { return specialUsersList; } public void setSpecialUsersList(List<JSONObject> specialUsersList) { this.specialUsersList = specialUsersList; } public Map<String, JSONObject> getUserInfoMap() { return userInfoMap; } public void setUserInfoMap(Map<String, JSONObject> userInfoMap) { this.userInfoMap = userInfoMap; } public boolean isUseHotReload() { return useHotReload; } public void setUseHotReload(boolean useHotReload) { this.useHotReload = useHotReload; } public String getHotReloadDir() { return hotReloadDir; } public void setHotReloadDir(String hotReloadDir) { this.hotReloadDir = hotReloadDir; } public int getReceivingRetryCount() { return receivingRetryCount; } public void setReceivingRetryCount(int receivingRetryCount) { this.receivingRetryCount = receivingRetryCount; } }
3e0054c1ea6b11ea76d2a2548db42e94c35d15ed
1,490
java
Java
eventhubs/azure-spring-cloud-stream-binder-eventhubs/eventhubs-binder/src/main/java/com/azure/spring/sample/eventhubs/binder/ReactiveEventProducerController.java
Netyyyy/azure-spring-boot-samples
803e5a1f54bb00c67e298f3877eca7a96834e5fc
[ "MIT" ]
35
2021-07-12T02:34:31.000Z
2022-03-31T03:23:55.000Z
eventhubs/azure-spring-cloud-stream-binder-eventhubs/eventhubs-binder/src/main/java/com/azure/spring/sample/eventhubs/binder/ReactiveEventProducerController.java
Netyyyy/azure-spring-boot-samples
803e5a1f54bb00c67e298f3877eca7a96834e5fc
[ "MIT" ]
106
2021-07-05T07:45:10.000Z
2022-03-30T03:13:29.000Z
eventhubs/azure-spring-cloud-stream-binder-eventhubs/eventhubs-binder/src/main/java/com/azure/spring/sample/eventhubs/binder/ReactiveEventProducerController.java
Netyyyy/azure-spring-boot-samples
803e5a1f54bb00c67e298f3877eca7a96834e5fc
[ "MIT" ]
69
2021-06-24T03:58:01.000Z
2022-03-31T03:23:56.000Z
33.863636
104
0.780537
142
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.sample.eventhubs.binder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.http.ResponseEntity; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Sinks; /** * @author Warren Zhu */ @RestController @Profile("manual") public class ReactiveEventProducerController { private static final Logger LOGGER = LoggerFactory.getLogger(ReactiveEventProducerController.class); @Autowired private Sinks.Many<Message<String>> many; @PostMapping("/messages/reactive") public ResponseEntity<String> reactiveSendMessage(@RequestParam String message) { LOGGER.info("Reactive method to send message: {} to destination.", message); many.emitNext(MessageBuilder.withPayload(message).build(), Sinks.EmitFailureHandler.FAIL_FAST); return ResponseEntity.ok(message); } @GetMapping("/") public String welcome() { return "welcome"; } }
3e0054f184bdb66f7fd480e3b8821d2317b538c2
760
java
Java
src/Sum.java
xabier100/EDA_Hackerrank_4.erronka
a654d651a95dded80c09da94ffb90a50a7fe50a3
[ "MIT" ]
null
null
null
src/Sum.java
xabier100/EDA_Hackerrank_4.erronka
a654d651a95dded80c09da94ffb90a50a7fe50a3
[ "MIT" ]
null
null
null
src/Sum.java
xabier100/EDA_Hackerrank_4.erronka
a654d651a95dded80c09da94ffb90a50a7fe50a3
[ "MIT" ]
null
null
null
17.272727
76
0.588158
143
import java.util.Scanner; /** * @author Xabier Garrote * */ public class Sum { // Complete both methods using recursion public static long power(long a, long b) { if (b==1) { return a; } else if (b==0) { return 1; } else { //2^2=2*2^1 return a*power(a, b-1); } } public static long calculateSum(long exponent, long upperLimit) { if (upperLimit==1) { return upperLimit; } else { return power(upperLimit, exponent)+calculateSum(exponent, upperLimit-1); } } public static void main(String[] args) { Scanner input = new Scanner(System.in); int k = input.nextInt(); int b = input.nextInt(); input.close(); System.out.println(calculateSum(k, b)); } }
3e00574fd8f1edbee5b8711ba780ab690b9576d1
4,252
java
Java
wava/src/main/java/wava/utils/MapUtils.java
AlexHff/wava
95267fa91d7a6e8248f772b25637b9703ced45f5
[ "Apache-2.0" ]
null
null
null
wava/src/main/java/wava/utils/MapUtils.java
AlexHff/wava
95267fa91d7a6e8248f772b25637b9703ced45f5
[ "Apache-2.0" ]
null
null
null
wava/src/main/java/wava/utils/MapUtils.java
AlexHff/wava
95267fa91d7a6e8248f772b25637b9703ced45f5
[ "Apache-2.0" ]
null
null
null
36.033898
91
0.610066
144
package wava.utils; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * This class consists of static methods that operate on or return maps. */ public final class MapUtils { public static final int ASC = 1; public static final int DESC = 2; private MapUtils() {} /** * Sorts the specified map into ascending order, according to the Comparable * natural ordering of its values. All elements in the map value set must * implement the Comparable interface. Furthermore, all elements in the value * set must be mutually comparable (that is, e1.compareTo(e2) must not throw a * ClassCastException for any elements e1 and e2 in the value set). * * @param m the map to be sorted * @return sorted map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> m) { List<Entry<K, V>> list = new ArrayList<>(m.entrySet()); list.sort(Entry.comparingByValue()); Map<K, V> s = new LinkedHashMap<>(); for (Entry<K, V> e: list) s.put(e.getKey(), e.getValue()); return s; } /** * Sorts the specified map into the order specified by the constant, according * to the Comparable natural ordering of its values. All elements in the map * value set must implement the Comparable interface. Furthermore, all elements * in the value set must be mutually comparable (that is, e1.compareTo(e2) must * not throw a ClassCastException for any elements e1 and e2 in the value set). * * @param m the map to be sorted * @param order integer specifying the sorting order * @return sorted map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> m, final int order) { if (order != 2) sortByValue(m); List<Entry<K, V>> list = new ArrayList<>(m.entrySet()); list.sort(Collections.reverseOrder(Entry.comparingByValue())); Map<K, V> s = new LinkedHashMap<>(); for (Entry<K, V> e: list) s.put(e.getKey(), e.getValue()); return s; } /** * Sorts the specified map according to the order induced by the specified * comparator. All elements in the map value set must implement the Comparable * interface. Furthermore, all elements in the value set must be mutually * comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for * any elements e1 and e2 in the value set). * * @param m the map to be sorted * @param c the comparator to determine the order of the map. A null value * indicates that the elements' natural ordering should be used * @return sorted map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> m, Comparator<? super Entry<K, V>> c) { List<Entry<K, V>> list = new ArrayList<>(m.entrySet()); list.sort(c); Map<K, V> s = new LinkedHashMap<>(); for (Entry<K, V> e: list) s.put(e.getKey(), e.getValue()); return s; } /** * Checks if a map is reversible i.e. verifies that all values are unique. * * @param m the map to be checked * @return true if the map is reversible, false otherwise */ public static <K, V> boolean isReversible(Map<K, V> m) { Set<V> s = new HashSet<>(); for (V v : m.values()) { if (s.contains(v)) return false; s.add(v); } return true; } /** * Reverses the given map if it is reversible. * * @param m the map to reverse * @return the reversed map or null if the map is not reversible */ public static <K, V> Map<V, K> reverse(Map<K, V> m) { if (!isReversible(m)) return null; Map<V, K> inv = new HashMap<>(); for (Entry<K, V> e : m.entrySet()) inv.put(e.getValue(), e.getKey()); return inv; } }
3e00581824a75d0a88da55882b90b4a057e7c8ff
3,514
java
Java
architectureeditor/test/de/peerthing/systembehavioureditor/mode/editor/ParameterTest.java
rju/peething
7abe8d3be11f5e66c8413b780640c3892503ce16
[ "Apache-2.0" ]
null
null
null
architectureeditor/test/de/peerthing/systembehavioureditor/mode/editor/ParameterTest.java
rju/peething
7abe8d3be11f5e66c8413b780640c3892503ce16
[ "Apache-2.0" ]
null
null
null
architectureeditor/test/de/peerthing/systembehavioureditor/mode/editor/ParameterTest.java
rju/peething
7abe8d3be11f5e66c8413b780640c3892503ce16
[ "Apache-2.0" ]
null
null
null
27.030769
118
0.743312
145
package de.peerthing.systembehavioureditor.mode.editor; import junit.framework.TestCase; import de.peerthing.systembehavioureditor.model.IAction; import de.peerthing.systembehavioureditor.model.editor.Action; import de.peerthing.systembehavioureditor.model.editor.Node; import de.peerthing.systembehavioureditor.model.editor.Parameter; import de.peerthing.systembehavioureditor.model.editor.State; import de.peerthing.systembehavioureditor.model.editor.Task; public class ParameterTest extends TestCase { Parameter para; Parameter paratwo; private IAction action; private String name; private String value; private String expression; private Node node; private State state; private Task task; protected void setUp() throws Exception { super.setUp(); para = new Parameter(); paratwo = new Parameter(name, action); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.Parameter(String, IAction, String)' */ public void testParameterStringIActionString() { } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.Parameter()' */ public void testParameter() { } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.setAction(IAction)' */ public void testSetAction() { para.setAction(action); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.getAction()' */ public void testGetAction() { assertNull(para.getAction()); para.setAction(action); assertSame(action, para.getAction()); assertSame(action, paratwo.getAction()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.setName(String)' */ public void testSetName() { para.setName(name); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.getName()' */ public void testGetName() { assertEquals("", para.getName()); para.setName(name); assertEquals(name, para.getName()); assertEquals(name, paratwo.getName()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.setValue(String)' */ public void testSetValue() { para.setValue(value); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.getValue()' */ public void testGetValue() { assertEquals("", para.getValue()); para.setValue(null); assertEquals("", para.getValue()); value = "test"; para.setValue(value); assertEquals(value, para.getValue()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.setExpression(String)' */ public void testSetExpression() { para.setExpression(expression); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.getExpression()' */ public void testGetExpression() { assertEquals("", para.getExpression()); para.setExpression(null); assertEquals("", para.getExpression()); expression = "test"; para.setExpression(expression); assertEquals(expression, para.getExpression()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.simulation.Parameter.getSystemBehaviour()' */ public void testGetSystemBehaviour() { action = new Action(); state = new State(); task = new Task(); node = new Node(); task.setNode(node); state.setTask(task); action.setContainer(state); para.setAction(action); assertEquals(action.getSystemBehaviour(), para.getSystemBehaviour()); } }
3e005882114296334b1d2c79668884e6ca972eef
3,395
java
Java
get-metrics/src/main/java/org/sonatype/cs/getmetrics/reports/QuarantinedComponents.java
richardpanman/nexusiq-successmetrics
17c92cfe24318b516563691f456f5f738bad039b
[ "Apache-2.0" ]
null
null
null
get-metrics/src/main/java/org/sonatype/cs/getmetrics/reports/QuarantinedComponents.java
richardpanman/nexusiq-successmetrics
17c92cfe24318b516563691f456f5f738bad039b
[ "Apache-2.0" ]
1
2021-12-23T09:20:50.000Z
2021-12-23T09:20:50.000Z
get-metrics/src/main/java/org/sonatype/cs/getmetrics/reports/QuarantinedComponents.java
richardpanman/nexusiq-successmetrics
17c92cfe24318b516563691f456f5f738bad039b
[ "Apache-2.0" ]
2
2021-12-20T15:28:51.000Z
2021-12-20T16:18:51.000Z
40.416667
91
0.642415
146
package org.sonatype.cs.getmetrics.reports; import org.apache.commons.lang3.NotImplementedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.cs.getmetrics.service.CsvFileService; import org.sonatype.cs.getmetrics.service.FileIoService; import org.sonatype.cs.getmetrics.util.FilenameInfo; import org.sonatype.cs.getmetrics.util.ParseReasons; import java.util.ArrayList; import java.util.List; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; public class QuarantinedComponents implements CsvFileService { private static final Logger log = LoggerFactory.getLogger(QuarantinedComponents.class); @Override public void makeCsvFile(FileIoService f, JsonReader reader) { throw new NotImplementedException(); } @Override public void makeCsvFile(FileIoService f, JsonObject dataObject) { log.info("Making QuarantinedComponents report"); List<String[]> data = getQuarentinedComponentsFromData(dataObject); f.writeCsvFile(FilenameInfo.quarantinedComponentsCsvFile, data); } static List<String[]> getQuarentinedComponentsFromData(JsonObject dataObject) { List<String[]> data = new ArrayList<>(); data.add(FilenameInfo.quarantinedComponentsFileHeader); JsonArray results = dataObject.getJsonArray("results"); for (JsonObject result : results.getValuesAs(JsonObject.class)) { String displayName = result.getString("displayName"); displayName = displayName.replace(" ", ""); String repository = result.getString("repository"); String quarantineDate = result.getString("quarantineDate"); String dateCleared = result.getString("dateCleared", "N/A"); boolean quarantined = result.getBoolean("quarantined"); JsonObject componentIdentifier = result.getJsonObject("componentIdentifier"); String format = componentIdentifier.getString("format"); JsonArray quarantinePolicyViolations = result.getJsonArray("quarantinePolicyViolations"); for (JsonObject quarantinePolicyViolation : quarantinePolicyViolations.getValuesAs(JsonObject.class)) { String policyName = quarantinePolicyViolation.getString("policyName"); int threatLevel = quarantinePolicyViolation.getInt("threatLevel"); JsonArray constraintViolations = quarantinePolicyViolation.getJsonArray("constraintViolations"); for (JsonObject constraintViolation : constraintViolations.getValuesAs(JsonObject.class)) { JsonArray reasons = constraintViolation.getJsonArray("reasons"); String reason = ParseReasons.getReason(policyName, reasons); String[] line = { repository, quarantineDate, dateCleared, displayName, format, String.valueOf(quarantined), policyName, String.valueOf(threatLevel), reason }; data.add(line); } } } return data; } }
3e005953bc1744525f336160ebe3e161ddab56aa
2,391
java
Java
feign-reactor-webclient/src/main/java/reactivefeign/webclient/client/WebReactiveHttpResponse.java
maccamlc/feign-reactive
521b1cd0243b619f1bcfddc19b5ded84b7c6c510
[ "Apache-2.0" ]
null
null
null
feign-reactor-webclient/src/main/java/reactivefeign/webclient/client/WebReactiveHttpResponse.java
maccamlc/feign-reactive
521b1cd0243b619f1bcfddc19b5ded84b7c6c510
[ "Apache-2.0" ]
null
null
null
feign-reactor-webclient/src/main/java/reactivefeign/webclient/client/WebReactiveHttpResponse.java
maccamlc/feign-reactive
521b1cd0243b619f1bcfddc19b5ded84b7c6c510
[ "Apache-2.0" ]
null
null
null
32.310811
93
0.806357
147
package reactivefeign.webclient.client; import org.reactivestreams.Publisher; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ResolvableType; import org.springframework.core.codec.ByteArrayDecoder; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.web.reactive.function.BodyExtractors; import org.springframework.web.reactive.function.client.ClientResponse; import reactivefeign.client.ReactiveHttpRequest; import reactivefeign.client.ReactiveHttpResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.lang.reflect.Type; import java.util.List; import java.util.Map; class WebReactiveHttpResponse implements ReactiveHttpResponse{ private ReactiveHttpRequest reactiveRequest; private final ClientResponse clientResponse; private final Type returnPublisherType; private final ParameterizedTypeReference<Object> returnActualType; private final ByteArrayDecoder byteArrayDecoder = new ByteArrayDecoder(); WebReactiveHttpResponse(ReactiveHttpRequest reactiveRequest, ClientResponse clientResponse, Type returnPublisherType, ParameterizedTypeReference<Object> returnActualType) { this.reactiveRequest = reactiveRequest; this.clientResponse = clientResponse; this.returnPublisherType = returnPublisherType; this.returnActualType = returnActualType; } @Override public ReactiveHttpRequest request() { return reactiveRequest; } @Override public int status() { return clientResponse.statusCode().value(); } @Override public Map<String, List<String>> headers() { return clientResponse.headers().asHttpHeaders(); } @Override public Publisher<Object> body() { if (returnPublisherType == Mono.class) { return clientResponse.bodyToMono(returnActualType); } else if(returnPublisherType == Flux.class){ return clientResponse.bodyToFlux(returnActualType); } else { throw new IllegalArgumentException("Unknown returnPublisherType: " + returnPublisherType); } } @Override public Mono<byte[]> bodyData() { Flux<DataBuffer> response = clientResponse.body(BodyExtractors.toDataBuffers()); return DataBufferUtils.join(response) .map(dataBuffer -> byteArrayDecoder.decode(dataBuffer, ResolvableType.NONE, null, null)) .defaultIfEmpty(new byte[0]); } }
3e005c1f585eea215e439a7adb949f8e68e0b14b
32,137
java
Java
openjdk/Generated/jdk/gensrc/sun/util/resources/cldr/mt/LocaleNames_mt.java
SunburstApps/OpenJSharp
4875672d1dc6f09f10bb99ec67f98672b2be7011
[ "Zlib" ]
12
2018-04-04T12:47:40.000Z
2022-01-02T04:36:38.000Z
openjdk-8u45-b14/build/linux-x86_64-normal-server-release/jdk/gensrc/sun/util/resources/cldr/mt/LocaleNames_mt.java
ams-ts-ikvm-bag/ikvm-src
60009f5bdb4c9db68121f393b8b4c790a326bd32
[ "Zlib" ]
null
null
null
openjdk-8u45-b14/build/linux-x86_64-normal-server-release/jdk/gensrc/sun/util/resources/cldr/mt/LocaleNames_mt.java
ams-ts-ikvm-bag/ikvm-src
60009f5bdb4c9db68121f393b8b4c790a326bd32
[ "Zlib" ]
1
2021-12-10T07:51:50.000Z
2021-12-10T07:51:50.000Z
38.719277
96
0.384915
148
/* * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * COPYRIGHT AND PERMISSION NOTICE * * Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under * the Terms of Use in http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of the Unicode data files and any associated documentation (the "Data * Files") or Unicode software and any associated documentation (the * "Software") to deal in the Data Files or Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Data Files or Software, and * to permit persons to whom the Data Files or Software are furnished to do so, * provided that (a) the above copyright notice(s) and this permission notice * appear with all copies of the Data Files or Software, (b) both the above * copyright notice(s) and this permission notice appear in associated * documentation, and (c) there is clear notice in each modified Data File or * in the Software as well as in the documentation associated with the Data * File(s) or Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR * CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall not * be used in advertising or otherwise to promote the sale, use or other * dealings in these Data Files or Software without prior written authorization * of the copyright holder. */ package sun.util.resources.cldr.mt; import sun.util.resources.OpenListResourceBundle; public class LocaleNames_mt extends OpenListResourceBundle { @Override protected final Object[][] getContents() { final Object[][] data = new Object[][] { { "001", "Dinja" }, { "002", "Affrika" }, { "005", "Amerika t\u2019Isfel" }, { "009", "O\u010bejanja" }, { "011", "Affrika tal-Punent" }, { "013", "Amerika \u010aentrali" }, { "014", "Affrika tal-Lvant" }, { "015", "Affrika ta\u2019 Fuq" }, { "017", "Affrika Nofsani" }, { "018", "Affrika t\u2019Isfel" }, { "019", "Amerika" }, { "029", "Karibew" }, { "030", "Asja tal-Lvant" }, { "034", "Asja t\u2019Isfel \u010aentrali" }, { "035", "Asja tax-Xlokk" }, { "039", "Ewropa t\u2019Isfel" }, { "053", "Awstralja u New Zealand" }, { "054", "Melanesja" }, { "057", "Re\u0121jun ta\u2019 Mikrone\u017cja" }, { "061", "Polinesja" }, { "142", "Asja" }, { "143", "Asja \u010aentrali" }, { "145", "Asja tal-Punent" }, { "150", "Ewropa" }, { "151", "Ewropa tal-Lvant" }, { "154", "Ewropa ta\u2019 Fuq" }, { "155", "Ewropa tal-Punent" }, { "419", "Amerika Latina" }, { "AD", "Andorra" }, { "AE", "Emirati G\u0127arab Maqg\u0127uda" }, { "AF", "Afganistan" }, { "AG", "Antigua and Barbuda" }, { "AI", "Angwilla" }, { "AL", "Albanija" }, { "AM", "Armenja" }, { "AN", "Antilles Olandi\u017ci" }, { "AO", "Angola" }, { "AQ", "Antartika" }, { "AR", "Ar\u0121entina" }, { "AS", "Samoa Amerikana" }, { "AT", "Awstrija" }, { "AU", "Awstralja" }, { "AW", "Aruba" }, { "AX", "G\u017cejjer Aland" }, { "AZ", "A\u017cerbaj\u0121an" }, { "BA", "Bo\u017cnija \u0126er\u017cegovina" }, { "BB", "Barbados" }, { "BD", "Bangladexx" }, { "BE", "Bel\u0121ju" }, { "BF", "Burkina Faso" }, { "BG", "Bulgarija" }, { "BH", "Ba\u0127rajn" }, { "BI", "Burundi" }, { "BJ", "Benin" }, { "BM", "Bermuda" }, { "BN", "Brunej" }, { "BO", "Bolivja" }, { "BR", "Bra\u017cil" }, { "BS", "Ba\u0127amas" }, { "BT", "Butan" }, { "BV", "Bouvet Island" }, { "BW", "Botswana" }, { "BY", "Bjelorussja" }, { "BZ", "Beli\u017ce" }, { "CA", "Kanada" }, { "CC", "Cocos (Keeling) Islands" }, { "CD", "Democratic Republic of the Congo" }, { "CF", "Repubblika Afrikana \u010aentrali" }, { "CG", "Kongo" }, { "CH", "Svizzera" }, { "CI", "Kosta ta\u2019 l-Avorju" }, { "CK", "Cook Islands" }, { "CL", "\u010aili" }, { "CM", "Kamerun" }, { "CN", "\u010aina" }, { "CO", "Kolumbja" }, { "CR", "Kosta Rika" }, { "CS", "Serbja u Montenegro" }, { "CU", "Kuba" }, { "CV", "Kape Verde" }, { "CX", "Christmas Island" }, { "CY", "\u010aipru" }, { "CZ", "Repubblika \u010aeka" }, { "DE", "\u0120ermanja" }, { "DJ", "\u0120ibuti" }, { "DK", "Danimarka" }, { "DM", "Dominika" }, { "DO", "Republikka Domenikana" }, { "DZ", "Al\u0121erija" }, { "EC", "Ekwador" }, { "EE", "Estonja" }, { "EG", "E\u0121ittu" }, { "EH", "Sahara tal-Punent" }, { "ER", "Eritreja" }, { "ES", "Spanja" }, { "ET", "Etijopja" }, { "EU", "Unjoni Ewropea" }, { "FI", "Finlandja" }, { "FJ", "Fi\u0121i" }, { "FK", "Falkland Islands" }, { "FM", "Mikronesja" }, { "FO", "G\u017cejjer Faroe" }, { "FR", "Franza" }, { "GA", "Gabon" }, { "GB", "Ingilterra" }, { "GD", "Grenada" }, { "GE", "\u0120or\u0121ja" }, { "GF", "Gujana Fran\u010bi\u017ca" }, { "GH", "Gana" }, { "GI", "Gibraltar" }, { "GL", "Grinlandja" }, { "GM", "Gambja" }, { "GN", "Gineja" }, { "GP", "Gwadelupe" }, { "GQ", "Ginea Ekwatorjali" }, { "GR", "Gre\u010bja" }, { "GS", "South Georgia and the South Sandwich Islands" }, { "GT", "Gwatemala" }, { "GU", "Gwam" }, { "GW", "Ginea-Bissaw" }, { "GY", "Gujana" }, { "HK", "\u0126ong Kong S.A.R., \u010aina" }, { "HM", "Heard Island and McDonald Islands" }, { "HN", "\u0126onduras" }, { "HR", "Kroazja" }, { "HT", "\u0126aiti" }, { "HU", "Ungerija" }, { "ID", "Indone\u017cja" }, { "IE", "Irlanda" }, { "IL", "I\u017crael" }, { "IM", "Isle of Man" }, { "IN", "Indja" }, { "IO", "British Indian Ocean Territory" }, { "IQ", "Iraq" }, { "IR", "Iran" }, { "IS", "Islanda" }, { "IT", "Italja" }, { "JM", "\u0120amajka" }, { "JO", "\u0120ordan" }, { "JP", "\u0120appun" }, { "KE", "Kenja" }, { "KG", "Kirgistan" }, { "KH", "Kambodja" }, { "KI", "Kiribati" }, { "KM", "Komoros" }, { "KN", "Saint Kitts and Nevis" }, { "KP", "Koreja ta\u2019 Fuq" }, { "KR", "Koreja t\u2019Isfel" }, { "KW", "Kuwajt" }, { "KY", "G\u017cejjer Kajmani" }, { "KZ", "Ka\u017cakstan" }, { "LA", "Laos" }, { "LB", "Libanu" }, { "LC", "Santa Lu\u010bija" }, { "LI", "Liechtenstein" }, { "LK", "Sri Lanka" }, { "LR", "Liberja" }, { "LS", "Lesoto" }, { "LT", "Litwanja" }, { "LU", "Lussemburgu" }, { "LV", "Latvja" }, { "LY", "Libja" }, { "MA", "Marokk" }, { "MC", "Monako" }, { "MD", "Maldova" }, { "MG", "Madagaskar" }, { "MH", "G\u017cejjer ta\u2019 Marshall" }, { "MK", "Ma\u010bedonja" }, { "ML", "Mali" }, { "MM", "Mjanmar" }, { "MN", "Mongolja" }, { "MO", "Macao S.A.R., China" }, { "MP", "G\u017cejjer Marjana ta\u2019 Fuq" }, { "MQ", "Martinik" }, { "MR", "Mawritanja" }, { "MS", "Montserrat" }, { "MT", "Malta" }, { "MU", "Mawrizju" }, { "MV", "Maldives" }, { "MW", "Malawi" }, { "MX", "Messiku" }, { "MY", "Malasja" }, { "MZ", "Mo\u017cambik" }, { "NA", "Namibja" }, { "NC", "New Caledonia" }, { "NE", "Ni\u0121er" }, { "NF", "Norfolk Island" }, { "NG", "Ni\u0121erja" }, { "NI", "Nikaragwa" }, { "NL", "Olanda" }, { "NO", "Norve\u0121ja" }, { "NP", "Nepal" }, { "NR", "Nauru" }, { "NU", "Niue" }, { "NZ", "New Zealand" }, { "OM", "Oman" }, { "PA", "Panama" }, { "PE", "Peru" }, { "PF", "Polinesja Fran\u010bi\u017ca" }, { "PG", "Papwa-Ginea \u0120dida" }, { "PH", "Filippini" }, { "PK", "Pakistan" }, { "PL", "Polonja" }, { "PM", "Saint Pierre and Miquelon" }, { "PN", "Pitcairn" }, { "PR", "Puerto Rico" }, { "PS", "Palestinian Territory" }, { "PT", "Portugall" }, { "PW", "Palau" }, { "PY", "Paragwaj" }, { "QA", "Qatar" }, { "RE", "R\u00e9union" }, { "RO", "Rumanija" }, { "RU", "Russja" }, { "RW", "Rwanda" }, { "SA", "G\u0127arabja Sawdita" }, { "SB", "Solomon Islands" }, { "SC", "Seychelles" }, { "SD", "Sudan" }, { "SE", "\u017bvezja" }, { "SG", "Singapor" }, { "SH", "Saint Helena" }, { "SI", "Slovenja" }, { "SJ", "Svalbard and Jan Mayen" }, { "SK", "Slovakkja" }, { "SL", "Sierra Leone" }, { "SM", "San Marino" }, { "SN", "Senegal" }, { "SO", "Somalja" }, { "SR", "Surinam" }, { "ST", "Sao Tome and Principe" }, { "SV", "El Salvador" }, { "SY", "Sirja" }, { "SZ", "Swa\u017ciland" }, { "TC", "Turks and Caicos Islands" }, { "TD", "\u010aad" }, { "TF", "Territorji Fran\u010bi\u017ci ta\u2019 Nofsinhar" }, { "TG", "Togo" }, { "TH", "Tajlandja" }, { "TJ", "Ta\u0121ikistan" }, { "TK", "Tokelaw" }, { "TL", "Timor tal-Lvant" }, { "TM", "Turkmenistan" }, { "TN", "Tune\u017c" }, { "TO", "Tonga" }, { "TR", "Turkija" }, { "TT", "Trinidad u Tobago" }, { "TV", "Tuvalu" }, { "TW", "Tajwan" }, { "TZ", "Tan\u017canija" }, { "UA", "Ukraina" }, { "UG", "Uganda" }, { "UM", "United States Minor Outlying Islands" }, { "US", "Stati Uniti" }, { "UY", "Urugwaj" }, { "UZ", "U\u017cbekistan" }, { "VA", "Vatikan" }, { "VC", "Saint Vincent and the Grenadines" }, { "VE", "Venezwela" }, { "VG", "British Virgin Islands" }, { "VI", "U.S. Virgin Islands" }, { "VN", "Vjetnam" }, { "VU", "Vanwatu" }, { "WF", "Wallis and Futuna" }, { "WS", "Samoa" }, { "YE", "Jemen" }, { "YT", "Majotte" }, { "ZA", "Afrika t\u2019Isfel" }, { "ZM", "\u017bambja" }, { "ZW", "\u017bimbabwe" }, { "ZZ", "Re\u0121jun Mhux Mag\u0127ruf jew Mhux Validu" }, { "aa", "Afar" }, { "ab", "Abka\u017cjan" }, { "ae", "Avestan" }, { "af", "Afrikans" }, { "ak", "Akan" }, { "am", "Am\u0127ariku" }, { "an", "Aragonese" }, { "ar", "G\u0127arbi" }, { "as", "Assamese" }, { "av", "Avarik" }, { "ay", "Ajmara" }, { "az", "A\u017cerbaj\u0121ani" }, { "ba", "Baxkir" }, { "be", "Belarussu" }, { "bg", "Bulgaru" }, { "bh", "Bi\u0127ari" }, { "bi", "Bislama" }, { "bm", "Bambara" }, { "bn", "Bengali" }, { "bo", "Tibetjan" }, { "br", "Brenton" }, { "bs", "Bosnijan" }, { "ca", "Katalan" }, { "ce", "\u010ae\u010ben" }, { "ch", "\u010aamorro" }, { "co", "Korsiku" }, { "cr", "Krij" }, { "cs", "\u010aek" }, { "cu", "Slaviku tal-Knisja" }, { "cv", "\u010auvax" }, { "cy", "Welx" }, { "da", "Dani\u017c" }, { "de", "\u0120ermani\u017c" }, { "dv", "Dive\u0127i" }, { "dz", "D\u017congka" }, { "ee", "Ewe" }, { "el", "Grieg" }, { "en", "Ingli\u017c" }, { "eo", "Esperanto" }, { "es", "Spanjol" }, { "et", "Estonjan" }, { "eu", "Bask" }, { "fa", "Persjan" }, { "ff", "Fula\u0127" }, { "fi", "Finlandi\u017c" }, { "fj", "Fi\u0121i" }, { "fo", "Fawri\u017c" }, { "fr", "Fran\u010bi\u017c" }, { "fy", "Fri\u017cjan" }, { "ga", "Irlandi\u017c" }, { "gd", "Galliku Sko\u010b\u010bi\u017c" }, { "gl", "Gallegjan" }, { "gn", "Gwarani" }, { "gu", "Gu\u0121arati" }, { "gv", "Manks" }, { "ha", "\u0126awsa" }, { "he", "Ebrajk" }, { "hi", "\u0126indi" }, { "ho", "\u0126iri Motu" }, { "hr", "Kroat" }, { "ht", "Haitian" }, { "hu", "Ungeri\u017c" }, { "hy", "Armenjan" }, { "hz", "\u0126erero" }, { "ia", "Interlingua" }, { "id", "Indone\u017cjan" }, { "ie", "Interlingue" }, { "ig", "Igbo" }, { "ii", "Sichuan Yi" }, { "ik", "Inupjak" }, { "io", "Ido" }, { "is", "I\u017clandi\u017c" }, { "it", "Taljan" }, { "iu", "Inukitut" }, { "ja", "\u0120appuni\u017c" }, { "jv", "\u0120avani\u017c" }, { "ka", "\u0120or\u0121jan" }, { "kg", "Kongo" }, { "ki", "Kikuju" }, { "kj", "Kuanyama" }, { "kk", "Ka\u017cak" }, { "kl", "Kalallisut" }, { "km", "Kmer" }, { "kn", "Kannada" }, { "ko", "Korejan" }, { "kr", "Kanuri" }, { "ks", "Kaxmiri" }, { "ku", "Kurdi\u017c" }, { "kv", "Komi" }, { "kw", "Korniku" }, { "ky", "Kirgi\u017c" }, { "la", "Latin" }, { "lb", "Let\u017cburgi\u017c" }, { "lg", "Ganda" }, { "li", "Limburgish" }, { "ln", "Lingaljan" }, { "lo", "Lao" }, { "lt", "Litwanjan" }, { "lu", "Luba-Katanga" }, { "lv", "Latvjan (Lettix)" }, { "mg", "Malaga\u017ci" }, { "mh", "Marxall" }, { "mi", "Maori" }, { "mk", "Ma\u010bedonjan" }, { "ml", "Malajalam" }, { "mn", "Mongoljan" }, { "mo", "Moldavjan" }, { "mr", "Marati" }, { "ms", "Malajan" }, { "mt", "Malti" }, { "my", "Burmi\u017c" }, { "na", "Nawuru" }, { "nb", "Bokmahal Norve\u0121i\u017c" }, { "nd", "Ndebele, ta\u2019 Fuq" }, { "ne", "Nepali\u017c" }, { "ng", "Ndonga" }, { "nl", "Olandi\u017c" }, { "nn", "Ninorsk Norve\u0121i\u017c" }, { "no", "Norve\u0121i\u017c" }, { "nr", "Ndebele, t\u2019Isfel" }, { "nv", "Nava\u0127o" }, { "ny", "\u010ai\u010bewa; Njan\u0121a" }, { "oc", "O\u010b\u010bitan" }, { "oj", "O\u0121ibwa" }, { "om", "Oromo (Afan)" }, { "or", "Orija" }, { "os", "Ossettiku" }, { "pa", "Pun\u0121abi" }, { "pi", "Pali" }, { "pl", "Pollakk" }, { "ps", "Paxtun" }, { "pt", "Portugi\u017c" }, { "qu", "Ke\u010bwa" }, { "rm", "Reto-Romanz" }, { "rn", "Rundi" }, { "ro", "Rumen" }, { "ru", "Russu" }, { "rw", "Kinjarwanda" }, { "sa", "Sanskrit" }, { "sc", "Sardinjan" }, { "sd", "Sindi" }, { "se", "Sami ta\u2019 Fuq" }, { "sg", "Sango" }, { "sh", "Serbo-Kroat" }, { "si", "Sin\u0127ali\u017c" }, { "sk", "Slovakk" }, { "sl", "Sloven" }, { "sm", "Samojan" }, { "sn", "Xona" }, { "so", "Somali" }, { "sq", "Albani\u017c" }, { "sr", "Serb" }, { "ss", "Swati" }, { "st", "Soto, t\u2019Isfel" }, { "su", "Sundani\u017c" }, { "sv", "Svedi\u017c" }, { "sw", "Swa\u0127ili" }, { "ta", "Tamil" }, { "te", "Telugu" }, { "tg", "Ta\u0121ik" }, { "th", "Tajlandi\u017c" }, { "ti", "Tigrinja" }, { "tk", "Turkmeni" }, { "tl", "Tagalog" }, { "tn", "Zwana" }, { "to", "Tongan (G\u017cejjer ta\u2019 Tonga)" }, { "tr", "Tork" }, { "ts", "Tsonga" }, { "tt", "Tatar" }, { "tw", "Twi" }, { "ty", "Ta\u0127itjan" }, { "ug", "Wigur" }, { "uk", "Ukranjan" }, { "ur", "Urdu" }, { "uz", "U\u017cbek" }, { "ve", "Venda" }, { "vi", "Vjetnami\u017c" }, { "vo", "Volapuk" }, { "wa", "Walloon" }, { "wo", "Wolof" }, { "xh", "\u0126o\u017ca" }, { "yi", "Jiddix" }, { "yo", "Joruba" }, { "za", "\u017bwang" }, { "zh", "\u010aini\u017c" }, { "zu", "\u017bulu" }, { "ace", "A\u010bini\u017c" }, { "ach", "Akoli" }, { "ada", "Adangme" }, { "ady", "Adyghe" }, { "afa", "Afro-Asjatiku (O\u0127ra)" }, { "afh", "Afri\u0127ili" }, { "ain", "Ajnu" }, { "akk", "Akkadjen" }, { "ale", "Aleut" }, { "alg", "Lingwi Algonqwinjani" }, { "ang", "Ingli\u017c, Antik" }, { "anp", "Angika" }, { "apa", "Lingwi Apa\u010bi" }, { "arc", "Aramajk" }, { "arn", "Arawkanjan" }, { "arp", "Arapa\u0127o" }, { "art", "Artifi\u010bjali (O\u0127ra)" }, { "arw", "Arawak" }, { "ast", "Asturian" }, { "ath", "Lingwi Atabaskani" }, { "aus", "Lingwi Awstraljani" }, { "awa", "Awad\u0127i" }, { "bad", "Banda" }, { "bai", "Lingwi Bamileke" }, { "bal", "Balu\u010bi" }, { "ban", "Balini\u017c" }, { "bas", "Basa" }, { "bat", "Baltiku (O\u0127ra)" }, { "bej", "Beja" }, { "bem", "Bemba" }, { "ber", "Beber" }, { "bho", "Bojpuri" }, { "bik", "Bikol" }, { "bin", "Bini" }, { "bla", "Siksika" }, { "bnt", "Bantu" }, { "bra", "Braj" }, { "btk", "Batak" }, { "bua", "Burjat" }, { "bug", "Bugini\u017c" }, { "byn", "Blin" }, { "cad", "Kaddo" }, { "cai", "Amerika \u010aentrali (O\u0127ra)" }, { "car", "Karib" }, { "cau", "Kawkasu (O\u0127ra)" }, { "cch", "Atsam" }, { "ceb", "Sibwano" }, { "cel", "Keltiku (O\u0127ra)" }, { "chb", "\u010aib\u010ba" }, { "chg", "\u010aagataj" }, { "chk", "\u010aukese" }, { "chm", "Mari" }, { "chn", "\u0120argon ta\u010b-\u010ainuk" }, { "cho", "\u010aostaw" }, { "chp", "\u010aipewjan" }, { "chr", "\u010aerokij" }, { "chy", "Xajenn" }, { "cmc", "Lingwi \u010aamiki" }, { "cop", "Koptiku" }, { "cpe", "Kreoli u Pi\u0121ini, Bba\u017cat fuq l-Ingli\u017c (O\u0127ra)" }, { "cpf", "Kreoli u Pi\u0121ini, Bba\u017cat fuq il-Fran\u010bi\u017c (O\u0127ra)" }, { "cpp", "Kreoli u Pi\u0121ini, Bba\u017cat fuq il-Portugi\u017c (O\u0127ra)" }, { "crh", "Crimean Turkish; Crimean Tatar" }, { "crp", "Kreoli u Pi\u0121ini (O\u0127ra)" }, { "csb", "Kashubian" }, { "cus", "Kuxtiku (O\u0127ra)" }, { "dak", "Dakota" }, { "dar", "Dargwa" }, { "day", "Dajak" }, { "del", "Delawerjan" }, { "den", "Slav" }, { "dgr", "Dogrib" }, { "din", "Dinka" }, { "doi", "Dogri" }, { "dra", "Dravidjan (O\u0127ra)" }, { "dsb", "Lower Sorbian" }, { "dua", "Dwala" }, { "dum", "Olandi\u017c, Medjevali" }, { "dyu", "Djula" }, { "efi", "Efik" }, { "egy", "E\u0121izzjan (Antik)" }, { "eka", "Ekajuk" }, { "elx", "Elamit" }, { "enm", "Ingli\u017c, Medjevali (1100-1500)" }, { "ewo", "Ewondo" }, { "fan", "Fang" }, { "fat", "Fanti" }, { "fil", "Filippino" }, { "fiu", "Finno - Ugrijan" }, { "fon", "Fon" }, { "frm", "Fran\u010bi\u017c, Medjevali" }, { "fro", "Fran\u010bi\u017c, Antik" }, { "fur", "Frijuljan" }, { "gaa", "Ga" }, { "gay", "Gajo" }, { "gba", "Gbaja" }, { "gem", "\u0120ermaniku (O\u0127ra)" }, { "gez", "Geez" }, { "gil", "Gilbertjan" }, { "gmh", "\u0120ermaniku, Medjevali Pulit" }, { "goh", "\u0120ermaniku, Antik Pulit" }, { "gon", "Gondi" }, { "gor", "Gorontalo" }, { "got", "Gotiku" }, { "grb", "\u0120erbo" }, { "grc", "Grieg, Antik (to 1453)" }, { "gwi", "Gwi\u010bin" }, { "hai", "\u0126ajda" }, { "haw", "\u0126awajjan" }, { "hil", "Hiligaynon" }, { "him", "\u0126ima\u010bali" }, { "hit", "\u0126ittit" }, { "hmn", "\u0126mong" }, { "hsb", "Upper Sorbian" }, { "hup", "\u0126upa" }, { "iba", "Iban" }, { "ijo", "I\u0121o" }, { "ilo", "Iloko" }, { "inc", "Indjan (O\u0127ra)" }, { "ine", "Indo-Ewropew" }, { "inh", "Ingush" }, { "ira", "Iranjan" }, { "iro", "Lingwi Irogwjani" }, { "jbo", "Lojban" }, { "jpr", "Lhudi-Persjan" }, { "jrb", "Lhudi-G\u0127arbi" }, { "kaa", "Kara-Kalpak" }, { "kab", "Kabuljan" }, { "kac", "Ka\u010bin" }, { "kam", "Kamba" }, { "kar", "Karen" }, { "kaw", "Kawi" }, { "kbd", "Kabardian" }, { "kha", "Kasi" }, { "khi", "Kojsan" }, { "kho", "Kotani\u017c" }, { "kmb", "Kimbundu" }, { "kok", "Konkani" }, { "kos", "Kosrejan" }, { "kpe", "Kpelle" }, { "krc", "Karachay-Balkar" }, { "kro", "Kru" }, { "kru", "Kurusk" }, { "kum", "Kumiku" }, { "kut", "Kutenaj" }, { "lad", "Ladino" }, { "lah", "Landa" }, { "lam", "Lamba" }, { "lez", "Le\u017cgjan" }, { "lol", "Mongo" }, { "loz", "Lo\u017ci" }, { "lua", "Luba-Luluwa" }, { "lui", "Luwisinu\u017c" }, { "lun", "Lunda" }, { "luo", "Luwa" }, { "lus", "Luxaj" }, { "mad", "Maduri\u017c" }, { "mag", "Maga\u0127i" }, { "mai", "Majtili" }, { "mak", "Makasar" }, { "man", "Mandingwan" }, { "map", "Awstronesjan" }, { "mas", "Masaj" }, { "mdf", "Moksha" }, { "mdr", "Mandar" }, { "men", "Mende" }, { "mga", "Irlandi\u017c, Medjevali (900-1200)" }, { "mic", "Mikmek" }, { "min", "Minangkabaw" }, { "mis", "Lingwi O\u0127ra" }, { "mkh", "Mon-Kmer (O\u0127ra)" }, { "mnc", "Man\u010burjan" }, { "mni", "Manipuri" }, { "mno", "Lingwi Manobo" }, { "moh", "Mo\u0127ak" }, { "mos", "Mossi" }, { "mul", "Lingwi Diversi" }, { "mun", "Lingwi tal-Munda" }, { "mus", "Kriek" }, { "mwl", "Mirandi\u017c" }, { "mwr", "Marwari" }, { "myn", "Majan" }, { "myv", "Erzya" }, { "nah", "Na\u0127watil" }, { "nai", "Indjan tal-Amerika ta\u2019 Fuq (O\u0127ra)" }, { "nap", "Neapolitan" }, { "nds", "\u0120ermani\u017c Komuni; Sassonu Komuni" }, { "new", "Newari" }, { "nia", "Nijas" }, { "nic", "Ni\u0121erjan - Kordofanjan" }, { "niu", "Nijuwejan" }, { "nog", "Nogai" }, { "non", "Skandinav, Antik" }, { "nso", "Soto, ta\u2019 Fuq" }, { "nub", "Lingwi Nubjani" }, { "nwc", "Classical Newari" }, { "nym", "Njamwe\u017ci" }, { "nyn", "Nyankole" }, { "nyo", "Njoro" }, { "nzi", "N\u017cima" }, { "osa", "Osa\u0121jan" }, { "ota", "Tork (Imperu Ottoman)" }, { "oto", "Lingwi Otomjani" }, { "paa", "Papwan (O\u0127ra)" }, { "pag", "Pangasinjan" }, { "pal", "Pa\u0127lavi" }, { "pam", "Pampamga" }, { "pap", "Papjamento" }, { "pau", "Palawjan" }, { "peo", "Persjan Antik" }, { "phi", "Filippin (O\u0127ra)" }, { "phn", "Feni\u010bju" }, { "pon", "Ponpejan" }, { "pra", "Lingwi Prakriti" }, { "pro", "Provenzal, Antik (sa l-1500)" }, { "raj", "Ra\u0121astani" }, { "rap", "Rapanwi" }, { "rar", "Rarotongani" }, { "roa", "Romanz (O\u0127ra)" }, { "rom", "\u017bingaru" }, { "rup", "Aromanijan" }, { "sad", "Sandawe" }, { "sah", "Jakut" }, { "sai", "Indjan tal-Amerika t\u2019Isfel (O\u0127ra)" }, { "sal", "Salixan" }, { "sam", "Samritan" }, { "sas", "Saska" }, { "sat", "Santali" }, { "sco", "Sko\u010b\u010bi\u017c" }, { "sel", "Selkup" }, { "sem", "Semitiku" }, { "sga", "Irlandi\u017c, Antik (sa l-900)" }, { "sgn", "Lingwa tas-Sinjali" }, { "shn", "Xan" }, { "sid", "Sidamo" }, { "sio", "Lingwi Suwjani" }, { "sit", "Sino-Tibetjani (O\u0127ra)" }, { "sla", "Slavic (Other)" }, { "sma", "Southern Sami" }, { "smi", "Sami languages (Other)" }, { "smj", "Lule Sami" }, { "smn", "Inari Sami" }, { "sms", "Skolt Sami" }, { "snk", "Soninke" }, { "sog", "Sogdien" }, { "son", "Songaj" }, { "srr", "Serer" }, { "ssa", "Nilo-Sa\u0127aram" }, { "suk", "Sukuma" }, { "sus", "Susu" }, { "sux", "Sumerjan" }, { "syr", "Sirjan" }, { "tai", "Tai (O\u0127ra)" }, { "tem", "Timne" }, { "ter", "Tereno" }, { "tet", "Tetum" }, { "tig", "Tigre" }, { "tiv", "Tiv" }, { "tkl", "Tokelau" }, { "tlh", "Klingon" }, { "tli", "Tlingit" }, { "tmh", "Tamaxek" }, { "tog", "Tonga (Njasa)" }, { "tpi", "Tok Pisin" }, { "tsi", "Zimxjan" }, { "tum", "Tumbuka" }, { "tup", "Tupi languages" }, { "tut", "Altajk (O\u0127ra)" }, { "tvl", "Tuvalu" }, { "tyv", "Tuvinjan" }, { "udm", "Udmurt" }, { "uga", "Ugaritiku" }, { "umb", "Umbundu" }, { "und", "Indeterminat" }, { "vai", "Vai" }, { "vot", "Votik" }, { "wak", "Lingwi Wakaxani" }, { "wal", "Walamo" }, { "war", "Waraj" }, { "was", "Waxo" }, { "wen", "Lingwi Sorbjani" }, { "xal", "Kalmyk" }, { "yao", "Jao" }, { "yap", "Japese" }, { "ypk", "Lingwi Jupi\u010bi" }, { "zap", "\u017bapotek" }, { "zen", "\u017benaga" }, { "znd", "\u017bande" }, { "zun", "\u017buni" }, { "Arab", "G\u0127arbi" }, { "Grek", "Grieg" }, { "Hans", "\u0126an Sempli\u010bi" }, { "Hant", "\u0126an Tradizzjonali" }, { "Latn", "Latin" }, { "Xpeo", "Persjan Antik" }, { "Zxxx", "Mhux Miktub" }, { "Zyyy", "Komuni" }, { "Zzzz", "Skritt Mhux Mag\u0127ruf jew Mhux Validu" }, { "root", "G\u0127erq" }, }; return data; } }
3e005c93530a3aed05f3c12b6fdcebee315c7ece
6,383
java
Java
lucene/src/edu/ucla/cs/cs144/HelloLucene.java
OrlandoLee/ForYou
ff11ae411a99f4e7f22fc8b2a6c550255c07482b
[ "MIT" ]
1
2019-03-10T22:01:50.000Z
2019-03-10T22:01:50.000Z
lucene/src/edu/ucla/cs/cs144/HelloLucene.java
OrlandoLee/ForYou
ff11ae411a99f4e7f22fc8b2a6c550255c07482b
[ "MIT" ]
null
null
null
lucene/src/edu/ucla/cs/cs144/HelloLucene.java
OrlandoLee/ForYou
ff11ae411a99f4e7f22fc8b2a6c550255c07482b
[ "MIT" ]
1
2020-11-19T03:06:28.000Z
2020-11-19T03:06:28.000Z
38.684848
430
0.628858
149
package edu.ucla.cs.cs144; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Version; public class HelloLucene { public HelloLucene() { } private IndexWriter indexWriter = null; private IndexSearcher searcher = null; // private QueryParser categoryParser = null; private Directory index = null; public IndexWriter getIndexWriter(boolean create) throws IOException { if(create){ if (indexWriter == null) { StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); index = new RAMDirectory(); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer); indexWriter = new IndexWriter(index,config); } } return indexWriter; } public void closeIndexWriter() throws IOException { if (indexWriter != null) { indexWriter.close(); } } public void indexCategory(String id, String category) throws IOException { //TO-DO we need a struct for id and category IndexWriter writer = getIndexWriter(false); Document doc = new Document(); doc.add(new Field("id", id, TextField.TYPE_STORED)); doc.add(new Field("category", category, TextField.TYPE_STORED)); // doc.add(new Field("id",id,Field.Store.YES,Field.Index.NO)); // doc.add(new Field("category",category,Field.Store.YES,Field.Index.TOKENIZED)); writer.addDocument(doc); } public void rebuildIndexes() throws SQLException { Connection conn = null; // create a connection to the database to retrieve Items from MySQL try { conn = DbManager.getConnection(true); } catch (SQLException ex) { System.out.println(ex); } Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select id, mainCategory, subCategory from podcast"); try{ getIndexWriter(true); while(rs.next()){ //System.out.println(rs.getString("id")+":"+rs.getString("mainCategory")+rs.getString("subCategory")); indexCategory(rs.getString("id"),rs.getString("mainCategory")+rs.getString("subCategory")); } closeIndexWriter(); }catch (Exception e) { System.out.println("Exception caught"); } // close the database connection try { conn.close(); } catch (SQLException ex) { System.out.println(ex); } } //////////////////////////////////////////// public void search() throws IOException, ParseException{ // 2. query 区域 本地 needs to be more specific String[] categoryArray = {"健康","儿童与家庭","商业","喜剧","宗教与精神生活","政府与组织","教育","新闻及政治","游戏与爱好","电视与电影","社会与文化","科学与医学","科技","艺术","运动与消遣","音乐","两性关系","投资","基督教","专业","业余","个人日记","中小学","伊斯兰教","佛教","健美与营养","全国","其他","其它游戏","励志自助","区域","医药","历史","另类保健","名胜与旅行","哲学","商业新闻","培训","大中院校","小工具","户外","播客发布","教育科技","文学","时尚美容","本地","汽车","爱好","社会科学","科技新闻","管理和营销","精神生活","美食","职业","自然科学","表演艺术","视频游戏","视频艺术","设计","语言教程","软件技巧","非营利","高等教育"}; String[] weightArray = {"1.3","1","1","100","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"}; // String[] categoryArray = {"健康","儿童与家庭"}; // String[] weightArray = {"1","1"}; String querystr = "";//"(表演艺术)^1.5 (视频)^2"; for(int i=0; i<categoryArray.length;i++) { querystr+="("+categoryArray[i]+")^"+weightArray[i]+" "; } // the "title" arg specifies the default field to use // when no field is explicitly specified in the query. StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); Query categoryParser = new QueryParser(Version.LUCENE_40, "category", analyzer).parse(querystr); // 3. search int hitsPerPage = 50; IndexReader reader = DirectoryReader.open(index); /* int num = reader.numDocs(); for ( int i = 0; i < num; i++) { Document d = reader.document( i); System.out.println( "d=" +d); } reader.close(); */ searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true); searcher.search(categoryParser, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; // 4. display results System.out.println("Found " + hits.length + " hits."); for(int i=0;i<hits.length;++i) { int docId = hits[i].doc; Document d = searcher.doc(docId); System.out.println((i + 1) + ". " + d.get("id") + "\t" + d.get("category")); } // reader can only be closed when there // is no need to access the documents any more. reader.close(); ///////////////////////////////////////////////////////////// } public static void main(String args[]) { HelloLucene idx = new HelloLucene(); try{ idx.rebuildIndexes(); idx.search(); } //catch(SQLException ex){ // System.out.println("SQLException caught"); // System.out.println("---"); // while ( ex != null ){ // System.out.println("Message : " + ex.getMessage()); // System.out.println("SQLState : " + ex.getSQLState()); // System.out.println("ErrorCode : " + ex.getErrorCode()); // System.out.println("---"); // ex = ex.getNextException(); // } catch(Exception ex){ System.out.println(ex); } //} } }
3e005ce9c4c345f89801d0a4024d33e594b1b885
2,045
java
Java
aggressor/bridges/ReportingBridge.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
1
2022-02-24T01:32:41.000Z
2022-02-24T01:32:41.000Z
aggressor/bridges/ReportingBridge.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
aggressor/bridges/ReportingBridge.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
34.661017
89
0.660147
150
package aggressor.bridges; import aggressor.AggressorClient; import aggressor.dialogs.ExportDataDialog; import aggressor.dialogs.ExportReportDialog; import cortana.Cortana; import java.util.Stack; import sleep.bridges.BridgeUtilities; import sleep.interfaces.Function; import sleep.interfaces.Loadable; import sleep.runtime.Scalar; import sleep.runtime.ScriptInstance; import sleep.runtime.SleepUtils; public class ReportingBridge implements Function, Loadable { protected AggressorClient client; public ReportingBridge(AggressorClient var1) { this.client = var1; } public void scriptLoaded(ScriptInstance var1) { Cortana.put(var1, "&reports", this); Cortana.put(var1, "&reportDescription", this); Cortana.put(var1, "&openReportDialog", this); Cortana.put(var1, "&openExportDataDialog", this); Cortana.put(var1, "&rehash_reports", this); } public void scriptUnloaded(ScriptInstance var1) { } public Scalar evaluate(String var1, ScriptInstance var2, Stack var3) { if ("&reports".equals(var1)) { return SleepUtils.getArrayWrapper(this.client.getReportEngine().reportTitles()); } else { String var4; if ("&reportDescription".equals(var1)) { var4 = BridgeUtilities.getString(var3, ""); return SleepUtils.getScalar(this.client.getReportEngine().describe(var4)); } else { if ("&openReportDialog".equals(var1)) { var4 = BridgeUtilities.getString(var3, ""); ExportReportDialog var5 = new ExportReportDialog(this.client, var4); var5.show(); } else if ("&openExportDataDialog".equals(var1)) { ExportDataDialog var6 = new ExportDataDialog(this.client); var6.show(); } else if ("&rehash_reports".equals(var1)) { this.client.getReportEngine().rehash(); return SleepUtils.getScalar("done"); } return SleepUtils.getEmptyScalar(); } } } }
3e005ced5ad8321da293998d1b93031eacc8db6d
1,492
java
Java
bundle_hello/src/main/java/com/gaia/hello/protocol/GithubUserInfoTask.java
neilnee/gaia
ed430f346d2d70c8affa59de8d6f8fadff5e4775
[ "Apache-2.0" ]
null
null
null
bundle_hello/src/main/java/com/gaia/hello/protocol/GithubUserInfoTask.java
neilnee/gaia
ed430f346d2d70c8affa59de8d6f8fadff5e4775
[ "Apache-2.0" ]
null
null
null
bundle_hello/src/main/java/com/gaia/hello/protocol/GithubUserInfoTask.java
neilnee/gaia
ed430f346d2d70c8affa59de8d6f8fadff5e4775
[ "Apache-2.0" ]
null
null
null
29.84
95
0.691689
151
package com.gaia.hello.protocol; import com.gaia.core.asyn.AbstractAsynTask; import com.gaia.core.asyn.AsynExecutor; import com.gaia.core.asyn.TaskEvent; import com.gaia.core.asyn.TaskException; import com.gaia.hello.model.GithubUserInfo; import java.io.IOException; public class GithubUserInfoTask extends AbstractAsynTask { public interface IGithubUserInfoTaskListener { void onDataObtain(GithubUserInfo info); } public static void queryUserInfo(String user, IGithubUserInfoTaskListener lis) { GithubUserInfoTask task = new GithubUserInfoTask(); task.mUser = user; task.setListener(lis); AsynExecutor.defaultExecutor().execute(task); } private String mUser = null; private GithubUserInfo mResultUser = null; private IGithubUserInfoTaskListener mListener = null; public void setListener(IGithubUserInfoTaskListener lis) { mListener = lis; } @Override protected void runWorkThread() { try { GithubService service = makeService(GithubService.class, "https://api.github.com"); mResultUser = requestHttpData(service.queryUserInfo(mUser)); postEventMainThread(new TaskEvent()); } catch (IOException | TaskException e) { e.printStackTrace(); } } @Override protected void handleEventMainThread(TaskEvent event) { if (mListener != null) { mListener.onDataObtain(mResultUser); } } }
3e005dce90c2cc024b6d96e05f309bb746bc3ce6
4,492
java
Java
app/src/main/java/com/alorma/github/GitskariosApplication.java
gitskarios/Gitskarios
e87b5e4d5e28b0ed5071c35ef3786154afe891b2
[ "MIT" ]
676
2015-04-17T11:14:16.000Z
2022-02-12T14:18:25.000Z
app/src/main/java/com/alorma/github/GitskariosApplication.java
gitskarios/Gitskarios
e87b5e4d5e28b0ed5071c35ef3786154afe891b2
[ "MIT" ]
552
2015-04-17T07:14:02.000Z
2019-03-13T15:53:41.000Z
app/src/main/java/com/alorma/github/GitskariosApplication.java
gitskarios/Gitskarios
e87b5e4d5e28b0ed5071c35ef3786154afe891b2
[ "MIT" ]
169
2015-04-18T03:27:00.000Z
2022-02-12T14:18:32.000Z
36.225806
119
0.790294
152
package com.alorma.github; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.multidex.MultiDexApplication; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; import com.alorma.github.gcm.GitskariosInstanceIDListenerService; import com.alorma.github.injector.component.ApplicationComponent; import com.alorma.github.injector.component.DaggerApplicationComponent; import com.alorma.github.injector.component.DaggerNotificationsComponent; import com.alorma.github.injector.component.NotificationsComponent; import com.alorma.github.injector.module.ApplicationModule; import com.alorma.github.injector.module.NotificationsModule; import com.alorma.github.notifications.AppNotificationsManager; import com.alorma.github.ui.activity.MainActivity; import com.alorma.github.ui.utils.UniversalImageLoaderUtils; import com.alorma.gitskarios.core.client.LogProvider; import com.alorma.gitskarios.core.client.TokenProvider; import com.alorma.gitskarios.core.client.UrlProvider; import com.alorma.gitskarios.core.client.UsernameProvider; import com.appsee.Appsee; import com.crashlytics.android.Crashlytics; import com.frogermcs.activityframemetrics.ActivityFrameMetrics; import com.google.firebase.FirebaseApp; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.database.FirebaseDatabase; import com.karumi.dexter.Dexter; import com.nostra13.universalimageloader.core.ImageLoader; import io.fabric.sdk.android.Fabric; import io.flowup.FlowUp; import javax.inject.Inject; public class GitskariosApplication extends MultiDexApplication { @Inject AppNotificationsManager notificationsManager; private ApplicationComponent applicationComponent; private NotificationsComponent notificationsComponent; public static GitskariosApplication get(Context context) { return (GitskariosApplication) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); Dexter.initialize(this); if (!FirebaseApp.getApps(this).isEmpty()) { FirebaseDatabase.getInstance().setPersistenceEnabled(true); } if (!BuildConfig.DEBUG) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerActivityLifecycleCallbacks(new ActivityFrameMetrics.Builder().build()); } CustomActivityOnCrash.install(this); CustomActivityOnCrash.setRestartActivityClass(MainActivity.class); CustomActivityOnCrash.setEnableAppRestart(true); } FlowUp.Builder.with(this) .apiKey(getString(R.string.flowup_api_key)) .forceReports(BuildConfig.DEBUG) .start(); Fabric.with(this, new Crashlytics()); Appsee.start(getString(R.string.com_appsee_apikey)); FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.getInstance(this); firebaseAnalytics.setAnalyticsCollectionEnabled(true); ImageLoader.getInstance().init(UniversalImageLoaderUtils.getImageLoaderConfiguration(this)); TokenProvider.setTokenProviderInstance(() -> getStoreCredentials().token()); UrlProvider.setUrlProviderInstance(() -> getStoreCredentials().getUrl()); UsernameProvider.setUsernameProviderInterface(() -> getStoreCredentials().getUserName()); LogProvider.setTokenProviderInstance(message -> { if (BuildConfig.DEBUG) { //Log.v("RETROFIT_LOG", message); } }); if (new GitskariosSettings(this).getGCMToken() == null) { Intent intent = new Intent(this, GitskariosInstanceIDListenerService.class); startService(intent); } initializeInjector(); notificationsManager.setNotificationsEnabled(notificationsManager.areNotificationsEnabled()); } private void initializeInjector() { applicationComponent = DaggerApplicationComponent.builder().applicationModule(new ApplicationModule(this)).build(); notificationsComponent = DaggerNotificationsComponent.builder() .applicationComponent(applicationComponent) .notificationsModule(new NotificationsModule()) .build(); notificationsComponent.inject(this); } public ApplicationComponent getApplicationComponent() { return applicationComponent; } @NonNull private StoreCredentials getStoreCredentials() { return new StoreCredentials(GitskariosApplication.this); } public void setNotificationsEnabled(boolean isChecked) { notificationsManager.setNotificationsEnabled(isChecked); } }
3e005e20e5c58be2454c4d31dba7c0079858268e
1,020
java
Java
src/main/java/com/marcnuri/demo/springmockmvc/language/LanguageRepository.java
marcnuri-demo/spring-mockmvc-test
4fa7455eb61bab25491a5e732777dad49db0e753
[ "Apache-2.0" ]
8
2018-05-13T21:26:22.000Z
2022-01-22T08:36:54.000Z
src/main/java/com/marcnuri/demo/springmockmvc/language/LanguageRepository.java
marcnuri-demo/spring-mockmvc-test
4fa7455eb61bab25491a5e732777dad49db0e753
[ "Apache-2.0" ]
1
2019-09-04T05:24:02.000Z
2019-09-19T05:23:30.000Z
src/main/java/com/marcnuri/demo/springmockmvc/language/LanguageRepository.java
marcnuri-demo/spring-mockmvc-test
4fa7455eb61bab25491a5e732777dad49db0e753
[ "Apache-2.0" ]
11
2018-10-24T00:55:46.000Z
2022-03-27T07:43:14.000Z
27.567568
80
0.686275
153
/* * SpringMockLanguagesRepository.java * * Created on 2018-05-20, 7:18 */ package com.marcnuri.demo.springmockmvc.language; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.springframework.stereotype.Repository; /** * Created by Marc Nuri <[email protected]> on 2018-05-20. */ @Repository public class LanguageRepository { protected static final List<Language> LANGUAGES = Arrays.asList( of("C", "Dennis Ritchie"), of("C++", "Bjarne Stroustrup"), of("Java", "James Gosling"), of("JavaScript", "Brendan Eich"), of("C#", "Microsoft"), of("Perl", "Larry Wall"), of("Python", "Guido van Rossum"), of("Ruby", "Yukihiro Matsumoto")); public List<Language> findAll() { return LANGUAGES; } public Optional<Language> findByName(String name) { return LANGUAGES.stream().filter(l -> l.getName().equals(name)).findFirst(); } private static final Language of(String name, String designer) { return new Language(name, designer); } }
3e005eb4088eead331503eb4d2f22661eff7063a
14,349
java
Java
src/src/jdk/tools/jaotc/binformat/elf/JELFRelocObject.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/elf/JELFRelocObject.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/elf/JELFRelocObject.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
43.350453
176
0.627012
154
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.tools.jaotc.binformat.elf; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import jdk.tools.jaotc.binformat.BinaryContainer; import jdk.tools.jaotc.binformat.ByteContainer; import jdk.tools.jaotc.binformat.CodeContainer; import jdk.tools.jaotc.binformat.ReadOnlyDataContainer; import jdk.tools.jaotc.binformat.Relocation; import jdk.tools.jaotc.binformat.Relocation.RelocType; import jdk.tools.jaotc.binformat.Symbol; import jdk.tools.jaotc.binformat.Symbol.Binding; import jdk.tools.jaotc.binformat.Symbol.Kind; import jdk.tools.jaotc.binformat.elf.ElfSymbol; import jdk.tools.jaotc.binformat.elf.ElfTargetInfo; import jdk.tools.jaotc.binformat.elf.Elf.Elf64_Ehdr; import jdk.tools.jaotc.binformat.elf.Elf.Elf64_Shdr; import jdk.tools.jaotc.binformat.elf.Elf.Elf64_Sym; import jdk.tools.jaotc.binformat.elf.Elf.Elf64_Rela; public abstract class JELFRelocObject { private final BinaryContainer binContainer; private final ElfContainer elfContainer; private final int segmentSize; protected JELFRelocObject(BinaryContainer binContainer, String outputFileName) { this.binContainer = binContainer; this.elfContainer = new ElfContainer(outputFileName); this.segmentSize = binContainer.getCodeSegmentSize(); } public static JELFRelocObject newInstance(BinaryContainer binContainer, String outputFileName) { String archStr = System.getProperty("os.arch").toLowerCase(); if (archStr.equals("amd64") || archStr.equals("x86_64")) { return new AMD64JELFRelocObject(binContainer, outputFileName); } else if (archStr.equals("aarch64")) { return new AArch64JELFRelocObject(binContainer, outputFileName); } throw new InternalError("Unsupported platform: " + archStr); } private static ElfSection createByteSection(ArrayList<ElfSection> sections, String sectName, byte[] scnData, boolean hasRelocs, int align, int scnFlags, int scnType) { ElfSection sect = new ElfSection(sectName, scnData, scnFlags, scnType, hasRelocs, align, sections.size()); // Add this section to our list sections.add(sect); return (sect); } private void createByteSection(ArrayList<ElfSection> sections, ByteContainer c, int scnFlags) { ElfSection sect; boolean hasRelocs = c.hasRelocations(); byte[] scnData = c.getByteArray(); int scnType = Elf64_Shdr.SHT_PROGBITS; boolean zeros = !hasRelocs; if (zeros) { for (byte b : scnData) { if (b != 0) { zeros = false; break; } } if (zeros) { scnType = Elf64_Shdr.SHT_NOBITS; } } sect = createByteSection(sections, c.getContainerName(), scnData, hasRelocs, segmentSize, scnFlags, scnType); c.setSectionId(sect.getSectionId()); } private void createCodeSection(ArrayList<ElfSection> sections, CodeContainer c) { createByteSection(sections, c, Elf64_Shdr.SHF_ALLOC | Elf64_Shdr.SHF_EXECINSTR); } private void createReadOnlySection(ArrayList<ElfSection> sections, ReadOnlyDataContainer c) { createByteSection(sections, c, Elf64_Shdr.SHF_ALLOC); } private void createReadWriteSection(ArrayList<ElfSection> sections, ByteContainer c) { createByteSection(sections, c, Elf64_Shdr.SHF_ALLOC | Elf64_Shdr.SHF_WRITE); } /** * Create an ELF relocatable object * * @param relocationTable * @param symbols * @throws IOException throws {@code IOException} as a result of file system access failures. */ public void createELFRelocObject(Map<Symbol, List<Relocation>> relocationTable, Collection<Symbol> symbols) throws IOException { // Allocate ELF Header ElfHeader eh = new ElfHeader(); ArrayList<ElfSection> sections = new ArrayList<>(); // Create the null section createByteSection(sections, null, null, false, 1, 0, 0); // Create text section createCodeSection(sections, binContainer.getCodeContainer()); createReadOnlySection(sections, binContainer.getMetaspaceNamesContainer()); createReadOnlySection(sections, binContainer.getKlassesOffsetsContainer()); createReadOnlySection(sections, binContainer.getMethodsOffsetsContainer()); createReadOnlySection(sections, binContainer.getKlassesDependenciesContainer()); createReadOnlySection(sections, binContainer.getMethodMetadataContainer()); createReadOnlySection(sections, binContainer.getStubsOffsetsContainer()); createReadOnlySection(sections, binContainer.getHeaderContainer().getContainer()); createReadOnlySection(sections, binContainer.getCodeSegmentsContainer()); createReadOnlySection(sections, binContainer.getConstantDataContainer()); createReadOnlySection(sections, binContainer.getConfigContainer()); createReadWriteSection(sections, binContainer.getKlassesGotContainer()); createReadWriteSection(sections, binContainer.getCountersGotContainer()); createReadWriteSection(sections, binContainer.getMetadataGotContainer()); createReadWriteSection(sections, binContainer.getOopGotContainer()); createReadWriteSection(sections, binContainer.getMethodStateContainer()); createReadWriteSection(sections, binContainer.getExtLinkageGOTContainer()); // Get ELF symbol data from BinaryContainer object's symbol tables ElfSymtab symtab = createELFSymbolTables(symbols); // Create string table section and symbol table sections in // that order since symtab section needs to set the index of // strtab in sh_link field ElfSection strTabSection = createByteSection(sections, ".strtab", symtab.getStrtabArray(), false, 1, 0, Elf64_Shdr.SHT_STRTAB); // Now create .symtab section with the symtab data constructed. // On Linux, sh_link of symtab contains the index of string table // its symbols reference and sh_info contains the index of first // non-local symbol ElfSection symTabSection = createByteSection(sections, ".symtab", symtab.getSymtabArray(), false, 8, 0, Elf64_Shdr.SHT_SYMTAB); symTabSection.setLink(strTabSection.getSectionId()); symTabSection.setInfo(symtab.getNumLocalSyms()); ElfRelocTable elfRelocTable = createElfRelocTable(sections, relocationTable); createElfRelocSections(sections, elfRelocTable, symTabSection.getSectionId()); // Now, finally, after creating all sections, create shstrtab section ElfSection shStrTabSection = createByteSection(sections, ".shstrtab", null, false, 1, 0, Elf64_Shdr.SHT_STRTAB); eh.setSectionStrNdx(shStrTabSection.getSectionId()); // Update all section offsets and the Elf header section offset // Write the Header followed by the contents of each section // and then the section structures (section table). int file_offset = Elf64_Ehdr.totalsize; // and round it up file_offset = (file_offset + (sections.get(1).getDataAlign() - 1)) & ~((sections.get(1).getDataAlign() - 1)); // Calc file offsets for section data skipping null section for (int i = 1; i < sections.size(); i++) { ElfSection sect = sections.get(i); file_offset = (file_offset + (sect.getDataAlign() - 1)) & ~((sect.getDataAlign() - 1)); sect.setOffset(file_offset); file_offset += sect.getSize(); } // Align the section table file_offset = (file_offset + (ElfSection.getShdrAlign() - 1)) & ~((ElfSection.getShdrAlign() - 1)); // Update the Elf Header with the offset of the first Elf64_Shdr // and the number of sections. eh.setSectionOff(file_offset); eh.setSectionNum(sections.size()); // Write out the Header elfContainer.writeBytes(eh.getArray()); // Write out each section contents skipping null section for (int i = 1; i < sections.size(); i++) { ElfSection sect = sections.get(i); elfContainer.writeBytes(sect.getDataArray(), sect.getDataAlign()); } // Write out the section table for (int i = 0; i < sections.size(); i++) { ElfSection sect = sections.get(i); elfContainer.writeBytes(sect.getArray(), ElfSection.getShdrAlign()); } elfContainer.close(); } /** * Construct ELF symbol data from BinaryContainer object's symbol tables. Both dynamic ELF symbol * table and ELF symbol table are created from BinaryContainer's symbol info. * * @param symbols */ private static ElfSymtab createELFSymbolTables(Collection<Symbol> symbols) { ElfSymtab symtab = new ElfSymtab(); // First, create the initial null symbol. This is a local symbol. symtab.addSymbolEntry("", (byte) 0, (byte) 0, Elf64_Shdr.SHN_UNDEF, 0, 0); // Now create ELF symbol entries for all symbols. for (Symbol symbol : symbols) { // Get the index of section this symbol is defined in. int secHdrIndex = symbol.getSection().getSectionId(); ElfSymbol elfSymbol = symtab.addSymbolEntry(symbol.getName(), getELFTypeOf(symbol), getELFBindOf(symbol), (byte) secHdrIndex, symbol.getOffset(), symbol.getSize()); symbol.setNativeSymbol(elfSymbol); } return (symtab); } private static byte getELFTypeOf(Symbol sym) { Kind kind = sym.getKind(); if (kind == Symbol.Kind.NATIVE_FUNCTION || kind == Symbol.Kind.JAVA_FUNCTION) { return Elf64_Sym.STT_FUNC; } else if (kind == Symbol.Kind.OBJECT) { return Elf64_Sym.STT_OBJECT; } return Elf64_Sym.STT_NOTYPE; } private static byte getELFBindOf(Symbol sym) { Binding binding = sym.getBinding(); if (binding == Symbol.Binding.GLOBAL) { return Elf64_Sym.STB_GLOBAL; } return Elf64_Sym.STB_LOCAL; } /** * Construct a Elf relocation table from BinaryContainer object's relocation tables. * * @param sections * @param relocationTable */ private ElfRelocTable createElfRelocTable(ArrayList<ElfSection> sections, Map<Symbol, List<Relocation>> relocationTable) { ElfRelocTable elfRelocTable = new ElfRelocTable(sections.size()); /* * For each of the symbols with associated relocation records, create a Elf relocation entry. */ for (Map.Entry<Symbol, List<Relocation>> entry : relocationTable.entrySet()) { List<Relocation> relocs = entry.getValue(); Symbol symbol = entry.getKey(); for (Relocation reloc : relocs) { createRelocation(symbol, reloc, elfRelocTable); } } for (Map.Entry<Symbol, Relocation> entry : binContainer.getUniqueRelocationTable().entrySet()) { createRelocation(entry.getKey(), entry.getValue(), elfRelocTable); } return (elfRelocTable); } private static void createElfRelocSections(ArrayList<ElfSection> sections, ElfRelocTable elfRelocTable, int symtabsectidx) { // Grab count before we create new sections int count = sections.size(); for (int i = 0; i < count; i++) { if (elfRelocTable.getNumRelocs(i) > 0) { ElfSection sect = sections.get(i); String relname = ".rela" + sect.getName(); ElfSection relocSection = createByteSection(sections, relname, elfRelocTable.getRelocData(i), false, 8, 0, Elf64_Shdr.SHT_RELA); relocSection.setLink(symtabsectidx); relocSection.setInfo(sect.getSectionId()); } } } abstract void createRelocation(Symbol symbol, Relocation reloc, ElfRelocTable elfRelocTable); }
3e005ebaaae1aaa81c4038cf0c9bc8ee2608e7c0
7,226
java
Java
src/main/java/org/earthtime/Tripoli/dataViews/simpleViews/usedByReflection/CorrectedRatioDataView.java
bowring/ET_Redux
ca80dcd76b6529b2cab82027f80a179be39f720c
[ "Apache-2.0" ]
15
2015-03-25T14:16:24.000Z
2022-03-05T02:17:00.000Z
src/main/java/org/earthtime/Tripoli/dataViews/simpleViews/usedByReflection/CorrectedRatioDataView.java
bowring/ET_Redux
ca80dcd76b6529b2cab82027f80a179be39f720c
[ "Apache-2.0" ]
104
2015-01-22T23:41:19.000Z
2022-02-20T12:46:03.000Z
src/main/java/org/earthtime/Tripoli/dataViews/simpleViews/usedByReflection/CorrectedRatioDataView.java
CIRDLES/ET_Redux
1f045fd39cf3dd76d5172b63355753bb8bacebc3
[ "Apache-2.0" ]
24
2015-01-23T15:30:35.000Z
2020-11-23T16:14:27.000Z
34.908213
99
0.633684
155
/* * CorrectedRatioDataView.java * * Copyright 2006-2018 James F. Bowring, CIRDLES.org, and Earth-Time.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.earthtime.Tripoli.dataViews.simpleViews.usedByReflection; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Path2D; import javax.swing.JLayeredPane; import org.earthtime.Tripoli.dataModels.DataModelInterface; import org.earthtime.Tripoli.dataModels.RawRatioDataModel; import org.earthtime.Tripoli.dataViews.AbstractRawDataView; import org.earthtime.Tripoli.fractions.TripoliFraction; import org.earthtime.dataDictionaries.IncludedTypeEnum; import org.earthtime.utilities.TicGeneratorForAxes; /** * * @author James F. Bowring */ public class CorrectedRatioDataView extends AbstractRawDataView { /** * */ public static int DEFAULT_WIDTH_OF_PANE = 128; /** * * @param sampleSessionDataView * @param tripoliFraction * @param rawRatioDataModel * @param bounds * @param invokeMouseListener */ public CorrectedRatioDataView(// JLayeredPane sampleSessionDataView, TripoliFraction tripoliFraction,// DataModelInterface rawRatioDataModel,// Rectangle bounds,// boolean invokeMouseListener) { super(sampleSessionDataView, tripoliFraction, bounds, invokeMouseListener, true); this.rawRatioDataModel = rawRatioDataModel; } /** * * @param g2d */ @Override public void paint(Graphics2D g2d) { //super.paint( g2d ); paintInit(g2d); double mean = ((RawRatioDataModel) rawRatioDataModel).getMeanOfCorrectedRatios(); double sigma = ((RawRatioDataModel) rawRatioDataModel).getStdDevOfCorrectedRatios(); double stdErr = ((RawRatioDataModel) rawRatioDataModel).getStdErrOfMeanCorrectedRatios(); //draw two-sigma Path2D twoSigmaArea = new Path2D.Double(); twoSigmaArea.moveTo(mapX(minX), mapY(mean - 2.0 * sigma)); twoSigmaArea.lineTo(mapX(minX), mapY(mean + 2.0 * sigma)); twoSigmaArea.lineTo(mapX(maxX), mapY(mean + 2.0 * sigma)); twoSigmaArea.lineTo(mapX(maxX), mapY(mean - 2.0 * sigma)); twoSigmaArea.closePath(); // pale red g2d.setColor(new Color(255, 233, 235)); g2d.fill(twoSigmaArea); //draw one-sigma Path2D oneSigmaArea = new Path2D.Double(); oneSigmaArea.moveTo(mapX(minX), mapY(mean - sigma)); oneSigmaArea.lineTo(mapX(minX), mapY(mean + sigma)); oneSigmaArea.lineTo(mapX(maxX), mapY(mean + sigma)); oneSigmaArea.lineTo(mapX(maxX), mapY(mean - sigma)); oneSigmaArea.closePath(); // pale yellow g2d.setColor(new Color(254, 255, 233)); g2d.fill(oneSigmaArea); //draw std err Path2D stdErrArea = new Path2D.Double(); stdErrArea.moveTo(mapX(minX), mapY(mean - stdErr)); stdErrArea.lineTo(mapX(minX), mapY(mean + stdErr)); stdErrArea.lineTo(mapX(maxX), mapY(mean + stdErr)); stdErrArea.lineTo(mapX(maxX), mapY(mean - stdErr)); stdErrArea.closePath(); // pale blue g2d.setColor(new Color(208, 222, 254)); g2d.fill(stdErrArea); // draw mean Path2D meanLine = new Path2D.Double(); meanLine.moveTo(mapX(minX), mapY(mean)); meanLine.lineTo(mapX(maxX), mapY(mean)); g2d.setPaint(Color.black); g2d.setStroke(new BasicStroke(1.0f)); g2d.draw(meanLine); drawTicsYAxisInBackground(g2d); if (tripoliFraction != null) { if (tripoliFraction.isColorMeExcluded()) { paintFractionExcludedColor(g2d); } int chosenDatumIndex = tripoliFraction.getShowVerticalLineAtThisIndex(); if (chosenDatumIndex > -1) { int secondChoiceIndex = tripoliFraction.getShowSecondVerticalLineAtThisIndex(); highlightSelectedData(g2d, chosenDatumIndex, secondChoiceIndex); } if (!tripoliFraction.isStandard()) { setBackground(new Color(245, 251, 252)); } } // draw data points for (int i = 0; i < myOnPeakData.length; i++) { Shape rawRatioPoint = new java.awt.geom.Ellipse2D.Double( // mapX(myOnPeakNormalizedAquireTimes[i]), mapY(myOnPeakData[i]), 1.0, 1.0); g2d.setPaint(determineDataColor(i, Color.black)); g2d.draw(rawRatioPoint); } } /** * * @param doReScale the value of doReScale * @param inLiveMode the value of inLiveMode */ @Override public void preparePanel(boolean doReScale, boolean inLiveMode) { this.removeAll(); if (doReScale) { setDisplayOffsetY(0.0); setDisplayOffsetX(0.0); } // walk ratios and get min and max for axes myOnPeakNormalizedAquireTimes = rawRatioDataModel.getNormalizedOnPeakAquireTimes(); myOnPeakData = ((RawRatioDataModel) rawRatioDataModel).getCorrectedRatios(); if (myOnPeakData == null) { myOnPeakData = new double[myOnPeakNormalizedAquireTimes.length]; } if (doReScale) { // X-axis lays out time evenly spaced minX = myOnPeakNormalizedAquireTimes[0]; maxX = myOnPeakNormalizedAquireTimes[myOnPeakNormalizedAquireTimes.length - 1]; // adjust margins for unknowns double xMarginStretch = TicGeneratorForAxes.generateMarginAdjustment(minX, maxX, 0.05); minX -= xMarginStretch; maxX += xMarginStretch; // Y-axis is ratios minY = Double.MAX_VALUE; maxY = -Double.MAX_VALUE; // find min and max y boolean[] myDataActiveMap = rawRatioDataModel.getDataActiveMap(); boolean showAll = showIncludedDataPoints.equals(IncludedTypeEnum.ALL); // rework logic April 2016 for (int i = 0; i < myOnPeakData.length; i++) { if (showAll || myDataActiveMap[i]) { minY = Math.min(minY, myOnPeakData[i]); maxY = Math.max(maxY, myOnPeakData[i]); } } double yMarginStretch = TicGeneratorForAxes.generateMarginAdjustment(minY, maxY, 0.05); minY -= yMarginStretch; maxY += yMarginStretch; } } /** * * @return */ @Override public DataModelInterface getDataModel() { return rawRatioDataModel; } }
3e005ef13d4667c90cc342a440541abfb392d57f
668
java
Java
jodd-core/src/main/java/jodd/io/watch/DirWatcherEvent.java
vilmospapp/jodd
26b14f773d1ebe826d321b133b4dca0d3aada506
[ "BSD-2-Clause" ]
null
null
null
jodd-core/src/main/java/jodd/io/watch/DirWatcherEvent.java
vilmospapp/jodd
26b14f773d1ebe826d321b133b4dca0d3aada506
[ "BSD-2-Clause" ]
null
null
null
jodd-core/src/main/java/jodd/io/watch/DirWatcherEvent.java
vilmospapp/jodd
26b14f773d1ebe826d321b133b4dca0d3aada506
[ "BSD-2-Clause" ]
null
null
null
14.212766
46
0.66018
156
package jodd.io.watch; import java.io.File; public class DirWatcherEvent { private final Type type; private final File target; private final long timestamp; /** * Event type that describes file change. */ public enum Type { CREATED, DELETED, MODIFIED } DirWatcherEvent(Type type, File target) { this.type = type; this.target = target; this.timestamp = System.currentTimeMillis(); } /** * Returns event type. */ public Type type() { return type; } /** * Returns event target. */ public File target() { return target; } /** * Returns event creation timestamp. */ public long timestamp() { return timestamp; } }
3e005f70aa4b2eab31e0e8c6d872dff0a060ef5a
2,158
java
Java
shardingsphere-features/shardingsphere-sharding/shardingsphere-sharding-core/src/main/java/org/apache/shardingsphere/sharding/merge/ddl/fetch/FetchOrderByValueQueuesHolder.java
misselvexu/shardingsphere
a7c853405d2bc5f4e486d89bd800470ec0792239
[ "Apache-2.0" ]
null
null
null
shardingsphere-features/shardingsphere-sharding/shardingsphere-sharding-core/src/main/java/org/apache/shardingsphere/sharding/merge/ddl/fetch/FetchOrderByValueQueuesHolder.java
misselvexu/shardingsphere
a7c853405d2bc5f4e486d89bd800470ec0792239
[ "Apache-2.0" ]
null
null
null
shardingsphere-features/shardingsphere-sharding/shardingsphere-sharding-core/src/main/java/org/apache/shardingsphere/sharding/merge/ddl/fetch/FetchOrderByValueQueuesHolder.java
misselvexu/shardingsphere
a7c853405d2bc5f4e486d89bd800470ec0792239
[ "Apache-2.0" ]
null
null
null
33.71875
143
0.722892
157
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.sharding.merge.ddl.fetch; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.shardingsphere.sharding.merge.dql.orderby.OrderByValue; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; /** * Hold fetch order by value queues for current thread. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class FetchOrderByValueQueuesHolder { private static final ThreadLocal<Map<String, Queue<OrderByValue>>> ORDER_BY_VALUE_QUEUES = ThreadLocal.withInitial(ConcurrentHashMap::new); private static final ThreadLocal<Map<String, Long>> REMAINING_ROW_COUNTS = ThreadLocal.withInitial(ConcurrentHashMap::new); /** * Get order by value queues. * * @return order by value queues */ public static Map<String, Queue<OrderByValue>> getOrderByValueQueues() { return ORDER_BY_VALUE_QUEUES.get(); } /** * Get remaining row counts. * * @return remaining row counts */ public static Map<String, Long> getRemainingRowCounts() { return REMAINING_ROW_COUNTS.get(); } /** * Remove fetch order by value queues. */ public static void remove() { ORDER_BY_VALUE_QUEUES.remove(); REMAINING_ROW_COUNTS.remove(); } }
3e005f8035d2ba5cbfed7992ea5538bf8baaac24
2,245
java
Java
app/model/telegram/api/UpdateMessage.java
m49n/tfsbot
42338b95ff0723a1f465284715a689b9ac53e505
[ "CC0-1.0" ]
null
null
null
app/model/telegram/api/UpdateMessage.java
m49n/tfsbot
42338b95ff0723a1f465284715a689b9ac53e505
[ "CC0-1.0" ]
null
null
null
app/model/telegram/api/UpdateMessage.java
m49n/tfsbot
42338b95ff0723a1f465284715a689b9ac53e505
[ "CC0-1.0" ]
null
null
null
23.154639
67
0.667409
158
package model.telegram.api; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Denis Danilin | [email protected] * 13.05.2020 * tfs ☭ sweat and blood */ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdateMessage { @JsonProperty("chat_id") private long chatId; @JsonProperty("message_id") private long messageId; @JsonProperty("inline_message_id") private long inlineMessageId; @JsonProperty("text") private String text; @JsonProperty("parse_mode") private String parseMode; @JsonProperty("disable_web_page_preview") private boolean disablePreview; @JsonProperty("reply_markup") private ReplyMarkup replyMarkup; public UpdateMessage() { } public UpdateMessage(final long chatId, final long messageId) { this.chatId = chatId; this.messageId = messageId; } public long getChatId() { return chatId; } public void setChatId(final long chatId) { this.chatId = chatId; } public long getMessageId() { return messageId; } public void setMessageId(final long messageId) { this.messageId = messageId; } public long getInlineMessageId() { return inlineMessageId; } public void setInlineMessageId(final long inlineMessageId) { this.inlineMessageId = inlineMessageId; } public String getText() { return text; } public void setText(final String text) { this.text = text; } public String getParseMode() { return parseMode; } public void setParseMode(final String parseMode) { this.parseMode = parseMode; } public boolean isDisablePreview() { return disablePreview; } public void setDisablePreview(final boolean disablePreview) { this.disablePreview = disablePreview; } public ReplyMarkup getReplyMarkup() { return replyMarkup; } public void setReplyMarkup(final ReplyMarkup replyMarkup) { this.replyMarkup = replyMarkup; } public UpdateMessage withReply(final ReplyMarkup reply) { setReplyMarkup(reply); return this; } }
3e0061c58ce8f1d95c4872e37cc99a191ba44305
19,761
java
Java
aesthetic/src/main/java/com/afollestad/aesthetic/TintHelper.java
iota9star/kisssub
edff44f5308acd660286096cf024cf996b1f29f2
[ "Apache-2.0" ]
15
2018-09-28T15:39:37.000Z
2022-03-28T08:49:34.000Z
aesthetic/src/main/java/com/afollestad/aesthetic/TintHelper.java
CeuiLiSA/kisssub
edff44f5308acd660286096cf024cf996b1f29f2
[ "Apache-2.0" ]
1
2017-11-22T09:29:19.000Z
2017-11-22T09:29:19.000Z
aesthetic/src/main/java/com/afollestad/aesthetic/TintHelper.java
CeuiLiSA/kisssub
edff44f5308acd660286096cf024cf996b1f29f2
[ "Apache-2.0" ]
4
2019-06-06T03:06:51.000Z
2021-07-09T13:39:55.000Z
51.062016
197
0.643287
159
/* * * * Copyright 2018. iota9star * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.afollestad.aesthetic; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.os.Build; import android.support.annotation.CheckResult; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TextInputEditText; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.view.TintableBackgroundView; import android.support.v4.view.ViewCompat; import android.support.v7.widget.SwitchCompat; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.SeekBar; import android.widget.Switch; import android.widget.TextView; import java.lang.reflect.Field; import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; /** * @author Aidan Follestad (afollestad) */ @RestrictTo(LIBRARY_GROUP) final class TintHelper { @SuppressLint("PrivateResource") @ColorInt private static int getDefaultRippleColor(@NonNull Context context, boolean useDarkRipple) { // Light ripple is actually translucent black, and vice versa return ContextCompat.getColor(context, useDarkRipple ? R.color.ripple_material_light : R.color.ripple_material_dark); } @NonNull private static ColorStateList getDisabledColorStateList(@ColorInt int normal, @ColorInt int disabled) { return new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled}}, new int[]{disabled, normal}); } @SuppressWarnings("deprecation") private static void setTintSelector( @NonNull View view, @ColorInt final int color, final boolean darker, final boolean useDarkTheme) { final boolean isColorLight = Util.isColorLight(color); final int disabled = ContextCompat.getColor(view.getContext(), useDarkTheme ? R.color.ate_button_disabled_dark : R.color.ate_button_disabled_light); final int pressed = Util.shiftColor(color, darker ? 0.9f : 1.1f); final int activated = Util.shiftColor(color, darker ? 1.1f : 0.9f); final int rippleColor = getDefaultRippleColor(view.getContext(), isColorLight); final int textColor = ContextCompat.getColor(view.getContext(), isColorLight ? R.color.ate_primary_text_light : R.color.ate_primary_text_dark); final ColorStateList sl; if (view instanceof Button) { sl = getDisabledColorStateList(color, disabled); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && view.getBackground() instanceof RippleDrawable) { RippleDrawable rd = (RippleDrawable) view.getBackground(); rd.setColor(ColorStateList.valueOf(rippleColor)); } // Disabled text color state for buttons, may get overridden later by ATE tags final Button button = (Button) view; button.setTextColor(getDisabledColorStateList( textColor, ContextCompat.getColor( view.getContext(), useDarkTheme ? R.color.ate_button_text_disabled_dark : R.color.ate_button_text_disabled_light))); } else if (view instanceof FloatingActionButton) { // FloatingActionButton doesn't support disabled state? sl = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_pressed}, new int[]{android.R.attr.state_pressed}}, new int[]{color, pressed}); final FloatingActionButton fab = (FloatingActionButton) view; fab.setRippleColor(rippleColor); fab.setBackgroundTintList(sl); if (fab.getDrawable() != null) fab.setImageDrawable(createTintedDrawable(fab.getDrawable(), textColor)); return; } else { sl = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed}, new int[]{android.R.attr.state_enabled, android.R.attr.state_activated}, new int[]{android.R.attr.state_enabled, android.R.attr.state_checked} }, new int[]{disabled, color, pressed, activated, activated}); } Drawable drawable = view.getBackground(); if (drawable != null) { drawable = createTintedDrawable(drawable, sl); Util.setBackgroundCompat(view, drawable); } if (view instanceof TextView && !(view instanceof Button)) { final TextView tv = (TextView) view; tv.setTextColor( getDisabledColorStateList( textColor, ContextCompat.getColor(view.getContext(), isColorLight ? R.color.ate_text_disabled_light : R.color.ate_text_disabled_dark))); } } @SuppressWarnings("deprecation") @SuppressLint("PrivateResource") static void setTintAuto(final @NonNull View view, final @ColorInt int color, boolean background, final boolean isDark) { if (!background) { if (view instanceof RadioButton) { setTint((RadioButton) view, color, isDark); } else if (view instanceof SeekBar) { setTint((SeekBar) view, color, isDark); } else if (view instanceof ProgressBar) { setTint((ProgressBar) view, color); } else if (view instanceof EditText) { setTint((EditText) view, color, isDark); } else if (view instanceof CheckBox) { setTint((CheckBox) view, color, isDark); } else if (view instanceof ImageView) { setTint((ImageView) view, color); } else if (view instanceof Switch) { setTint((Switch) view, color, isDark); } else if (view instanceof SwitchCompat) { setTint((SwitchCompat) view, color, isDark); } else { background = true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !background && view.getBackground() instanceof RippleDrawable) { // Ripples for the above views (e.g. when you tap and hold a switch or checkbox) RippleDrawable rd = (RippleDrawable) view.getBackground(); final int unchecked = ContextCompat.getColor(view.getContext(), isDark ? R.color.ripple_material_dark : R.color.ripple_material_light); final int checked = Util.adjustAlpha(color, 0.4f); final ColorStateList sl = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_activated, -android.R.attr.state_checked}, new int[]{android.R.attr.state_activated}, new int[]{android.R.attr.state_checked} }, new int[]{unchecked, checked, checked}); rd.setColor(sl); } } if (background) { // Need to tint the background of a view if (view instanceof FloatingActionButton || view instanceof Button) { setTintSelector(view, color, false, isDark); } else if (view.getBackground() != null) { Drawable drawable = view.getBackground(); if (drawable != null) { if (view instanceof TextInputEditText) { drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN); } else { drawable = createTintedDrawable(drawable, color); Util.setBackgroundCompat(view, drawable); } } } } } static void setTint(@NonNull RadioButton radioButton, @ColorInt int color, boolean useDarker) { ColorStateList sl = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled, -android.R.attr.state_checked}, new int[]{android.R.attr.state_enabled, android.R.attr.state_checked} }, new int[]{ // Rdio button includes own alpha for disabled state Util.stripAlpha(ContextCompat.getColor( radioButton.getContext(), useDarker ? R.color.ate_control_disabled_dark : R.color.ate_control_disabled_light)), ContextCompat.getColor(radioButton.getContext(), useDarker ? R.color.ate_control_normal_dark : R.color.ate_control_normal_light), color}); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { radioButton.setButtonTintList(sl); } else { @SuppressLint("PrivateResource") Drawable d = createTintedDrawable(ContextCompat.getDrawable(radioButton.getContext(), R.drawable.abc_btn_radio_material), sl); radioButton.setButtonDrawable(d); } } static void setTint(@NonNull SeekBar seekBar, @ColorInt int color, boolean useDarker) { final ColorStateList s1 = getDisabledColorStateList(color, ContextCompat.getColor(seekBar.getContext(), useDarker ? R.color.ate_control_disabled_dark : R.color.ate_control_disabled_light)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { seekBar.setThumbTintList(s1); seekBar.setProgressTintList(s1); } else { Drawable progressDrawable = createTintedDrawable(seekBar.getProgressDrawable(), s1); seekBar.setProgressDrawable(progressDrawable); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Drawable thumbDrawable = createTintedDrawable(seekBar.getThumb(), s1); seekBar.setThumb(thumbDrawable); } } } static void setTint(@NonNull ProgressBar progressBar, @ColorInt int color) { setTint(progressBar, color, false); } private static void setTint( @NonNull ProgressBar progressBar, @ColorInt int color, boolean skipIndeterminate) { ColorStateList sl = ColorStateList.valueOf(color); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { progressBar.setProgressTintList(sl); progressBar.setSecondaryProgressTintList(sl); if (!skipIndeterminate) { progressBar.setIndeterminateTintList(sl); } } else { PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN; if (!skipIndeterminate && progressBar.getIndeterminateDrawable() != null) { progressBar.getIndeterminateDrawable().setColorFilter(color, mode); } if (progressBar.getProgressDrawable() != null) { progressBar.getProgressDrawable().setColorFilter(color, mode); } } } private static void setTint(@NonNull EditText editText, @ColorInt int color, boolean useDarker) { final ColorStateList editTextColorStateList = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled, -android.R.attr.state_pressed, -android.R.attr.state_focused }, new int[]{} }, new int[]{ContextCompat.getColor( editText.getContext(), useDarker ? R.color.ate_text_disabled_dark : R.color.ate_text_disabled_light), ContextCompat.getColor( editText.getContext(), useDarker ? R.color.ate_control_normal_dark : R.color.ate_control_normal_light), color}); if (editText instanceof TintableBackgroundView) { ViewCompat.setBackgroundTintList(editText, editTextColorStateList); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { editText.setBackgroundTintList(editTextColorStateList); } setCursorTint(editText, color); } static void setTint(@NonNull CheckBox box, @ColorInt int color, boolean useDarker) { ColorStateList sl = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled, -android.R.attr.state_checked}, new int[]{android.R.attr.state_enabled, android.R.attr.state_checked} }, new int[]{ ContextCompat.getColor(box.getContext(), useDarker ? R.color.ate_control_disabled_dark : R.color.ate_control_disabled_light), ContextCompat.getColor(box.getContext(), useDarker ? R.color.ate_control_normal_dark : R.color.ate_control_normal_light), color}); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { box.setButtonTintList(sl); } else { @SuppressLint("PrivateResource") Drawable drawable = createTintedDrawable(ContextCompat.getDrawable(box.getContext(), R.drawable.abc_btn_check_material), sl); box.setButtonDrawable(drawable); } } private static void setTint(@NonNull ImageView image, @ColorInt int color) { image.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } private static Drawable modifySwitchDrawable(@NonNull Context context, @NonNull Drawable from, @ColorInt int tint, boolean thumb, boolean compatSwitch, boolean useDarker) { if (useDarker) { tint = Util.shiftColor(tint, 1.1f); } tint = Util.adjustAlpha(tint, (compatSwitch && !thumb) ? 0.5f : 1.0f); int disabled; int normal; if (thumb) { disabled = ContextCompat.getColor(context, useDarker ? R.color.ate_switch_thumb_disabled_dark : R.color.ate_switch_thumb_disabled_light); normal = ContextCompat.getColor(context, useDarker ? R.color.ate_switch_thumb_normal_dark : R.color.ate_switch_thumb_normal_light); } else { disabled = ContextCompat.getColor(context, useDarker ? R.color.ate_switch_track_disabled_dark : R.color.ate_switch_track_disabled_light); normal = ContextCompat.getColor(context, useDarker ? R.color.ate_switch_track_normal_dark : R.color.ate_switch_track_normal_light); } // Stock switch includes its own alpha if (!compatSwitch) { normal = Util.stripAlpha(normal); } final ColorStateList sl = new ColorStateList(new int[][]{ new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled, -android.R.attr.state_activated, -android.R.attr.state_checked}, new int[]{android.R.attr.state_enabled, android.R.attr.state_activated}, new int[]{android.R.attr.state_enabled, android.R.attr.state_checked} }, new int[]{disabled, normal, tint, tint}); return createTintedDrawable(from, sl); } static void setTint(@NonNull Switch switchView, @ColorInt int color, boolean useDarker) { if (switchView.getTrackDrawable() != null) { switchView.setTrackDrawable(modifySwitchDrawable(switchView.getContext(), switchView.getTrackDrawable(), color, false, false, useDarker)); } if (switchView.getThumbDrawable() != null) { switchView.setThumbDrawable(modifySwitchDrawable(switchView.getContext(), switchView.getThumbDrawable(), color, true, false, useDarker)); } } static void setTint(@NonNull SwitchCompat switchView, @ColorInt int color, boolean useDarker) { if (switchView.getTrackDrawable() != null) { switchView.setTrackDrawable(modifySwitchDrawable(switchView.getContext(), switchView.getTrackDrawable(), color, false, true, useDarker)); } if (switchView.getThumbDrawable() != null) { switchView.setThumbDrawable(modifySwitchDrawable(switchView.getContext(), switchView.getThumbDrawable(), color, true, true, useDarker)); } } // This returns a NEW Drawable because of the mutate() call. The mutate() call is necessary because Drawables with the same resource have shared states otherwise. @CheckResult @Nullable static Drawable createTintedDrawable(@Nullable Drawable drawable, @ColorInt int color) { if (drawable == null) return null; drawable = DrawableCompat.wrap(drawable.mutate()); DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN); DrawableCompat.setTint(drawable, color); return drawable; } // This returns a NEW Drawable because of the mutate() call. The mutate() call is necessary because Drawables with the same resource have shared states otherwise. @CheckResult @Nullable static Drawable createTintedDrawable(@Nullable Drawable drawable, @NonNull ColorStateList sl) { if (drawable == null) return null; drawable = DrawableCompat.wrap(drawable.mutate()); DrawableCompat.setTintList(drawable, sl); return drawable; } static void setCursorTint(@NonNull EditText editText, @ColorInt int color) { try { Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes"); fCursorDrawableRes.setAccessible(true); int mCursorDrawableRes = fCursorDrawableRes.getInt(editText); Field fEditor = TextView.class.getDeclaredField("mEditor"); fEditor.setAccessible(true); Object editor = fEditor.get(editText); Class<?> clazz = editor.getClass(); Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable"); fCursorDrawable.setAccessible(true); Drawable[] drawables = new Drawable[2]; drawables[0] = ContextCompat.getDrawable(editText.getContext(), mCursorDrawableRes); drawables[0] = createTintedDrawable(drawables[0], color); drawables[1] = ContextCompat.getDrawable(editText.getContext(), mCursorDrawableRes); drawables[1] = createTintedDrawable(drawables[1], color); fCursorDrawable.set(editor, drawables); } catch (Exception e) { e.printStackTrace(); } } }
3e0061ec52f5f281b8153234bb01176aa4876263
80,685
java
Java
src/main/java/uk/ac/leeds/ccg/data/census/data/cas/Census_CAS002Record.java
agdturner/agdt-java-generic-data-Census
6bf68d7c0419da74aa58b393da6930064e011113
[ "Apache-2.0" ]
null
null
null
src/main/java/uk/ac/leeds/ccg/data/census/data/cas/Census_CAS002Record.java
agdturner/agdt-java-generic-data-Census
6bf68d7c0419da74aa58b393da6930064e011113
[ "Apache-2.0" ]
null
null
null
src/main/java/uk/ac/leeds/ccg/data/census/data/cas/Census_CAS002Record.java
agdturner/agdt-java-generic-data-Census
6bf68d7c0419da74aa58b393da6930064e011113
[ "Apache-2.0" ]
null
null
null
30.117581
82
0.624168
160
/* * Copyright 2019 Centre for Computational Geography, University of Leeds. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.leeds.ccg.data.census.data.cas; import uk.ac.leeds.ccg.data.census.data.Census_AreaRecord; import uk.ac.leeds.ccg.data.census.data.id.Census_RecordID; import uk.ac.leeds.ccg.math.Math_Integer; /** * For storing a CAS001 Record. * * @author Andy Turner * @version 1.0.0 */ public class Census_CAS002Record extends Census_AreaRecord { /* * Table CS002 Age by Sex and Marital Status: All People Footnotes and * Comments for Table CS002 1 ONS have confirmed that table CS002 should * contain separate categories of 65-69 and 70-74 years of age instead of * the combined 65-74 category that is actually present. This error was due * to a fault in the production of the table. The data available for this * category does fit the description within the table framework (i.e. it is * genuinely for a category of 65-74 years of age). */ /** * CS0020001 = allPeople */ protected int allPeopleTotal; /** * CS0020002 = allPeopleMarried */ protected int allPeopleMarried; /** * CS0020003 = allPeopleSingle */ protected int allPeopleSingle; /** * CS0020004 = malesTotal */ protected int malesTotal; /** * CS0020005 = malesMarried */ protected int malesMarried; /** * CS0020006 = malesSingle */ protected int malesSingle; /** * CS0020007 = femalesTotal */ protected int femalesTotal; /** * CS0020008 = femalesMarried */ protected int femalesMarried; /** * CS0020009 = femalesSingle */ protected int femalesSingle; /** * CS0020010 = allPeopleAge0to15 */ protected int allPeopleTotalAge0to15; /** * CS0020011 = allPeopleMarriedAge0to15 */ protected int allPeopleMarriedAge0to15; /** * CS0020012 = allPeopleSingleAge0to15 */ protected int allPeopleSingleAge0to15; /** * CS0020013 = malesTotalAge0to15 */ protected int malesTotalAge0to15; /** * CS0020014 = malesMarriedAge0to15 */ protected int malesMarriedAge0to15; /** * CS0020015 = malesSingleAge0to15 */ protected int malesSingleAge0to15; /** * CS0020016 = femalesTotalAge0to15 */ protected int femalesTotalAge0to15; /** * CS0020017 = femalesMarriedAge0to15 */ protected int femalesMarriedAge0to15; /** * CS0020018 = femalesSingleAge0to15 */ protected int femalesSingleAge0to15; /** * CS0020019 = allPeopleAge16to19 */ protected int allPeopleTotalAge16to19; /** * CS0020020 = allPeopleMarriedAge16to19 */ protected int allPeopleMarriedAge16to19; /** * CS0020021 = allPeopleSingleAge16to19 */ protected int allPeopleSingleAge16to19; /** * CS0020022 = malesTotalAge16to19 */ protected int malesTotalAge16to19; /** * CS0020023 = malesMarriedAge16to19 */ protected int malesMarriedAge16to19; /** * CS0020024 = malesSingleAge16to19 */ protected int malesSingleAge16to19; /** * CS0020025 = femalesTotalAge16to19 */ protected int femalesTotalAge16to19; /** * CS0020026 = femalesMarriedAge16to19 */ protected int femalesMarriedAge16to19; /** * CS0020027 = femalesSingleAge16to19 */ protected int femalesSingleAge16to19; /** * CS0020028 = allPeopleAge20to24 */ protected int allPeopleTotalAge20to24; /** * CS0020029 = allPeopleMarriedAge20to24 */ protected int allPeopleMarriedAge20to24; /** * CS0020030 = allPeopleSingleAge20to24 */ protected int allPeopleSingleAge20to24; /** * CS0020031 = malesTotalAge20to24 */ protected int malesTotalAge20to24; /** * CS0020032 = malesMarriedAge20to24 */ protected int malesMarriedAge20to24; /** * CS0020033 = malesSingleAge20to24 */ protected int malesSingleAge20to24; /** * CS0020034 = femalesTotalAge20to24 */ protected int femalesTotalAge20to24; /** * CS0020035 = femalesMarriedAge20to24 */ protected int femalesMarriedAge20to24; /** * CS0020036 = femalesSingleAge20to24 */ protected int femalesSingleAge20to24; /** * CS0020037 = allPeopleAge25to29 */ protected int allPeopleTotalAge25to29; /** * CS0020038 = allPeopleMarriedAge25to29 */ protected int allPeopleMarriedAge25to29; /** * CS0020039 = allPeopleSingleAge25to29 */ protected int allPeopleSingleAge25to29; /** * CS0020040 = malesTotalAge25to29 */ protected int malesTotalAge25to29; /** * CS0020041 = malesMarriedAge25to29 */ protected int malesMarriedAge25to29; /** * CS0020042 = malesSingleAge25to29 */ protected int malesSingleAge25to29; /** * CS0020043 = femalesTotalAge25to29 */ protected int femalesTotalAge25to29; /** * CS0020044 = femalesMarriedAge25to29 */ protected int femalesMarriedAge25to29; /** * CS0020045 = femalesSingleAge25to29 */ protected int femalesSingleAge25to29; /** * CS0020046 = allPeopleAge30to34 */ protected int allPeopleTotalAge30to34; /** * CS0020047 = allPeopleMarriedAge30to34 */ protected int allPeopleMarriedAge30to34; /** * CS0020048 = allPeopleSingleAge30to34 */ protected int allPeopleSingleAge30to34; /** * CS0020049 = malesTotalAge30to34 */ protected int malesTotalAge30to34; /** * CS0020050 = malesMarriedAge30to34 */ protected int malesMarriedAge30to34; /** * CS0020051 = malesSingleAge30to34 */ protected int malesSingleAge30to34; /** * CS0020052 = femalesTotalAge30to34 */ protected int femalesTotalAge30to34; /** * CS0020053 = femalesMarriedAge30to34 */ protected int femalesMarriedAge30to34; /** * CS0020054 = femalesSingleAge30to34 */ protected int femalesSingleAge30to34; /** * CS0020055 = allPeopleAge35to39 */ protected int allPeopleTotalAge35to39; /** * CS0020056 = allPeopleMarriedAge35to39 */ protected int allPeopleMarriedAge35to39; /** * CS0020057 = allPeopleSingleAge35to39 */ protected int allPeopleSingleAge35to39; /** * CS0020058 = malesTotalAge35to39 */ protected int malesTotalAge35to39; /** * CS0020059 = malesMarriedAge35to39 */ protected int malesMarriedAge35to39; /** * CS0020060 = malesSingleAge35to39 */ protected int malesSingleAge35to39; /** * CS0020061 = femalesTotalAge35to39 */ protected int femalesTotalAge35to39; /** * CS0020062 = femalesMarriedAge35to39 */ protected int femalesMarriedAge35to39; /** * CS0020063 = femalesSingleAge35to39 */ protected int femalesSingleAge35to39; /** * CS0020064 = allPeopleAge40to44 */ protected int allPeopleTotalAge40to44; /** * CS0020065 = allPeopleMarriedAge40to44 */ protected int allPeopleMarriedAge40to44; /** * CS0020066 = allPeopleSingleAge40to44 */ protected int allPeopleSingleAge40to44; /** * CS0020067 = malesTotalAge40to44 */ protected int malesTotalAge40to44; /** * CS0020068 = malesMarriedAge40to44 */ protected int malesMarriedAge40to44; /** * CS0020069 = malesSingleAge40to44 */ protected int malesSingleAge40to44; /** * CS0020070 = femalesTotalAge40to44 */ protected int femalesTotalAge40to44; /** * CS0020071 = femalesMarriedAge40to44 */ protected int femalesMarriedAge40to44; /** * CS0020072 = femalesSingleAge40to44 */ protected int femalesSingleAge40to44; /** * CS0020073 = allPeopleAge45to49 */ protected int allPeopleTotalAge45to49; /** * CS0020074 = allPeopleMarriedAge45to49 */ protected int allPeopleMarriedAge45to49; /** * CS0020075 = allPeopleSingleAge45to49 */ protected int allPeopleSingleAge45to49; /** * CS0020076 = malesTotalAge45to49 */ protected int malesTotalAge45to49; /** * CS0020077 = malesMarriedAge45to49 */ protected int malesMarriedAge45to49; /** * CS0020078 = malesSingleAge45to49 */ protected int malesSingleAge45to49; /** * CS0020079 = femalesTotalAge45to49 */ protected int femalesTotalAge45to49; /** * CS0020080 = femalesMarriedAge45to49 */ protected int femalesMarriedAge45to49; /** * CS0020081 = femalesSingleAge45to49 */ protected int femalesSingleAge45to49; /** * CS0020082 = allPeopleAge50to54 */ protected int allPeopleTotalAge50to54; /** * CS0020083 = allPeopleMarriedAge50to54 */ protected int allPeopleMarriedAge50to54; /** * CS0020084 = allPeopleSingleAge50to54 */ protected int allPeopleSingleAge50to54; /** * CS0020085 = malesTotalAge50to54 */ protected int malesTotalAge50to54; /** * CS0020086 = malesMarriedAge50to54 */ protected int malesMarriedAge50to54; /** * CS0020087 = malesSingleAge50to54 */ protected int malesSingleAge50to54; /** * CS0020088 = femalesTotalAge50to54 */ protected int femalesTotalAge50to54; /** * CS0020089 = femalesMarriedAge50to54 */ protected int femalesMarriedAge50to54; /** * CS0020090 = femalesSingleAge50to54 */ protected int femalesSingleAge50to54; /** * CS0020091 = allPeopleAge55to59 */ protected int allPeopleTotalAge55to59; /** * CS0020092 = allPeopleMarriedAge55to59 */ protected int allPeopleMarriedAge55to59; /** * CS0020093 = allPeopleSingleAge55to59 */ protected int allPeopleSingleAge55to59; /** * CS0020094 = malesTotalAge55to59 */ protected int malesTotalAge55to59; /** * CS0020095 = malesMarriedAge55to59 */ protected int malesMarriedAge55to59; /** * CS0020096 = malesSingleAge55to59 */ protected int malesSingleAge55to59; /** * CS0020097 = femalesTotalAge55to59 */ protected int femalesTotalAge55to59; /** * CS0020098 = femalesMarriedAge55to59 */ protected int femalesMarriedAge55to59; /** * CS0020099 = femalesSingleAge55to59 */ protected int femalesSingleAge55to59; /** * CS0020100 = allPeopleAge60to64 */ protected int allPeopleTotalAge60to64; /** * CS0020101 = allPeopleMarriedAge60to64 */ protected int allPeopleMarriedAge60to64; /** * CS0020102 = allPeopleSingleAge60to64 */ protected int allPeopleSingleAge60to64; /** * CS0020103 = malesTotalAge60to64 */ protected int malesTotalAge60to64; /** * CS0020104 = malesMarriedAge60to64 */ protected int malesMarriedAge60to64; /** * CS0020105 = malesSingleAge60to64 */ protected int malesSingleAge60to64; /** * CS0020106 = femalesTotalAge60to64 */ protected int femalesTotalAge60to64; /** * CS0020107 = femalesMarriedAge60to64 */ protected int femalesMarriedAge60to64; /** * CS0020108 = femalesSingleAge60to64 */ protected int femalesSingleAge60to64; /** * CS0020109 = allPeopleAge65to74 */ protected int allPeopleTotalAge65to74; /** * CS0020110 = allPeopleMarriedAge65to74 */ protected int allPeopleMarriedAge65to74; /** * CS0020111 = allPeopleSingleAge65to74 */ protected int allPeopleSingleAge65to74; /** * CS0020112 = malesTotalAge65to74 */ protected int malesTotalAge65to74; /** * CS0020113 = malesMarriedAge65to74 */ protected int malesMarriedAge65to74; /** * CS0020114 = malesSingleAge65to74 */ protected int malesSingleAge65to74; /** * CS0020115 = femalesTotalAge65to74 */ protected int femalesTotalAge65to74; /** * CS0020116 = femalesMarriedAge65to74 */ protected int femalesMarriedAge65to74; /** * CS0020117 = femalesSingleAge65to74 */ protected int femalesSingleAge65to74; /** * CS0020118 = allPeopleAge75to79 */ protected int allPeopleTotalAge75to79; /** * CS0020119 = allPeopleMarriedAge75to79 */ protected int allPeopleMarriedAge75to79; /** * CS0020120 = allPeopleSingleAge75to79 */ protected int allPeopleSingleAge75to79; /** * CS0020121 = malesTotalAge75to79 */ protected int malesTotalAge75to79; /** * CS0020122 = malesMarriedAge75to79 */ protected int malesMarriedAge75to79; /** * CS0020123 = malesSingleAge75to79 */ protected int malesSingleAge75to79; /** * CS0020124 = femalesTotalAge75to79 */ protected int femalesTotalAge75to79; /** * CS0020125 = femalesMarriedAge75to79 */ protected int femalesMarriedAge75to79; /** * CS0020126 = femalesSingleAge75to79 */ protected int femalesSingleAge75to79; /** * CS0020127 = allPeopleAge80to84 */ protected int allPeopleTotalAge80to84; /** * CS0020128 = allPeopleMarriedAge80to84 */ protected int allPeopleMarriedAge80to84; /** * CS0020129 = allPeopleSingleAge80to84 */ protected int allPeopleSingleAge80to84; /** * CS0020130 = malesTotalAge80to84 */ protected int malesTotalAge80to84; /** * CS0020131 = malesMarriedAge80to84 */ protected int malesMarriedAge80to84; /** * CS0020132 = malesSingleAge80to84 */ protected int malesSingleAge80to84; /** * CS0020133 = femalesTotalAge80to84 */ protected int femalesTotalAge80to84; /** * CS0020134 = femalesMarriedAge80to84 */ protected int femalesMarriedAge80to84; /** * CS0020135 = femalesSingleAge80to84 */ protected int femalesSingleAge80to84; /** * CS0020136 = allPeopleAge85to89 */ protected int allPeopleTotalAge85to89; /** * CS0020137 = allPeopleMarriedAge85to89 */ protected int allPeopleMarriedAge85to89; /** * CS0020138 = allPeopleSingleAge85to89 */ protected int allPeopleSingleAge85to89; /** * CS0020139 = malesTotalAge85to89 */ protected int malesTotalAge85to89; /** * CS0020140 = malesMarriedAge85to89 */ protected int malesMarriedAge85to89; /** * CS0020141 = malesSingleAge85to89 */ protected int malesSingleAge85to89; /** * CS0020142 = femalesTotalAge85to89 */ protected int femalesTotalAge85to89; /** * CS0020143 = femalesMarriedAge85to89 */ protected int femalesMarriedAge85to89; /** * CS0020144 = femalesSingleAge85to89 */ protected int femalesSingleAge85to89; /** * CS0020145 = allPeopleAge90AndOver */ protected int allPeopleTotalAge90AndOver; /** * CS0020146 = allPeopleMarriedAge90AndOver */ protected int allPeopleMarriedAge90AndOver; /** * CS0020147 = allPeopleSingleAge90AndOver */ protected int allPeopleSingleAge90AndOver; /** * CS0020148 = malesTotalAge90AndOver */ protected int malesTotalAge90AndOver; /** * CS0020149 = malesMarriedAge90AndOver */ protected int malesMarriedAge90AndOver; /** * CS0020150 = malesSingleAge90AndOver */ protected int malesSingleAge90AndOver; /** * CS0020151 = femalesTotalAge90AndOver */ protected int femalesTotalAge90AndOver; /** * CS0020152 = femalesMarriedAge90AndOver */ protected int femalesMarriedAge90AndOver; /** * CS0020153 = femalesSingleAge90AndOver */ protected int femalesSingleAge90AndOver; /** * Creates a new record with all numerical fields set to 0. * * @param rID What {@link #ID} is set to. */ public Census_CAS002Record(Census_RecordID rID) { super(rID); } /** * Creates a new record with fields set from line. * * @param rID What {@link #ID} is set to. * @param line A line for a CSV file. */ public Census_CAS002Record(Census_RecordID rID, String line) { super(rID); String[] fields = line.split(","); this.zoneCode = fields[0].substring(1, 11); // From Table CAS002 this.allPeopleTotal = Math_Integer.parseInt(fields[1]); this.allPeopleMarried = Math_Integer.parseInt(fields[2]); this.allPeopleSingle = Math_Integer.parseInt(fields[3]); this.malesTotal = Math_Integer.parseInt(fields[4]); this.malesMarried = Math_Integer.parseInt(fields[5]); this.malesSingle = Math_Integer.parseInt(fields[6]); this.femalesTotal = Math_Integer.parseInt(fields[7]); this.femalesMarried = Math_Integer.parseInt(fields[8]); this.femalesSingle = Math_Integer.parseInt(fields[9]); this.allPeopleTotalAge0to15 = Math_Integer.parseInt(fields[10]); this.allPeopleMarriedAge0to15 = Math_Integer.parseInt(fields[11]); this.allPeopleSingleAge0to15 = Math_Integer.parseInt(fields[12]); this.malesTotalAge0to15 = Math_Integer.parseInt(fields[13]); this.malesMarriedAge0to15 = Math_Integer.parseInt(fields[14]); this.malesSingleAge0to15 = Math_Integer.parseInt(fields[15]); this.femalesTotalAge0to15 = Math_Integer.parseInt(fields[16]); this.femalesMarriedAge0to15 = Math_Integer.parseInt(fields[17]); this.femalesSingleAge0to15 = Math_Integer.parseInt(fields[18]); this.allPeopleTotalAge16to19 = Math_Integer.parseInt(fields[19]); this.allPeopleMarriedAge16to19 = Math_Integer.parseInt(fields[20]); this.allPeopleSingleAge16to19 = Math_Integer.parseInt(fields[21]); this.malesTotalAge16to19 = Math_Integer.parseInt(fields[22]); this.malesMarriedAge16to19 = Math_Integer.parseInt(fields[23]); this.malesSingleAge16to19 = Math_Integer.parseInt(fields[24]); this.femalesTotalAge16to19 = Math_Integer.parseInt(fields[25]); this.femalesMarriedAge16to19 = Math_Integer.parseInt(fields[26]); this.femalesSingleAge16to19 = Math_Integer.parseInt(fields[27]); this.allPeopleTotalAge20to24 = Math_Integer.parseInt(fields[28]); this.allPeopleMarriedAge20to24 = Math_Integer.parseInt(fields[29]); this.allPeopleSingleAge20to24 = Math_Integer.parseInt(fields[30]); this.malesTotalAge20to24 = Math_Integer.parseInt(fields[31]); this.malesMarriedAge20to24 = Math_Integer.parseInt(fields[32]); this.malesSingleAge20to24 = Math_Integer.parseInt(fields[33]); this.femalesTotalAge20to24 = Math_Integer.parseInt(fields[34]); this.femalesMarriedAge20to24 = Math_Integer.parseInt(fields[35]); this.femalesSingleAge20to24 = Math_Integer.parseInt(fields[36]); this.allPeopleTotalAge25to29 = Math_Integer.parseInt(fields[37]); this.allPeopleMarriedAge25to29 = Math_Integer.parseInt(fields[38]); this.allPeopleSingleAge25to29 = Math_Integer.parseInt(fields[39]); this.malesTotalAge25to29 = Math_Integer.parseInt(fields[40]); this.malesMarriedAge25to29 = Math_Integer.parseInt(fields[41]); this.malesSingleAge25to29 = Math_Integer.parseInt(fields[42]); this.femalesTotalAge25to29 = Math_Integer.parseInt(fields[43]); this.femalesMarriedAge25to29 = Math_Integer.parseInt(fields[44]); this.femalesSingleAge25to29 = Math_Integer.parseInt(fields[45]); this.allPeopleTotalAge30to34 = Math_Integer.parseInt(fields[46]); this.allPeopleMarriedAge30to34 = Math_Integer.parseInt(fields[47]); this.allPeopleSingleAge30to34 = Math_Integer.parseInt(fields[48]); this.malesTotalAge30to34 = Math_Integer.parseInt(fields[49]); this.malesMarriedAge30to34 = Math_Integer.parseInt(fields[50]); this.malesSingleAge30to34 = Math_Integer.parseInt(fields[51]); this.femalesTotalAge30to34 = Math_Integer.parseInt(fields[52]); this.femalesMarriedAge30to34 = Math_Integer.parseInt(fields[53]); this.femalesSingleAge30to34 = Math_Integer.parseInt(fields[54]); this.allPeopleTotalAge35to39 = Math_Integer.parseInt(fields[55]); this.allPeopleMarriedAge35to39 = Math_Integer.parseInt(fields[56]); this.allPeopleSingleAge35to39 = Math_Integer.parseInt(fields[57]); this.malesTotalAge35to39 = Math_Integer.parseInt(fields[58]); this.malesMarriedAge35to39 = Math_Integer.parseInt(fields[59]); this.malesSingleAge35to39 = Math_Integer.parseInt(fields[60]); this.femalesTotalAge35to39 = Math_Integer.parseInt(fields[61]); this.femalesMarriedAge35to39 = Math_Integer.parseInt(fields[62]); this.femalesSingleAge35to39 = Math_Integer.parseInt(fields[63]); this.allPeopleTotalAge40to44 = Math_Integer.parseInt(fields[64]); this.allPeopleMarriedAge40to44 = Math_Integer.parseInt(fields[65]); this.allPeopleSingleAge40to44 = Math_Integer.parseInt(fields[66]); this.malesTotalAge40to44 = Math_Integer.parseInt(fields[67]); this.malesMarriedAge40to44 = Math_Integer.parseInt(fields[68]); this.malesSingleAge40to44 = Math_Integer.parseInt(fields[69]); this.femalesTotalAge40to44 = Math_Integer.parseInt(fields[70]); this.femalesMarriedAge40to44 = Math_Integer.parseInt(fields[71]); this.femalesSingleAge40to44 = Math_Integer.parseInt(fields[72]); this.allPeopleTotalAge45to49 = Math_Integer.parseInt(fields[73]); this.allPeopleMarriedAge45to49 = Math_Integer.parseInt(fields[74]); this.allPeopleSingleAge45to49 = Math_Integer.parseInt(fields[75]); this.malesTotalAge45to49 = Math_Integer.parseInt(fields[76]); this.malesMarriedAge45to49 = Math_Integer.parseInt(fields[77]); this.malesSingleAge45to49 = Math_Integer.parseInt(fields[78]); this.femalesTotalAge45to49 = Math_Integer.parseInt(fields[79]); this.femalesMarriedAge45to49 = Math_Integer.parseInt(fields[80]); this.femalesSingleAge45to49 = Math_Integer.parseInt(fields[81]); this.allPeopleTotalAge50to54 = Math_Integer.parseInt(fields[82]); this.allPeopleMarriedAge50to54 = Math_Integer.parseInt(fields[83]); this.allPeopleSingleAge50to54 = Math_Integer.parseInt(fields[84]); this.malesTotalAge50to54 = Math_Integer.parseInt(fields[85]); this.malesMarriedAge50to54 = Math_Integer.parseInt(fields[86]); this.malesSingleAge50to54 = Math_Integer.parseInt(fields[87]); this.femalesTotalAge50to54 = Math_Integer.parseInt(fields[88]); this.femalesMarriedAge50to54 = Math_Integer.parseInt(fields[89]); this.femalesSingleAge50to54 = Math_Integer.parseInt(fields[90]); this.allPeopleTotalAge55to59 = Math_Integer.parseInt(fields[91]); this.allPeopleMarriedAge55to59 = Math_Integer.parseInt(fields[92]); this.allPeopleSingleAge55to59 = Math_Integer.parseInt(fields[93]); this.malesTotalAge55to59 = Math_Integer.parseInt(fields[94]); this.malesMarriedAge55to59 = Math_Integer.parseInt(fields[95]); this.malesSingleAge55to59 = Math_Integer.parseInt(fields[96]); this.femalesTotalAge55to59 = Math_Integer.parseInt(fields[97]); this.femalesMarriedAge55to59 = Math_Integer.parseInt(fields[98]); this.femalesSingleAge55to59 = Math_Integer.parseInt(fields[99]); this.allPeopleTotalAge60to64 = Math_Integer.parseInt(fields[100]); this.allPeopleMarriedAge60to64 = Math_Integer.parseInt(fields[101]); this.allPeopleSingleAge60to64 = Math_Integer.parseInt(fields[102]); this.malesTotalAge60to64 = Math_Integer.parseInt(fields[103]); this.malesMarriedAge60to64 = Math_Integer.parseInt(fields[104]); this.malesSingleAge60to64 = Math_Integer.parseInt(fields[105]); this.femalesTotalAge60to64 = Math_Integer.parseInt(fields[106]); this.femalesMarriedAge60to64 = Math_Integer.parseInt(fields[107]); this.femalesSingleAge60to64 = Math_Integer.parseInt(fields[108]); this.allPeopleTotalAge65to74 = Math_Integer.parseInt(fields[109]); this.allPeopleMarriedAge65to74 = Math_Integer.parseInt(fields[110]); this.allPeopleSingleAge65to74 = Math_Integer.parseInt(fields[111]); this.malesTotalAge65to74 = Math_Integer.parseInt(fields[112]); this.malesMarriedAge65to74 = Math_Integer.parseInt(fields[113]); this.malesSingleAge65to74 = Math_Integer.parseInt(fields[114]); this.femalesTotalAge65to74 = Math_Integer.parseInt(fields[115]); this.femalesMarriedAge65to74 = Math_Integer.parseInt(fields[116]); this.femalesSingleAge65to74 = Math_Integer.parseInt(fields[117]); this.allPeopleTotalAge75to79 = Math_Integer.parseInt(fields[118]); this.allPeopleMarriedAge75to79 = Math_Integer.parseInt(fields[119]); this.allPeopleSingleAge75to79 = Math_Integer.parseInt(fields[120]); this.malesTotalAge75to79 = Math_Integer.parseInt(fields[121]); this.malesMarriedAge75to79 = Math_Integer.parseInt(fields[122]); this.malesSingleAge75to79 = Math_Integer.parseInt(fields[123]); this.femalesTotalAge75to79 = Math_Integer.parseInt(fields[124]); this.femalesMarriedAge75to79 = Math_Integer.parseInt(fields[125]); this.femalesSingleAge75to79 = Math_Integer.parseInt(fields[126]); this.allPeopleTotalAge80to84 = Math_Integer.parseInt(fields[127]); this.allPeopleMarriedAge80to84 = Math_Integer.parseInt(fields[128]); this.allPeopleSingleAge80to84 = Math_Integer.parseInt(fields[129]); this.malesTotalAge80to84 = Math_Integer.parseInt(fields[130]); this.malesMarriedAge80to84 = Math_Integer.parseInt(fields[131]); this.malesSingleAge80to84 = Math_Integer.parseInt(fields[132]); this.femalesTotalAge80to84 = Math_Integer.parseInt(fields[133]); this.femalesMarriedAge80to84 = Math_Integer.parseInt(fields[134]); this.femalesSingleAge80to84 = Math_Integer.parseInt(fields[135]); this.allPeopleTotalAge85to89 = Math_Integer.parseInt(fields[136]); this.allPeopleMarriedAge85to89 = Math_Integer.parseInt(fields[137]); this.allPeopleSingleAge85to89 = Math_Integer.parseInt(fields[138]); this.malesTotalAge85to89 = Math_Integer.parseInt(fields[139]); this.malesMarriedAge85to89 = Math_Integer.parseInt(fields[140]); this.malesSingleAge85to89 = Math_Integer.parseInt(fields[141]); this.femalesTotalAge85to89 = Math_Integer.parseInt(fields[142]); this.femalesMarriedAge85to89 = Math_Integer.parseInt(fields[143]); this.femalesSingleAge85to89 = Math_Integer.parseInt(fields[144]); this.allPeopleTotalAge90AndOver = Math_Integer.parseInt(fields[145]); this.allPeopleMarriedAge90AndOver = Math_Integer.parseInt(fields[146]); this.allPeopleSingleAge90AndOver = Math_Integer.parseInt(fields[147]); this.malesTotalAge90AndOver = Math_Integer.parseInt(fields[148]); this.malesMarriedAge90AndOver = Math_Integer.parseInt(fields[149]); this.malesSingleAge90AndOver = Math_Integer.parseInt(fields[150]); this.femalesTotalAge90AndOver = Math_Integer.parseInt(fields[151]); this.femalesMarriedAge90AndOver = Math_Integer.parseInt(fields[152]); this.femalesSingleAge90AndOver = Math_Integer.parseInt(fields[153]); } /** * @return A String description of this. */ @Override public String toString() { String r = super.toString() + ", allPeopleTotal=" + allPeopleTotal + ", allPeopleMarried=" + allPeopleMarried + ", allPeopleSingle=" + allPeopleSingle + ", malesTotal=" + malesTotal + ", malesMarried=" + malesMarried + ", malesSingle=" + malesSingle + ", femalesTotal=" + femalesTotal + ", femalesMarried=" + femalesMarried + ", femalesSingle=" + femalesSingle + ", allPeopleTotalAge0to15=" + allPeopleTotalAge0to15 + ", allPeopleMarriedAge0to15=" + allPeopleMarriedAge0to15 + ", allPeopleSingleAge0to15=" + allPeopleSingleAge0to15 + ", malesTotalAge0to15=" + malesTotalAge0to15 + ", malesMarriedAge0to15=" + malesMarriedAge0to15 + ", malesSingleAge0to15=" + malesSingleAge0to15 + ", femalesTotalAge0to15=" + femalesTotalAge0to15 + ", femalesMarriedAge0to15=" + femalesMarriedAge0to15 + ", femalesSingleAge0to15=" + femalesSingleAge0to15 + ", allPeopleTotalAge16to19=" + allPeopleTotalAge16to19 + ", allPeopleMarriedAge16to19=" + allPeopleMarriedAge16to19 + ", allPeopleSingleAge16to19=" + allPeopleSingleAge16to19 + ", malesTotalAge16to19=" + malesTotalAge16to19 + ", malesMarriedAge16to19=" + malesMarriedAge16to19 + ", malesSingleAge16to19=" + malesSingleAge16to19 + ", femalesTotalAge16to19=" + femalesTotalAge16to19 + ", femalesMarriedAge16to19=" + femalesMarriedAge16to19 + ", femalesSingleAge16to19=" + femalesSingleAge16to19 + ", allPeopleTotalAge20to24=" + allPeopleTotalAge20to24 + ", allPeopleMarriedAge20to24=" + allPeopleMarriedAge20to24 + ", allPeopleSingleAge20to24=" + allPeopleSingleAge20to24 + ", malesTotalAge20to24=" + malesTotalAge20to24 + ", malesMarriedAge20to24=" + malesMarriedAge20to24 + ", malesSingleAge20to24=" + malesSingleAge20to24 + ", femalesTotalAge20to24=" + femalesTotalAge20to24 + ", femalesMarriedAge20to24=" + femalesMarriedAge20to24 + ", femalesSingleAge20to24=" + femalesSingleAge20to24 + ", allPeopleTotalAge25to29=" + allPeopleTotalAge25to29 + ", allPeopleMarriedAge25to29=" + allPeopleMarriedAge25to29 + ", allPeopleSingleAge25to29=" + allPeopleSingleAge25to29 + ", malesTotalAge25to29=" + malesTotalAge25to29 + ", malesMarriedAge25to29=" + malesMarriedAge25to29 + ", malesSingleAge25to29=" + malesSingleAge25to29 + ", femalesTotalAge25to29=" + femalesTotalAge25to29 + ", femalesMarriedAge25to29=" + femalesMarriedAge25to29 + ", femalesSingleAge25to29=" + femalesSingleAge25to29 + ", allPeopleTotalAge30to34=" + allPeopleTotalAge30to34 + ", allPeopleMarriedAge30to34=" + allPeopleMarriedAge30to34 + ", allPeopleSingleAge30to34=" + allPeopleSingleAge30to34 + ", malesTotalAge30to34=" + malesTotalAge30to34 + ", malesMarriedAge30to34=" + malesMarriedAge30to34 + ", malesSingleAge30to34=" + malesSingleAge30to34 + ", femalesTotalAge30to34=" + femalesTotalAge30to34 + ", femalesMarriedAge30to34=" + femalesMarriedAge30to34 + ", femalesSingleAge30to34=" + femalesSingleAge30to34 + ", allPeopleTotalAge35to39=" + allPeopleTotalAge35to39 + ", allPeopleMarriedAge35to39=" + allPeopleMarriedAge35to39 + ", allPeopleSingleAge35to39=" + allPeopleSingleAge35to39 + ", malesTotalAge35to39=" + malesTotalAge35to39 + ", malesMarriedAge35to39=" + malesMarriedAge35to39 + ", malesSingleAge35to39=" + malesSingleAge35to39 + ", femalesTotalAge35to39=" + femalesTotalAge35to39 + ", femalesMarriedAge35to39=" + femalesMarriedAge35to39 + ", femalesSingleAge35to39=" + femalesSingleAge35to39 + ", allPeopleTotalAge40to44=" + allPeopleTotalAge40to44 + ", allPeopleMarriedAge40to44=" + allPeopleMarriedAge40to44 + ", allPeopleSingleAge40to44=" + allPeopleSingleAge40to44 + ", malesTotalAge40to44=" + malesTotalAge40to44 + ", malesMarriedAge40to44=" + malesMarriedAge40to44 + ", malesSingleAge40to44=" + malesSingleAge40to44 + ", femalesTotalAge40to44=" + femalesTotalAge40to44 + ", femalesMarriedAge40to44=" + femalesMarriedAge40to44 + ", femalesSingleAge40to44=" + femalesSingleAge40to44 + ", allPeopleTotalAge45to49=" + allPeopleTotalAge45to49 + ", allPeopleMarriedAge45to49=" + allPeopleMarriedAge45to49 + ", allPeopleSingleAge45to49=" + allPeopleSingleAge45to49 + ", malesTotalAge45to49=" + malesTotalAge45to49 + ", malesMarriedAge45to49=" + malesMarriedAge45to49 + ", malesSingleAge45to49=" + malesSingleAge45to49 + ", femalesTotalAge45to49=" + femalesTotalAge45to49 + ", femalesMarriedAge45to49=" + femalesMarriedAge45to49 + ", femalesSingleAge45to49=" + femalesSingleAge45to49 + ", allPeopleTotalAge50to54=" + allPeopleTotalAge50to54 + ", allPeopleMarriedAge50to54=" + allPeopleMarriedAge50to54 + ", allPeopleSingleAge50to54=" + allPeopleSingleAge50to54 + ", malesTotalAge50to54=" + malesTotalAge50to54 + ", malesMarriedAge50to54=" + malesMarriedAge50to54 + ", malesSingleAge50to54=" + malesSingleAge50to54 + ", femalesTotalAge50to54=" + femalesTotalAge50to54 + ", femalesMarriedAge50to54=" + femalesMarriedAge50to54 + ", femalesSingleAge50to54=" + femalesSingleAge50to54 + ", allPeopleTotalAge55to59=" + allPeopleTotalAge55to59 + ", allPeopleMarriedAge55to59=" + allPeopleMarriedAge55to59 + ", allPeopleSingleAge55to59=" + allPeopleSingleAge55to59 + ", malesTotalAge55to59=" + malesTotalAge55to59 + ", malesMarriedAge55to59=" + malesMarriedAge55to59 + ", malesSingleAge55to59=" + malesSingleAge55to59 + ", femalesTotalAge55to59=" + femalesTotalAge55to59 + ", femalesMarriedAge55to59=" + femalesMarriedAge55to59 + ", femalesSingleAge55to59=" + femalesSingleAge55to59 + ", allPeopleTotalAge65to74=" + allPeopleTotalAge65to74 + ", allPeopleMarriedAge65to74=" + allPeopleMarriedAge65to74 + ", allPeopleSingleAge65to74=" + allPeopleSingleAge65to74 + ", malesTotalAge65to74=" + malesTotalAge65to74 + ", malesMarriedAge65to74=" + malesMarriedAge65to74 + ", malesSingleAge65to74=" + malesSingleAge65to74 + ", femalesTotalAge65to74=" + femalesTotalAge65to74 + ", femalesMarriedAge65to74=" + femalesMarriedAge65to74 + ", femalesSingleAge65to74=" + femalesSingleAge65to74 + ", allPeopleTotalAge75to79=" + allPeopleTotalAge75to79 + ", allPeopleMarriedAge75to79=" + allPeopleMarriedAge75to79 + ", allPeopleSingleAge75to79=" + allPeopleSingleAge75to79 + ", malesTotalAge75to79=" + malesTotalAge75to79 + ", malesMarriedAge75to79=" + malesMarriedAge75to79 + ", malesSingleAge75to79=" + malesSingleAge75to79 + ", femalesTotalAge75to79=" + femalesTotalAge75to79 + ", femalesMarriedAge75to79=" + femalesMarriedAge75to79 + ", femalesSingleAge75to79=" + femalesSingleAge75to79 + ", allPeopleTotalAge80to84=" + allPeopleTotalAge80to84 + ", allPeopleMarriedAge80to84=" + allPeopleMarriedAge80to84 + ", allPeopleSingleAge80to84=" + allPeopleSingleAge80to84 + ", malesTotalAge80to84=" + malesTotalAge80to84 + ", malesMarriedAge80to84=" + malesMarriedAge80to84 + ", malesSingleAge80to84=" + malesSingleAge80to84 + ", femalesTotalAge80to84=" + femalesTotalAge80to84 + ", femalesMarriedAge80to84=" + femalesMarriedAge80to84 + ", femalesSingleAge80to84=" + femalesSingleAge80to84 + ", allPeopleTotalAge85to89=" + allPeopleTotalAge85to89 + ", allPeopleMarriedAge85to89=" + allPeopleMarriedAge85to89 + ", allPeopleSingleAge85to89=" + allPeopleSingleAge85to89 + ", malesTotalAge85to89=" + malesTotalAge85to89 + ", malesMarriedAge85to89=" + malesMarriedAge85to89 + ", malesSingleAge85to89=" + malesSingleAge85to89 + ", femalesTotalAge85to89=" + femalesTotalAge85to89 + ", femalesMarriedAge85to89=" + femalesMarriedAge85to89 + ", femalesSingleAge85to89=" + femalesSingleAge85to89 + ", allPeopleTotalAge90AndOver=" + allPeopleTotalAge90AndOver + ", allPeopleMarriedAge90AndOver=" + allPeopleMarriedAge90AndOver + ", allPeopleSingleAge90AndOver=" + allPeopleSingleAge90AndOver + ", malesTotalAge90AndOver=" + malesTotalAge90AndOver + ", malesMarriedAge90AndOver=" + malesMarriedAge90AndOver + ", malesSingleAge90AndOver=" + malesSingleAge90AndOver + ", femalesTotalAge90AndOver=" + femalesTotalAge90AndOver + ", femalesMarriedAge90AndOver=" + femalesMarriedAge90AndOver + ", femalesSingleAge90AndOver=" + femalesSingleAge90AndOver; return r; } /** * @return A Comma Separated Version (CSV) of this. */ @Override public String toCSV() { String r = super.toCSV(); r += "," + this.allPeopleTotal; r += "," + this.allPeopleMarried; r += "," + this.allPeopleSingle; r += "," + this.malesTotal; r += "," + this.malesMarried; r += "," + this.malesSingle; r += "," + this.femalesTotal; r += "," + this.femalesMarried; r += "," + this.femalesSingle; r += "," + this.allPeopleTotalAge0to15; r += "," + this.allPeopleMarriedAge0to15; r += "," + this.allPeopleSingleAge0to15; r += "," + this.malesTotalAge0to15; r += "," + this.malesMarriedAge0to15; r += "," + this.malesSingleAge0to15; r += "," + this.femalesTotalAge0to15; r += "," + this.femalesMarriedAge0to15; r += "," + this.femalesSingleAge0to15; r += "," + this.allPeopleTotalAge16to19; r += "," + this.allPeopleMarriedAge16to19; r += "," + this.allPeopleSingleAge16to19; r += "," + this.malesTotalAge16to19; r += "," + this.malesMarriedAge16to19; r += "," + this.malesSingleAge16to19; r += "," + this.femalesTotalAge16to19; r += "," + this.femalesMarriedAge16to19; r += "," + this.femalesSingleAge16to19; r += "," + this.allPeopleTotalAge20to24; r += "," + this.allPeopleMarriedAge20to24; r += "," + this.allPeopleSingleAge20to24; r += "," + this.malesTotalAge20to24; r += "," + this.malesMarriedAge20to24; r += "," + this.malesSingleAge20to24; r += "," + this.femalesTotalAge20to24; r += "," + this.femalesMarriedAge20to24; r += "," + this.femalesSingleAge20to24; r += "," + this.allPeopleTotalAge25to29; r += "," + this.allPeopleMarriedAge25to29; r += "," + this.allPeopleSingleAge25to29; r += "," + this.malesTotalAge25to29; r += "," + this.malesMarriedAge25to29; r += "," + this.malesSingleAge25to29; r += "," + this.femalesTotalAge25to29; r += "," + this.femalesMarriedAge25to29; r += "," + this.femalesSingleAge25to29; r += "," + this.allPeopleTotalAge30to34; r += "," + this.allPeopleMarriedAge30to34; r += "," + this.allPeopleSingleAge30to34; r += "," + this.malesTotalAge30to34; r += "," + this.malesMarriedAge30to34; r += "," + this.malesSingleAge30to34; r += "," + this.femalesTotalAge30to34; r += "," + this.femalesMarriedAge30to34; r += "," + this.femalesSingleAge30to34; r += "," + this.allPeopleTotalAge35to39; r += "," + this.allPeopleMarriedAge35to39; r += "," + this.allPeopleSingleAge35to39; r += "," + this.malesTotalAge35to39; r += "," + this.malesMarriedAge35to39; r += "," + this.malesSingleAge35to39; r += "," + this.femalesTotalAge35to39; r += "," + this.femalesMarriedAge35to39; r += "," + this.femalesSingleAge35to39; r += "," + this.allPeopleTotalAge40to44; r += "," + this.allPeopleMarriedAge40to44; r += "," + this.allPeopleSingleAge40to44; r += "," + this.malesTotalAge40to44; r += "," + this.malesMarriedAge40to44; r += "," + this.malesSingleAge40to44; r += "," + this.femalesTotalAge40to44; r += "," + this.femalesMarriedAge40to44; r += "," + this.femalesSingleAge40to44; r += "," + this.allPeopleTotalAge45to49; r += "," + this.allPeopleMarriedAge45to49; r += "," + this.allPeopleSingleAge45to49; r += "," + this.malesTotalAge45to49; r += "," + this.malesMarriedAge45to49; r += "," + this.malesSingleAge45to49; r += "," + this.femalesTotalAge45to49; r += "," + this.femalesMarriedAge45to49; r += "," + this.femalesSingleAge45to49; r += "," + this.allPeopleTotalAge50to54; r += "," + this.allPeopleMarriedAge50to54; r += "," + this.allPeopleSingleAge50to54; r += "," + this.malesTotalAge50to54; r += "," + this.malesMarriedAge50to54; r += "," + this.malesSingleAge50to54; r += "," + this.femalesTotalAge50to54; r += "," + this.femalesMarriedAge50to54; r += "," + this.femalesSingleAge50to54; r += "," + this.allPeopleTotalAge55to59; r += "," + this.allPeopleMarriedAge55to59; r += "," + this.allPeopleSingleAge55to59; r += "," + this.malesTotalAge55to59; r += "," + this.malesMarriedAge55to59; r += "," + this.malesSingleAge55to59; r += "," + this.femalesTotalAge55to59; r += "," + this.femalesMarriedAge55to59; r += "," + this.femalesSingleAge55to59; r += "," + this.allPeopleTotalAge60to64; r += "," + this.allPeopleMarriedAge60to64; r += "," + this.allPeopleSingleAge60to64; r += "," + this.malesTotalAge60to64; r += "," + this.malesMarriedAge60to64; r += "," + this.malesSingleAge60to64; r += "," + this.femalesTotalAge60to64; r += "," + this.femalesMarriedAge60to64; r += "," + this.femalesSingleAge60to64; r += "," + this.allPeopleTotalAge65to74; r += "," + this.allPeopleMarriedAge65to74; r += "," + this.allPeopleSingleAge65to74; r += "," + this.malesTotalAge65to74; r += "," + this.malesMarriedAge65to74; r += "," + this.malesSingleAge65to74; r += "," + this.femalesTotalAge65to74; r += "," + this.femalesMarriedAge65to74; r += "," + this.femalesSingleAge65to74; r += "," + this.allPeopleTotalAge75to79; r += "," + this.allPeopleMarriedAge75to79; r += "," + this.allPeopleSingleAge75to79; r += "," + this.malesTotalAge75to79; r += "," + this.malesMarriedAge75to79; r += "," + this.malesSingleAge75to79; r += "," + this.femalesTotalAge75to79; r += "," + this.femalesMarriedAge75to79; r += "," + this.femalesSingleAge75to79; r += "," + this.allPeopleTotalAge80to84; r += "," + this.allPeopleMarriedAge80to84; r += "," + this.allPeopleSingleAge80to84; r += "," + this.malesTotalAge80to84; r += "," + this.malesMarriedAge80to84; r += "," + this.malesSingleAge80to84; r += "," + this.femalesTotalAge80to84; r += "," + this.femalesMarriedAge80to84; r += "," + this.femalesSingleAge80to84; r += "," + this.allPeopleTotalAge85to89; r += "," + this.allPeopleMarriedAge85to89; r += "," + this.allPeopleSingleAge85to89; r += "," + this.malesTotalAge85to89; r += "," + this.malesMarriedAge85to89; r += "," + this.malesSingleAge85to89; r += "," + this.femalesTotalAge85to89; r += "," + this.femalesMarriedAge85to89; r += "," + this.femalesSingleAge85to89; r += "," + this.allPeopleTotalAge90AndOver; r += "," + this.allPeopleMarriedAge90AndOver; r += "," + this.allPeopleSingleAge90AndOver; r += "," + this.malesTotalAge90AndOver; r += "," + this.malesMarriedAge90AndOver; r += "," + this.malesSingleAge90AndOver; r += "," + this.femalesTotalAge90AndOver; r += "," + this.femalesMarriedAge90AndOver; return r; } /** * @return A Comma Separated Version (CSV) of the names of the * fields/variables. */ @Override public String toCSVHeader() { String r = super.toCSVHeader(); r += ",allPeopleTotal"; r += ",allPeopleMarried"; r += ",allPeopleSingle"; r += ",malesTotal"; r += ",malesMarried"; r += ",malesSingle"; r += ",femalesTotal"; r += ",femalesMarried"; r += ",femalesSingle"; r += ",allPeopleTotalAge0to15"; r += ",allPeopleMarriedAge0to15"; r += ",allPeopleSingleAge0to15"; r += ",malesTotalAge0to15"; r += ",malesMarriedAge0to15"; r += ",malesSingleAge0to15"; r += ",femalesTotalAge0to15"; r += ",femalesMarriedAge0to15"; r += ",femalesSingleAge0to15"; r += ",allPeopleTotalAge16to19"; r += ",allPeopleMarriedAge16to19"; r += ",allPeopleSingleAge16to19"; r += ",malesTotalAge16to19"; r += ",malesMarriedAge16to19"; r += ",malesSingleAge16to19"; r += ",femalesTotalAge16to19"; r += ",femalesMarriedAge16to19"; r += ",femalesSingleAge16to19"; r += ",allPeopleTotalAge20to24"; r += ",allPeopleMarriedAge20to24"; r += ",allPeopleSingleAge20to24"; r += ",malesTotalAge20to24"; r += ",malesMarriedAge20to24"; r += ",malesSingleAge20to24"; r += ",femalesTotalAge20to24"; r += ",femalesMarriedAge20to24"; r += ",femalesSingleAge20to24"; r += ",allPeopleTotalAge25to29"; r += ",allPeopleMarriedAge25to29"; r += ",allPeopleSingleAge25to29"; r += ",malesTotalAge25to29"; r += ",malesMarriedAge25to29"; r += ",malesSingleAge25to29"; r += ",femalesTotalAge25to29"; r += ",femalesMarriedAge25to29"; r += ",femalesSingleAge25to29"; r += ",allPeopleTotalAge30to34"; r += ",allPeopleMarriedAge30to34"; r += ",allPeopleSingleAge30to34"; r += ",malesTotalAge30to34"; r += ",malesMarriedAge30to34"; r += ",malesSingleAge30to34"; r += ",femalesTotalAge30to34"; r += ",femalesMarriedAge30to34"; r += ",femalesSingleAge30to34"; r += ",allPeopleTotalAge35to39"; r += ",allPeopleMarriedAge35to39"; r += ",allPeopleSingleAge35to39"; r += ",malesTotalAge35to39"; r += ",malesMarriedAge35to39"; r += ",malesSingleAge35to39"; r += ",femalesTotalAge35to39"; r += ",femalesMarriedAge35to39"; r += ",femalesSingleAge35to39"; r += ",allPeopleTotalAge40to44"; r += ",allPeopleMarriedAge40to44"; r += ",allPeopleSingleAge40to44"; r += ",malesTotalAge40to44"; r += ",malesMarriedAge40to44"; r += ",malesSingleAge40to44"; r += ",femalesTotalAge40to44"; r += ",femalesMarriedAge40to44"; r += ",femalesSingleAge40to44"; r += ",allPeopleTotalAge45to49"; r += ",allPeopleMarriedAge45to49"; r += ",allPeopleSingleAge45to49"; r += ",malesTotalAge45to49"; r += ",malesMarriedAge45to49"; r += ",malesSingleAge45to49"; r += ",femalesTotalAge45to49"; r += ",femalesMarriedAge45to49"; r += ",femalesSingleAge45to49"; r += ",allPeopleTotalAge50to54"; r += ",allPeopleMarriedAge50to54"; r += ",allPeopleSingleAge50to54"; r += ",malesTotalAge50to54"; r += ",malesMarriedAge50to54"; r += ",malesSingleAge50to54"; r += ",femalesTotalAge50to54"; r += ",femalesMarriedAge50to54"; r += ",femalesSingleAge50to54"; r += ",allPeopleTotalAge55to59"; r += ",allPeopleMarriedAge55to59"; r += ",allPeopleSingleAge55to59"; r += ",malesTotalAge55to59"; r += ",malesMarriedAge55to59"; r += ",malesSingleAge55to59"; r += ",femalesTotalAge55to59"; r += ",femalesMarriedAge55to59"; r += ",femalesSingleAge55to59"; r += ",allPeopleTotalAge60to64"; r += ",allPeopleMarriedAge60to64"; r += ",allPeopleSingleAge60to64"; r += ",malesTotalAge60to64"; r += ",malesMarriedAge60to64"; r += ",malesSingleAge60to64"; r += ",femalesTotalAge60to64"; r += ",femalesMarriedAge60to64"; r += ",femalesSingleAge60to64"; r += ",allPeopleTotalAge65to74"; r += ",allPeopleMarriedAge65to74"; r += ",allPeopleSingleAge65to74"; r += ",malesTotalAge65to74"; r += ",malesMarriedAge65to74"; r += ",malesSingleAge65to74"; r += ",femalesTotalAge65to74"; r += ",femalesMarriedAge65to74"; r += ",femalesSingleAge65to74"; r += ",allPeopleTotalAge75to79"; r += ",allPeopleMarriedAge75to79"; r += ",allPeopleSingleAge75to79"; r += ",malesTotalAge75to79"; r += ",malesMarriedAge75to79"; r += ",malesSingleAge75to79"; r += ",femalesTotalAge75to79"; r += ",femalesMarriedAge75to79"; r += ",femalesSingleAge75to79"; r += ",allPeopleTotalAge80to84"; r += ",allPeopleMarriedAge80to84"; r += ",allPeopleSingleAge80to84"; r += ",malesTotalAge80to84"; r += ",malesMarriedAge80to84"; r += ",malesSingleAge80to84"; r += ",femalesTotalAge80to84"; r += ",femalesMarriedAge80to84"; r += ",femalesSingleAge80to84"; r += ",allPeopleTotalAge85to89"; r += ",allPeopleMarriedAge85to89"; r += ",allPeopleSingleAge85to89"; r += ",malesTotalAge85to89"; r += ",malesMarriedAge85to89"; r += ",malesSingleAge85to89"; r += ",femalesTotalAge85to89"; r += ",femalesMarriedAge85to89"; r += ",femalesSingleAge85to89"; r += ",allPeopleTotalAge90AndOver"; r += ",allPeopleMarriedAge90AndOver"; r += ",allPeopleSingleAge90AndOver"; r += ",malesTotalAge90AndOver"; r += ",malesMarriedAge90AndOver"; r += ",malesSingleAge90AndOver"; r += ",femalesTotalAge90AndOver"; r += ",femalesMarriedAge90AndOver"; return r; } /** * Returns a copy of this.allPeopleTotal * * @return */ public int getAllPeopleTotal() { return this.allPeopleTotal; } /** * Returns a copy of this.allPeopleMarried * * @return */ public int getAllPeopleMarried() { return this.allPeopleMarried; } /** * Returns a copy of this.allPeopleSingle * * @return */ public int getAllPeopleSingle() { return this.allPeopleSingle; } /** * Returns a copy of this.malesTotal * * @return */ public int getMalesTotal() { return this.malesTotal; } /** * Returns a copy of this.malesMarried * * @return */ public int getMalesMarried() { return this.malesMarried; } /** * Returns a copy of this.malesSingle * * @return */ public int getMalesSingle() { return this.malesSingle; } /** * Returns a copy of this.femalesTotal * * @return */ public int getFemalesTotal() { return this.femalesTotal; } /** * Returns a copy of this.femalesMarried * * @return */ public int getFemalesMarried() { return this.femalesMarried; } /** * Returns a copy of this.femalesSingle * * @return */ public int getFemalesSingle() { return this.femalesSingle; } /** * Returns a copy of this.allPeopleTotalAge0to15 * * @return */ public int getAllPeopleTotalAge0to15() { return this.allPeopleTotalAge0to15; } /** * Returns a copy of this.allPeopleMarriedAge0to15 * * @return */ public int getAllPeopleMarriedAge0to15() { return this.allPeopleMarriedAge0to15; } /** * Returns a copy of this.allPeopleSingleAge0to15 * * @return */ public int getAllPeopleSingleAge0to15() { return this.allPeopleSingleAge0to15; } /** * Returns a copy of this.malesTotalAge0to15 * * @return */ public int getMalesTotalAge0to15() { return this.malesTotalAge0to15; } /** * Returns a copy of this.malesMarriedAge0to15 * * @return */ public int getMalesMarriedAge0to15() { return this.malesMarriedAge0to15; } /** * Returns a copy of this.malesSingleAge0to15 * * @return */ public int getMalesSingleAge0to15() { return this.malesSingleAge0to15; } /** * Returns a copy of this.femalesTotalAge0to15 * * @return */ public int getFemalesTotalAge0to15() { return this.femalesTotalAge0to15; } /** * Returns a copy of this.femalesMarriedAge0to15 * * @return */ public int getFemalesMarriedAge0to15() { return this.femalesMarriedAge0to15; } /** * Returns a copy of this.femalesSingleAge0to15 * * @return */ public int getFemalesSingleAge0to15() { return this.femalesSingleAge0to15; } /** * Returns a copy of this.allPeopleTotalAge16to19 * * @return */ public int getAllPeopleTotalAge16to19() { return this.allPeopleTotalAge16to19; } /** * Returns a copy of this.allPeopleMarriedAge16to19 * * @return */ public int getAllPeopleMarriedAge16to19() { return this.allPeopleMarriedAge16to19; } /** * Returns a copy of this.allPeopleSingleAge16to19 * * @return */ public int getAllPeopleSingleAge16to19() { return this.allPeopleSingleAge16to19; } /** * Returns a copy of this.malesTotalAge16to19 * * @return */ public int getMalesTotalAge16to19() { return this.malesTotalAge16to19; } /** * Returns a copy of this.malesMarriedAge16to19 * * @return */ public int getMalesMarriedAge16to19() { return this.malesMarriedAge16to19; } /** * Returns a copy of this.malesSingleAge16to19 * * @return */ public int getMalesSingleAge16to19() { return this.malesSingleAge16to19; } /** * Returns a copy of this.femalesTotalAge16to19 * * @return */ public int getFemalesTotalAge16to19() { return this.femalesTotalAge16to19; } /** * Returns a copy of this.femalesMarriedAge16to19 * * @return */ public int getFemalesMarriedAge16to19() { return this.femalesMarriedAge16to19; } /** * Returns a copy of this.femalesSingleAge16to19 * * @return */ public int getFemalesSingleAge16to19() { return this.femalesSingleAge16to19; } /** * Returns a copy of this.allPeopleTotalAge20to24 * * @return */ public int getAllPeopleTotalAge20to24() { return this.allPeopleTotalAge20to24; } /** * Returns a copy of this.allPeopleMarriedAge20to24 * * @return */ public int getAllPeopleMarriedAge20to24() { return this.allPeopleMarriedAge20to24; } /** * Returns a copy of this.allPeopleSingleAge20to24 * * @return */ public int getAllPeopleSingleAge20to24() { return this.allPeopleSingleAge20to24; } /** * Returns a copy of this.malesTotalAge20to24 * * @return */ public int getMalesTotalAge20to24() { return this.malesTotalAge20to24; } /** * Returns a copy of this.malesMarriedAge20to24 * * @return */ public int getMalesMarriedAge20to24() { return this.malesMarriedAge20to24; } /** * Returns a copy of this.malesSingleAge20to24 * * @return */ public int getMalesSingleAge20to24() { return this.malesSingleAge20to24; } /** * Returns a copy of this.femalesTotalAge20to24 * * @return */ public int getFemalesTotalAge20to24() { return this.femalesTotalAge20to24; } /** * Returns a copy of this.femalesMarriedAge20to24 * * @return */ public int getFemalesMarriedAge20to24() { return this.femalesMarriedAge20to24; } /** * Returns a copy of this.femalesSingleAge20to24 * * @return */ public int getFemalesSingleAge20to24() { return this.femalesSingleAge20to24; } /** * Returns a copy of this.allPeopleTotalAge25to29 * * @return */ public int getAllPeopleTotalAge25to29() { return this.allPeopleTotalAge25to29; } /** * Returns a copy of this.allPeopleMarriedAge25to29 * * @return */ public int getAllPeopleMarriedAge25to29() { return this.allPeopleMarriedAge25to29; } /** * Returns a copy of this.allPeopleSingleAge25to29 * * @return */ public int getAllPeopleSingleAge25to29() { return this.allPeopleSingleAge25to29; } /** * Returns a copy of this.malesTotalAge25to29 * * @return */ public int getMalesTotalAge25to29() { return this.malesTotalAge25to29; } /** * Returns a copy of this.malesMarriedAge25to29 * * @return */ public int getMalesMarriedAge25to29() { return this.malesMarriedAge25to29; } /** * Returns a copy of this.malesSingleAge25to29 * * @return */ public int getMalesSingleAge25to29() { return this.malesSingleAge25to29; } /** * Returns a copy of this.femalesTotalAge25to29 * * @return */ public int getFemalesTotalAge25to29() { return this.femalesTotalAge25to29; } /** * Returns a copy of this.femalesMarriedAge25to29 * * @return */ public int getFemalesMarriedAge25to29() { return this.femalesMarriedAge25to29; } /** * Returns a copy of this.femalesSingleAge25to29 * * @return */ public int getFemalesSingleAge25to29() { return this.femalesSingleAge25to29; } /** * Returns a copy of this.allPeopleTotalAge30to34 * * @return */ public int getAllPeopleTotalAge30to34() { return this.allPeopleTotalAge30to34; } /** * Returns a copy of this.allPeopleMarriedAge30to34 * * @return */ public int getAllPeopleMarriedAge30to34() { return this.allPeopleMarriedAge30to34; } /** * Returns a copy of this.allPeopleSingleAge30to34 * * @return */ public int getAllPeopleSingleAge30to34() { return this.allPeopleSingleAge30to34; } /** * Returns a copy of this.malesTotalAge30to34 * * @return */ public int getMalesTotalAge30to34() { return this.malesTotalAge30to34; } /** * Returns a copy of this.malesMarriedAge30to34 * * @return */ public int getMalesMarriedAge30to34() { return this.malesMarriedAge30to34; } /** * Returns a copy of this.malesSingleAge30to34 * * @return */ public int getMalesSingleAge30to34() { return this.malesSingleAge30to34; } /** * Returns a copy of this.femalesTotalAge30to34 * * @return */ public int getFemalesTotalAge30to34() { return this.femalesTotalAge30to34; } /** * Returns a copy of this.femalesMarriedAge30to34 * * @return */ public int getFemalesMarriedAge30to34() { return this.femalesMarriedAge30to34; } /** * Returns a copy of this.femalesSingleAge30to34 * * @return */ public int getFemalesSingleAge30to34() { return this.femalesSingleAge30to34; } /** * Returns a copy of this.allPeopleTotalAge35to39 * * @return */ public int getAllPeopleTotalAge35to39() { return this.allPeopleTotalAge35to39; } /** * Returns a copy of this.allPeopleMarriedAge35to39 * * @return */ public int getAllPeopleMarriedAge35to39() { return this.allPeopleMarriedAge35to39; } /** * Returns a copy of this.allPeopleSingleAge35to39 * * @return */ public int getAllPeopleSingleAge35to39() { return this.allPeopleSingleAge35to39; } /** * Returns a copy of this.malesTotalAge35to39 * * @return */ public int getMalesTotalAge35to39() { return this.malesTotalAge35to39; } /** * Returns a copy of this.malesMarriedAge35to39 * * @return */ public int getMalesMarriedAge35to39() { return this.malesMarriedAge35to39; } /** * Returns a copy of this.malesSingleAge35to39 * * @return */ public int getMalesSingleAge35to39() { return this.malesSingleAge35to39; } /** * Returns a copy of this.femalesTotalAge35to39 * * @return */ public int getFemalesTotalAge35to39() { return this.femalesTotalAge35to39; } /** * Returns a copy of this.femalesMarriedAge35to39 * * @return */ public int getFemalesMarriedAge35to39() { return this.femalesMarriedAge35to39; } /** * Returns a copy of this.femalesSingleAge35to39 * * @return */ public int getFemalesSingleAge35to39() { return this.femalesSingleAge35to39; } /** * Returns a copy of this.allPeopleTotalAge40to44 * * @return */ public int getAllPeopleTotalAge40to44() { return this.allPeopleTotalAge40to44; } /** * Returns a copy of this.allPeopleMarriedAge40to44 * * @return */ public int getAllPeopleMarriedAge40to44() { return this.allPeopleMarriedAge40to44; } /** * Returns a copy of this.allPeopleSingleAge40to44 * * @return */ public int getAllPeopleSingleAge40to44() { return this.allPeopleSingleAge40to44; } /** * Returns a copy of this.malesTotalAge40to44 * * @return */ public int getMalesTotalAge40to44() { return this.malesTotalAge40to44; } /** * Returns a copy of this.malesMarriedAge40to44 * * @return */ public int getMalesMarriedAge40to44() { return this.malesMarriedAge40to44; } /** * Returns a copy of this.malesSingleAge40to44 * * @return */ public int getMalesSingleAge40to44() { return this.malesSingleAge40to44; } /** * Returns a copy of this.femalesTotalAge40to44 * * @return */ public int getFemalesTotalAge40to44() { return this.femalesTotalAge40to44; } /** * Returns a copy of this.femalesMarriedAge40to44 * * @return */ public int getFemalesMarriedAge40to44() { return this.femalesMarriedAge40to44; } /** * Returns a copy of this.femalesSingleAge40to44 * * @return */ public int getFemalesSingleAge40to44() { return this.femalesSingleAge40to44; } /** * Returns a copy of this.allPeopleTotalAge45to49 * * @return */ public int getAllPeopleTotalAge45to49() { return this.allPeopleTotalAge45to49; } /** * Returns a copy of this.allPeopleMarriedAge45to49 * * @return */ public int getAllPeopleMarriedAge45to49() { return this.allPeopleMarriedAge45to49; } /** * Returns a copy of this.allPeopleSingleAge45to49 * * @return */ public int getAllPeopleSingleAge45to49() { return this.allPeopleSingleAge45to49; } /** * Returns a copy of this.malesTotalAge45to49 * * @return */ public int getMalesTotalAge45to49() { return this.malesTotalAge45to49; } /** * Returns a copy of this.malesMarriedAge45to49 * * @return */ public int getMalesMarriedAge45to49() { return this.malesMarriedAge45to49; } /** * Returns a copy of this.malesSingleAge45to49 * * @return */ public int getMalesSingleAge45to49() { return this.malesSingleAge45to49; } /** * Returns a copy of this.femalesTotalAge45to49 * * @return */ public int getFemalesTotalAge45to49() { return this.femalesTotalAge45to49; } /** * Returns a copy of this.femalesMarriedAge45to49 * * @return */ public int getFemalesMarriedAge45to49() { return this.femalesMarriedAge45to49; } /** * Returns a copy of this.femalesSingleAge45to49 * * @return */ public int getFemalesSingleAge45to49() { return this.femalesSingleAge45to49; } /** * Returns a copy of this.allPeopleTotalAge50to54 * * @return */ public int getAllPeopleTotalAge50to54() { return this.allPeopleTotalAge50to54; } /** * Returns a copy of this.allPeopleMarriedAge50to54 * * @return */ public int getAllPeopleMarriedAge50to54() { return this.allPeopleMarriedAge50to54; } /** * Returns a copy of this.allPeopleSingleAge50to54 * * @return */ public int getAllPeopleSingleAge50to54() { return this.allPeopleSingleAge50to54; } /** * Returns a copy of this.malesTotalAge50to54 * * @return */ public int getMalesTotalAge50to54() { return this.malesTotalAge50to54; } /** * Returns a copy of this.malesMarriedAge50to54 * * @return */ public int getMalesMarriedAge50to54() { return this.malesMarriedAge50to54; } /** * Returns a copy of this.malesSingleAge50to54 * * @return */ public int getMalesSingleAge50to54() { return this.malesSingleAge50to54; } /** * Returns a copy of this.femalesTotalAge50to54 * * @return */ public int getFemalesTotalAge50to54() { return this.femalesTotalAge50to54; } /** * Returns a copy of this.femalesMarriedAge50to54 * * @return */ public int getFemalesMarriedAge50to54() { return this.femalesMarriedAge50to54; } /** * Returns a copy of this.femalesSingleAge50to54 * * @return */ public int getFemalesSingleAge50to54() { return this.femalesSingleAge50to54; } /** * Returns a copy of this.allPeopleTotalAge55to59 * * @return */ public int getAllPeopleTotalAge55to59() { return this.allPeopleTotalAge55to59; } /** * Returns a copy of this.allPeopleMarriedAge55to59 * * @return */ public int getAllPeopleMarriedAge55to59() { return this.allPeopleMarriedAge55to59; } /** * Returns a copy of this.allPeopleSingleAge55to59 * * @return */ public int getAllPeopleSingleAge55to59() { return this.allPeopleSingleAge55to59; } /** * Returns a copy of this.malesTotalAge55to59 * * @return */ public int getMalesTotalAge55to59() { return this.malesTotalAge55to59; } /** * Returns a copy of this.malesMarriedAge55to59 * * @return */ public int getMalesMarriedAge55to59() { return this.malesMarriedAge55to59; } /** * Returns a copy of this.malesSingleAge55to59 * * @return */ public int getMalesSingleAge55to59() { return this.malesSingleAge55to59; } /** * Returns a copy of this.femalesTotalAge55to59 * * @return */ public int getFemalesTotalAge55to59() { return this.femalesTotalAge55to59; } /** * Returns a copy of this.femalesMarriedAge55to59 * * @return */ public int getFemalesMarriedAge55to59() { return this.femalesMarriedAge55to59; } /** * Returns a copy of this.femalesSingleAge55to59 * * @return */ public int getFemalesSingleAge55to59() { return this.femalesSingleAge55to59; } /** * Returns a copy of this.allPeopleTotalAge60to64 * * @return */ public int getAllPeopleTotalAge60to64() { return this.allPeopleTotalAge60to64; } /** * Returns a copy of this.allPeopleMarriedAge60to64 * * @return */ public int getAllPeopleMarriedAge60to64() { return this.allPeopleMarriedAge60to64; } /** * Returns a copy of this.allPeopleSingleAge60to64 * * @return */ public int getAllPeopleSingleAge60to64() { return this.allPeopleSingleAge60to64; } /** * Returns a copy of this.malesTotalAge60to64 * * @return */ public int getMalesTotalAge60to64() { return this.malesTotalAge60to64; } /** * Returns a copy of this.malesMarriedAge60to64 * * @return */ public int getMalesMarriedAge60to64() { return this.malesMarriedAge60to64; } /** * Returns a copy of this.malesSingleAge60to64 * * @return */ public int getMalesSingleAge60to64() { return this.malesSingleAge60to64; } /** * Returns a copy of this.femalesTotalAge60to64 * * @return */ public int getFemalesTotalAge60to64() { return this.femalesTotalAge60to64; } /** * Returns a copy of this.femalesMarriedAge60to64 * * @return */ public int getFemalesMarriedAge60to64() { return this.femalesMarriedAge60to64; } /** * Returns a copy of this.femalesSingleAge60to64 * * @return */ public int getFemalesSingleAge60to64() { return this.femalesSingleAge60to64; } /** * Returns a copy of this.allPeopleTotalAge65to74 * * @return */ public int getAllPeopleTotalAge65to74() { return this.allPeopleTotalAge65to74; } /** * Returns a copy of this.allPeopleMarriedAge65to74 * * @return */ public int getAllPeopleMarriedAge65to74() { return this.allPeopleMarriedAge65to74; } /** * Returns a copy of this.allPeopleSingleAge65to74 * * @return */ public int getAllPeopleSingleAge65to74() { return this.allPeopleSingleAge65to74; } /** * Returns a copy of this.malesTotalAge65to74 * * @return */ public int getMalesTotalAge65to74() { return this.malesTotalAge65to74; } /** * Returns a copy of this.malesMarriedAge65to74 * * @return */ public int getMalesMarriedAge65to74() { return this.malesMarriedAge65to74; } /** * Returns a copy of this.malesSingleAge65to74 * * @return */ public int getMalesSingleAge65to74() { return this.malesSingleAge65to74; } /** * Returns a copy of this.femalesTotalAge65to74 * * @return */ public int getFemalesTotalAge65to74() { return this.femalesTotalAge65to74; } /** * Returns a copy of this.femalesMarriedAge65to74 * * @return */ public int getFemalesMarriedAge65to74() { return this.femalesMarriedAge65to74; } /** * Returns a copy of this.femalesSingleAge65to74 * * @return */ public int getFemalesSingleAge65to74() { return this.femalesSingleAge65to74; } /** * Returns a copy of this.allPeopleTotalAge75to79 * * @return */ public int getAllPeopleTotalAge75to79() { return this.allPeopleTotalAge75to79; } /** * Returns a copy of this.allPeopleMarriedAge75to79 * * @return */ public int getAllPeopleMarriedAge75to79() { return this.allPeopleMarriedAge75to79; } /** * Returns a copy of this.allPeopleSingleAge75to79 * * @return */ public int getAllPeopleSingleAge75to79() { return this.allPeopleSingleAge75to79; } /** * Returns a copy of this.malesTotalAge75to79 * * @return */ public int getMalesTotalAge75to79() { return this.malesTotalAge75to79; } /** * Returns a copy of this.malesMarriedAge75to79 * * @return */ public int getMalesMarriedAge75to79() { return this.malesMarriedAge75to79; } /** * Returns a copy of this.malesSingleAge75to79 * * @return */ public int getMalesSingleAge75to79() { return this.malesSingleAge75to79; } /** * Returns a copy of this.femalesTotalAge75to79 * * @return */ public int getFemalesTotalAge75to79() { return this.femalesTotalAge75to79; } /** * Returns a copy of this.femalesMarriedAge75to79 * * @return */ public int getFemalesMarriedAge75to79() { return this.femalesMarriedAge75to79; } /** * Returns a copy of this.femalesSingleAge75to79 * * @return */ public int getFemalesSingleAge75to79() { return this.femalesSingleAge75to79; } /** * Returns a copy of this.allPeopleTotalAge80to84 * * @return */ public int getAllPeopleTotalAge80to84() { return this.allPeopleTotalAge80to84; } /** * Returns a copy of this.allPeopleMarriedAge80to84 * * @return */ public int getAllPeopleMarriedAge80to84() { return this.allPeopleMarriedAge80to84; } /** * Returns a copy of this.allPeopleSingleAge80to84 * * @return */ public int getAllPeopleSingleAge80to84() { return this.allPeopleSingleAge80to84; } /** * Returns a copy of this.malesTotalAge80to84 * * @return */ public int getMalesTotalAge80to84() { return this.malesTotalAge80to84; } /** * Returns a copy of this.malesMarriedAge80to84 * * @return */ public int getMalesMarriedAge80to84() { return this.malesMarriedAge80to84; } /** * Returns a copy of this.malesSingleAge80to84 * * @return */ public int getMalesSingleAge80to84() { return this.malesSingleAge80to84; } /** * Returns a copy of this.femalesTotalAge80to84 * * @return */ public int getFemalesTotalAge80to84() { return this.femalesTotalAge80to84; } /** * Returns a copy of this.femalesMarriedAge80to84 * * @return */ public int getFemalesMarriedAge80to84() { return this.femalesMarriedAge80to84; } /** * Returns a copy of this.femalesSingleAge80to84 * * @return */ public int getFemalesSingleAge80to84() { return this.femalesSingleAge80to84; } /** * Returns a copy of this.allPeopleTotalAge85to89 * * @return */ public int getAllPeopleTotalAge85to89() { return this.allPeopleTotalAge85to89; } /** * Returns a copy of this.allPeopleMarriedAge85to89 * * @return */ public int getAllPeopleMarriedAge85to89() { return this.allPeopleMarriedAge85to89; } /** * Returns a copy of this.allPeopleSingleAge85to89 * * @return */ public int getAllPeopleSingleAge85to89() { return this.allPeopleSingleAge85to89; } /** * Returns a copy of this.malesTotalAge85to89 * * @return */ public int getMalesTotalAge85to89() { return this.malesTotalAge85to89; } /** * Returns a copy of this.malesMarriedAge85to89 * * @return */ public int getMalesMarriedAge85to89() { return this.malesMarriedAge85to89; } /** * Returns a copy of this.malesSingleAge85to89 * * @return */ public int getMalesSingleAge85to89() { return this.malesSingleAge85to89; } /** * Returns a copy of this.femalesTotalAge85to89 * * @return */ public int getFemalesTotalAge85to89() { return this.femalesTotalAge85to89; } /** * Returns a copy of this.femalesMarriedAge85to89 * * @return */ public int getFemalesMarriedAge85to89() { return this.femalesMarriedAge85to89; } /** * Returns a copy of this.femalesSingleAge85to89 * * @return */ public int getFemalesSingleAge85to89() { return this.femalesSingleAge85to89; } /** * Returns a copy of this.allPeopleTotalAge90AndOver * * @return */ public int getAllPeopleTotalAge90AndOver() { return this.allPeopleTotalAge90AndOver; } /** * Returns a copy of this.allPeopleMarriedAge90AndOver * * @return */ public int getAllPeopleMarriedAge90AndOver() { return this.allPeopleMarriedAge90AndOver; } /** * Returns a copy of this.allPeopleSingleAge90AndOver * * @return */ public int getAllPeopleSingleAge90AndOver() { return this.allPeopleSingleAge90AndOver; } /** * Returns a copy of this.malesTotalAge90AndOver * * @return */ public int getMalesTotalAge90AndOver() { return this.malesTotalAge90AndOver; } /** * Returns a copy of this.malesMarriedAge90AndOver * * @return */ public int getMalesMarriedAge90AndOver() { return this.malesMarriedAge90AndOver; } /** * Returns a copy of this.malesSingleAge90AndOver * * @return */ public int getMalesSingleAge90AndOver() { return this.malesSingleAge90AndOver; } /** * Returns a copy of this.femalesTotalAge90AndOver * * @return */ public int getFemalesTotalAge90AndOver() { return this.femalesTotalAge90AndOver; } /** * Returns a copy of this.femalesMarriedAge90AndOver * * @return */ public int getFemalesMarriedAge90AndOver() { return this.femalesMarriedAge90AndOver; } /** * Returns a copy of this.femalesSingleAge90AndOver * * @return */ public int getFemalesSingleAge90AndOver() { return this.femalesSingleAge90AndOver; } }
3e00626394bdd0501a63e0d9c452790d0e08bd80
5,975
java
Java
java/src/com/vmware/avi/sdk/model/LdapUserBindSettings.java
yograjshisode/sdk
ad5579229a2821ba6d85f61bff3e7f457e0cce77
[ "Apache-2.0" ]
37
2016-03-14T22:27:17.000Z
2022-03-03T05:18:39.000Z
java/src/com/vmware/avi/sdk/model/LdapUserBindSettings.java
yograjshisode/sdk
ad5579229a2821ba6d85f61bff3e7f457e0cce77
[ "Apache-2.0" ]
195
2016-03-14T23:47:55.000Z
2021-05-12T11:28:56.000Z
java/src/com/vmware/avi/sdk/model/LdapUserBindSettings.java
yograjshisode/sdk
ad5579229a2821ba6d85f61bff3e7f457e0cce77
[ "Apache-2.0" ]
50
2016-03-14T05:52:14.000Z
2022-01-06T06:12:00.000Z
36.212121
114
0.671632
161
package com.vmware.avi.sdk.model; import java.util.*; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; /** * The LdapUserBindSettings is a POJO class extends AviRestResource that used for creating * LdapUserBindSettings. * * @version 1.0 * @since * */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class LdapUserBindSettings { @JsonProperty("dn_template") private String dnTemplate = null; @JsonProperty("token") private String token = "<user>"; @JsonProperty("user_attributes") private List<String> userAttributes = null; @JsonProperty("user_id_attribute") private String userIdAttribute = null; /** * This is the getter method this will return the attribute value. * Ldap user dn pattern is used to bind ldap user after replacing the user token with real username. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @return dnTemplate */ public String getDnTemplate() { return dnTemplate; } /** * This is the setter method to the attribute. * Ldap user dn pattern is used to bind ldap user after replacing the user token with real username. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @param dnTemplate set the dnTemplate. */ public void setDnTemplate(String dnTemplate) { this.dnTemplate = dnTemplate; } /** * This is the getter method this will return the attribute value. * Ldap token is replaced with real user name in the user dn pattern. * Default value when not specified in API or module is interpreted by Avi Controller as "<user>". * @return token */ public String getToken() { return token; } /** * This is the setter method to the attribute. * Ldap token is replaced with real user name in the user dn pattern. * Default value when not specified in API or module is interpreted by Avi Controller as "<user>". * @param token set the token. */ public void setToken(String token) { this.token = token; } /** * This is the getter method this will return the attribute value. * Ldap user attributes to fetch on a successful user bind. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @return userAttributes */ public List<String> getUserAttributes() { return userAttributes; } /** * This is the setter method. this will set the userAttributes * Ldap user attributes to fetch on a successful user bind. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @return userAttributes */ public void setUserAttributes(List<String> userAttributes) { this.userAttributes = userAttributes; } /** * This is the setter method this will set the userAttributes * Ldap user attributes to fetch on a successful user bind. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @return userAttributes */ public LdapUserBindSettings addUserAttributesItem(String userAttributesItem) { if (this.userAttributes == null) { this.userAttributes = new ArrayList<String>(); } this.userAttributes.add(userAttributesItem); return this; } /** * This is the getter method this will return the attribute value. * Ldap user id attribute is the login attribute that uniquely identifies a single user record. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @return userIdAttribute */ public String getUserIdAttribute() { return userIdAttribute; } /** * This is the setter method to the attribute. * Ldap user id attribute is the login attribute that uniquely identifies a single user record. * Default value when not specified in API or module is interpreted by Avi Controller as null. * @param userIdAttribute set the userIdAttribute. */ public void setUserIdAttribute(String userIdAttribute) { this.userIdAttribute = userIdAttribute; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LdapUserBindSettings objLdapUserBindSettings = (LdapUserBindSettings) o; return Objects.equals(this.dnTemplate, objLdapUserBindSettings.dnTemplate)&& Objects.equals(this.token, objLdapUserBindSettings.token)&& Objects.equals(this.userIdAttribute, objLdapUserBindSettings.userIdAttribute)&& Objects.equals(this.userAttributes, objLdapUserBindSettings.userAttributes); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LdapUserBindSettings {\n"); sb.append(" dnTemplate: ").append(toIndentedString(dnTemplate)).append("\n"); sb.append(" token: ").append(toIndentedString(token)).append("\n"); sb.append(" userAttributes: ").append(toIndentedString(userAttributes)).append("\n"); sb.append(" userIdAttribute: ").append(toIndentedString(userIdAttribute)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0062aa7f7f07613605a974c9f9206b2f48b254
1,955
java
Java
src/main/java/grondag/frex/impl/event/BlockStateRendererImpl.java
spiralhalo/frex
b7af25a4f7d14e8df3c166c4e3940bfbd3ac7405
[ "Apache-2.0" ]
27
2019-04-12T11:52:40.000Z
2021-12-28T03:35:07.000Z
src/main/java/grondag/frex/impl/event/BlockStateRendererImpl.java
spiralhalo/frex
b7af25a4f7d14e8df3c166c4e3940bfbd3ac7405
[ "Apache-2.0" ]
6
2019-07-08T02:34:27.000Z
2021-09-03T19:11:34.000Z
src/main/java/grondag/frex/impl/event/BlockStateRendererImpl.java
spiralhalo/frex
b7af25a4f7d14e8df3c166c4e3940bfbd3ac7405
[ "Apache-2.0" ]
8
2019-07-21T20:36:01.000Z
2021-07-24T11:51:40.000Z
38.333333
127
0.792839
162
/* * Copyright 2019, 2020 grondag * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package grondag.frex.impl.event; import net.minecraft.block.BlockState; import net.minecraft.client.render.block.BlockRenderManager; import net.minecraft.client.render.chunk.ChunkRendererRegion; import net.minecraft.client.render.model.BakedModel; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.util.math.BlockPos; import net.fabricmc.fabric.impl.client.indigo.renderer.accessor.AccessChunkRendererRegion; import grondag.frex.api.event.RenderRegionBakeListener.BlockStateRenderer; public class BlockStateRendererImpl implements BlockStateRenderer { private BlockRenderManager blockRenderManager; private MatrixStack matrixStack; private ChunkRendererRegion chunkRendererRegion; public void prepare(BlockRenderManager blockRenderManager, MatrixStack matrixStack, ChunkRendererRegion chunkRendererRegion) { this.blockRenderManager = blockRenderManager; this.matrixStack = matrixStack; this.chunkRendererRegion = chunkRendererRegion; } @Override public void bake(BlockPos pos, BlockState state) { final BakedModel model = blockRenderManager.getModel(state); matrixStack.push(); matrixStack.translate(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15); ((AccessChunkRendererRegion) chunkRendererRegion).fabric_getRenderer().tesselateBlock(state, pos, model, matrixStack); matrixStack.pop(); } }
3e006367050cbad24edad2808572582ba1f420ee
2,525
java
Java
cql-engine-fhir/src/main/java/org/opencds/cqf/cql/data/fhir/FhirBundleCursorR4.java
zoedalley/cql_engine
44c9ca1d7c5f6fd7bed8a4c6510a9c3754e94fc3
[ "Apache-2.0" ]
null
null
null
cql-engine-fhir/src/main/java/org/opencds/cqf/cql/data/fhir/FhirBundleCursorR4.java
zoedalley/cql_engine
44c9ca1d7c5f6fd7bed8a4c6510a9c3754e94fc3
[ "Apache-2.0" ]
null
null
null
cql-engine-fhir/src/main/java/org/opencds/cqf/cql/data/fhir/FhirBundleCursorR4.java
zoedalley/cql_engine
44c9ca1d7c5f6fd7bed8a4c6510a9c3754e94fc3
[ "Apache-2.0" ]
null
null
null
32.792208
122
0.601584
163
package org.opencds.cqf.cql.data.fhir; import ca.uhn.fhir.rest.client.api.IGenericClient; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.instance.model.api.IBaseBundle; import java.util.Iterator; import java.util.NoSuchElementException; /** * Created by Bryn on 4/16/2016. */ public class FhirBundleCursorR4 implements Iterable<Object> { public FhirBundleCursorR4(IGenericClient fhirClient, Bundle results) { this.fhirClient = fhirClient; this.results = results; } private IGenericClient fhirClient; private Bundle results; /** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ public Iterator<Object> iterator() { return new FhirBundleIterator(fhirClient, results); } private class FhirBundleIterator implements Iterator<Object> { public FhirBundleIterator(IGenericClient fhirClient, Bundle results) { this.fhirClient = fhirClient; this.results = results; this.current = -1; } private IGenericClient fhirClient; private Bundle results; private int current; /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ public boolean hasNext() { return current < results.getEntry().size() - 1 || results.getLink(IBaseBundle.LINK_NEXT) != null; } /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ public Object next() { current++; if (current < results.getEntry().size()) { return results.getEntry().get(current).getResource(); } else { results = fhirClient.loadPage().next(results).execute(); current = 0; if (current < results.getEntry().size()) { return results.getEntry().get(current).getResource(); } } // TODO: It would be possible to get here if the next link was present, but the returned page had 0 entries... throw new NoSuchElementException(); } } }
3e0063a4f36668e50dab0de55a3b781f84d6e1bd
1,427
java
Java
src/test/java/io/jenkins/plugins/oak9/utils/FileScannerTest.java
MarkEWaite/oak9-plugin
97cc892dbbe9b79530b5c550cdc6fc08910c7cf2
[ "Apache-2.0" ]
2
2021-08-10T18:44:56.000Z
2021-09-07T15:10:07.000Z
src/test/java/io/jenkins/plugins/oak9/utils/FileScannerTest.java
MarkEWaite/oak9-plugin
97cc892dbbe9b79530b5c550cdc6fc08910c7cf2
[ "Apache-2.0" ]
1
2021-08-12T19:20:02.000Z
2021-08-12T19:20:02.000Z
src/test/java/io/jenkins/plugins/oak9/utils/FileScannerTest.java
MarkEWaite/oak9-plugin
97cc892dbbe9b79530b5c550cdc6fc08910c7cf2
[ "Apache-2.0" ]
1
2022-03-27T14:37:20.000Z
2022-03-27T14:37:20.000Z
38.567568
122
0.607568
164
package io.jenkins.plugins.oak9.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import hudson.FilePath; import java.io.FileFilter; import java.io.IOException; import java.nio.file.Paths; import org.junit.jupiter.api.Test; public class FileScannerTest { @Test public void testScanForIacFiles() throws IOException, IllegalArgumentException { assertThrows(IOException.class, () -> FileScanner.scanForIacFiles( new FilePath(Paths.get(System.getProperty("java.io.tmpdir"), "test.txt").toFile()), mock(FileFilter.class))); assertEquals(0, FileScanner .scanForIacFiles(new FilePath(Paths.get(System.getProperty("java.io.tmpdir"), "").toFile()), mock(FileFilter.class)) .size()); assertEquals(0, FileScanner .scanForIacFiles(new FilePath(Paths.get(System.getProperty("java.io.tmpdir")).toFile()), mock(FileFilter.class)) .size()); assertThrows(IOException.class, () -> FileScanner .scanForIacFiles(new FilePath(Paths.get(System.getProperty("tf"), "").toFile()), mock(FileFilter.class))); } }
3e0063b01b916eab4f836fd9ff92f92bbe9bde0c
5,851
java
Java
litho-widget/src/main/java/com/facebook/litho/widget/LayoutInfo.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
7,886
2017-04-18T19:27:19.000Z
2022-03-29T13:18:19.000Z
litho-widget/src/main/java/com/facebook/litho/widget/LayoutInfo.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
667
2017-04-18T20:43:18.000Z
2022-03-28T15:21:43.000Z
litho-widget/src/main/java/com/facebook/litho/widget/LayoutInfo.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
824
2017-04-18T19:56:51.000Z
2022-03-25T07:17:34.000Z
42.093525
100
0.73731
165
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.widget; import androidx.recyclerview.widget.OrientationHelper; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView.LayoutManager; import java.util.List; /** * An implementation of this interface will provide the {@link RecyclerBinder} with all the * information about the {@link RecyclerView} layout. */ public interface LayoutInfo extends ViewportInfo { /** * This is the main scrolling direction that the {@link LayoutManager} passed to this binder will * use. * * @return either {@link OrientationHelper#HORIZONTAL} or {@link OrientationHelper#VERTICAL}. */ int getScrollDirection(); /** @return The {@link LayoutManager} to be used with the {@link RecyclerView}. */ LayoutManager getLayoutManager(); /** @param renderInfoCollection */ void setRenderInfoCollection(RenderInfoCollection renderInfoCollection); /** * RecyclerBinder delegates scrolling responsibilities to the LayoutInfo, as the varied * LayoutManagers wrapped by a LayoutInfo lack a common scrolling interface. Typical * implementations should forward the call to the underlying LayoutManager's * scrollToPositionWithOffset() or an equivalent. * * @param position Index of the item in the adapter * @param offset Additional adjustment to control the precise position the scroll moves to. */ void scrollToPositionWithOffset(int position, int offset); /** * This is called when the {@link RecyclerBinder} needs to calculate a range size. The returned * value should be an approximate range size based on the size of the first measured item. * * @param firstMeasuredItemWidth The width of the first item measured while computing the range. * @param firstMeasuredItemHeight The height of the first item measured while computing the range. * @param recyclerMeasuredWidth The measured width of the RecyclerView. If the RecyclerView * scrolls vertically this might be not significant. * @param recyclerMeasuredHeight The measured height of the RecyclerView. If the RecyclerView * scrolls horizontally this might be not significant. * @return The estimated number of items that are needed to fill one viewport of the RecyclerView. */ int approximateRangeSize( int firstMeasuredItemWidth, int firstMeasuredItemHeight, int recyclerMeasuredWidth, int recyclerMeasuredHeight); /** * @param widthSpec the widthSpec used to measure the parent {@link RecyclerSpec}. * @param renderInfo retrieve SpanSize of the component if it is a {@link GridLayoutInfo} * @return the widthSpec to be used to measure the size of the components within this {@link * RecyclerBinder}. */ int getChildWidthSpec(int widthSpec, RenderInfo renderInfo); /** * @param heightSpec the heightSpec used to measure the parent {@link RecyclerSpec}. * @param renderInfo retrieve SpanSize of the component if it is a {@link GridLayoutInfo} * @return the heightSpec to be used to measure the size of the components within this {@link * RecyclerBinder}. */ int getChildHeightSpec(int heightSpec, RenderInfo renderInfo); /** * @param measuredWidth the width of the RecyclerView * @param measuredHeight the height of the RecyclerView * @return a {@link ViewportFiller} to fill the RecyclerView viewport with views, or null to not * pre-fill the RecyclerView. */ ViewportFiller createViewportFiller(int measuredWidth, int measuredHeight); /** * @param maxHeight the max height of the parent {@link RecyclerSpec}. * @param componentTreeHolders the list of {@link ComponentTreeHolder} in this {@link * RecyclerBinder}. * @return the measured height of this {@link RecyclerBinder}. */ int computeWrappedHeight(int maxHeight, List<ComponentTreeHolder> componentTreeHolders); interface RenderInfoCollection { RenderInfo getRenderInfoAt(int position); } /** * Interface that is responsible for filling the viewport of the list with initial layouts * according to the LayoutManager. The goal here is to have the layouts that the RecyclerView will * ask for when it comes onto the screen already computed, e.g. in the background, so that we * don't drop frames on the main thread. NB: This class should try to respect the layout of views * as they will appear in the RecyclerView. */ interface ViewportFiller { /** * Implementations should return true if they need more views to be computed in order to fill * the screen. */ boolean wantsMore(); /** * This will be called to inform implementations that the next layout has been computed. * Implementations should use the width/height to determine whether they still need more views * to fill their initial viewport (which should be reflected in the next call to {@link * #wantsMore()} */ void add(RenderInfo renderInfo, int width, int height); /** * Return the fill along the main axis (i.e. height for VERTICAL and width for HORIZONTAL), this * method is available after {@link ViewportFiller#add(RenderInfo, int, int)} is called. */ int getFill(); } }
3e00644acf9d18b1807c83667c6c1fd8fac4c6c2
2,730
java
Java
src/test/java/org/fest/assertions/error/NotEqualErrorFactory_newAssertionError_without_JUnit_Test.java
akram/fest-assert-2.x
bff5925af00fc732ba3a0e85f6774acba77ec7c8
[ "Apache-2.0" ]
123
2015-01-04T05:44:08.000Z
2022-03-04T02:13:39.000Z
src/test/java/org/fest/assertions/error/NotEqualErrorFactory_newAssertionError_without_JUnit_Test.java
akram/fest-assert-2.x
bff5925af00fc732ba3a0e85f6774acba77ec7c8
[ "Apache-2.0" ]
6
2015-04-25T00:16:58.000Z
2020-11-04T11:50:54.000Z
src/test/java/org/fest/assertions/error/NotEqualErrorFactory_newAssertionError_without_JUnit_Test.java
akram/fest-assert-2.x
bff5925af00fc732ba3a0e85f6774acba77ec7c8
[ "Apache-2.0" ]
29
2015-01-06T21:08:05.000Z
2020-09-26T02:25:53.000Z
40.147059
118
0.776557
166
/* * Created on Aug 6, 2010 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright @2010-2013 the original author or authors. */ package org.fest.assertions.error; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static org.fest.assertions.error.NotEqualErrorFactory.shouldBeEqual; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.fest.assertions.description.Description; import org.fest.assertions.internal.TestDescription; import org.junit.Before; import org.junit.ComparisonFailure; import org.junit.Test; /** * Tests for >{@link NotEqualErrorFactory#newAssertionError(Description)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class NotEqualErrorFactory_newAssertionError_without_JUnit_Test { private Description description; private ConstructorInvoker constructorInvoker; private NotEqualErrorFactory factory; @Before public void setUp() { description = new TestDescription("Jedi"); constructorInvoker = mock(ConstructorInvoker.class); factory = shouldBeEqual("Luke", "Yoda"); factory.constructorInvoker = constructorInvoker; } @Test public void should_create_AssertionError_if_created_ComparisonFailure_is_null() throws Exception { when(constructorInvoker.newInstance(anyString(), any(Class[].class), any(Object[].class))).thenReturn(null); AssertionError actual = factory.newAssertionError(description); assertFalse(actual instanceof ComparisonFailure); assertEquals("[Jedi] expected:<'Yoda'> but was:<'Luke'>", actual.getMessage()); } @Test public void should_create_AssertionError_if_error_is_thrown_when_creating_ComparisonFailure() throws Exception { RuntimeException error = new RuntimeException("Thrown on purpose"); when(constructorInvoker.newInstance(anyString(), any(Class[].class), any(Object[].class))).thenThrow(error); AssertionError actual = factory.newAssertionError(description); assertFalse(actual instanceof ComparisonFailure); assertEquals("[Jedi] expected:<'Yoda'> but was:<'Luke'>", actual.getMessage()); } }
3e006479e3d50bb56661462c604e7993bdcf2ed6
1,193
java
Java
app/src/main/java/rstech/bluetoothpoc/obd_reader/ObdCommandJob.java
restriglio/bluetoothPOC
cb5d4bb079b6392850c98fc74ee7e347970efb08
[ "Apache-2.0" ]
null
null
null
app/src/main/java/rstech/bluetoothpoc/obd_reader/ObdCommandJob.java
restriglio/bluetoothPOC
cb5d4bb079b6392850c98fc74ee7e347970efb08
[ "Apache-2.0" ]
null
null
null
app/src/main/java/rstech/bluetoothpoc/obd_reader/ObdCommandJob.java
restriglio/bluetoothPOC
cb5d4bb079b6392850c98fc74ee7e347970efb08
[ "Apache-2.0" ]
null
null
null
17.80597
52
0.575859
167
package rstech.bluetoothpoc.obd_reader; import com.github.pires.obd.commands.ObdCommand; /** * Created by raulstriglio on 8/20/17. */ public class ObdCommandJob { private Long _id; private ObdCommand _command; private ObdCommandJobState _state; /** * Default ctor. * * @param command the ObCommand to encapsulate. */ public ObdCommandJob(ObdCommand command) { _command = command; _state = ObdCommandJobState.NEW; } public Long getId() { return _id; } public void setId(Long id) { _id = id; } public ObdCommand getCommand() { return _command; } /** * @return job current state. */ public ObdCommandJobState getState() { return _state; } /** * Sets a new job state. * * @param state the new job state. */ public void setState(ObdCommandJobState state) { _state = state; } /** * The state of the command. */ public enum ObdCommandJobState { NEW, RUNNING, FINISHED, EXECUTION_ERROR, BROKEN_PIPE, QUEUE_ERROR, NOT_SUPPORTED } }
3e0064ab6a37fdfcbcb6837c5b504c5bb1cdecf5
1,486
java
Java
core/transport/src/main/java/alluxio/grpc/BlockLocationOrBuilder.java
piaobeizu/alluxio
273ac84ec117809296550fad7e1663cb1bcdf064
[ "Apache-2.0" ]
3
2019-09-02T09:17:13.000Z
2019-09-02T09:17:17.000Z
core/transport/src/main/java/alluxio/grpc/BlockLocationOrBuilder.java
piaobeizu/alluxio
273ac84ec117809296550fad7e1663cb1bcdf064
[ "Apache-2.0" ]
5
2020-03-05T00:06:05.000Z
2021-08-02T17:19:58.000Z
core/transport/src/main/java/alluxio/grpc/BlockLocationOrBuilder.java
piaobeizu/alluxio
273ac84ec117809296550fad7e1663cb1bcdf064
[ "Apache-2.0" ]
1
2020-02-07T12:38:29.000Z
2020-02-07T12:38:29.000Z
24.766667
77
0.666891
168
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: grpc/common.proto package alluxio.grpc; public interface BlockLocationOrBuilder extends // @@protoc_insertion_point(interface_extends:alluxio.grpc.BlockLocation) com.google.protobuf.MessageOrBuilder { /** * <code>optional int64 workerId = 1;</code> */ boolean hasWorkerId(); /** * <code>optional int64 workerId = 1;</code> */ long getWorkerId(); /** * <code>optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;</code> */ boolean hasWorkerAddress(); /** * <code>optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;</code> */ alluxio.grpc.WorkerNetAddress getWorkerAddress(); /** * <code>optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;</code> */ alluxio.grpc.WorkerNetAddressOrBuilder getWorkerAddressOrBuilder(); /** * <code>optional string tierAlias = 3;</code> */ boolean hasTierAlias(); /** * <code>optional string tierAlias = 3;</code> */ java.lang.String getTierAlias(); /** * <code>optional string tierAlias = 3;</code> */ com.google.protobuf.ByteString getTierAliasBytes(); /** * <code>optional string mediumType = 4;</code> */ boolean hasMediumType(); /** * <code>optional string mediumType = 4;</code> */ java.lang.String getMediumType(); /** * <code>optional string mediumType = 4;</code> */ com.google.protobuf.ByteString getMediumTypeBytes(); }
3e0065b319438393d8951d5d21e14d69c4829a3d
6,844
java
Java
app/src/main/java/org/hyunjun/school/School.java
paranSaeu/SmartClass
72a9e7968faf599dc7976ab5d8f8b8fc3ca429c3
[ "MIT" ]
5
2018-03-03T15:32:32.000Z
2019-07-19T11:20:58.000Z
app/src/main/java/org/hyunjun/school/School.java
paranSaeu/SmartClass
72a9e7968faf599dc7976ab5d8f8b8fc3ca429c3
[ "MIT" ]
1
2018-05-02T13:11:35.000Z
2018-05-02T13:13:14.000Z
app/src/main/java/org/hyunjun/school/School.java
paranSaeu/SmartClass
72a9e7968faf599dc7976ab5d8f8b8fc3ca429c3
[ "MIT" ]
1
2018-09-14T03:59:16.000Z
2018-09-14T03:59:16.000Z
31.539171
115
0.553624
169
package org.hyunjun.school; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.List; /** * School API * 전국 교육청 소속 교육기관의 학사일정, 메뉴를 간단히 불러올 수 있습니다. * * @author HyunJun Kim * @version 3.0 */ public class School { /** * 불러올 교육청 소속 교육기관의 종류 */ public enum Type { /* 병설유치원 */ KINDERGARTEN("1"), /* 초등학교 */ ELEMENTARY("2"), /* 중학교 */ MIDDLE("3"), /* 고등학교 */ HIGH("4"); private String id; Type(String id) { this.id = id; } } /** * 불러올 교육기관의 관할 지역 (교육청) */ public enum Region { /* 서울 */ SEOUL("stu.sen.go.kr"), /* 인천 */ INCHEON("stu.ice.go.kr"), /* 부산 */ BUSAN("stu.pen.go.kr"), /* 광주 */ GWANGJU("stu.gen.go.kr"), /* 대전 */ DAEJEON("stu.dje.go.kr"), /* 대구 */ DAEGU("stu.dge.go.kr"), /* 세종 */ SEJONG("stu.sje.go.kr"), /* 울산 */ ULSAN("stu.use.go.kr"), /* 경기 */ GYEONGGI("stu.goe.go.kr"), /* 강원 */ KANGWON("stu.kwe.go.kr"), /* 충북 */ CHUNGBUK("stu.cbe.go.kr"), /* 충남 */ CHUNGNAM("stu.cne.go.kr"), /* 경북 */ GYEONGBUK("stu.gbe.go.kr"), /* 경남 */ GYEONGNAM("stu.gne.go.kr"), /* 전북 */ JEONBUK("stu.jbe.go.kr"), /* 전남 */ JEONNAM("stu.jne.go.kr"), /* 제주 */ JEJU("stu.jje.go.kr"); private String url; Region(String url) { this.url = url; } } private enum MealTime { BREAKFAST(1), LUNCH(2), DINNER(3); private int id; MealTime(int id) { this.id = id; } } private static final String MONTHLY_MENU_URL = "sts_sci_md00_001.do"; private static final String WEEKLY_MENU_URL = "sts_sci_md01_001.do"; private static final String SCHEDULE_URL = "sts_sci_sf01_001.do"; /** * 교육기관의 종류 */ public Type schoolType; /** * 교육기관 관할 지역 */ public Region schoolRegion; /** * 교육기관 고유 코드 */ public String schoolCode; /** * 불러올 학교 정보를 설정합니다. * * @param schoolType 교육기관의 종류입니다. (School.Type 에서 병설유치원, 초등학교, 중학교, 고등학교 중 선택) * @param schoolRegion 관할 교육청의 위치입니다. (School.Region 에서 선택) * @param schoolCode 교육기관의 고유 코드입니다. */ public School(Type schoolType, Region schoolRegion, String schoolCode) { this.schoolType = schoolType; this.schoolRegion = schoolRegion; this.schoolCode = schoolCode; } /** * 월간 급식 메뉴를 불러옵니다. * * @param year 해당 년도를 yyyy 형식으로 입력. (ex. 2016) * @param month 해당 월을 m 형식으로 입력. (ex. 3, 12) * @return 각 일자별 급식메뉴 리스트 */ public List<SchoolMenu> getMonthlyMenu(int year, int month) throws SchoolException { StringBuffer targetUrl = new StringBuffer("https://" + schoolRegion.url + "/" + MONTHLY_MENU_URL); targetUrl.append("?"); targetUrl.append("schulCode=").append(schoolCode).append("&"); targetUrl.append("schulCrseScCode=").append(schoolType.id).append("&"); targetUrl.append("schulKndScCode=").append("0").append(schoolType.id).append("&"); targetUrl.append("schYm=").append(year).append(String.format("%02d", month)).append("&"); try { String content = getContentFromUrl(new URL(targetUrl.toString()), "<tbody>", "</tbody>"); return SchoolMenuParser.parse(content); } catch (MalformedURLException e) { throw new SchoolException("교육청 접속 주소가 올바르지 않습니다."); } } /** * * @param year 해당 연도를 yyyy 형식으로 입력 * @param month 해당 월을 m 형식으로 입력 * @param day 해당 주간에 포함된 일자를 d 형식으로 입력 * @param mealTime 받아올 식사 시간을 선택 * @return 각 일자별 자세한 급식메뉴 리스트 * @throws SchoolException */ public List<SchoolMenu> getWeeklyMenu(int year, int month, int day, MealTime mealTime) throws SchoolException { StringBuffer targetUrl = new StringBuffer("https://" + schoolRegion.url + "/" + WEEKLY_MENU_URL); targetUrl.append("?"); targetUrl.append("schulCode=").append(schoolCode).append("&"); targetUrl.append("schulCrseScCode=").append(schoolType.id).append("&"); targetUrl.append("schulKndScCode=").append("0").append(schoolType.id).append("&"); targetUrl.append("schYmd=") .append(year).append(String.format("%02d%02d", month, day)).append("&"); targetUrl.append("schMmealScCode=").append(mealTime.id).append("&"); try { String content = getContentFromUrl(new URL(targetUrl.toString()), "<>", "<>"); return SchoolMenuParser.parse(content); } catch (MalformedURLException e) { throw new SchoolException("교육청 접속 주소가 올바르지 않습니다."); } } /** * 월간 학사 일정을 불러옵니다. * * @param year 해당 년도를 yyyy 형식으로 입력. (ex. 2016) * @param month 해당 월을 m 형식으로 입력. (ex. 3, 12) * @return 각 일자별 학사일정 리스트 */ public List<SchoolSchedule> getMonthlySchedule(int year, int month) throws SchoolException { StringBuffer targetUrl = new StringBuffer("https://" + schoolRegion.url + "/" + SCHEDULE_URL); targetUrl.append("?"); targetUrl.append("schulCode=" + schoolCode + "&"); targetUrl.append("schulCrseScCode=" + schoolType.id + "&"); targetUrl.append("schulKndScCode=" + "0" + schoolType.id + "&"); targetUrl.append("ay=" + year + "&"); targetUrl.append("mm=" + String.format("%02d", month) + "&"); try { String content = getContentFromUrl(new URL(targetUrl.toString()), "<tbody>", "</tbody>"); return SchoolScheduleParser.parse(content); } catch (MalformedURLException e) { throw new SchoolException("교육청 접속 주소가 올바르지 않습니다."); } } private String getContentFromUrl(URL url, String readAfter, String readBefore) throws SchoolException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); String inputLine; boolean reading = false; while ((inputLine = reader.readLine()) != null) { if (reading) { if (inputLine.contains(readBefore)) break; buffer.append(inputLine); } else { if (inputLine.contains(readAfter)) reading = true; } } reader.close(); return buffer.toString(); } catch (IOException e) { throw new SchoolException("교육청 서버에 접속하지 못하였습니다."); } } }
3e00664c2ec4bc8e0d0e7df7fa8593a549c93c7e
5,684
java
Java
src/main/java/com/blazebit/jbake/mojo/watcher/WatcherTimerService.java
bshannon/jbake-maven-plugin
7651879d093c2989fa87bc8fe7b224138666772a
[ "Apache-2.0" ]
6
2017-01-22T22:52:01.000Z
2020-12-18T14:01:26.000Z
src/main/java/com/blazebit/jbake/mojo/watcher/WatcherTimerService.java
bshannon/jbake-maven-plugin
7651879d093c2989fa87bc8fe7b224138666772a
[ "Apache-2.0" ]
4
2017-05-24T12:05:19.000Z
2021-06-23T20:42:22.000Z
src/main/java/com/blazebit/jbake/mojo/watcher/WatcherTimerService.java
bshannon/jbake-maven-plugin
7651879d093c2989fa87bc8fe7b224138666772a
[ "Apache-2.0" ]
3
2018-03-09T08:52:55.000Z
2022-01-19T21:37:21.000Z
33.833333
133
0.603448
170
/* * Copyright 2016 Blazebit. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blazebit.jbake.mojo.watcher; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Christian Beikov */ public class WatcherTimerService { private static final Logger LOG = Logger.getLogger(WatcherTimerService.class.getName()); private static final long DEFAULT_TIMEOUT = 400L; private final Timer timer = new Timer("WatcherTimerService"); private final ConcurrentMap<WatchDir, WatcherTimerTask> queuedRefreshTasks = new ConcurrentHashMap<WatchDir, WatcherTimerTask>(); private volatile boolean running = true; public void shutdown() { running = false; timer.cancel(); Iterator<WatcherTimerTask> iter = queuedRefreshTasks.values().iterator(); while (iter.hasNext()) { WatcherTimerTask task = iter.next(); task.await(); } queuedRefreshTasks.clear(); } /** * Queues a refresh. Re-queues unscheduled existing refreshes if possible. * * @param watchDir * @param listener */ public void queue(WatchDir watchDir, WatcherListener listener) { if (!running) { return; } final WatcherTimerTask task = new WatcherTimerTask(watchDir, listener); final WatcherTimerTask previousTask = queuedRefreshTasks.putIfAbsent(watchDir, task); if (previousTask == null) { LOG.finest("Scheduled refresh"); timer.schedule(task, DEFAULT_TIMEOUT); } else { // Try rescheduling the previous task if (previousTask.cancel()) { LOG.finest("Canceled and rescheduled refresh"); // Queued task is canceled and then rescheduled timer.schedule(task, DEFAULT_TIMEOUT); } else { // If not successful, schedule this task LOG.finest("Additionally scheduled refresh"); if (!queuedRefreshTasks.replace(watchDir, previousTask, task)) { // Since queuing is single-threaded this replace must always succeed, but just to be safe queuedRefreshTasks.put(watchDir, task); } // Since the timer is single-threaded there is no need for a lock per WatchDir timer.schedule(task, DEFAULT_TIMEOUT); } } } /** * Re-queues a refresh or awaits it. * * @param watchDir * @return true if queued refresh was requeued, false if none existed */ public boolean requeue(WatchDir watchDir, WatcherListener listener) { if (!running) { return false; } final WatcherTimerTask task = queuedRefreshTasks.get(watchDir); if (task == null) { return false; } if (task.cancel()) { LOG.finest("Requeued refresh"); // Queued task is canceled and then rescheduled final WatcherTimerTask newTask = new WatcherTimerTask(watchDir, listener); if (!queuedRefreshTasks.replace(watchDir, task, newTask)) { // Since queuing is single-threaded this replace must always succeed, but just to be safe queuedRefreshTasks.put(watchDir, newTask); } timer.schedule(newTask, DEFAULT_TIMEOUT); return true; } LOG.finest("Awaiting refresh"); task.await(); LOG.finest("Awaited refresh"); return false; } private class WatcherTimerTask extends TimerTask { private final WatchDir watchDir; private final WatcherListener listener; private final Object lock = new Object(); public WatcherTimerTask(WatchDir watchDir, WatcherListener listener) { this.watchDir = watchDir; this.listener = listener; } @Override public boolean cancel() { boolean prevented = super.cancel(); return prevented; } @Override public void run() { synchronized (lock) { try { LOG.finest("Refreshing"); listener.refresh(); } catch (RuntimeException ex) { logException(ex); } finally { // Remove the runnable from the queue queuedRefreshTasks.remove(watchDir, this); LOG.finest("Refreshed"); } } } public void await() { // The task is currently running, so wait until it's done // TODO: maybe do a timed wait and reschedule refresh if time exceeded synchronized (lock) { return; } } private void logException(Throwable e) { LOG.log(Level.SEVERE, "An error occurred in the watcher timer service!", e); } } }
3e0066885021bdc4e55f67700924cf55fb7485d2
585
java
Java
service/service_edu8001/src/main/java/com/github/eduservice/rabbitmq/BuyCount.java
lg266/Online-Education-Backend
2e831abb1a88774737546295c9025c389fe2324f
[ "MIT" ]
21
2021-05-24T16:27:39.000Z
2022-03-24T15:38:19.000Z
service/service_edu8001/src/main/java/com/github/eduservice/rabbitmq/BuyCount.java
lg266/Online-Education-Backend
2e831abb1a88774737546295c9025c389fe2324f
[ "MIT" ]
1
2022-03-12T13:55:21.000Z
2022-03-13T04:32:45.000Z
service/service_edu8001/src/main/java/com/github/eduservice/rabbitmq/BuyCount.java
lg266/Online-Education-Backend
2e831abb1a88774737546295c9025c389fe2324f
[ "MIT" ]
9
2021-05-06T10:33:10.000Z
2022-03-22T13:14:49.000Z
22.5
63
0.758974
171
package com.github.eduservice.rabbitmq; import com.github.eduservice.service.EduCourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.function.Consumer; /** * @author HAN * @version 1.0 * @create 04-30-4:58 */ @Component public class BuyCount { @Autowired private EduCourseService eduCourseService; @Bean public Consumer<Long> buyCountCourse() { return courseId -> eduCourseService.buyCount(courseId); } }
3e00669762c083f6593277539369c82a443b823a
3,857
java
Java
interlok-core/src/test/java/com/adaptris/core/FormattedFilenameCreatorTest.java
quotidian-ennui/interlok
4ce92e0811ccda1b797b34adc19719c0d3a27b95
[ "Apache-2.0" ]
21
2015-10-27T08:26:15.000Z
2021-12-18T13:24:28.000Z
interlok-core/src/test/java/com/adaptris/core/FormattedFilenameCreatorTest.java
adaptris/interlok
be2598baac2f806acc999ec3b21be789416921a9
[ "Apache-2.0" ]
816
2016-01-18T13:17:16.000Z
2022-03-31T16:03:10.000Z
interlok-core/src/test/java/com/adaptris/core/FormattedFilenameCreatorTest.java
gerco/interlok
d2e538df749498a73dc381113ac183a25422e510
[ "Apache-2.0" ]
10
2015-10-20T14:33:53.000Z
2021-03-24T21:46:14.000Z
35.385321
93
0.725175
172
/* * Copyright 2015 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Date; import org.junit.Test; import com.adaptris.interlok.junit.scaffolding.BaseCase; public class FormattedFilenameCreatorTest { @Test public void testSetFormat() { FormattedFilenameCreator creator = new FormattedFilenameCreator(); try { creator.setFilenameFormat(null); fail("null allowed"); } catch (IllegalArgumentException e) { } assertEquals(creator.getFilenameFormat(), "%1$s"); try { creator.setFilenameFormat(""); fail("'' allowed"); } catch (IllegalArgumentException e) { } assertEquals(creator.getFilenameFormat(), "%1$s"); creator.setFilenameFormat("message"); assertEquals("message", creator.getFilenameFormat()); } @Test public void testPlain() throws Exception { FormattedFilenameCreator creator = new FormattedFilenameCreator(); AdaptrisMessage msg = new DefaultMessageFactory().newMessage(""); String expectedName = msg.getUniqueId(); String fileName = creator.createName(msg); assertEquals(fileName, expectedName); } @Test public void testWithTimestamp() throws Exception { FormattedFilenameCreator creator = new FormattedFilenameCreator(); creator.setFilenameFormat("%1$s-%2$tF"); AdaptrisMessage msg = new DefaultMessageFactory().newMessage(""); String expectedName = String.format("%1$s-%2$tF", msg.getUniqueId(), new Date()); String fname = creator.createName(msg); assertEquals(expectedName, fname); } @Test public void testWithConstants() throws Exception { FormattedFilenameCreator creator = new FormattedFilenameCreator(); creator.setFilenameFormat("message-%1$s-%2$tF"); AdaptrisMessage msg = new DefaultMessageFactory().newMessage(""); String expectedName = String.format("message-%1$s-%2$tF", msg.getUniqueId(), new Date()); String fname = creator.createName(msg); assertEquals(expectedName, fname); } @Test public void testWithoutUniqueid() throws Exception { FormattedFilenameCreator creator = new FormattedFilenameCreator(); creator.setFilenameFormat("message-%2$tF"); AdaptrisMessage msg = new DefaultMessageFactory().newMessage(""); String expectedName = String.format("message-%2$tF", msg.getUniqueId(), new Date()); String fname = creator.createName(msg); assertEquals(expectedName, fname); } @Test public void testReversedOrder() throws Exception { FormattedFilenameCreator creator = new FormattedFilenameCreator(); creator.setFilenameFormat("%2$tF-%1$s"); AdaptrisMessage msg = new DefaultMessageFactory().newMessage(""); String expectedName = String.format("%2$tF-%1$s", msg.getUniqueId(), new Date()); String fname = creator.createName(msg); assertEquals(expectedName, fname); } @Test public void testXmlRoundTrip() throws Exception { FormattedFilenameCreator input = new FormattedFilenameCreator(); AdaptrisMarshaller m = DefaultMarshaller.getDefaultMarshaller(); String xml = m.marshal(input); FormattedFilenameCreator output = (FormattedFilenameCreator) m.unmarshal(xml); BaseCase.assertRoundtripEquality(input, output); } }
3e0066988c8b72d60bcf02d0c47ef20e8e43f9d8
139
java
Java
app/src/main/java/com/siziksu/bluetooth/domain/BaseDomainContract.java
Siziksu/AndroidBluetoothForArduino
88f5298626651bbacf7a38994cf6360d3f695e64
[ "Apache-2.0" ]
3
2019-03-26T01:15:10.000Z
2020-03-02T10:39:10.000Z
app/src/main/java/com/siziksu/bluetooth/domain/BaseDomainContract.java
Siziksu/AndroidBluetoothForArduino
88f5298626651bbacf7a38994cf6360d3f695e64
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/siziksu/bluetooth/domain/BaseDomainContract.java
Siziksu/AndroidBluetoothForArduino
88f5298626651bbacf7a38994cf6360d3f695e64
[ "Apache-2.0" ]
null
null
null
15.444444
40
0.733813
173
package com.siziksu.bluetooth.domain; public interface BaseDomainContract<D> { void register(D presenter); void unregister(); }
3e0067621f8e23d4473e5c773d50b6f540ed3450
1,165
java
Java
src/main/java/net/kodar/restaurantapi/business/processor/orderstatus/OrderStatusProcessorImpl.java
kamentr/API_Restaurant
d8b448c984b87c1a723b17ee366bddeb94b59eae
[ "MIT" ]
1
2021-01-27T14:55:29.000Z
2021-01-27T14:55:29.000Z
src/main/java/net/kodar/restaurantapi/business/processor/orderstatus/OrderStatusProcessorImpl.java
kamentr/API_Restaurant
d8b448c984b87c1a723b17ee366bddeb94b59eae
[ "MIT" ]
null
null
null
src/main/java/net/kodar/restaurantapi/business/processor/orderstatus/OrderStatusProcessorImpl.java
kamentr/API_Restaurant
d8b448c984b87c1a723b17ee366bddeb94b59eae
[ "MIT" ]
null
null
null
48.541667
261
0.851502
174
package net.kodar.restaurantapi.business.processor.orderstatus; import org.springframework.stereotype.Service; import net.kodar.restaurantapi.business.processor.ProcessorGenericImpl; import net.kodar.restaurantapi.business.transformer.param.orderstatus.OrderStatusParamTransformer; import net.kodar.restaurantapi.business.transformer.result.orderstatus.OrderStatusResultTransformer; import net.kodar.restaurantapi.business.validator.orderstatus.OrderStatusValidatorImpl; import net.kodar.restaurantapi.data.entities.OrderStatus; import net.kodar.restaurantapi.dataaccess.dao.orderstatus.OrderStatusDaoImpl; import net.kodar.restaurantapi.presentation.param.OrderStatusParam; import net.kodar.restaurantapi.presentation.result.OrderStatusResult; @Service public class OrderStatusProcessorImpl extends ProcessorGenericImpl<OrderStatusParam, OrderStatusResult, Long, OrderStatus, OrderStatusDaoImpl, OrderStatusParamTransformer, OrderStatusResultTransformer, OrderStatusValidatorImpl> implements OrderStatusProcessor{ @Override public Long getID(OrderStatusParam param) { // TODO Auto-generated method stub return param.getId(); } }
3e0069b85b30f9f50a899680757f80c00901e3c2
273,348
java
Java
test/com/google/javascript/rhino/jstype/JSTypeTest.java
gisshare2015/closure-compiler
f8e657686c864db0554534213d7581a36a5545ef
[ "Apache-2.0" ]
4
2018-09-03T18:35:59.000Z
2020-08-08T14:35:20.000Z
test/com/google/javascript/rhino/jstype/JSTypeTest.java
gaearon/closure-compiler
d66ab8e8562c313b873070ba59a3f1211a30f7eb
[ "Apache-2.0" ]
null
null
null
test/com/google/javascript/rhino/jstype/JSTypeTest.java
gaearon/closure-compiler
d66ab8e8562c313b873070ba59a3f1211a30f7eb
[ "Apache-2.0" ]
2
2018-09-03T18:36:00.000Z
2021-01-10T13:23:58.000Z
42.710625
100
0.757375
175
/* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Nick Santos * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.FALSE; import static com.google.javascript.rhino.jstype.TernaryValue.TRUE; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSDocInfoBuilder; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SimpleErrorReporter; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TypeI; import com.google.javascript.rhino.jstype.JSType.TypePair; import com.google.javascript.rhino.testing.AbstractStaticScope; import com.google.javascript.rhino.testing.Asserts; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.MapBasedScope; import java.util.ArrayList; import java.util.HashSet; import java.util.List; // TODO(nicksantos): Split some of this up into per-class unit tests. public class JSTypeTest extends BaseJSTypeTestCase { private FunctionType dateMethod; private FunctionType functionType; private NamedType unresolvedNamedType; private FunctionType googBar; private FunctionType googSubBar; private FunctionType googSubSubBar; private ObjectType googBarInst; private ObjectType googSubBarInst; private ObjectType googSubSubBarInst; private NamedType namedGoogBar; private ObjectType subclassOfUnresolvedNamedType; private FunctionType subclassCtor; private FunctionType interfaceType; private ObjectType interfaceInstType; private FunctionType subInterfaceType; private ObjectType subInterfaceInstType; private JSType recordType; private EnumType enumType; private EnumElementType elementsType; private NamedType forwardDeclaredNamedType; private static final StaticTypedScope<JSType> EMPTY_SCOPE = MapBasedScope.emptyScope(); /** * A non exhaustive list of representative types used to test simple * properties that should hold for all types (such as the reflexivity * of subtyping). */ private List<JSType> types; @Override protected void setUp() throws Exception { super.setUp(); RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); recordType = builder.build(); enumType = new EnumType(registry, "Enum", null, NUMBER_TYPE); elementsType = enumType.getElementsType(); functionType = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .build(); dateMethod = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .withTypeOfThis(DATE_TYPE) .build(); unresolvedNamedType = new NamedType(registry, "not.resolved.named.type", null, -1, -1); namedGoogBar = new NamedType(registry, "goog.Bar", null, -1, -1); subclassCtor = new FunctionType( registry, null, null, createArrowType(null), null, null, true, false, false); subclassCtor.setPrototypeBasedOn(unresolvedNamedType); subclassOfUnresolvedNamedType = subclassCtor.getInstanceType(); interfaceType = FunctionType.forInterface(registry, "Interface", null, registry.createTemplateTypeMap(null, null)); interfaceInstType = interfaceType.getInstanceType(); subInterfaceType = FunctionType.forInterface( registry, "SubInterface", null, registry.createTemplateTypeMap(null, null)); subInterfaceType.setExtendedInterfaces( Lists.<ObjectType>newArrayList(interfaceInstType)); subInterfaceInstType = subInterfaceType.getInstanceType(); googBar = registry.createConstructorType("goog.Bar", null, null, null, null, false); googBar.getPrototype().defineDeclaredProperty("date", DATE_TYPE, null); googBar.setImplementedInterfaces( Lists.<ObjectType>newArrayList(interfaceInstType)); googBarInst = googBar.getInstanceType(); googSubBar = registry.createConstructorType("googSubBar", null, null, null, null, false); googSubBar.setPrototypeBasedOn(googBar.getInstanceType()); googSubBarInst = googSubBar.getInstanceType(); googSubSubBar = registry.createConstructorType("googSubSubBar", null, null, null, null, false); googSubSubBar.setPrototypeBasedOn(googSubBar.getInstanceType()); googSubSubBarInst = googSubSubBar.getInstanceType(); final ObjectType googObject = registry.createAnonymousObjectType(null); googObject.defineDeclaredProperty("Bar", googBar, null); namedGoogBar.resolve(null, new AbstractStaticScope<JSType>() { @Override public StaticTypedSlot<JSType> getSlot(String name) { if ("goog".equals(name)) { return new SimpleSlot("goog", googObject, false); } else { return null; } } }); assertNotNull(namedGoogBar.getImplicitPrototype()); forwardDeclaredNamedType = new NamedType(registry, "forwardDeclared", "source", 1, 0); forwardDeclaredNamedType.resolve( new SimpleErrorReporter(), EMPTY_SCOPE); types = ImmutableList.of( NO_OBJECT_TYPE, NO_RESOLVED_TYPE, NO_TYPE, BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE, STRING_OBJECT_TYPE, STRING_TYPE, VOID_TYPE, UNKNOWN_TYPE, NULL_TYPE, NUMBER_OBJECT_TYPE, NUMBER_TYPE, DATE_TYPE, ERROR_TYPE, SYNTAX_ERROR_TYPE, dateMethod, functionType, unresolvedNamedType, googBar, googSubBar, googSubSubBar, namedGoogBar, googBar.getInstanceType(), subclassOfUnresolvedNamedType, subclassCtor, recordType, enumType, elementsType, googBar, googSubBar, forwardDeclaredNamedType); } /** * Tests the behavior of the top constructor type. */ public void testUniversalConstructorType() throws Exception { // isXxx assertFalse(U2U_CONSTRUCTOR_TYPE.isNoObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNoType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isArrayType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isBooleanValueType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isDateType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isEnumElementType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNullType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNamedType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNullType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumber()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumberObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumberValueType()); assertTrue(U2U_CONSTRUCTOR_TYPE.isObject()); assertFalse(U2U_CONSTRUCTOR_TYPE.isFunctionPrototypeType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isRegexpType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isString()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStringObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStringValueType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isEnumType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isUnionType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStruct()); assertFalse(U2U_CONSTRUCTOR_TYPE.isDict()); assertFalse(U2U_CONSTRUCTOR_TYPE.isAllType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isVoidType()); assertTrue(U2U_CONSTRUCTOR_TYPE.isConstructor()); assertTrue(U2U_CONSTRUCTOR_TYPE.isInstanceType()); // isSubtype assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NO_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(DATE_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(functionType)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(STRING_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(ALL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NO_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NO_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ALL_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(BOOLEAN_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(DATE_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(functionType)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NUMBER_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(URI_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(RANGE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(STRING_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(STRING_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(TYPE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(VOID_TYPE)); // canTestForShallowEqualityWith assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NO_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(functionType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(U2U_CONSTRUCTOR_TYPE.isNullable()); assertFalse(U2U_CONSTRUCTOR_TYPE.isVoidable()); // isObject assertTrue(U2U_CONSTRUCTOR_TYPE.isObject()); // matchesXxx assertFalse(U2U_CONSTRUCTOR_TYPE.matchesInt32Context()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesNumberContext()); assertTrue(U2U_CONSTRUCTOR_TYPE.matchesObjectContext()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesStringContext()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesUint32Context()); // toString assertEquals("Function", U2U_CONSTRUCTOR_TYPE.toString()); assertTrue(U2U_CONSTRUCTOR_TYPE.hasDisplayName()); assertEquals("Function", U2U_CONSTRUCTOR_TYPE.getDisplayName()); // getPropertyType assertTypeEquals(UNKNOWN_TYPE, U2U_CONSTRUCTOR_TYPE.getPropertyType("anyProperty")); assertTrue(U2U_CONSTRUCTOR_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(U2U_CONSTRUCTOR_TYPE); assertTrue(U2U_CONSTRUCTOR_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Bottom Object type. */ public void testNoObjectType() throws Exception { // isXxx assertTrue(NO_OBJECT_TYPE.isNoObjectType()); assertFalse(NO_OBJECT_TYPE.isNoType()); assertFalse(NO_OBJECT_TYPE.isArrayType()); assertFalse(NO_OBJECT_TYPE.isBooleanValueType()); assertFalse(NO_OBJECT_TYPE.isDateType()); assertFalse(NO_OBJECT_TYPE.isEnumElementType()); assertFalse(NO_OBJECT_TYPE.isNullType()); assertFalse(NO_OBJECT_TYPE.isNamedType()); assertFalse(NO_OBJECT_TYPE.isNullType()); assertTrue(NO_OBJECT_TYPE.isNumber()); assertFalse(NO_OBJECT_TYPE.isNumberObjectType()); assertFalse(NO_OBJECT_TYPE.isNumberValueType()); assertTrue(NO_OBJECT_TYPE.isObject()); assertFalse(NO_OBJECT_TYPE.isFunctionPrototypeType()); assertFalse(NO_OBJECT_TYPE.isRegexpType()); assertTrue(NO_OBJECT_TYPE.isString()); assertFalse(NO_OBJECT_TYPE.isStringObjectType()); assertFalse(NO_OBJECT_TYPE.isStringValueType()); assertFalse(NO_OBJECT_TYPE.isEnumType()); assertFalse(NO_OBJECT_TYPE.isUnionType()); assertFalse(NO_OBJECT_TYPE.isStruct()); assertFalse(NO_OBJECT_TYPE.isDict()); assertFalse(NO_OBJECT_TYPE.isAllType()); assertFalse(NO_OBJECT_TYPE.isVoidType()); assertFalse(NO_OBJECT_TYPE.isConstructor()); assertFalse(NO_OBJECT_TYPE.isInstanceType()); // isSubtype assertFalse(NO_OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(functionType)); assertTrue(NO_OBJECT_TYPE.isSubtype(recordType)); assertFalse(NO_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCannotTestForEqualityWith(NO_OBJECT_TYPE, NO_TYPE); assertCannotTestForEqualityWith(NO_OBJECT_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(NO_OBJECT_TYPE, recordType); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(NO_OBJECT_TYPE.isNullable()); assertFalse(NO_OBJECT_TYPE.isVoidable()); // isObject assertTrue(NO_OBJECT_TYPE.isObject()); // matchesXxx assertTrue(NO_OBJECT_TYPE.matchesInt32Context()); assertTrue(NO_OBJECT_TYPE.matchesNumberContext()); assertTrue(NO_OBJECT_TYPE.matchesObjectContext()); assertTrue(NO_OBJECT_TYPE.matchesStringContext()); assertTrue(NO_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("NoObject", NO_OBJECT_TYPE.toString()); assertFalse(NO_OBJECT_TYPE.hasDisplayName()); assertEquals(null, NO_OBJECT_TYPE.getDisplayName()); // getPropertyType assertTypeEquals(NO_TYPE, NO_OBJECT_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_OBJECT_TYPE); assertFalse(NO_OBJECT_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Bottom type. */ public void testNoType() throws Exception { // isXxx assertFalse(NO_TYPE.isNoObjectType()); assertTrue(NO_TYPE.isNoType()); assertFalse(NO_TYPE.isArrayType()); assertFalse(NO_TYPE.isBooleanValueType()); assertFalse(NO_TYPE.isDateType()); assertFalse(NO_TYPE.isEnumElementType()); assertFalse(NO_TYPE.isNullType()); assertFalse(NO_TYPE.isNamedType()); assertFalse(NO_TYPE.isNullType()); assertTrue(NO_TYPE.isNumber()); assertFalse(NO_TYPE.isNumberObjectType()); assertFalse(NO_TYPE.isNumberValueType()); assertTrue(NO_TYPE.isObject()); assertFalse(NO_TYPE.isFunctionPrototypeType()); assertFalse(NO_TYPE.isRegexpType()); assertTrue(NO_TYPE.isString()); assertFalse(NO_TYPE.isStringObjectType()); assertFalse(NO_TYPE.isStringValueType()); assertFalse(NO_TYPE.isEnumType()); assertFalse(NO_TYPE.isUnionType()); assertFalse(NO_TYPE.isStruct()); assertFalse(NO_TYPE.isDict()); assertFalse(NO_TYPE.isAllType()); assertFalse(NO_TYPE.isVoidType()); assertFalse(NO_TYPE.isConstructor()); assertFalse(NO_TYPE.isInstanceType()); // isSubtype assertTrue(NO_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(functionType)); assertTrue(NO_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCannotTestForEqualityWith(NO_TYPE, NO_TYPE); assertCannotTestForEqualityWith(NO_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, functionType); assertCanTestForEqualityWith(NO_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NO_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(NO_TYPE.isNullable()); assertTrue(NO_TYPE.isVoidable()); // isObject assertTrue(NO_TYPE.isObject()); // matchesXxx assertTrue(NO_TYPE.matchesInt32Context()); assertTrue(NO_TYPE.matchesNumberContext()); assertTrue(NO_TYPE.matchesObjectContext()); assertTrue(NO_TYPE.matchesStringContext()); assertTrue(NO_TYPE.matchesUint32Context()); // toString assertEquals("None", NO_TYPE.toString()); assertEquals(null, NO_TYPE.getDisplayName()); assertFalse(NO_TYPE.hasDisplayName()); // getPropertyType assertTypeEquals(NO_TYPE, NO_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_TYPE); assertFalse(NO_TYPE.isNominalConstructor()); } /** * Tests the behavior of the unresolved Bottom type. */ public void testNoResolvedType() throws Exception { // isXxx assertFalse(NO_RESOLVED_TYPE.isNoObjectType()); assertFalse(NO_RESOLVED_TYPE.isNoType()); assertTrue(NO_RESOLVED_TYPE.isNoResolvedType()); assertFalse(NO_RESOLVED_TYPE.isArrayType()); assertFalse(NO_RESOLVED_TYPE.isBooleanValueType()); assertFalse(NO_RESOLVED_TYPE.isDateType()); assertFalse(NO_RESOLVED_TYPE.isEnumElementType()); assertFalse(NO_RESOLVED_TYPE.isNullType()); assertFalse(NO_RESOLVED_TYPE.isNamedType()); assertTrue(NO_RESOLVED_TYPE.isNumber()); assertFalse(NO_RESOLVED_TYPE.isNumberObjectType()); assertFalse(NO_RESOLVED_TYPE.isNumberValueType()); assertTrue(NO_RESOLVED_TYPE.isObject()); assertFalse(NO_RESOLVED_TYPE.isFunctionPrototypeType()); assertFalse(NO_RESOLVED_TYPE.isRegexpType()); assertTrue(NO_RESOLVED_TYPE.isString()); assertFalse(NO_RESOLVED_TYPE.isStringObjectType()); assertFalse(NO_RESOLVED_TYPE.isStringValueType()); assertFalse(NO_RESOLVED_TYPE.isEnumType()); assertFalse(NO_RESOLVED_TYPE.isUnionType()); assertFalse(NO_RESOLVED_TYPE.isStruct()); assertFalse(NO_RESOLVED_TYPE.isDict()); assertFalse(NO_RESOLVED_TYPE.isAllType()); assertFalse(NO_RESOLVED_TYPE.isVoidType()); assertFalse(NO_RESOLVED_TYPE.isConstructor()); assertFalse(NO_RESOLVED_TYPE.isInstanceType()); // isSubtype assertTrue(NO_RESOLVED_TYPE.isSubtype(NO_RESOLVED_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(functionType)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_RESOLVED_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, functionType); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NO_RESOLVED_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(NO_RESOLVED_TYPE.isNullable()); assertTrue(NO_RESOLVED_TYPE.isVoidable()); // isObject assertTrue(NO_RESOLVED_TYPE.isObject()); // matchesXxx assertTrue(NO_RESOLVED_TYPE.matchesInt32Context()); assertTrue(NO_RESOLVED_TYPE.matchesNumberContext()); assertTrue(NO_RESOLVED_TYPE.matchesObjectContext()); assertTrue(NO_RESOLVED_TYPE.matchesStringContext()); assertTrue(NO_RESOLVED_TYPE.matchesUint32Context()); // toString assertEquals("NoResolvedType", NO_RESOLVED_TYPE.toString()); assertEquals(null, NO_RESOLVED_TYPE.getDisplayName()); assertFalse(NO_RESOLVED_TYPE.hasDisplayName()); // getPropertyType assertTypeEquals(CHECKED_UNKNOWN_TYPE, NO_RESOLVED_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_RESOLVED_TYPE); assertTrue(forwardDeclaredNamedType.isEmptyType()); assertTrue(forwardDeclaredNamedType.isNoResolvedType()); UnionType nullable = (UnionType) registry.createNullableType(NO_RESOLVED_TYPE); assertTypeEquals( nullable, nullable.getGreatestSubtype(NULL_TYPE)); assertTypeEquals(NO_RESOLVED_TYPE, nullable.getRestrictedUnion(NULL_TYPE)); } /** * Tests the behavior of the Array type. */ public void testArrayType() throws Exception { // isXxx assertTrue(ARRAY_TYPE.isArrayType()); assertFalse(ARRAY_TYPE.isBooleanValueType()); assertFalse(ARRAY_TYPE.isDateType()); assertFalse(ARRAY_TYPE.isEnumElementType()); assertFalse(ARRAY_TYPE.isNamedType()); assertFalse(ARRAY_TYPE.isNullType()); assertFalse(ARRAY_TYPE.isNumber()); assertFalse(ARRAY_TYPE.isNumberObjectType()); assertFalse(ARRAY_TYPE.isNumberValueType()); assertTrue(ARRAY_TYPE.isObject()); assertFalse(ARRAY_TYPE.isFunctionPrototypeType()); assertTrue(ARRAY_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(ARRAY_TYPE.isRegexpType()); assertFalse(ARRAY_TYPE.isString()); assertFalse(ARRAY_TYPE.isStringObjectType()); assertFalse(ARRAY_TYPE.isStringValueType()); assertFalse(ARRAY_TYPE.isEnumType()); assertFalse(ARRAY_TYPE.isUnionType()); assertFalse(ARRAY_TYPE.isStruct()); assertFalse(ARRAY_TYPE.isDict()); assertFalse(ARRAY_TYPE.isAllType()); assertFalse(ARRAY_TYPE.isVoidType()); assertFalse(ARRAY_TYPE.isConstructor()); assertTrue(ARRAY_TYPE.isInstanceType()); // isSubtype assertFalse(ARRAY_TYPE.isSubtype(NO_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ALL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(functionType)); assertFalse(ARRAY_TYPE.isSubtype(recordType)); assertFalse(ARRAY_TYPE.isSubtype(NULL_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(DATE_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(unresolvedNamedType)); assertFalse(ARRAY_TYPE.isSubtype(namedGoogBar)); assertFalse(ARRAY_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(ARRAY_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(ARRAY_TYPE, NO_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, ALL_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, functionType); assertCanTestForEqualityWith(ARRAY_TYPE, recordType); assertCannotTestForEqualityWith(ARRAY_TYPE, VOID_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, DATE_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(ARRAY_TYPE.isNullable()); assertFalse(ARRAY_TYPE.isVoidable()); assertTrue(createUnionType(ARRAY_TYPE, NULL_TYPE).isNullable()); assertTrue(createUnionType(ARRAY_TYPE, VOID_TYPE).isVoidable()); // isObject assertTrue(ARRAY_TYPE.isObject()); // getLeastSupertype assertTypeEquals(ALL_TYPE, ARRAY_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(STRING_OBJECT_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(ARRAY_TYPE, functionType), ARRAY_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, ARRAY_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(17, ARRAY_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(18, ARRAY_TYPE.getPropertiesCount()); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("concat")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("join")); assertReturnTypeEquals(UNKNOWN_TYPE, ARRAY_TYPE.getPropertyType("pop")); assertReturnTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("push")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("reverse")); assertReturnTypeEquals(UNKNOWN_TYPE, ARRAY_TYPE.getPropertyType("shift")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("slice")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("sort")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("splice")); assertReturnTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("unshift")); assertTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("length")); // isPropertyType* assertPropertyTypeDeclared(ARRAY_TYPE, "pop"); // matchesXxx assertFalse(ARRAY_TYPE.matchesInt32Context()); assertFalse(ARRAY_TYPE.matchesNumberContext()); assertTrue(ARRAY_TYPE.matchesObjectContext()); assertTrue(ARRAY_TYPE.matchesStringContext()); assertFalse(ARRAY_TYPE.matchesUint32Context()); // toString assertEquals("Array", ARRAY_TYPE.toString()); assertTrue(ARRAY_TYPE.hasDisplayName()); assertEquals("Array", ARRAY_TYPE.getDisplayName()); assertTrue(ARRAY_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(ARRAY_TYPE); assertFalse(ARRAY_TYPE.isNominalConstructor()); assertTrue(ARRAY_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the unknown type. */ public void testUnknownType() throws Exception { // isXxx assertFalse(UNKNOWN_TYPE.isArrayType()); assertFalse(UNKNOWN_TYPE.isBooleanObjectType()); assertFalse(UNKNOWN_TYPE.isBooleanValueType()); assertFalse(UNKNOWN_TYPE.isDateType()); assertFalse(UNKNOWN_TYPE.isEnumElementType()); assertFalse(UNKNOWN_TYPE.isNamedType()); assertFalse(UNKNOWN_TYPE.isNullType()); assertFalse(UNKNOWN_TYPE.isNumberObjectType()); assertFalse(UNKNOWN_TYPE.isNumberValueType()); assertTrue(UNKNOWN_TYPE.isObject()); assertFalse(UNKNOWN_TYPE.isFunctionPrototypeType()); assertFalse(UNKNOWN_TYPE.isRegexpType()); assertFalse(UNKNOWN_TYPE.isStringObjectType()); assertFalse(UNKNOWN_TYPE.isStringValueType()); assertFalse(UNKNOWN_TYPE.isEnumType()); assertFalse(UNKNOWN_TYPE.isUnionType()); assertFalse(UNKNOWN_TYPE.isStruct()); assertFalse(UNKNOWN_TYPE.isDict()); assertTrue(UNKNOWN_TYPE.isUnknownType()); assertFalse(UNKNOWN_TYPE.isVoidType()); assertFalse(UNKNOWN_TYPE.isConstructor()); assertFalse(UNKNOWN_TYPE.isInstanceType()); // autoboxesTo assertNull(UNKNOWN_TYPE.autoboxesTo()); // isSubtype assertTrue(UNKNOWN_TYPE.isSubtype(UNKNOWN_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(STRING_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(functionType)); assertTrue(UNKNOWN_TYPE.isSubtype(recordType)); assertTrue(UNKNOWN_TYPE.isSubtype(NULL_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(DATE_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(namedGoogBar)); assertTrue(UNKNOWN_TYPE.isSubtype(unresolvedNamedType)); assertTrue(UNKNOWN_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertTrue(UNKNOWN_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(UNKNOWN_TYPE, UNKNOWN_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, STRING_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, functionType); assertCanTestForEqualityWith(UNKNOWN_TYPE, recordType); assertCanTestForEqualityWith(UNKNOWN_TYPE, VOID_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, DATE_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, BOOLEAN_TYPE); // canTestForShallowEqualityWith assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(recordType)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); // canHaveNullValue assertTrue(UNKNOWN_TYPE.isNullable()); assertTrue(UNKNOWN_TYPE.isVoidable()); // getGreatestCommonType assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(STRING_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(functionType)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(UNKNOWN_TYPE.matchesInt32Context()); assertTrue(UNKNOWN_TYPE.matchesNumberContext()); assertTrue(UNKNOWN_TYPE.matchesObjectContext()); assertTrue(UNKNOWN_TYPE.matchesStringContext()); assertTrue(UNKNOWN_TYPE.matchesUint32Context()); // isPropertyType* assertPropertyTypeUnknown(UNKNOWN_TYPE, "XXX"); // toString assertEquals("?", UNKNOWN_TYPE.toString()); assertTrue(UNKNOWN_TYPE.hasDisplayName()); assertEquals("Unknown", UNKNOWN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(UNKNOWN_TYPE); assertFalse(UNKNOWN_TYPE.isNominalConstructor()); assertEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getPropertyType("abc")); } /** * Tests the behavior of the checked unknown type. */ public void testCheckedUnknownType() throws Exception { // isPropertyType* assertPropertyTypeUnknown(CHECKED_UNKNOWN_TYPE, "XXX"); // toString assertEquals("??", CHECKED_UNKNOWN_TYPE.toString()); assertTrue(CHECKED_UNKNOWN_TYPE.hasDisplayName()); assertEquals("Unknown", CHECKED_UNKNOWN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(CHECKED_UNKNOWN_TYPE); assertFalse(CHECKED_UNKNOWN_TYPE.isNominalConstructor()); assertEquals(CHECKED_UNKNOWN_TYPE, CHECKED_UNKNOWN_TYPE.getPropertyType("abc")); } /** * Tests the behavior of the unknown type. */ public void testAllType() throws Exception { // isXxx assertFalse(ALL_TYPE.isArrayType()); assertFalse(ALL_TYPE.isBooleanValueType()); assertFalse(ALL_TYPE.isDateType()); assertFalse(ALL_TYPE.isEnumElementType()); assertFalse(ALL_TYPE.isNamedType()); assertFalse(ALL_TYPE.isNullType()); assertFalse(ALL_TYPE.isNumber()); assertFalse(ALL_TYPE.isNumberObjectType()); assertFalse(ALL_TYPE.isNumberValueType()); assertFalse(ALL_TYPE.isObject()); assertFalse(ALL_TYPE.isFunctionPrototypeType()); assertFalse(ALL_TYPE.isRegexpType()); assertFalse(ALL_TYPE.isString()); assertFalse(ALL_TYPE.isStringObjectType()); assertFalse(ALL_TYPE.isStringValueType()); assertFalse(ALL_TYPE.isEnumType()); assertFalse(ALL_TYPE.isUnionType()); assertFalse(ALL_TYPE.isStruct()); assertFalse(ALL_TYPE.isDict()); assertTrue(ALL_TYPE.isAllType()); assertFalse(ALL_TYPE.isVoidType()); assertFalse(ALL_TYPE.isConstructor()); assertFalse(ALL_TYPE.isInstanceType()); // isSubtype assertFalse(ALL_TYPE.isSubtype(NO_TYPE)); assertFalse(ALL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ALL_TYPE.isSubtype(ALL_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ALL_TYPE.isSubtype(functionType)); assertFalse(ALL_TYPE.isSubtype(recordType)); assertFalse(ALL_TYPE.isSubtype(NULL_TYPE)); assertFalse(ALL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(DATE_TYPE)); assertTrue(ALL_TYPE.isSubtype(unresolvedNamedType)); assertFalse(ALL_TYPE.isSubtype(namedGoogBar)); assertFalse(ALL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ALL_TYPE.isSubtype(VOID_TYPE)); assertTrue(ALL_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(ALL_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(ALL_TYPE, ALL_TYPE); assertCanTestForEqualityWith(ALL_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(ALL_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(ALL_TYPE, functionType); assertCanTestForEqualityWith(ALL_TYPE, recordType); assertCanTestForEqualityWith(ALL_TYPE, VOID_TYPE); assertCanTestForEqualityWith(ALL_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(ALL_TYPE, DATE_TYPE); assertCanTestForEqualityWith(ALL_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(recordType)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(ALL_TYPE.isNullable()); assertTrue(ALL_TYPE.isVoidable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(functionType)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertFalse(ALL_TYPE.matchesInt32Context()); assertFalse(ALL_TYPE.matchesNumberContext()); assertTrue(ALL_TYPE.matchesObjectContext()); assertTrue(ALL_TYPE.matchesStringContext()); assertFalse(ALL_TYPE.matchesUint32Context()); // toString assertEquals("*", ALL_TYPE.toString()); assertTrue(ALL_TYPE.hasDisplayName()); assertEquals("<Any Type>", ALL_TYPE.getDisplayName()); Asserts.assertResolvesToSame(ALL_TYPE); assertFalse(ALL_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Object type (the object * at the top of the JavaScript hierarchy). */ public void testTheObjectType() throws Exception { // implicit prototype assertTypeEquals(OBJECT_PROTOTYPE, OBJECT_TYPE.getImplicitPrototype()); // isXxx assertFalse(OBJECT_TYPE.isNoObjectType()); assertFalse(OBJECT_TYPE.isNoType()); assertFalse(OBJECT_TYPE.isArrayType()); assertFalse(OBJECT_TYPE.isBooleanValueType()); assertFalse(OBJECT_TYPE.isDateType()); assertFalse(OBJECT_TYPE.isEnumElementType()); assertFalse(OBJECT_TYPE.isNullType()); assertFalse(OBJECT_TYPE.isNamedType()); assertFalse(OBJECT_TYPE.isNullType()); assertFalse(OBJECT_TYPE.isNumber()); assertFalse(OBJECT_TYPE.isNumberObjectType()); assertFalse(OBJECT_TYPE.isNumberValueType()); assertTrue(OBJECT_TYPE.isObject()); assertFalse(OBJECT_TYPE.isFunctionPrototypeType()); assertTrue(OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(OBJECT_TYPE.isRegexpType()); assertFalse(OBJECT_TYPE.isString()); assertFalse(OBJECT_TYPE.isStringObjectType()); assertFalse(OBJECT_TYPE.isStringValueType()); assertFalse(OBJECT_TYPE.isEnumType()); assertFalse(OBJECT_TYPE.isUnionType()); assertFalse(OBJECT_TYPE.isStruct()); assertFalse(OBJECT_TYPE.isDict()); assertFalse(OBJECT_TYPE.isAllType()); assertFalse(OBJECT_TYPE.isVoidType()); assertFalse(OBJECT_TYPE.isConstructor()); assertTrue(OBJECT_TYPE.isInstanceType()); // isSubtype assertFalse(OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(functionType)); assertFalse(OBJECT_TYPE.isSubtype(recordType)); assertFalse(OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(namedGoogBar)); assertTrue(OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, functionType); assertCanTestForEqualityWith(OBJECT_TYPE, recordType); assertCannotTestForEqualityWith(OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(OBJECT_TYPE.isNullable()); assertFalse(OBJECT_TYPE.isVoidable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, OBJECT_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(OBJECT_TYPE, NUMBER_TYPE), OBJECT_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(7, OBJECT_TYPE.getPropertiesCount()); assertReturnTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, OBJECT_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, OBJECT_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(UNKNOWN_TYPE, OBJECT_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("hasOwnProperty")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("isPrototypeOf")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("propertyIsEnumerable")); // matchesXxx assertFalse(OBJECT_TYPE.matchesInt32Context()); assertFalse(OBJECT_TYPE.matchesNumberContext()); assertTrue(OBJECT_TYPE.matchesObjectContext()); assertTrue(OBJECT_TYPE.matchesStringContext()); assertFalse(OBJECT_TYPE.matchesUint32Context()); // implicit prototype assertTypeEquals(OBJECT_PROTOTYPE, OBJECT_TYPE.getImplicitPrototype()); // toString assertEquals("Object", OBJECT_TYPE.toString()); assertTrue(OBJECT_TYPE.isNativeObjectType()); assertTrue(OBJECT_TYPE.getImplicitPrototype().isNativeObjectType()); Asserts.assertResolvesToSame(OBJECT_TYPE); assertFalse(OBJECT_TYPE.isNominalConstructor()); assertTrue(OBJECT_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the number value type. */ public void testNumberObjectType() throws Exception { // isXxx assertFalse(NUMBER_OBJECT_TYPE.isArrayType()); assertFalse(NUMBER_OBJECT_TYPE.isBooleanObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isBooleanValueType()); assertFalse(NUMBER_OBJECT_TYPE.isDateType()); assertFalse(NUMBER_OBJECT_TYPE.isEnumElementType()); assertFalse(NUMBER_OBJECT_TYPE.isNamedType()); assertFalse(NUMBER_OBJECT_TYPE.isNullType()); assertTrue(NUMBER_OBJECT_TYPE.isNumber()); assertTrue(NUMBER_OBJECT_TYPE.isNumberObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isNumberValueType()); assertTrue(NUMBER_OBJECT_TYPE.isObject()); assertFalse(NUMBER_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( NUMBER_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(NUMBER_OBJECT_TYPE.isRegexpType()); assertFalse(NUMBER_OBJECT_TYPE.isString()); assertFalse(NUMBER_OBJECT_TYPE.isStringObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isStringValueType()); assertFalse(NUMBER_OBJECT_TYPE.isEnumType()); assertFalse(NUMBER_OBJECT_TYPE.isUnionType()); assertFalse(NUMBER_OBJECT_TYPE.isStruct()); assertFalse(NUMBER_OBJECT_TYPE.isDict()); assertFalse(NUMBER_OBJECT_TYPE.isAllType()); assertFalse(NUMBER_OBJECT_TYPE.isVoidType()); assertFalse(NUMBER_OBJECT_TYPE.isConstructor()); assertTrue(NUMBER_OBJECT_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(NUMBER_OBJECT_TYPE, NUMBER_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(NUMBER_TYPE, NUMBER_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(NUMBER_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(functionType)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(namedGoogBar)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype( createUnionType(NUMBER_OBJECT_TYPE, NULL_TYPE))); assertFalse(NUMBER_OBJECT_TYPE.isSubtype( createUnionType(NUMBER_TYPE, NULL_TYPE))); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(NUMBER_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NO_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, elementsType); assertCannotTestForEqualityWith(NUMBER_OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(NUMBER_OBJECT_TYPE.isNullable()); assertFalse(NUMBER_OBJECT_TYPE.isVoidable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, NUMBER_OBJECT_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, STRING_OBJECT_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, NUMBER_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, functionType), NUMBER_OBJECT_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, NUMBER_OBJECT_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, DATE_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, REGEXP_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NUMBER_OBJECT_TYPE.matchesInt32Context()); assertTrue(NUMBER_OBJECT_TYPE.matchesNumberContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesObjectContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesStringContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("Number", NUMBER_OBJECT_TYPE.toString()); assertTrue(NUMBER_OBJECT_TYPE.hasDisplayName()); assertEquals("Number", NUMBER_OBJECT_TYPE.getDisplayName()); assertTrue(NUMBER_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(NUMBER_OBJECT_TYPE); } /** * Tests the behavior of the number value type. */ public void testNumberValueType() throws Exception { // isXxx assertFalse(NUMBER_TYPE.isArrayType()); assertFalse(NUMBER_TYPE.isBooleanObjectType()); assertFalse(NUMBER_TYPE.isBooleanValueType()); assertFalse(NUMBER_TYPE.isDateType()); assertFalse(NUMBER_TYPE.isEnumElementType()); assertFalse(NUMBER_TYPE.isNamedType()); assertFalse(NUMBER_TYPE.isNullType()); assertTrue(NUMBER_TYPE.isNumber()); assertFalse(NUMBER_TYPE.isNumberObjectType()); assertTrue(NUMBER_TYPE.isNumberValueType()); assertFalse(NUMBER_TYPE.isFunctionPrototypeType()); assertFalse(NUMBER_TYPE.isRegexpType()); assertFalse(NUMBER_TYPE.isString()); assertFalse(NUMBER_TYPE.isStringObjectType()); assertFalse(NUMBER_TYPE.isStringValueType()); assertFalse(NUMBER_TYPE.isEnumType()); assertFalse(NUMBER_TYPE.isUnionType()); assertFalse(NUMBER_TYPE.isStruct()); assertFalse(NUMBER_TYPE.isDict()); assertFalse(NUMBER_TYPE.isAllType()); assertFalse(NUMBER_TYPE.isVoidType()); assertFalse(NUMBER_TYPE.isConstructor()); assertFalse(NUMBER_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(NUMBER_OBJECT_TYPE, NUMBER_TYPE.autoboxesTo()); // isSubtype assertTrue(NUMBER_TYPE.isSubtype(ALL_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NUMBER_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(functionType)); assertFalse(NUMBER_TYPE.isSubtype(NULL_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(DATE_TYPE)); assertTrue(NUMBER_TYPE.isSubtype(unresolvedNamedType)); assertFalse(NUMBER_TYPE.isSubtype(namedGoogBar)); assertTrue(NUMBER_TYPE.isSubtype( createUnionType(NUMBER_TYPE, NULL_TYPE))); assertTrue(NUMBER_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(NUMBER_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NUMBER_TYPE, NO_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(NUMBER_TYPE, functionType); assertCannotTestForEqualityWith(NUMBER_TYPE, VOID_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NUMBER_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(NUMBER_TYPE.isNullable()); assertFalse(NUMBER_TYPE.isVoidable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, NUMBER_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, STRING_OBJECT_TYPE), NUMBER_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, functionType), NUMBER_TYPE.getLeastSupertype(functionType)); assertTypeEquals(createUnionType(NUMBER_TYPE, OBJECT_TYPE), NUMBER_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, DATE_TYPE), NUMBER_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, REGEXP_TYPE), NUMBER_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NUMBER_TYPE.matchesInt32Context()); assertTrue(NUMBER_TYPE.matchesNumberContext()); assertTrue(NUMBER_TYPE.matchesObjectContext()); assertTrue(NUMBER_TYPE.matchesStringContext()); assertTrue(NUMBER_TYPE.matchesUint32Context()); // toString assertEquals("number", NUMBER_TYPE.toString()); assertTrue(NUMBER_TYPE.hasDisplayName()); assertEquals("number", NUMBER_TYPE.getDisplayName()); Asserts.assertResolvesToSame(NUMBER_TYPE); assertFalse(NUMBER_TYPE.isNominalConstructor()); } /** * Tests the behavior of the null type. */ public void testNullType() throws Exception { // isXxx assertFalse(NULL_TYPE.isArrayType()); assertFalse(NULL_TYPE.isBooleanValueType()); assertFalse(NULL_TYPE.isDateType()); assertFalse(NULL_TYPE.isEnumElementType()); assertFalse(NULL_TYPE.isNamedType()); assertTrue(NULL_TYPE.isNullType()); assertFalse(NULL_TYPE.isNumber()); assertFalse(NULL_TYPE.isNumberObjectType()); assertFalse(NULL_TYPE.isNumberValueType()); assertFalse(NULL_TYPE.isFunctionPrototypeType()); assertFalse(NULL_TYPE.isRegexpType()); assertFalse(NULL_TYPE.isString()); assertFalse(NULL_TYPE.isStringObjectType()); assertFalse(NULL_TYPE.isStringValueType()); assertFalse(NULL_TYPE.isEnumType()); assertFalse(NULL_TYPE.isUnionType()); assertFalse(NULL_TYPE.isStruct()); assertFalse(NULL_TYPE.isDict()); assertFalse(NULL_TYPE.isAllType()); assertFalse(NULL_TYPE.isVoidType()); assertFalse(NULL_TYPE.isConstructor()); assertFalse(NULL_TYPE.isInstanceType()); // autoboxesTo assertNull(NULL_TYPE.autoboxesTo()); // isSubtype assertFalse(NULL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(NO_TYPE)); assertTrue(NULL_TYPE.isSubtype(NULL_TYPE)); assertTrue(NULL_TYPE.isSubtype(ALL_TYPE)); assertFalse(NULL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NULL_TYPE.isSubtype(functionType)); assertFalse(NULL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(DATE_TYPE)); assertFalse(NULL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NULL_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NULL_TYPE.isSubtype(UNKNOWN_TYPE)); assertTrue(NULL_TYPE.isSubtype(createNullableType(NO_OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NO_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NULL_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(ALL_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(STRING_OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NUMBER_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(functionType))); assertTrue(NULL_TYPE.isSubtype(createNullableType(OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(DATE_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(REGEXP_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(ARRAY_TYPE))); // canBeCalled assertFalse(NULL_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NULL_TYPE, NO_TYPE); assertCanTestForEqualityWith(NULL_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NULL_TYPE, ALL_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, ARRAY_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, BOOLEAN_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, BOOLEAN_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, DATE_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, EVAL_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, functionType); assertCannotTestForEqualityWith(NULL_TYPE, NULL_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, NUMBER_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, NUMBER_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, URI_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, RANGE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, REFERENCE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, REGEXP_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, STRING_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, SYNTAX_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, TYPE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NULL_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NULL_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NULL_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith( createNullableType(STRING_OBJECT_TYPE))); // getLeastSupertype assertTypeEquals(NULL_TYPE, NULL_TYPE.getLeastSupertype(NULL_TYPE)); assertTypeEquals(ALL_TYPE, NULL_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createNullableType(STRING_OBJECT_TYPE), NULL_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createNullableType(NUMBER_TYPE), NULL_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createNullableType(functionType), NULL_TYPE.getLeastSupertype(functionType)); assertTypeEquals(createNullableType(OBJECT_TYPE), NULL_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createNullableType(DATE_TYPE), NULL_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createNullableType(REGEXP_TYPE), NULL_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NULL_TYPE.matchesInt32Context()); assertTrue(NULL_TYPE.matchesNumberContext()); assertFalse(NULL_TYPE.matchesObjectContext()); assertTrue(NULL_TYPE.matchesStringContext()); assertTrue(NULL_TYPE.matchesUint32Context()); // matchesObjectContext assertFalse(NULL_TYPE.matchesObjectContext()); // toString assertEquals("null", NULL_TYPE.toString()); assertTrue(NULL_TYPE.hasDisplayName()); assertEquals("null", NULL_TYPE.getDisplayName()); Asserts.assertResolvesToSame(NULL_TYPE); // getGreatestSubtype assertTrue( NULL_TYPE.isSubtype( createUnionType(forwardDeclaredNamedType, NULL_TYPE))); assertTypeEquals( createUnionType(forwardDeclaredNamedType, NULL_TYPE), NULL_TYPE.getGreatestSubtype( createUnionType(forwardDeclaredNamedType, NULL_TYPE))); assertFalse(NULL_TYPE.isNominalConstructor()); assertTrue(NULL_TYPE.differsFrom(UNKNOWN_TYPE)); } /** * Tests the behavior of the Date type. */ public void testDateType() throws Exception { // isXxx assertFalse(DATE_TYPE.isArrayType()); assertFalse(DATE_TYPE.isBooleanValueType()); assertTrue(DATE_TYPE.isDateType()); assertFalse(DATE_TYPE.isEnumElementType()); assertFalse(DATE_TYPE.isNamedType()); assertFalse(DATE_TYPE.isNullType()); assertFalse(DATE_TYPE.isNumberValueType()); assertFalse(DATE_TYPE.isFunctionPrototypeType()); assertTrue(DATE_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(DATE_TYPE.isRegexpType()); assertFalse(DATE_TYPE.isStringValueType()); assertFalse(DATE_TYPE.isEnumType()); assertFalse(DATE_TYPE.isUnionType()); assertFalse(DATE_TYPE.isStruct()); assertFalse(DATE_TYPE.isDict()); assertFalse(DATE_TYPE.isAllType()); assertFalse(DATE_TYPE.isVoidType()); assertFalse(DATE_TYPE.isConstructor()); assertTrue(DATE_TYPE.isInstanceType()); // autoboxesTo assertNull(DATE_TYPE.autoboxesTo()); // isSubtype assertFalse(DATE_TYPE.isSubtype(NO_TYPE)); assertFalse(DATE_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(DATE_TYPE)); assertFalse(DATE_TYPE.isSubtype(ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(functionType)); assertFalse(DATE_TYPE.isSubtype(NULL_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.isSubtype(ALL_TYPE)); assertFalse(DATE_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertFalse(DATE_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(DATE_TYPE, ALL_TYPE); assertCanTestForEqualityWith(DATE_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(DATE_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(DATE_TYPE, functionType); assertCannotTestForEqualityWith(DATE_TYPE, VOID_TYPE); assertCanTestForEqualityWith(DATE_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(DATE_TYPE, DATE_TYPE); assertCanTestForEqualityWith(DATE_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(DATE_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(DATE_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(DATE_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(DATE_TYPE.isNullable()); assertFalse(DATE_TYPE.isVoidable()); assertTrue(createNullableType(DATE_TYPE).isNullable()); assertTrue(createUnionType(DATE_TYPE, VOID_TYPE).isVoidable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, DATE_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, STRING_OBJECT_TYPE), DATE_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, NUMBER_TYPE), DATE_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, functionType), DATE_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, DATE_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(DATE_TYPE, DATE_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, REGEXP_TYPE), DATE_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(46, DATE_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(46, DATE_TYPE.getPropertiesCount()); assertReturnTypeEquals(DATE_TYPE, DATE_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toDateString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toTimeString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleDateString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleTimeString")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getTime")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getDay")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCDay")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getTimezoneOffset")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setTime")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCFullYear")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toUTCString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toGMTString")); // matchesXxx assertTrue(DATE_TYPE.matchesInt32Context()); assertTrue(DATE_TYPE.matchesNumberContext()); assertTrue(DATE_TYPE.matchesObjectContext()); assertTrue(DATE_TYPE.matchesStringContext()); assertTrue(DATE_TYPE.matchesUint32Context()); // toString assertEquals("Date", DATE_TYPE.toString()); assertTrue(DATE_TYPE.hasDisplayName()); assertEquals("Date", DATE_TYPE.getDisplayName()); assertTrue(DATE_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(DATE_TYPE); assertFalse(DATE_TYPE.isNominalConstructor()); assertTrue(DATE_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the RegExp type. */ public void testRegExpType() throws Exception { // isXxx assertFalse(REGEXP_TYPE.isNoType()); assertFalse(REGEXP_TYPE.isNoObjectType()); assertFalse(REGEXP_TYPE.isArrayType()); assertFalse(REGEXP_TYPE.isBooleanValueType()); assertFalse(REGEXP_TYPE.isDateType()); assertFalse(REGEXP_TYPE.isEnumElementType()); assertFalse(REGEXP_TYPE.isNamedType()); assertFalse(REGEXP_TYPE.isNullType()); assertFalse(REGEXP_TYPE.isNumberValueType()); assertFalse(REGEXP_TYPE.isFunctionPrototypeType()); assertTrue(REGEXP_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertTrue(REGEXP_TYPE.isRegexpType()); assertFalse(REGEXP_TYPE.isStringValueType()); assertFalse(REGEXP_TYPE.isEnumType()); assertFalse(REGEXP_TYPE.isUnionType()); assertFalse(REGEXP_TYPE.isStruct()); assertFalse(REGEXP_TYPE.isDict()); assertFalse(REGEXP_TYPE.isAllType()); assertFalse(REGEXP_TYPE.isVoidType()); // autoboxesTo assertNull(REGEXP_TYPE.autoboxesTo()); // isSubtype assertFalse(REGEXP_TYPE.isSubtype(NO_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(DATE_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(functionType)); assertFalse(REGEXP_TYPE.isSubtype(NULL_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(STRING_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(ALL_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertTrue(REGEXP_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(REGEXP_TYPE, ALL_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, functionType); assertCannotTestForEqualityWith(REGEXP_TYPE, VOID_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, DATE_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(REGEXP_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(REGEXP_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(REGEXP_TYPE.isNullable()); assertFalse(REGEXP_TYPE.isVoidable()); assertTrue(createNullableType(REGEXP_TYPE).isNullable()); assertTrue(createUnionType(REGEXP_TYPE, VOID_TYPE).isVoidable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, REGEXP_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, STRING_OBJECT_TYPE), REGEXP_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, NUMBER_TYPE), REGEXP_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, functionType), REGEXP_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, REGEXP_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, REGEXP_TYPE), REGEXP_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(REGEXP_TYPE, REGEXP_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(9, REGEXP_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(14, REGEXP_TYPE.getPropertiesCount()); assertReturnTypeEquals(REGEXP_TYPE, REGEXP_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(createNullableType(ARRAY_TYPE), REGEXP_TYPE.getPropertyType("exec")); assertReturnTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("test")); assertReturnTypeEquals(STRING_TYPE, REGEXP_TYPE.getPropertyType("toString")); assertTypeEquals(STRING_TYPE, REGEXP_TYPE.getPropertyType("source")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("global")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("ignoreCase")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("multiline")); assertTypeEquals(NUMBER_TYPE, REGEXP_TYPE.getPropertyType("lastIndex")); // matchesXxx assertFalse(REGEXP_TYPE.matchesInt32Context()); assertFalse(REGEXP_TYPE.matchesNumberContext()); assertTrue(REGEXP_TYPE.matchesObjectContext()); assertTrue(REGEXP_TYPE.matchesStringContext()); assertFalse(REGEXP_TYPE.matchesUint32Context()); // toString assertEquals("RegExp", REGEXP_TYPE.toString()); assertTrue(REGEXP_TYPE.hasDisplayName()); assertEquals("RegExp", REGEXP_TYPE.getDisplayName()); assertTrue(REGEXP_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(REGEXP_TYPE); assertFalse(REGEXP_TYPE.isNominalConstructor()); assertTrue(REGEXP_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the string object type. */ public void testStringObjectType() throws Exception { // isXxx assertFalse(STRING_OBJECT_TYPE.isArrayType()); assertFalse(STRING_OBJECT_TYPE.isBooleanObjectType()); assertFalse(STRING_OBJECT_TYPE.isBooleanValueType()); assertFalse(STRING_OBJECT_TYPE.isDateType()); assertFalse(STRING_OBJECT_TYPE.isEnumElementType()); assertFalse(STRING_OBJECT_TYPE.isNamedType()); assertFalse(STRING_OBJECT_TYPE.isNullType()); assertFalse(STRING_OBJECT_TYPE.isNumber()); assertFalse(STRING_OBJECT_TYPE.isNumberObjectType()); assertFalse(STRING_OBJECT_TYPE.isNumberValueType()); assertFalse(STRING_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( STRING_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(STRING_OBJECT_TYPE.isRegexpType()); assertTrue(STRING_OBJECT_TYPE.isString()); assertTrue(STRING_OBJECT_TYPE.isStringObjectType()); assertFalse(STRING_OBJECT_TYPE.isStringValueType()); assertFalse(STRING_OBJECT_TYPE.isEnumType()); assertFalse(STRING_OBJECT_TYPE.isUnionType()); assertFalse(STRING_OBJECT_TYPE.isStruct()); assertFalse(STRING_OBJECT_TYPE.isDict()); assertFalse(STRING_OBJECT_TYPE.isAllType()); assertFalse(STRING_OBJECT_TYPE.isVoidType()); assertFalse(STRING_OBJECT_TYPE.isConstructor()); assertTrue(STRING_OBJECT_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(STRING_OBJECT_TYPE, STRING_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(STRING_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertTrue(STRING_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(STRING_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(STRING_TYPE)); // canBeCalled assertFalse(STRING_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(STRING_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // properties (ECMA-262 page 98 - 106) assertEquals(24, STRING_OBJECT_TYPE.getImplicitPrototype(). getPropertiesCount()); assertEquals(25, STRING_OBJECT_TYPE.getPropertiesCount()); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("charAt")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("charCodeAt")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("concat")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("indexOf")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("lastIndexOf")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("localeCompare")); assertReturnTypeEquals(createNullableType(ARRAY_TYPE), STRING_OBJECT_TYPE.getPropertyType("match")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("replace")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("search")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("slice")); assertReturnTypeEquals(ARRAY_TYPE, STRING_OBJECT_TYPE.getPropertyType("split")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("substr")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("substring")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLowerCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLocaleLowerCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toUpperCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLocaleUpperCase")); assertTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("length")); // matchesXxx assertTrue(STRING_OBJECT_TYPE.matchesInt32Context()); assertTrue(STRING_OBJECT_TYPE.matchesNumberContext()); assertTrue(STRING_OBJECT_TYPE.matchesObjectContext()); assertTrue(STRING_OBJECT_TYPE.matchesStringContext()); assertTrue(STRING_OBJECT_TYPE.matchesUint32Context()); // isNullable assertFalse(STRING_OBJECT_TYPE.isNullable()); assertFalse(STRING_OBJECT_TYPE.isVoidable()); assertTrue(createNullableType(STRING_OBJECT_TYPE).isNullable()); assertTrue(createUnionType(STRING_OBJECT_TYPE, VOID_TYPE).isVoidable()); assertTrue(STRING_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(STRING_OBJECT_TYPE); assertTrue(STRING_OBJECT_TYPE.hasDisplayName()); assertEquals("String", STRING_OBJECT_TYPE.getDisplayName()); assertFalse(STRING_OBJECT_TYPE.isNominalConstructor()); assertTrue(STRING_OBJECT_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the string value type. */ public void testStringValueType() throws Exception { // isXxx assertFalse(STRING_TYPE.isArrayType()); assertFalse(STRING_TYPE.isBooleanObjectType()); assertFalse(STRING_TYPE.isBooleanValueType()); assertFalse(STRING_TYPE.isDateType()); assertFalse(STRING_TYPE.isEnumElementType()); assertFalse(STRING_TYPE.isNamedType()); assertFalse(STRING_TYPE.isNullType()); assertFalse(STRING_TYPE.isNumber()); assertFalse(STRING_TYPE.isNumberObjectType()); assertFalse(STRING_TYPE.isNumberValueType()); assertFalse(STRING_TYPE.isFunctionPrototypeType()); assertFalse(STRING_TYPE.isRegexpType()); assertTrue(STRING_TYPE.isString()); assertFalse(STRING_TYPE.isStringObjectType()); assertTrue(STRING_TYPE.isStringValueType()); assertFalse(STRING_TYPE.isEnumType()); assertFalse(STRING_TYPE.isUnionType()); assertFalse(STRING_TYPE.isStruct()); assertFalse(STRING_TYPE.isDict()); assertFalse(STRING_TYPE.isAllType()); assertFalse(STRING_TYPE.isVoidType()); assertFalse(STRING_TYPE.isConstructor()); assertFalse(STRING_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(STRING_OBJECT_TYPE, STRING_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(STRING_TYPE.isSubtype(ALL_TYPE)); assertFalse(STRING_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(STRING_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(STRING_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_TYPE.isSubtype(DATE_TYPE)); assertFalse(STRING_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(STRING_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(STRING_TYPE.isSubtype(STRING_TYPE)); assertTrue(STRING_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(STRING_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(STRING_TYPE, ALL_TYPE); assertCanTestForEqualityWith(STRING_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(STRING_TYPE, functionType); assertCanTestForEqualityWith(STRING_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(STRING_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(STRING_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(STRING_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_TYPE, DATE_TYPE); assertCanTestForEqualityWith(STRING_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(STRING_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(STRING_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(STRING_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(STRING_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertTrue(STRING_TYPE.matchesInt32Context()); assertTrue(STRING_TYPE.matchesNumberContext()); assertTrue(STRING_TYPE.matchesObjectContext()); assertTrue(STRING_TYPE.matchesStringContext()); assertTrue(STRING_TYPE.matchesUint32Context()); // isNullable assertFalse(STRING_TYPE.isNullable()); assertFalse(STRING_TYPE.isVoidable()); assertTrue(createNullableType(STRING_TYPE).isNullable()); assertTrue(createUnionType(STRING_TYPE, VOID_TYPE).isVoidable()); // toString assertEquals("string", STRING_TYPE.toString()); assertTrue(STRING_TYPE.hasDisplayName()); assertEquals("string", STRING_TYPE.getDisplayName()); // findPropertyType assertTypeEquals(NUMBER_TYPE, STRING_TYPE.findPropertyType("length")); assertEquals(null, STRING_TYPE.findPropertyType("unknownProperty")); Asserts.assertResolvesToSame(STRING_TYPE); assertFalse(STRING_TYPE.isNominalConstructor()); } private void assertPropertyTypeDeclared(ObjectType ownerType, String prop) { assertTrue(ownerType.isPropertyTypeDeclared(prop)); assertFalse(ownerType.isPropertyTypeInferred(prop)); } private void assertPropertyTypeInferred(ObjectType ownerType, String prop) { assertFalse(ownerType.isPropertyTypeDeclared(prop)); assertTrue(ownerType.isPropertyTypeInferred(prop)); } private void assertPropertyTypeUnknown(ObjectType ownerType, String prop) { assertFalse(ownerType.isPropertyTypeDeclared(prop)); assertFalse(ownerType.isPropertyTypeInferred(prop)); assertTrue(ownerType.getPropertyType(prop).isUnknownType()); } private void assertReturnTypeEquals(JSType expectedReturnType, JSType function) { assertTrue(function instanceof FunctionType); assertTypeEquals(expectedReturnType, ((FunctionType) function).getReturnType()); } /** * Tests the behavior of record types. */ public void testRecordType() throws Exception { // isXxx assertTrue(recordType.isObject()); assertFalse(recordType.isFunctionPrototypeType()); // isSubtype assertTrue(recordType.isSubtype(ALL_TYPE)); assertFalse(recordType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(recordType.isSubtype(NUMBER_TYPE)); assertFalse(recordType.isSubtype(DATE_TYPE)); assertFalse(recordType.isSubtype(REGEXP_TYPE)); assertTrue(recordType.isSubtype(UNKNOWN_TYPE)); assertTrue(recordType.isSubtype(OBJECT_TYPE)); assertFalse(recordType.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(recordType.autoboxesTo()); // canBeCalled assertFalse(recordType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(recordType, ALL_TYPE); assertCanTestForEqualityWith(recordType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(recordType, recordType); assertCanTestForEqualityWith(recordType, functionType); assertCanTestForEqualityWith(recordType, OBJECT_TYPE); assertCanTestForEqualityWith(recordType, NUMBER_TYPE); assertCanTestForEqualityWith(recordType, DATE_TYPE); assertCanTestForEqualityWith(recordType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(recordType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(recordType. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(recordType)); assertFalse(recordType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(recordType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(recordType.matchesInt32Context()); assertFalse(recordType.matchesNumberContext()); assertTrue(recordType.matchesObjectContext()); assertFalse(recordType.matchesStringContext()); assertFalse(recordType.matchesUint32Context()); Asserts.assertResolvesToSame(recordType); } /** * Tests the behavior of the instance of Function. */ public void testFunctionInstanceType() throws Exception { FunctionType functionInst = FUNCTION_INSTANCE_TYPE; // isXxx assertTrue(functionInst.isObject()); assertFalse(functionInst.isFunctionPrototypeType()); assertTrue(functionInst.getImplicitPrototype() .isFunctionPrototypeType()); // isSubtype assertTrue(functionInst.isSubtype(ALL_TYPE)); assertFalse(functionInst.isSubtype(STRING_OBJECT_TYPE)); assertFalse(functionInst.isSubtype(NUMBER_TYPE)); assertFalse(functionInst.isSubtype(DATE_TYPE)); assertFalse(functionInst.isSubtype(REGEXP_TYPE)); assertTrue(functionInst.isSubtype(UNKNOWN_TYPE)); assertTrue(functionInst.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(functionInst.autoboxesTo()); // canBeCalled assertTrue(functionInst.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(functionInst, ALL_TYPE); assertCanTestForEqualityWith(functionInst, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(functionInst, functionInst); assertCanTestForEqualityWith(functionInst, OBJECT_TYPE); assertCannotTestForEqualityWith(functionInst, NUMBER_TYPE); assertCanTestForEqualityWith(functionInst, DATE_TYPE); assertCanTestForEqualityWith(functionInst, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(functionInst.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(functionInst. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(functionInst)); assertFalse(functionInst.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(functionInst. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(functionInst.matchesInt32Context()); assertFalse(functionInst.matchesNumberContext()); assertTrue(functionInst.matchesObjectContext()); assertFalse(functionInst.matchesStringContext()); assertFalse(functionInst.matchesUint32Context()); // hasProperty assertTrue(functionInst.hasProperty("prototype")); assertPropertyTypeInferred(functionInst, "prototype"); // misc assertTypeEquals(FUNCTION_FUNCTION_TYPE, functionInst.getConstructor()); assertTypeEquals(FUNCTION_PROTOTYPE, functionInst.getImplicitPrototype()); assertTypeEquals(functionInst, FUNCTION_FUNCTION_TYPE.getInstanceType()); Asserts.assertResolvesToSame(functionInst); } /** * Tests the behavior of functional types. */ public void testFunctionType() throws Exception { // isXxx assertTrue(functionType.isObject()); assertFalse(functionType.isFunctionPrototypeType()); assertTrue(functionType.getImplicitPrototype().getImplicitPrototype() .isFunctionPrototypeType()); // isSubtype assertTrue(functionType.isSubtype(ALL_TYPE)); assertFalse(functionType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(functionType.isSubtype(NUMBER_TYPE)); assertFalse(functionType.isSubtype(DATE_TYPE)); assertFalse(functionType.isSubtype(REGEXP_TYPE)); assertTrue(functionType.isSubtype(UNKNOWN_TYPE)); assertTrue(functionType.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(functionType.autoboxesTo()); // canBeCalled assertTrue(functionType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(functionType, ALL_TYPE); assertCanTestForEqualityWith(functionType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(functionType, functionType); assertCanTestForEqualityWith(functionType, OBJECT_TYPE); assertCannotTestForEqualityWith(functionType, NUMBER_TYPE); assertCanTestForEqualityWith(functionType, DATE_TYPE); assertCanTestForEqualityWith(functionType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(functionType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(functionType. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(functionType)); assertFalse(functionType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(functionType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(functionType.matchesInt32Context()); assertFalse(functionType.matchesNumberContext()); assertTrue(functionType.matchesObjectContext()); assertFalse(functionType.matchesStringContext()); assertFalse(functionType.matchesUint32Context()); // hasProperty assertTrue(functionType.hasProperty("prototype")); assertPropertyTypeInferred(functionType, "prototype"); Asserts.assertResolvesToSame(functionType); assertEquals("aFunctionName", new FunctionBuilder(registry). withName("aFunctionName").build().getDisplayName()); } /** * Tests the subtyping relation of record types. */ public void testRecordTypeSubtyping() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); assertTrue(subRecordType.isSubtype(recordType)); assertFalse(recordType.isSubtype(subRecordType)); builder = new RecordTypeBuilder(registry); builder.addProperty("a", OBJECT_TYPE, null); builder.addProperty("b", STRING_TYPE, null); JSType differentRecordType = builder.build(); assertFalse(differentRecordType.isSubtype(recordType)); assertFalse(recordType.isSubtype(differentRecordType)); } /** * Tests the subtyping relation of record types when an object has * an inferred property.. */ public void testRecordTypeSubtypingWithInferredProperties() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", googSubBarInst, null); JSType record = builder.build(); ObjectType subtypeProp = registry.createAnonymousObjectType(null); subtypeProp.defineInferredProperty("a", googSubSubBarInst, null); assertTrue(subtypeProp.isSubtype(record)); assertFalse(record.isSubtype(subtypeProp)); ObjectType supertypeProp = registry.createAnonymousObjectType(null); supertypeProp.defineInferredProperty("a", googBarInst, null); assertFalse(supertypeProp.isSubtype(record)); assertFalse(record.isSubtype(supertypeProp)); ObjectType declaredSubtypeProp = registry.createAnonymousObjectType(null); declaredSubtypeProp.defineDeclaredProperty("a", googSubSubBarInst, null); assertTrue(declaredSubtypeProp.isSubtype(record)); assertFalse(record.isSubtype(declaredSubtypeProp)); } /** * Tests the getLeastSupertype method for record types. */ public void testRecordTypeLeastSuperType1() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType leastSupertype = recordType.getLeastSupertype(subRecordType); assertTypeEquals(leastSupertype, recordType); } public void testRecordTypeLeastSuperType2() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("e", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType otherRecordType = builder.build(); assertTypeEquals( registry.createUnionType(recordType, otherRecordType), recordType.getLeastSupertype(otherRecordType)); } public void testRecordTypeLeastSuperType3() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType otherRecordType = builder.build(); assertTypeEquals( registry.createUnionType(recordType, otherRecordType), recordType.getLeastSupertype(otherRecordType)); } public void testRecordTypeLeastSuperType4() { JSType leastSupertype = recordType.getLeastSupertype(OBJECT_TYPE); assertTypeEquals(leastSupertype, OBJECT_TYPE); } /** * Tests the getGreatestSubtype method for record types. */ public void testRecordTypeGreatestSubType1() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType2() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType3() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType4() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); assertTypeEquals(subtype, NO_TYPE); } public void testRecordTypeGreatestSubType5() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if Function is given a property "a" of type "string", then it's // a subtype of the record type {a: string}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("a", STRING_TYPE, null); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType6() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("x", UNKNOWN_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if Function is given a property "x" of type "string", then it's // also a subtype of the record type {x: ?}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("x", STRING_TYPE, null); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType7() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("x", NUMBER_TYPE, null); JSType recordType = builder.build(); // if Function is given a property "x" of type "string", then it's // not a subtype of the record type {x: number}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("x", STRING_TYPE, null); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); } public void testRecordTypeGreatestSubType8() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("xyz", UNKNOWN_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if goog.Bar is given a property "xyz" of type "string", then it's // also a subtype of the record type {x: ?}. googBar.defineDeclaredProperty("xyz", STRING_TYPE, null); assertTypeEquals(googBar, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(googBar, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); ObjectType googBarInst = googBar.getInstanceType(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(googBarInst)); assertTypeEquals(NO_OBJECT_TYPE, googBarInst.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType9() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getPrototype(), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType recordType1 = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getInstanceType(), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType recordType2 = builder.build(); JSType subtype = recordType1.getGreatestSubtype(recordType2); builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getInstanceType(), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType10() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getPrototype(), null); builder.addProperty("e", STRING_TYPE, null); JSType recordType1 = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getInstanceType(), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType recordType2 = builder.build(); JSType subtype = recordType2.getGreatestSubtype(recordType1); builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getInstanceType(), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType11() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", createUnionType(NUMBER_TYPE, STRING_TYPE), null); builder.addProperty("e", STRING_TYPE, null); JSType recordType1 = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("d", createUnionType(NUMBER_TYPE, BOOLEAN_TYPE), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType recordType2 = builder.build(); JSType subtype = recordType2.getGreatestSubtype(recordType1); builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType12() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBar.getPrototype(), null); builder.addProperty("e", STRING_TYPE, null); JSType recordType1 = builder.build(); FunctionType googBarArgConstructor = registry.createConstructorType( "barArg", null, registry.createParameters(googBar), null, null, false); builder = new RecordTypeBuilder(registry); builder.addProperty("d", googBarArgConstructor, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType recordType2 = builder.build(); JSType subtype = recordType2.getGreatestSubtype(recordType1); builder = new RecordTypeBuilder(registry); builder.addProperty("d", registry.getNativeObjectType( JSTypeNative.NO_OBJECT_TYPE), null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } /** * Tests the "apply" method on the function type. */ public void testApplyOfDateMethod() { JSType applyType = dateMethod.getPropertyType("apply"); assertTrue("apply should be a function", applyType instanceof FunctionType); FunctionType applyFn = (FunctionType) applyType; assertTypeEquals("apply should have the same return type as its function", NUMBER_TYPE, applyFn.getReturnType()); Node params = applyFn.getParametersNode(); assertEquals("apply takes two args", 2, params.getChildCount()); assertTypeEquals("apply's first arg is the @this type", registry.createOptionalNullableType(DATE_TYPE), params.getFirstChild().getJSType()); assertTypeEquals("apply's second arg is an Array", registry.createOptionalNullableType(OBJECT_TYPE), params.getLastChild().getJSType()); assertTrue("apply's args must be optional", params.getFirstChild().isOptionalArg()); assertTrue("apply's args must be optional", params.getLastChild().isOptionalArg()); } /** * Tests the "call" method on the function type. */ public void testCallOfDateMethod() { JSType callType = dateMethod.getPropertyType("call"); assertTrue("call should be a function", callType instanceof FunctionType); FunctionType callFn = (FunctionType) callType; assertTypeEquals("call should have the same return type as its function", NUMBER_TYPE, callFn.getReturnType()); Node params = callFn.getParametersNode(); assertEquals("call takes one argument in this case", 1, params.getChildCount()); assertTypeEquals("call's first arg is the @this type", registry.createOptionalNullableType(DATE_TYPE), params.getFirstChild().getJSType()); assertTrue("call's args must be optional", params.getFirstChild().isOptionalArg()); } /** * Tests the representation of function types. */ public void testFunctionTypeRepresentation() { assertEquals("function(number, string): boolean", registry.createFunctionType(BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE).toString()); assertEquals("function(new:Array, ...*): Array", ARRAY_FUNCTION_TYPE.toString()); assertEquals("function(new:Boolean, *=): boolean", BOOLEAN_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function(new:Number, *=): number", NUMBER_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function(new:String, *=): string", STRING_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function(...number): boolean", registry.createFunctionTypeWithVarArgs(BOOLEAN_TYPE, NUMBER_TYPE).toString()); assertEquals("function(number, ...string): boolean", registry.createFunctionTypeWithVarArgs(BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE).toString()); assertEquals("function(this:Date, number): (boolean|number|string)", new FunctionBuilder(registry) .withParamsNode(registry.createParameters(NUMBER_TYPE)) .withReturnType(NUMBER_STRING_BOOLEAN) .withTypeOfThis(DATE_TYPE) .build().toString()); } /** * Tests relationships between structural function types. */ public void testFunctionTypeRelationships() { FunctionType dateMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(DATE_TYPE).build(); FunctionType dateMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createOptionalParameters(NUMBER_TYPE)) .withTypeOfThis(DATE_TYPE).build(); FunctionType dateMethodWithReturn = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .withTypeOfThis(DATE_TYPE).build(); FunctionType stringMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(STRING_OBJECT_TYPE).build(); FunctionType stringMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createOptionalParameters(NUMBER_TYPE)) .withTypeOfThis(STRING_OBJECT_TYPE).build(); FunctionType stringMethodWithReturn = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .withTypeOfThis(STRING_OBJECT_TYPE).build(); // One-off tests. assertFalse(stringMethodEmpty.isSubtype(dateMethodEmpty)); // Systemic tests. List<FunctionType> allFunctions = ImmutableList.of( dateMethodEmpty, dateMethodWithParam, dateMethodWithReturn, stringMethodEmpty, stringMethodWithParam, stringMethodWithReturn); for (int i = 0; i < allFunctions.size(); i++) { for (int j = 0; j < allFunctions.size(); j++) { FunctionType typeA = allFunctions.get(i); FunctionType typeB = allFunctions.get(j); assertEquals(String.format("equals(%s, %s)", typeA, typeB), i == j, typeA.isEquivalentTo(typeB)); // For this particular set of functions, the functions are subtypes // of each other iff they have the same "this" type. assertEquals(String.format("isSubtype(%s, %s)", typeA, typeB), typeA.getTypeOfThis().isEquivalentTo(typeB.getTypeOfThis()), typeA.isSubtype(typeB)); if (i == j) { assertTypeEquals(typeA, typeA.getLeastSupertype(typeB)); assertTypeEquals(typeA, typeA.getGreatestSubtype(typeB)); } else { assertTypeEquals(String.format("sup(%s, %s)", typeA, typeB), U2U_CONSTRUCTOR_TYPE, typeA.getLeastSupertype(typeB)); assertTypeEquals(String.format("inf(%s, %s)", typeA, typeB), LEAST_FUNCTION_TYPE, typeA.getGreatestSubtype(typeB)); } } } } public void testProxiedFunctionTypeRelationships() { FunctionType dateMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(DATE_TYPE).build().toMaybeFunctionType(); FunctionType dateMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(NUMBER_TYPE)) .withTypeOfThis(DATE_TYPE).build().toMaybeFunctionType(); ProxyObjectType proxyDateMethodEmpty = new ProxyObjectType(registry, dateMethodEmpty); ProxyObjectType proxyDateMethodWithParam = new ProxyObjectType(registry, dateMethodWithParam); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, proxyDateMethodEmpty.getLeastSupertype(proxyDateMethodWithParam)); assertTypeEquals(LEAST_FUNCTION_TYPE, proxyDateMethodEmpty.getGreatestSubtype(proxyDateMethodWithParam)); } /** * Tests relationships between structural function types. */ public void testFunctionSubTypeRelationships() { FunctionType googBarMethod = new FunctionBuilder(registry) .withTypeOfThis(googBar).build(); FunctionType googBarParamFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(googBar)).build(); FunctionType googBarReturnFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withReturnType(googBar).build(); FunctionType googSubBarMethod = new FunctionBuilder(registry) .withTypeOfThis(googSubBar).build(); FunctionType googSubBarParamFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(googSubBar)).build(); FunctionType googSubBarReturnFn = new FunctionBuilder(registry) .withReturnType(googSubBar).build(); assertTrue(googBarMethod.isSubtype(googSubBarMethod)); assertTrue(googBarReturnFn.isSubtype(googSubBarReturnFn)); List<FunctionType> allFunctions = ImmutableList.of( googBarMethod, googBarParamFn, googBarReturnFn, googSubBarMethod, googSubBarParamFn, googSubBarReturnFn); for (int i = 0; i < allFunctions.size(); i++) { for (int j = 0; j < allFunctions.size(); j++) { FunctionType typeA = allFunctions.get(i); FunctionType typeB = allFunctions.get(j); assertEquals(String.format("equals(%s, %s)", typeA, typeB), i == j, typeA.isEquivalentTo(typeB)); // TODO(nicksantos): This formulation of least subtype and greatest // supertype is a bit loose. We might want to tighten it up later. if (i == j) { assertTypeEquals(typeA, typeA.getLeastSupertype(typeB)); assertTypeEquals(typeA, typeA.getGreatestSubtype(typeB)); } else { assertTypeEquals(String.format("sup(%s, %s)", typeA, typeB), U2U_CONSTRUCTOR_TYPE, typeA.getLeastSupertype(typeB)); assertTypeEquals(String.format("inf(%s, %s)", typeA, typeB), LEAST_FUNCTION_TYPE, typeA.getGreatestSubtype(typeB)); } } } } /** * Tests that defining a property of a function's {@code prototype} adds the * property to it instance type. */ public void testFunctionPrototypeAndImplicitPrototype1() { FunctionType constructor = registry.createConstructorType("Foo", null, null, null, null, false); ObjectType instance = constructor.getInstanceType(); // adding one property on the prototype ObjectType prototype = (ObjectType) constructor.getPropertyType("prototype"); prototype.defineDeclaredProperty("foo", DATE_TYPE, null); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instance.getPropertiesCount()); } /** * Tests that replacing a function's {@code prototype} changes the visible * properties of its instance type. */ public void testFunctionPrototypeAndImplicitPrototype2() { FunctionType constructor = registry.createConstructorType( null, null, registry.createParameters(null, null, null), null, null, false); ObjectType instance = constructor.getInstanceType(); // replacing the prototype ObjectType prototype = registry.createAnonymousObjectType(null); prototype.defineDeclaredProperty("foo", DATE_TYPE, null); constructor.defineDeclaredProperty("prototype", prototype, null); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instance.getPropertiesCount()); } /** Tests assigning JsDoc on a prototype property. */ public void testJSDocOnPrototypeProperty() throws Exception { subclassCtor.setPropertyJSDocInfo("prototype", new JSDocInfoBuilder(false).build()); assertNull(subclassCtor.getOwnPropertyJSDocInfo("prototype")); } /** * Tests operation of {@code isVoidable}. * @throws Exception */ public void testIsVoidable() throws Exception { assertTrue(VOID_TYPE.isVoidable()); assertFalse(NULL_TYPE.isVoidable()); assertTrue(createUnionType(NUMBER_TYPE, VOID_TYPE).isVoidable()); } /** * Tests the behavior of the void type. */ public void testVoidType() throws Exception { // isSubtype assertTrue(VOID_TYPE.isSubtype(ALL_TYPE)); assertFalse(VOID_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(VOID_TYPE.isSubtype(REGEXP_TYPE)); // autoboxesTo assertNull(VOID_TYPE.autoboxesTo()); // canTestForEqualityWith assertCanTestForEqualityWith(VOID_TYPE, ALL_TYPE); assertCannotTestForEqualityWith(VOID_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(VOID_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith( createUnionType(NUMBER_TYPE, VOID_TYPE))); // matchesXxx assertFalse(VOID_TYPE.matchesInt32Context()); assertFalse(VOID_TYPE.matchesNumberContext()); assertFalse(VOID_TYPE.matchesObjectContext()); assertTrue(VOID_TYPE.matchesStringContext()); assertFalse(VOID_TYPE.matchesUint32Context()); Asserts.assertResolvesToSame(VOID_TYPE); } /** * Tests the behavior of the boolean type. */ public void testBooleanValueType() throws Exception { // isXxx assertFalse(BOOLEAN_TYPE.isArrayType()); assertFalse(BOOLEAN_TYPE.isBooleanObjectType()); assertTrue(BOOLEAN_TYPE.isBooleanValueType()); assertFalse(BOOLEAN_TYPE.isDateType()); assertFalse(BOOLEAN_TYPE.isEnumElementType()); assertFalse(BOOLEAN_TYPE.isNamedType()); assertFalse(BOOLEAN_TYPE.isNullType()); assertFalse(BOOLEAN_TYPE.isNumberObjectType()); assertFalse(BOOLEAN_TYPE.isNumberValueType()); assertFalse(BOOLEAN_TYPE.isFunctionPrototypeType()); assertFalse(BOOLEAN_TYPE.isRegexpType()); assertFalse(BOOLEAN_TYPE.isStringObjectType()); assertFalse(BOOLEAN_TYPE.isStringValueType()); assertFalse(BOOLEAN_TYPE.isEnumType()); assertFalse(BOOLEAN_TYPE.isUnionType()); assertFalse(BOOLEAN_TYPE.isStruct()); assertFalse(BOOLEAN_TYPE.isDict()); assertFalse(BOOLEAN_TYPE.isAllType()); assertFalse(BOOLEAN_TYPE.isVoidType()); assertFalse(BOOLEAN_TYPE.isConstructor()); assertFalse(BOOLEAN_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(BOOLEAN_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(DATE_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(unresolvedNamedType)); assertFalse(BOOLEAN_TYPE.isSubtype(namedGoogBar)); assertFalse(BOOLEAN_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(BOOLEAN_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(BOOLEAN_TYPE, ALL_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, NUMBER_TYPE); assertCannotTestForEqualityWith(BOOLEAN_TYPE, functionType); assertCannotTestForEqualityWith(BOOLEAN_TYPE, VOID_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, DATE_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(BOOLEAN_TYPE.isNullable()); assertFalse(BOOLEAN_TYPE.isVoidable()); // matchesXxx assertTrue(BOOLEAN_TYPE.matchesInt32Context()); assertTrue(BOOLEAN_TYPE.matchesNumberContext()); assertTrue(BOOLEAN_TYPE.matchesObjectContext()); assertTrue(BOOLEAN_TYPE.matchesStringContext()); assertTrue(BOOLEAN_TYPE.matchesUint32Context()); // toString assertEquals("boolean", BOOLEAN_TYPE.toString()); assertTrue(BOOLEAN_TYPE.hasDisplayName()); assertEquals("boolean", BOOLEAN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(BOOLEAN_TYPE); } /** * Tests the behavior of the Boolean type. */ public void testBooleanObjectType() throws Exception { // isXxx assertFalse(BOOLEAN_OBJECT_TYPE.isArrayType()); assertTrue(BOOLEAN_OBJECT_TYPE.isBooleanObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isBooleanValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isDateType()); assertFalse(BOOLEAN_OBJECT_TYPE.isEnumElementType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNamedType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNullType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNumberObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNumberValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( BOOLEAN_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(BOOLEAN_OBJECT_TYPE.isRegexpType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStringObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStringValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isEnumType()); assertFalse(BOOLEAN_OBJECT_TYPE.isUnionType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStruct()); assertFalse(BOOLEAN_OBJECT_TYPE.isDict()); assertFalse(BOOLEAN_OBJECT_TYPE.isAllType()); assertFalse(BOOLEAN_OBJECT_TYPE.isVoidType()); assertFalse(BOOLEAN_OBJECT_TYPE.isConstructor()); assertTrue(BOOLEAN_OBJECT_TYPE.isInstanceType()); // isSubtype assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(namedGoogBar)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(BOOLEAN_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, functionType); assertCannotTestForEqualityWith(BOOLEAN_OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(BOOLEAN_OBJECT_TYPE.isNullable()); assertFalse(BOOLEAN_OBJECT_TYPE.isVoidable()); // matchesXxx assertTrue(BOOLEAN_OBJECT_TYPE.matchesInt32Context()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesNumberContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesObjectContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesStringContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("Boolean", BOOLEAN_OBJECT_TYPE.toString()); assertTrue(BOOLEAN_OBJECT_TYPE.hasDisplayName()); assertEquals("Boolean", BOOLEAN_OBJECT_TYPE.getDisplayName()); assertTrue(BOOLEAN_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(BOOLEAN_OBJECT_TYPE); } /** * Tests the behavior of the enum type. */ public void testEnumType() throws Exception { EnumType enumType = new EnumType(registry, "Enum", null, NUMBER_TYPE); // isXxx assertFalse(enumType.isArrayType()); assertFalse(enumType.isBooleanObjectType()); assertFalse(enumType.isBooleanValueType()); assertFalse(enumType.isDateType()); assertFalse(enumType.isEnumElementType()); assertFalse(enumType.isNamedType()); assertFalse(enumType.isNullType()); assertFalse(enumType.isNumberObjectType()); assertFalse(enumType.isNumberValueType()); assertFalse(enumType.isFunctionPrototypeType()); assertFalse(enumType.isRegexpType()); assertFalse(enumType.isStringObjectType()); assertFalse(enumType.isStringValueType()); assertTrue(enumType.isEnumType()); assertFalse(enumType.isUnionType()); assertFalse(enumType.isStruct()); assertFalse(enumType.isDict()); assertFalse(enumType.isAllType()); assertFalse(enumType.isVoidType()); assertFalse(enumType.isConstructor()); assertFalse(enumType.isInstanceType()); // isSubtype assertTrue(enumType.isSubtype(ALL_TYPE)); assertFalse(enumType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(enumType.isSubtype(NUMBER_TYPE)); assertFalse(enumType.isSubtype(functionType)); assertFalse(enumType.isSubtype(NULL_TYPE)); assertTrue(enumType.isSubtype(OBJECT_TYPE)); assertFalse(enumType.isSubtype(DATE_TYPE)); assertTrue(enumType.isSubtype(unresolvedNamedType)); assertFalse(enumType.isSubtype(namedGoogBar)); assertFalse(enumType.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(enumType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(enumType, ALL_TYPE); assertCanTestForEqualityWith(enumType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(enumType, NUMBER_TYPE); assertCanTestForEqualityWith(enumType, functionType); assertCannotTestForEqualityWith(enumType, VOID_TYPE); assertCanTestForEqualityWith(enumType, OBJECT_TYPE); assertCanTestForEqualityWith(enumType, DATE_TYPE); assertCanTestForEqualityWith(enumType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(enumType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(enumType. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(enumType. canTestForShallowEqualityWith(enumType)); assertFalse(enumType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(functionType)); assertFalse(enumType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(enumType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(enumType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(enumType.isNullable()); assertFalse(enumType.isVoidable()); // matchesXxx assertFalse(enumType.matchesInt32Context()); assertFalse(enumType.matchesNumberContext()); assertTrue(enumType.matchesObjectContext()); assertTrue(enumType.matchesStringContext()); assertFalse(enumType.matchesUint32Context()); // toString assertEquals("enum{Enum}", enumType.toString()); assertTrue(enumType.hasDisplayName()); assertEquals("Enum", enumType.getDisplayName()); assertEquals("AnotherEnum", new EnumType(registry, "AnotherEnum", null, NUMBER_TYPE).getDisplayName()); assertFalse( new EnumType(registry, null, null, NUMBER_TYPE).hasDisplayName()); Asserts.assertResolvesToSame(enumType); } /** * Tests the behavior of the enum element type. */ public void testEnumElementType() throws Exception { // isXxx assertFalse(elementsType.isArrayType()); assertFalse(elementsType.isBooleanObjectType()); assertFalse(elementsType.isBooleanValueType()); assertFalse(elementsType.isDateType()); assertTrue(elementsType.isEnumElementType()); assertFalse(elementsType.isNamedType()); assertFalse(elementsType.isNullType()); assertFalse(elementsType.isNumberObjectType()); assertFalse(elementsType.isNumberValueType()); assertFalse(elementsType.isFunctionPrototypeType()); assertFalse(elementsType.isRegexpType()); assertFalse(elementsType.isStringObjectType()); assertFalse(elementsType.isStringValueType()); assertFalse(elementsType.isEnumType()); assertFalse(elementsType.isUnionType()); assertFalse(elementsType.isStruct()); assertFalse(elementsType.isDict()); assertFalse(elementsType.isAllType()); assertFalse(elementsType.isVoidType()); assertFalse(elementsType.isConstructor()); assertFalse(elementsType.isInstanceType()); // isSubtype assertTrue(elementsType.isSubtype(ALL_TYPE)); assertFalse(elementsType.isSubtype(STRING_OBJECT_TYPE)); assertTrue(elementsType.isSubtype(NUMBER_TYPE)); assertFalse(elementsType.isSubtype(functionType)); assertFalse(elementsType.isSubtype(NULL_TYPE)); assertFalse(elementsType.isSubtype(OBJECT_TYPE)); // no more autoboxing assertFalse(elementsType.isSubtype(DATE_TYPE)); assertTrue(elementsType.isSubtype(unresolvedNamedType)); assertFalse(elementsType.isSubtype(namedGoogBar)); assertFalse(elementsType.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(elementsType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(elementsType, ALL_TYPE); assertCanTestForEqualityWith(elementsType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, NUMBER_TYPE); assertCanTestForEqualityWith(elementsType, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, elementsType); assertCannotTestForEqualityWith(elementsType, functionType); assertCannotTestForEqualityWith(elementsType, VOID_TYPE); assertCanTestForEqualityWith(elementsType, OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, DATE_TYPE); assertCanTestForEqualityWith(elementsType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(elementsType.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(elementsType. canTestForShallowEqualityWith(elementsType)); assertFalse(elementsType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(functionType)); assertFalse(elementsType.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(elementsType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(elementsType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(elementsType.isNullable()); assertFalse(elementsType.isVoidable()); // matchesXxx assertTrue(elementsType.matchesInt32Context()); assertTrue(elementsType.matchesNumberContext()); assertTrue(elementsType.matchesObjectContext()); assertTrue(elementsType.matchesStringContext()); assertTrue(elementsType.matchesUint32Context()); // toString assertEquals("Enum<number>", elementsType.toString()); assertTrue(elementsType.hasDisplayName()); assertEquals("Enum", elementsType.getDisplayName()); Asserts.assertResolvesToSame(elementsType); } public void testStringEnumType() throws Exception { EnumElementType stringEnum = new EnumType(registry, "Enum", null, STRING_TYPE).getElementsType(); assertTypeEquals(UNKNOWN_TYPE, stringEnum.getPropertyType("length")); assertTypeEquals(NUMBER_TYPE, stringEnum.findPropertyType("length")); assertEquals(false, stringEnum.hasProperty("length")); assertTypeEquals(STRING_OBJECT_TYPE, stringEnum.autoboxesTo()); assertNull(stringEnum.getConstructor()); Asserts.assertResolvesToSame(stringEnum); } public void testStringObjectEnumType() throws Exception { EnumElementType stringEnum = new EnumType(registry, "Enum", null, STRING_OBJECT_TYPE) .getElementsType(); assertTypeEquals(NUMBER_TYPE, stringEnum.getPropertyType("length")); assertTypeEquals(NUMBER_TYPE, stringEnum.findPropertyType("length")); assertEquals(true, stringEnum.hasProperty("length")); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, stringEnum.getConstructor()); } /** * Tests object types. */ public void testObjectType() throws Exception { PrototypeObjectType objectType = new PrototypeObjectType(registry, null, null); // isXxx assertFalse(objectType.isAllType()); assertFalse(objectType.isArrayType()); assertFalse(objectType.isDateType()); assertFalse(objectType.isFunctionPrototypeType()); assertTrue(objectType.getImplicitPrototype() == OBJECT_TYPE); // isSubtype assertTrue(objectType.isSubtype(ALL_TYPE)); assertFalse(objectType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(objectType.isSubtype(NUMBER_TYPE)); assertFalse(objectType.isSubtype(functionType)); assertFalse(objectType.isSubtype(NULL_TYPE)); assertFalse(objectType.isSubtype(DATE_TYPE)); assertTrue(objectType.isSubtype(OBJECT_TYPE)); assertTrue(objectType.isSubtype(unresolvedNamedType)); assertFalse(objectType.isSubtype(namedGoogBar)); assertFalse(objectType.isSubtype(REGEXP_TYPE)); // autoboxesTo assertNull(objectType.autoboxesTo()); // canTestForEqualityWith assertCanTestForEqualityWith(objectType, NUMBER_TYPE); // matchesXxxContext assertFalse(objectType.matchesInt32Context()); assertFalse(objectType.matchesNumberContext()); assertTrue(objectType.matchesObjectContext()); assertFalse(objectType.matchesStringContext()); assertFalse(objectType.matchesUint32Context()); // isNullable assertFalse(objectType.isNullable()); assertFalse(objectType.isVoidable()); assertTrue(createNullableType(objectType).isNullable()); assertTrue(createUnionType(objectType, VOID_TYPE).isVoidable()); // toString assertEquals("{...}", objectType.toString()); assertEquals(null, objectType.getDisplayName()); assertFalse(objectType.hasReferenceName()); assertEquals("anObject", new PrototypeObjectType(registry, "anObject", null).getDisplayName()); Asserts.assertResolvesToSame(objectType); } /** * Tests the goog.Bar type. */ public void testGoogBar() throws Exception { assertTrue(namedGoogBar.isInstanceType()); assertFalse(googBar.isInstanceType()); assertFalse(namedGoogBar.isConstructor()); assertTrue(googBar.isConstructor()); assertTrue(googBar.getInstanceType().isInstanceType()); assertTrue(namedGoogBar.getConstructor().isConstructor()); assertTrue(namedGoogBar.getImplicitPrototype().isFunctionPrototypeType()); // isSubtype assertTypeCanAssignToItself(googBar); assertTypeCanAssignToItself(namedGoogBar); googBar.isSubtype(namedGoogBar); namedGoogBar.isSubtype(googBar); assertTypeEquals(googBar, googBar); assertTypeNotEquals(googBar, googSubBar); Asserts.assertResolvesToSame(googBar); Asserts.assertResolvesToSame(googSubBar); } /** * Tests how properties are counted for object types. */ public void testObjectTypePropertiesCount() throws Exception { ObjectType sup = registry.createAnonymousObjectType(null); int nativeProperties = sup.getPropertiesCount(); sup.defineDeclaredProperty("a", DATE_TYPE, null); assertEquals(nativeProperties + 1, sup.getPropertiesCount()); sup.defineDeclaredProperty("b", DATE_TYPE, null); assertEquals(nativeProperties + 2, sup.getPropertiesCount()); ObjectType sub = registry.createObjectType(null, sup); assertEquals(nativeProperties + 2, sub.getPropertiesCount()); } /** * Tests how properties are defined. */ public void testDefineProperties() { ObjectType prototype = googBar.getPrototype(); ObjectType instance = googBar.getInstanceType(); assertTypeEquals(instance.getImplicitPrototype(), prototype); // Test declarations. assertTrue( prototype.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertFalse( prototype.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertFalse( instance.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertTypeEquals(NUMBER_TYPE, instance.getPropertyType("declared")); // Test inferring different types. assertTrue(prototype.defineInferredProperty("inferred1", STRING_TYPE, null)); assertTrue(prototype.defineInferredProperty("inferred1", NUMBER_TYPE, null)); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), instance.getPropertyType("inferred1")); // Test inferring different types on different objects. assertTrue(prototype.defineInferredProperty("inferred2", STRING_TYPE, null)); assertTrue(instance.defineInferredProperty("inferred2", NUMBER_TYPE, null)); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), instance.getPropertyType("inferred2")); // Test inferring on the supertype and declaring on the subtype. assertTrue( prototype.defineInferredProperty("prop", STRING_TYPE, null)); assertTrue( instance.defineDeclaredProperty("prop", NUMBER_TYPE, null)); assertTypeEquals(NUMBER_TYPE, instance.getPropertyType("prop")); assertTypeEquals(STRING_TYPE, prototype.getPropertyType("prop")); } /** * Tests that properties are correctly counted even when shadowing occurs. */ public void testObjectTypePropertiesCountWithShadowing() { ObjectType sup = registry.createAnonymousObjectType(null); int nativeProperties = sup.getPropertiesCount(); sup.defineDeclaredProperty("a", OBJECT_TYPE, null); assertEquals(nativeProperties + 1, sup.getPropertiesCount()); ObjectType sub = registry.createObjectType(null, sup); sub.defineDeclaredProperty("a", OBJECT_TYPE, null); assertEquals(nativeProperties + 1, sub.getPropertiesCount()); } /** * Tests the named type goog.Bar. */ public void testNamedGoogBar() throws Exception { // isXxx assertFalse(namedGoogBar.isFunctionPrototypeType()); assertTrue(namedGoogBar.getImplicitPrototype().isFunctionPrototypeType()); // isSubtype assertTrue(namedGoogBar.isSubtype(ALL_TYPE)); assertFalse(namedGoogBar.isSubtype(STRING_OBJECT_TYPE)); assertFalse(namedGoogBar.isSubtype(NUMBER_TYPE)); assertFalse(namedGoogBar.isSubtype(functionType)); assertFalse(namedGoogBar.isSubtype(NULL_TYPE)); assertTrue(namedGoogBar.isSubtype(OBJECT_TYPE)); assertFalse(namedGoogBar.isSubtype(DATE_TYPE)); assertTrue(namedGoogBar.isSubtype(namedGoogBar)); assertTrue(namedGoogBar.isSubtype(unresolvedNamedType)); assertFalse(namedGoogBar.isSubtype(REGEXP_TYPE)); assertFalse(namedGoogBar.isSubtype(ARRAY_TYPE)); // autoboxesTo assertNull(namedGoogBar.autoboxesTo()); // properties assertTypeEquals(DATE_TYPE, namedGoogBar.getPropertyType("date")); assertFalse(namedGoogBar.isNativeObjectType()); assertFalse(namedGoogBar.getImplicitPrototype().isNativeObjectType()); JSType resolvedNamedGoogBar = Asserts.assertValidResolve(namedGoogBar); assertNotSame(resolvedNamedGoogBar, namedGoogBar); assertSame(resolvedNamedGoogBar, googBar.getInstanceType()); } /** * Tests the prototype chaining of native objects. */ public void testPrototypeChaining() throws Exception { // equals assertTypeEquals( ARRAY_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( BOOLEAN_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( DATE_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( EVAL_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( NUMBER_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( URI_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( RANGE_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( REFERENCE_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( STRING_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( REGEXP_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( SYNTAX_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( TYPE_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); // not same assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), URI_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), RANGE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), RANGE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(REFERENCE_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(REFERENCE_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(SYNTAX_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); } /** * Tests that function instances have their constructor pointer back at the * function that created them. */ public void testInstanceFunctionChaining() throws Exception { // Array assertTypeEquals( ARRAY_FUNCTION_TYPE, ARRAY_TYPE.getConstructor()); // Boolean assertTypeEquals( BOOLEAN_OBJECT_FUNCTION_TYPE, BOOLEAN_OBJECT_TYPE.getConstructor()); // Date assertTypeEquals( DATE_FUNCTION_TYPE, DATE_TYPE.getConstructor()); // Error assertTypeEquals( ERROR_FUNCTION_TYPE, ERROR_TYPE.getConstructor()); // EvalError assertTypeEquals( EVAL_ERROR_FUNCTION_TYPE, EVAL_ERROR_TYPE.getConstructor()); // Number assertTypeEquals( NUMBER_OBJECT_FUNCTION_TYPE, NUMBER_OBJECT_TYPE.getConstructor()); // Object assertTypeEquals( OBJECT_FUNCTION_TYPE, OBJECT_TYPE.getConstructor()); // RangeError assertTypeEquals( RANGE_ERROR_FUNCTION_TYPE, RANGE_ERROR_TYPE.getConstructor()); // ReferenceError assertTypeEquals( REFERENCE_ERROR_FUNCTION_TYPE, REFERENCE_ERROR_TYPE.getConstructor()); // RegExp assertTypeEquals(REGEXP_FUNCTION_TYPE, REGEXP_TYPE.getConstructor()); // String assertTypeEquals( STRING_OBJECT_FUNCTION_TYPE, STRING_OBJECT_TYPE.getConstructor()); // SyntaxError assertTypeEquals( SYNTAX_ERROR_FUNCTION_TYPE, SYNTAX_ERROR_TYPE.getConstructor()); // TypeError assertTypeEquals( TYPE_ERROR_FUNCTION_TYPE, TYPE_ERROR_TYPE.getConstructor()); // URIError assertTypeEquals( URI_ERROR_FUNCTION_TYPE, URI_ERROR_TYPE.getConstructor()); } /** * Tests that the method {@link JSType#canTestForEqualityWith(JSType)} handles * special corner cases. */ @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases() { // null == undefined is always true assertCannotTestForEqualityWith(NULL_TYPE, VOID_TYPE); // (Object,null) == undefined could be true or false UnionType nullableObject = (UnionType) createUnionType(OBJECT_TYPE, NULL_TYPE); assertCanTestForEqualityWith(nullableObject, VOID_TYPE); assertCanTestForEqualityWith(VOID_TYPE, nullableObject); } /** * Tests the {@link JSType#testForEquality(JSType)} method. */ public void testTestForEquality() { compare(TRUE, NO_OBJECT_TYPE, NO_OBJECT_TYPE); compare(UNKNOWN, ALL_TYPE, ALL_TYPE); compare(TRUE, NO_TYPE, NO_TYPE); compare(UNKNOWN, NO_RESOLVED_TYPE, NO_RESOLVED_TYPE); compare(UNKNOWN, NO_OBJECT_TYPE, NUMBER_TYPE); compare(UNKNOWN, ALL_TYPE, NUMBER_TYPE); compare(UNKNOWN, NO_TYPE, NUMBER_TYPE); compare(FALSE, NULL_TYPE, BOOLEAN_TYPE); compare(TRUE, NULL_TYPE, NULL_TYPE); compare(FALSE, NULL_TYPE, NUMBER_TYPE); compare(FALSE, NULL_TYPE, OBJECT_TYPE); compare(FALSE, NULL_TYPE, STRING_TYPE); compare(TRUE, NULL_TYPE, VOID_TYPE); compare(UNKNOWN, NULL_TYPE, createUnionType(UNKNOWN_TYPE, VOID_TYPE)); compare(UNKNOWN, NULL_TYPE, createUnionType(OBJECT_TYPE, VOID_TYPE)); compare(UNKNOWN, NULL_TYPE, unresolvedNamedType); compare(UNKNOWN, NULL_TYPE, createUnionType(unresolvedNamedType, DATE_TYPE)); compare(FALSE, VOID_TYPE, REGEXP_TYPE); compare(TRUE, VOID_TYPE, VOID_TYPE); compare(UNKNOWN, VOID_TYPE, createUnionType(REGEXP_TYPE, VOID_TYPE)); compare(UNKNOWN, NUMBER_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, NUMBER_TYPE, NUMBER_TYPE); compare(UNKNOWN, NUMBER_TYPE, OBJECT_TYPE); compare(UNKNOWN, ARRAY_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, OBJECT_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, OBJECT_TYPE, STRING_TYPE); compare(UNKNOWN, STRING_TYPE, STRING_TYPE); compare(UNKNOWN, STRING_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, STRING_TYPE, NUMBER_TYPE); compare(FALSE, STRING_TYPE, VOID_TYPE); compare(FALSE, STRING_TYPE, NULL_TYPE); compare(FALSE, STRING_TYPE, createUnionType(NULL_TYPE, VOID_TYPE)); compare(UNKNOWN, UNKNOWN_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, UNKNOWN_TYPE, NULL_TYPE); compare(UNKNOWN, UNKNOWN_TYPE, VOID_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, BOOLEAN_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, NUMBER_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, STRING_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, VOID_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, NULL_TYPE); compare(UNKNOWN, U2U_CONSTRUCTOR_TYPE, OBJECT_TYPE); compare(UNKNOWN, U2U_CONSTRUCTOR_TYPE, ALL_TYPE); compare(UNKNOWN, NULL_TYPE, subclassOfUnresolvedNamedType); JSType functionAndNull = createUnionType(NULL_TYPE, dateMethod); compare(UNKNOWN, functionAndNull, dateMethod); compare(UNKNOWN, NULL_TYPE, NO_TYPE); compare(UNKNOWN, VOID_TYPE, NO_TYPE); compare(UNKNOWN, NULL_TYPE, unresolvedNamedType); compare(UNKNOWN, VOID_TYPE, unresolvedNamedType); compare(TRUE, NO_TYPE, NO_TYPE); } private void compare(TernaryValue r, JSType t1, JSType t2) { assertEquals(r, t1.testForEquality(t2)); assertEquals(r, t2.testForEquality(t1)); } private void assertCanTestForEqualityWith(JSType t1, JSType t2) { assertTrue(t1.canTestForEqualityWith(t2)); assertTrue(t2.canTestForEqualityWith(t1)); } private void assertCannotTestForEqualityWith(JSType t1, JSType t2) { assertFalse(t1.canTestForEqualityWith(t2)); assertFalse(t2.canTestForEqualityWith(t1)); } /** * Tests the subtyping relationships among simple types. */ public void testSubtypingSimpleTypes() throws Exception { // Any assertTrue(NO_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(functionType)); assertTrue(NO_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_TYPE.isSubtype(VOID_TYPE)); // AnyObject assertFalse(NO_OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(functionType)); assertFalse(NO_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(VOID_TYPE)); // Array assertFalse(ARRAY_TYPE.isSubtype(NO_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(DATE_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(functionType)); assertFalse(ARRAY_TYPE.isSubtype(NULL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ALL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(VOID_TYPE)); // boolean assertFalse(BOOLEAN_TYPE.isSubtype(NO_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(DATE_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(VOID_TYPE)); // Boolean assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NO_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(VOID_TYPE)); // Date assertFalse(DATE_TYPE.isSubtype(NO_TYPE)); assertFalse(DATE_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(DATE_TYPE)); assertFalse(DATE_TYPE.isSubtype(ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(functionType)); assertFalse(DATE_TYPE.isSubtype(NULL_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.isSubtype(ALL_TYPE)); assertFalse(DATE_TYPE.isSubtype(VOID_TYPE)); // Error assertFalse(ERROR_TYPE.isSubtype(NO_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ERROR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ERROR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertTrue(ERROR_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(functionType)); assertFalse(ERROR_TYPE.isSubtype(NULL_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(ERROR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ERROR_TYPE.isSubtype(STRING_TYPE)); assertFalse(ERROR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ERROR_TYPE.isSubtype(ALL_TYPE)); assertFalse(ERROR_TYPE.isSubtype(VOID_TYPE)); // EvalError assertFalse(EVAL_ERROR_TYPE.isSubtype(NO_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(ERROR_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(functionType)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NULL_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(STRING_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(ALL_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(VOID_TYPE)); // RangeError assertTrue(RANGE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // ReferenceError assertTrue(REFERENCE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // TypeError assertTrue(TYPE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // UriError assertTrue(URI_ERROR_TYPE.isSubtype(ERROR_TYPE)); // Unknown assertFalse(ALL_TYPE.isSubtype(NO_TYPE)); assertFalse(ALL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ALL_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ALL_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertFalse(ALL_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(functionType)); assertFalse(ALL_TYPE.isSubtype(NULL_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ALL_TYPE.isSubtype(ALL_TYPE)); assertFalse(ALL_TYPE.isSubtype(VOID_TYPE)); } /** * Tests that the Object type is the greatest element (top) of the object * hierarchy. */ public void testSubtypingObjectTopOfObjects() throws Exception { assertTrue(OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(createUnionType(DATE_TYPE, REGEXP_TYPE).isSubtype(OBJECT_TYPE)); assertTrue(createUnionType(OBJECT_TYPE, NO_OBJECT_TYPE). isSubtype(OBJECT_TYPE)); assertTrue(functionType.isSubtype(OBJECT_TYPE)); } public void testSubtypingFunctionPrototypeType() throws Exception { FunctionType sub1 = registry.createConstructorType( null, null, registry.createParameters(null, null, null), null, null, false); sub1.setPrototypeBasedOn(googBar); FunctionType sub2 = registry.createConstructorType( null, null, registry.createParameters(null, null, null), null, null, false); sub2.setPrototypeBasedOn(googBar); ObjectType o1 = sub1.getInstanceType(); ObjectType o2 = sub2.getInstanceType(); assertFalse(o1.isSubtype(o2)); assertFalse(o1.getImplicitPrototype().isSubtype(o2.getImplicitPrototype())); assertTrue(o1.getImplicitPrototype().isSubtype(googBar)); assertTrue(o2.getImplicitPrototype().isSubtype(googBar)); } public void testSubtypingFunctionFixedArgs() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, BOOLEAN_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, BOOLEAN_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionMultipleFixedArgs() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, EVAL_ERROR_TYPE, STRING_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, ERROR_TYPE, ALL_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionFixedArgsNotMatching() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, EVAL_ERROR_TYPE, UNKNOWN_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, ERROR_TYPE, ALL_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionVariableArgsOneOnly() throws Exception { // f1 = (EvalError...) -> Object FunctionType f1 = registry.createFunctionTypeWithVarArgs(OBJECT_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object) -> String FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, ERROR_TYPE, OBJECT_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertFalse(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionVariableArgsBoth() throws Exception { // f1 = (UriError, EvalError, EvalError...) -> Object FunctionType f1 = registry.createFunctionTypeWithVarArgs( OBJECT_TYPE, URI_ERROR_TYPE, EVAL_ERROR_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object, EvalError...) -> String FunctionType f2 = registry.createFunctionTypeWithVarArgs( STRING_OBJECT_TYPE, ERROR_TYPE, OBJECT_TYPE, EVAL_ERROR_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingMostGeneralFunction() throws Exception { // (EvalError, String) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, EVAL_ERROR_TYPE, STRING_TYPE); // (string, void) -> number FunctionType f2 = registry.createFunctionType(NUMBER_TYPE, STRING_TYPE, VOID_TYPE); // (Date, string, number) -> AnyObject FunctionType f3 = registry.createFunctionType( NO_OBJECT_TYPE, DATE_TYPE, STRING_TYPE, NUMBER_TYPE); // (Number) -> Any FunctionType f4 = registry.createFunctionType(NO_TYPE, NUMBER_OBJECT_TYPE); // f1 = (EvalError...) -> Object FunctionType f5 = registry.createFunctionTypeWithVarArgs(OBJECT_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object) -> String FunctionType f6 = registry.createFunctionType(STRING_OBJECT_TYPE, ERROR_TYPE, OBJECT_TYPE); // f1 = (UriError, EvalError...) -> Object FunctionType f7 = registry.createFunctionTypeWithVarArgs( OBJECT_TYPE, URI_ERROR_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object, EvalError...) -> String FunctionType f8 = registry.createFunctionTypeWithVarArgs( STRING_OBJECT_TYPE, ERROR_TYPE, OBJECT_TYPE, EVAL_ERROR_TYPE); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(LEAST_FUNCTION_TYPE)); assertTrue(GREATEST_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f1.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f2.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f3.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f4.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f5.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f6.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f7.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f8.isSubtype(GREATEST_FUNCTION_TYPE)); assertFalse(f1.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f2.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f3.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f4.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f5.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f6.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f7.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f8.isSubtype(LEAST_FUNCTION_TYPE)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f1)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f2)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f3)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f4)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f5)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f6)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f7)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f8)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f1)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f2)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f3)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f4)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f5)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f6)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f7)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f8)); } /** * Types to test for symmetrical relationships. */ private List<JSType> getTypesToTestForSymmetry() { return ImmutableList.of( UNKNOWN_TYPE, NULL_TYPE, VOID_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, OBJECT_TYPE, U2U_CONSTRUCTOR_TYPE, LEAST_FUNCTION_TYPE, GREATEST_FUNCTION_TYPE, ALL_TYPE, NO_TYPE, NO_OBJECT_TYPE, NO_RESOLVED_TYPE, createUnionType(BOOLEAN_TYPE, STRING_TYPE), createUnionType(NUMBER_TYPE, STRING_TYPE), createUnionType(NULL_TYPE, dateMethod), createUnionType(UNKNOWN_TYPE, dateMethod), createUnionType(namedGoogBar, dateMethod), createUnionType(NULL_TYPE, unresolvedNamedType), enumType, elementsType, dateMethod, functionType, unresolvedNamedType, googBar, namedGoogBar, googBar.getInstanceType(), namedGoogBar, subclassOfUnresolvedNamedType, subclassCtor, recordType, forwardDeclaredNamedType, createUnionType(forwardDeclaredNamedType, NULL_TYPE), createTemplatizedType(OBJECT_TYPE, STRING_TYPE), createTemplatizedType(OBJECT_TYPE, NUMBER_TYPE), createTemplatizedType(ARRAY_TYPE, STRING_TYPE), createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), createUnionType( createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), createUnionType( createTemplatizedType(OBJECT_TYPE, BOOLEAN_TYPE), NULL_TYPE) ); } public void testSymmetryOfTestForEquality() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { TernaryValue aOnB = typeA.testForEquality(typeB); TernaryValue bOnA = typeB.testForEquality(typeA); assertTrue( String.format("testForEquality not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.testForEquality(b): %s\n" + "b.testForEquality(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB == bOnA); } } } /** * Tests that getLeastSupertype is a symmetric relation. */ public void testSymmetryOfLeastSupertype() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { JSType aOnB = typeA.getLeastSupertype(typeB); JSType bOnA = typeB.getLeastSupertype(typeA); // Use a custom assert message instead of the normal assertTypeEquals, // to make it more helpful. assertTrue( String.format("getLeastSupertype not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.getLeastSupertype(b): %s\n" + "b.getLeastSupertype(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB.isEquivalentTo(bOnA)); } } } public void testWeirdBug() { assertTypeNotEquals(googBar, googBar.getInstanceType()); assertFalse(googBar.isSubtype(googBar.getInstanceType())); assertFalse(googBar.getInstanceType().isSubtype(googBar)); } /** * Tests that getGreatestSubtype is a symmetric relation. */ public void testSymmetryOfGreatestSubtype() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { JSType aOnB = typeA.getGreatestSubtype(typeB); JSType bOnA = typeB.getGreatestSubtype(typeA); // Use a custom assert message instead of the normal assertTypeEquals, // to make it more helpful. assertTrue( String.format("getGreatestSubtype not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.getGreatestSubtype(b): %s\n" + "b.getGreatestSubtype(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB.isEquivalentTo(bOnA)); } } } /** * Tests that getLeastSupertype is a reflexive relation. */ public void testReflexivityOfLeastSupertype() { List<JSType> list = getTypesToTestForSymmetry(); for (JSType type : list) { assertTypeEquals("getLeastSupertype not reflexive", type, type.getLeastSupertype(type)); } } /** * Tests that getGreatestSubtype is a reflexive relation. */ public void testReflexivityOfGreatestSubtype() { List<JSType> list = getTypesToTestForSymmetry(); for (JSType type : list) { assertTypeEquals("getGreatestSubtype not reflexive", type, type.getGreatestSubtype(type)); } } /** * Tests {@link JSType#getLeastSupertype(JSType)} for unresolved named types. */ public void testLeastSupertypeUnresolvedNamedType() { // (undefined,function(?):?) and ? unresolved named type JSType expected = registry.createUnionType( unresolvedNamedType, U2U_FUNCTION_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(U2U_FUNCTION_TYPE)); assertTypeEquals(expected, U2U_FUNCTION_TYPE.getLeastSupertype(unresolvedNamedType)); assertEquals("(function(...?): ?|not.resolved.named.type)", expected.toString()); } public void testLeastSupertypeUnresolvedNamedType2() { JSType expected = registry.createUnionType( unresolvedNamedType, UNKNOWN_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(expected, UNKNOWN_TYPE.getLeastSupertype(unresolvedNamedType)); assertTypeEquals(UNKNOWN_TYPE, expected); } public void testLeastSupertypeUnresolvedNamedType3() { JSType expected = registry.createUnionType( unresolvedNamedType, CHECKED_UNKNOWN_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(CHECKED_UNKNOWN_TYPE)); assertTypeEquals(expected, CHECKED_UNKNOWN_TYPE.getLeastSupertype(unresolvedNamedType)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, expected); } /** Tests the subclass of an unresolved named type */ public void testSubclassOfUnresolvedNamedType() { assertTrue(subclassOfUnresolvedNamedType.isUnknownType()); } /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */ public void testSupertypeOfProxiedFunctionTypes() { ObjectType fn1 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .build(); ObjectType fn2 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(STRING_TYPE) .build(); ObjectType p1 = new ProxyObjectType(registry, fn1); ObjectType p2 = new ProxyObjectType(registry, fn2); ObjectType supremum = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(registry.createUnionType(STRING_TYPE, NUMBER_TYPE)) .build(); assertTypeEquals(fn1.getLeastSupertype(fn2), p1.getLeastSupertype(p2)); assertTypeEquals(supremum, fn1.getLeastSupertype(fn2)); assertTypeEquals(supremum, fn1.getLeastSupertype(p2)); assertTypeEquals(supremum, p1.getLeastSupertype(fn2)); assertTypeEquals(supremum, p1.getLeastSupertype(p2)); } public void testTypeOfThisIsProxied() { ObjectType fnType = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE).withTypeOfThis(OBJECT_TYPE).build(); ObjectType proxyType = new ProxyObjectType(registry, fnType); assertTypeEquals(fnType.getTypeOfThis(), proxyType.getTypeOfThis()); } /** * Tests the {@link NamedType#equals} function, which had a bug in it. */ public void testNamedTypeEquals() { JSTypeRegistry jst = new JSTypeRegistry(null); // test == if references are equal NamedType a = new NamedType(jst, "type1", "source", 1, 0); NamedType b = new NamedType(jst, "type1", "source", 1, 0); assertTrue(a.isEquivalentTo(b)); // test == instance of referenced type assertTrue(namedGoogBar.isEquivalentTo(googBar.getInstanceType())); assertTrue(googBar.getInstanceType().isEquivalentTo(namedGoogBar)); } /** * Tests the {@link NamedType#equals} function against other types. */ public void testNamedTypeEquals2() { // test == if references are equal NamedType a = new NamedType(registry, "typeA", "source", 1, 0); NamedType b = new NamedType(registry, "typeB", "source", 1, 0); ObjectType realA = registry.createConstructorType("typeA", null, null, null, null, false).getInstanceType(); ObjectType realB = registry.createEnumType( "typeB", null, NUMBER_TYPE).getElementsType(); registry.declareType("typeA", realA); registry.declareType("typeB", realB); assertTypeEquals(a, realA); assertTypeEquals(b, realB); a.resolve(null, null); b.resolve(null, null); assertTrue(a.isResolved()); assertTrue(b.isResolved()); assertTypeEquals(a, realA); assertTypeEquals(b, realB); JSType resolvedA = Asserts.assertValidResolve(a); assertNotSame(resolvedA, a); assertSame(resolvedA, realA); JSType resolvedB = Asserts.assertValidResolve(b); assertNotSame(resolvedB, b); assertSame(resolvedB, realB); } /** * Tests the {@link NamedType#equals} function against other types * when it's forward-declared. */ public void testForwardDeclaredNamedTypeEquals() { // test == if references are equal NamedType a = new NamedType(registry, "forwardDeclared", "source", 1, 0); NamedType b = new NamedType(registry, "forwardDeclared", "source", 1, 0); assertTypeEquals(a, b); a.resolve(null, EMPTY_SCOPE); assertTrue(a.isResolved()); assertFalse(b.isResolved()); assertTypeEquals(a, b); assertFalse(a.isEquivalentTo(UNKNOWN_TYPE)); assertFalse(b.isEquivalentTo(UNKNOWN_TYPE)); assertTrue(a.isEmptyType()); assertFalse(a.isNoType()); assertTrue(a.isNoResolvedType()); } public void testForwardDeclaredNamedType() { NamedType a = new NamedType(registry, "forwardDeclared", "source", 1, 0); assertTypeEquals(UNKNOWN_TYPE, a.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, a.getLeastSupertype(CHECKED_UNKNOWN_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(a)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, CHECKED_UNKNOWN_TYPE.getLeastSupertype(a)); } /** * Tests {@link JSType#getGreatestSubtype(JSType)} on simple types. */ public void testGreatestSubtypeSimpleTypes() { assertTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getGreatestSubtype(ALL_TYPE)); assertTypeEquals(ARRAY_TYPE, ALL_TYPE.getGreatestSubtype(ARRAY_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, REGEXP_TYPE.getGreatestSubtype(NO_OBJECT_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, NO_OBJECT_TYPE.getGreatestSubtype(REGEXP_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(STRING_OBJECT_TYPE)); assertTypeEquals(NO_TYPE, ARRAY_TYPE.getGreatestSubtype(NUMBER_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(functionType)); assertTypeEquals(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE.getGreatestSubtype(OBJECT_TYPE)); assertTypeEquals(STRING_OBJECT_TYPE, OBJECT_TYPE.getGreatestSubtype(STRING_OBJECT_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(DATE_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(REGEXP_TYPE)); assertTypeEquals(EVAL_ERROR_TYPE, ERROR_TYPE.getGreatestSubtype(EVAL_ERROR_TYPE)); assertTypeEquals(EVAL_ERROR_TYPE, EVAL_ERROR_TYPE.getGreatestSubtype(ERROR_TYPE)); assertTypeEquals(NO_TYPE, NULL_TYPE.getGreatestSubtype(ERROR_TYPE)); assertTypeEquals(UNKNOWN_TYPE, NUMBER_TYPE.getGreatestSubtype(UNKNOWN_TYPE)); assertTypeEquals(NO_RESOLVED_TYPE, NO_OBJECT_TYPE.getGreatestSubtype(forwardDeclaredNamedType)); assertTypeEquals(NO_RESOLVED_TYPE, forwardDeclaredNamedType.getGreatestSubtype(NO_OBJECT_TYPE)); } /** * Tests that a derived class extending a type via a named type is a subtype * of it. */ public void testSubtypingDerivedExtendsNamedBaseType() throws Exception { ObjectType derived = registry.createObjectType(null, registry.createObjectType(null, namedGoogBar)); assertTrue(derived.isSubtype(googBar.getInstanceType())); } public void testNamedSubtypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), googBar.getPrototype(), googBar.getInstanceType(), googSubBar.getPrototype(), googSubBar.getInstanceType(), googSubSubBar.getPrototype(), googSubSubBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordSubtypeChain() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); JSType aType = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); JSType abType = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType acType = builder.build(); JSType abOrAcType = registry.createUnionType(abType, acType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", NUMBER_TYPE, null); JSType abcType = builder.build(); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), aType, abOrAcType, abType, abcType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordAndObjectChain2() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("date", DATE_TYPE, null); JSType hasDateProperty = builder.build(); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.OBJECT_TYPE), hasDateProperty, googBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordAndObjectChain3() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("date", UNKNOWN_TYPE, null); JSType hasUnknownDateProperty = builder.build(); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.OBJECT_TYPE), hasUnknownDateProperty, googBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testNullableNamedTypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.ALL_TYPE)), registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE)), registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.OBJECT_TYPE)), registry.createOptionalNullableType(googBar.getPrototype()), registry.createOptionalNullableType(googBar.getInstanceType()), registry.createNullableType(googSubBar.getPrototype()), registry.createNullableType(googSubBar.getInstanceType()), googSubSubBar.getPrototype(), googSubSubBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testEnumTypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), enumType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testFunctionSubtypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE), registry.getNativeType(JSTypeNative.GREATEST_FUNCTION_TYPE), dateMethod, registry.getNativeType(JSTypeNative.LEAST_FUNCTION_TYPE), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testFunctionUnionSubtypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( createUnionType( OBJECT_TYPE, STRING_TYPE), createUnionType( GREATEST_FUNCTION_TYPE, googBarInst, STRING_TYPE), createUnionType( STRING_TYPE, registry.createFunctionType( createUnionType(STRING_TYPE, NUMBER_TYPE)), googBarInst), createUnionType( registry.createFunctionType(NUMBER_TYPE), googSubBarInst), LEAST_FUNCTION_TYPE, NO_OBJECT_TYPE, NO_TYPE); verifySubtypeChain(typeChain); } public void testConstructorSubtypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE), registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testGoogBarSubtypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), googBar, googSubBar, googSubSubBar, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE)); verifySubtypeChain(typeChain, false); } public void testConstructorWithArgSubtypeChain() throws Exception { FunctionType googBarArgConstructor = registry.createConstructorType( "barArg", null, registry.createParameters(googBar), null, null, false); FunctionType googSubBarArgConstructor = registry.createConstructorType( "subBarArg", null, registry.createParameters(googSubBar), null, null, false); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), googBarArgConstructor, googSubBarArgConstructor, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE)); verifySubtypeChain(typeChain, false); } public void testInterfaceInstanceSubtypeChain() throws Exception { List<JSType> typeChain = ImmutableList.of( ALL_TYPE, OBJECT_TYPE, interfaceInstType, googBar.getPrototype(), googBarInst, googSubBar.getPrototype(), googSubBarInst, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testInterfaceInheritanceSubtypeChain() throws Exception { FunctionType tempType = registry.createConstructorType("goog.TempType", null, null, null, null, false); tempType.setImplementedInterfaces( Lists.<ObjectType>newArrayList(subInterfaceInstType)); List<JSType> typeChain = ImmutableList.of( ALL_TYPE, OBJECT_TYPE, interfaceInstType, subInterfaceInstType, tempType.getPrototype(), tempType.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testAnonymousObjectChain() throws Exception { List<JSType> typeChain = ImmutableList.of( ALL_TYPE, createNullableType(OBJECT_TYPE), OBJECT_TYPE, registry.createAnonymousObjectType(null), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testAnonymousEnumElementChain() throws Exception { ObjectType enumElemType = registry.createEnumType( "typeB", null, registry.createAnonymousObjectType(null)).getElementsType(); List<JSType> typeChain = ImmutableList.of( ALL_TYPE, createNullableType(OBJECT_TYPE), OBJECT_TYPE, enumElemType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testTemplatizedArrayChain() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfStringOrNumber = createTemplatizedType( ARRAY_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType arrayOfAllType = createTemplatizedType( ARRAY_TYPE, ALL_TYPE); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), arrayOfAllType, arrayOfStringOrNumber, arrayOfString, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedArrayChain2() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfNoObjectType = createTemplatizedType( ARRAY_TYPE, NO_OBJECT_TYPE); JSType arrayOfArray = createTemplatizedType( ARRAY_TYPE, ARRAY_TYPE); JSType arrayOfObject = createTemplatizedType( ARRAY_TYPE, OBJECT_TYPE); JSType arrayOfAllType = createTemplatizedType( ARRAY_TYPE, ALL_TYPE); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), arrayOfAllType, arrayOfObject, arrayOfArray, arrayOfNoObjectType, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedObjectChain() throws Exception { JSType objectOfNoType = createTemplatizedType( OBJECT_TYPE, NO_TYPE); JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType objectOfStringOrNumber = createTemplatizedType( OBJECT_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType objectOfAllType = createTemplatizedType( OBJECT_TYPE, ALL_TYPE); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), objectOfAllType, objectOfStringOrNumber, objectOfString, objectOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testMixedTemplatizedTypeChain() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType objectOfStringOrNumber = createTemplatizedType( OBJECT_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType objectOfAllType = createTemplatizedType( OBJECT_TYPE, ALL_TYPE); List<JSType> typeChain = ImmutableList.of( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), objectOfAllType, objectOfStringOrNumber, objectOfString, arrayOfString, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedTypeSubtypes() { JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfUnknown = createTemplatizedType( ARRAY_TYPE, UNKNOWN_TYPE); assertFalse(objectOfString.isSubtype(ARRAY_TYPE)); // TODO(johnlenz): should this be false? assertTrue(ARRAY_TYPE.isSubtype(objectOfString)); assertFalse(objectOfString.isSubtype(ARRAY_TYPE)); // TODO(johnlenz): should this be false? assertTrue(ARRAY_TYPE.isSubtype(objectOfString)); assertTrue(arrayOfString.isSubtype(ARRAY_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(arrayOfString)); assertTrue(arrayOfString.isSubtype(arrayOfUnknown)); assertTrue(arrayOfUnknown.isSubtype(arrayOfString)); assertFalse(arrayOfString.isSubtype(arrayOfNumber)); assertFalse(arrayOfNumber.isSubtype(arrayOfString)); assertTrue(arrayOfNumber.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); assertFalse(createUnionType(arrayOfNumber, NULL_VOID).isSubtype(arrayOfNumber)); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testTemplatizedTypeRelations() throws Exception { JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); // Union and least super type cases: // // 1) alternate:Array<string> and current:Object ==> Object // 2) alternate:Array<string> and current:Array ==> Array // 3) alternate:Object<string> and current:Array ==> Array|Object<string> // 4) alternate:Object and current:Array<string> ==> Object // 5) alternate:Array and current:Array<string> ==> Array // 6) alternate:Array and current:Object<string> ==> Array|Object<string> // 7) alternate:Array<string> and current:Array<number> ==> Array<?> // 8) alternate:Array<string> and current:Array<string> ==> Array<string> // 9) alternate:Array<string> and // current:Object<string> ==> Object<string>|Array<string> assertTypeEquals( OBJECT_TYPE, JSType.getLeastSupertype(arrayOfString, OBJECT_TYPE)); assertTypeEquals( OBJECT_TYPE, JSType.getLeastSupertype(OBJECT_TYPE, arrayOfString)); assertTypeEquals( ARRAY_TYPE, JSType.getLeastSupertype(arrayOfString, ARRAY_TYPE)); assertTypeEquals( ARRAY_TYPE, JSType.getLeastSupertype(ARRAY_TYPE, arrayOfString)); assertEquals( "(Array|Object<string,?>)", JSType.getLeastSupertype(objectOfString, ARRAY_TYPE).toString()); assertEquals( "(Array|Object<string,?>)", JSType.getLeastSupertype(ARRAY_TYPE, objectOfString).toString()); assertEquals( "Array", JSType.getLeastSupertype(arrayOfString, arrayOfNumber).toString()); assertEquals( "Array", JSType.getLeastSupertype(arrayOfNumber, arrayOfString).toString()); assertTypeEquals( arrayOfString, JSType.getLeastSupertype(arrayOfString, arrayOfString)); assertEquals( "(Array<string>|Object<string,?>)", JSType.getLeastSupertype(objectOfString, arrayOfString).toString()); assertEquals( "(Array<string>|Object<string,?>)", JSType.getLeastSupertype(arrayOfString, objectOfString).toString()); assertTypeEquals( objectOfString, JSType.getGreatestSubtype(OBJECT_TYPE, objectOfString)); assertTypeEquals( objectOfString, JSType.getGreatestSubtype(objectOfString, OBJECT_TYPE)); assertTypeEquals( ARRAY_TYPE, JSType.getGreatestSubtype(objectOfString, ARRAY_TYPE)); assertTypeEquals( JSType.getGreatestSubtype(objectOfString, arrayOfString), NO_OBJECT_TYPE); assertTypeEquals( JSType.getGreatestSubtype(OBJECT_TYPE, arrayOfString), arrayOfString); } /** * Tests that the given chain of types has a total ordering defined * by the subtype relationship, with types at the top of the lattice * listed first. * * Also verifies that the infimum of any two types on the chain * is the lower type, and the supremum of any two types on the chain * is the higher type. */ public void verifySubtypeChain(List<JSType> typeChain) throws Exception { verifySubtypeChain(typeChain, true); } public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception { // Ugh. This wouldn't require so much copy-and-paste if we had a functional // programming language. for (int i = 0; i < typeChain.size(); i++) { for (int j = 0; j < typeChain.size(); j++) { JSType typeI = typeChain.get(i); JSType typeJ = typeChain.get(j); JSType namedTypeI = getNamedWrapper("TypeI", typeI); JSType namedTypeJ = getNamedWrapper("TypeJ", typeJ); JSType proxyTypeI = new ProxyObjectType(registry, typeI); JSType proxyTypeJ = new ProxyObjectType(registry, typeJ); if (i == j) { assertTrue(typeI + " should equal itself", typeI.isEquivalentTo(typeI)); assertTrue("Named " + typeI + " should equal itself", namedTypeI.isEquivalentTo(namedTypeI)); assertTrue("Proxy " + typeI + " should equal itself", proxyTypeI.isEquivalentTo(proxyTypeI)); } else { boolean shouldCheck = true; // due to structural interface matching and its updated equivalence // checking, a subtype interface could be considered as equivalent // to its super type interface (if they are structurally the same) // when this happens, the following checks are skipped. ObjectType objectI = typeI.toObjectType(); ObjectType objectJ = typeJ.toObjectType(); if (objectI != null && objectJ != null) { FunctionType constructorI = objectI.getConstructor(); FunctionType constructorJ = objectJ.getConstructor(); if (constructorI != null && constructorJ != null && constructorI.isStructuralInterface() && constructorJ.isStructuralInterface()) { if (constructorI.checkEquivalenceHelper(constructorJ, EquivalenceMethod.IDENTITY)) { shouldCheck = false; } } } if (shouldCheck) { assertFalse(typeI + " should not equal " + typeJ, typeI.isEquivalentTo(typeJ)); assertFalse("Named " + typeI + " should not equal " + typeJ, namedTypeI.isEquivalentTo(namedTypeJ)); assertFalse("Proxy " + typeI + " should not equal " + typeJ, proxyTypeI.isEquivalentTo(proxyTypeJ)); } } assertTrue(typeJ + " should be castable to " + typeI, typeJ.canCastTo(typeI)); assertTrue(typeJ + " should be castable to Named " + namedTypeI, typeJ.canCastTo(namedTypeI)); assertTrue(typeJ + " should be castable to Proxy " + proxyTypeI, typeJ.canCastTo(proxyTypeI)); assertTrue( "Named " + typeJ + " should be castable to " + typeI, namedTypeJ.canCastTo(typeI)); assertTrue( "Named " + typeJ + " should be castable to Named " + typeI, namedTypeJ.canCastTo(namedTypeI)); assertTrue( "Named " + typeJ + " should be castable to Proxy " + typeI, namedTypeJ.canCastTo(proxyTypeI)); assertTrue( "Proxy " + typeJ + " should be castable to " + typeI, proxyTypeJ.canCastTo(typeI)); assertTrue( "Proxy " + typeJ + " should be castable to Named " + typeI, proxyTypeJ.canCastTo(namedTypeI)); assertTrue( "Proxy " + typeJ + " should be castable to Proxy " + typeI, proxyTypeJ.canCastTo(proxyTypeI)); // due to structural interface matching, a subtype could be considered // as the super type of its super type (if they are structurally the same) // when this happens, the following checks are skipped. if (typeI.isSubtype(typeJ) && typeJ.isSubtype(typeI)) { continue; } if (checkSubtyping) { if (i <= j) { assertTrue(typeJ + " should be a subtype of " + typeI, typeJ.isSubtype(typeI)); assertTrue( "Named " + typeJ + " should be a subtype of Named " + typeI, namedTypeJ.isSubtype(namedTypeI)); assertTrue( "Proxy " + typeJ + " should be a subtype of Proxy " + typeI, proxyTypeJ.isSubtype(proxyTypeI)); } else { assertFalse(typeJ + " should not be a subtype of " + typeI, typeJ.isSubtype(typeI)); assertFalse( "Named " + typeJ + " should not be a subtype of Named " + typeI, namedTypeJ.isSubtype(namedTypeI)); assertFalse( "Named " + typeJ + " should not be a subtype of Named " + typeI, proxyTypeJ.isSubtype(proxyTypeI)); } JSType expectedSupremum = i < j ? typeI : typeJ; JSType expectedInfimum = i > j ? typeI : typeJ; assertTypeEquals( expectedSupremum + " should be the least supertype of " + typeI + " and " + typeJ, expectedSupremum, typeI.getLeastSupertype(typeJ)); // TODO(nicksantos): Should these tests pass? //assertTypeEquals( // expectedSupremum + " should be the least supertype of Named " + // typeI + " and Named " + typeJ, // expectedSupremum, namedTypeI.getLeastSupertype(namedTypeJ)); //assertTypeEquals( // expectedSupremum + " should be the least supertype of Proxy " + // typeI + " and Proxy " + typeJ, // expectedSupremum, proxyTypeI.getLeastSupertype(proxyTypeJ)); assertTypeEquals( expectedInfimum + " should be the greatest subtype of " + typeI + " and " + typeJ, expectedInfimum, typeI.getGreatestSubtype(typeJ)); // TODO(nicksantos): Should these tests pass? //assertTypeEquals( // expectedInfimum + " should be the greatest subtype of Named " + // typeI + " and Named " + typeJ, // expectedInfimum, namedTypeI.getGreatestSubtype(namedTypeJ)); //assertTypeEquals( // expectedInfimum + " should be the greatest subtype of Proxy " + // typeI + " and Proxy " + typeJ, // expectedInfimum, proxyTypeI.getGreatestSubtype(proxyTypeJ)); } } } } JSType getNamedWrapper(String name, JSType jstype) { // Normally, there is no way to create a Named NoType alias so // avoid confusing things by doing it here.. if (!jstype.isNoType()) { NamedType namedWrapper = new NamedType( registry, name, "[testcode]", -1, -1); namedWrapper.setReferencedType(jstype); return namedWrapper; } else { return jstype; } } /** * Tests the behavior of * {@link JSType#getRestrictedTypeGivenToBooleanOutcome(boolean)}. */ @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean() { // simple cases assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, NULL_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NULL_TYPE, NULL_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(STRING_TYPE, STRING_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(STRING_TYPE, STRING_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, STRING_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, VOID_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(VOID_TYPE, VOID_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_OBJECT_TYPE, NO_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, NO_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, NO_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, NO_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, UNKNOWN_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); // unions UnionType nullableStringValue = (UnionType) createNullableType(STRING_TYPE); assertTypeEquals(STRING_TYPE, nullableStringValue.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(nullableStringValue, nullableStringValue.getRestrictedTypeGivenToBooleanOutcome(false)); UnionType nullableStringObject = (UnionType) createNullableType(STRING_OBJECT_TYPE); assertTypeEquals(STRING_OBJECT_TYPE, nullableStringObject.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NULL_TYPE, nullableStringObject.getRestrictedTypeGivenToBooleanOutcome(false)); } public void testRegisterProperty() { int i = 0; List<JSType> allObjects = new ArrayList<>(); for (JSType type : types) { String propName = "ALF" + i++; if (type instanceof ObjectType) { ObjectType objType = (ObjectType) type; objType.defineDeclaredProperty(propName, UNKNOWN_TYPE, null); objType.defineDeclaredProperty("allHaz", UNKNOWN_TYPE, null); // We exclude {a: number, b: string} because, for inline record types, // we register their properties on a sentinel object literal in the registry. if (!type.equals(this.recordType)) { assertTypeEquals(type, registry.getGreatestSubtypeWithProperty(type, propName)); } assertTypeEquals(NO_TYPE, registry.getGreatestSubtypeWithProperty(type, "GRRR")); allObjects.add(type); } } } public void testRegisterPropertyMemoization() { ObjectType derived1 = registry.createObjectType("d1", namedGoogBar); ObjectType derived2 = registry.createObjectType("d2", namedGoogBar); derived1.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(derived1, registry.getGreatestSubtypeWithProperty(derived1, "propz")); assertTypeEquals(NO_OBJECT_TYPE, registry.getGreatestSubtypeWithProperty(derived2, "propz")); derived2.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(derived1, registry.getGreatestSubtypeWithProperty(derived1, "propz")); assertTypeEquals(derived2, registry.getGreatestSubtypeWithProperty(derived2, "propz")); } /** * Tests * {@link JSTypeRegistry#getGreatestSubtypeWithProperty(JSType, String)}. */ public void testGreatestSubtypeWithProperty() { ObjectType foo = registry.createObjectType("foo", OBJECT_TYPE); ObjectType bar = registry.createObjectType("bar", namedGoogBar); foo.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); bar.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(bar, registry.getGreatestSubtypeWithProperty(namedGoogBar, "propz")); } public void testGoodSetPrototypeBasedOn() { FunctionType fun = registry.createConstructorType("fun", null, null, null, null, false); fun.setPrototypeBasedOn(unresolvedNamedType); assertTrue(fun.getInstanceType().isUnknownType()); } public void testLateSetPrototypeBasedOn() { FunctionType fun = registry.createConstructorType("fun", null, null, null, null, false); assertFalse(fun.getInstanceType().isUnknownType()); fun.setPrototypeBasedOn(unresolvedNamedType); assertTrue(fun.getInstanceType().isUnknownType()); } public void testGetTypeUnderEquality1() { for (JSType type : types) { testGetTypeUnderEquality(type, type, type, type); } } public void testGetTypesUnderEquality2() { // objects can be equal to numbers testGetTypeUnderEquality( NUMBER_TYPE, OBJECT_TYPE, NUMBER_TYPE, OBJECT_TYPE); } public void testGetTypesUnderEquality3() { // null == undefined testGetTypeUnderEquality( NULL_TYPE, VOID_TYPE, NULL_TYPE, VOID_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderEquality4() { // (number,string) and number/string UnionType stringNumber = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE); testGetTypeUnderEquality( stringNumber, STRING_TYPE, stringNumber, STRING_TYPE); testGetTypeUnderEquality( stringNumber, NUMBER_TYPE, stringNumber, NUMBER_TYPE); } public void testGetTypesUnderEquality5() { // (number,null) and undefined JSType nullUndefined = createUnionType(VOID_TYPE, NULL_TYPE); testGetTypeUnderEquality( nullUndefined, NULL_TYPE, nullUndefined, NULL_TYPE); testGetTypeUnderEquality( nullUndefined, VOID_TYPE, nullUndefined, VOID_TYPE); } public void testGetTypesUnderEquality6() { // (number,undefined,null) == null JSType optNullNumber = createUnionType(VOID_TYPE, NULL_TYPE, NUMBER_TYPE); testGetTypeUnderEquality( optNullNumber, NULL_TYPE, createUnionType(NULL_TYPE, VOID_TYPE), NULL_TYPE); } private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq) { // creating the pairs TypePair p12 = t1.getTypesUnderEquality(t2); TypePair p21 = t2.getTypesUnderEquality(t1); // t1Eq assertTypeEquals(t1Eq, p12.typeA); assertTypeEquals(t1Eq, p21.typeB); // t2Eq assertTypeEquals(t2Eq, p12.typeB); assertTypeEquals(t2Eq, p21.typeA); } @SuppressWarnings("checked") public void testGetTypesUnderInequality1() { // objects can be not equal to numbers UnionType numberObject = (UnionType) createUnionType(NUMBER_TYPE, OBJECT_TYPE); testGetTypesUnderInequality( numberObject, NUMBER_TYPE, numberObject, NUMBER_TYPE); testGetTypesUnderInequality( numberObject, OBJECT_TYPE, numberObject, OBJECT_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality2() { // null == undefined UnionType nullUndefined = (UnionType) createUnionType(VOID_TYPE, NULL_TYPE); testGetTypesUnderInequality( nullUndefined, NULL_TYPE, NO_TYPE, NO_TYPE); testGetTypesUnderInequality( nullUndefined, VOID_TYPE, NO_TYPE, NO_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality3() { // (number,string) UnionType stringNumber = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE); testGetTypesUnderInequality( stringNumber, NUMBER_TYPE, stringNumber, NUMBER_TYPE); testGetTypesUnderInequality( stringNumber, STRING_TYPE, stringNumber, STRING_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception { // (number,undefined,null) and null UnionType nullableOptionalNumber = (UnionType) createUnionType(NULL_TYPE, VOID_TYPE, NUMBER_TYPE); testGetTypesUnderInequality( nullableOptionalNumber, NULL_TYPE, NUMBER_TYPE, NULL_TYPE); } private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq) { // creating the pairs TypePair p12 = t1.getTypesUnderInequality(t2); TypePair p21 = t2.getTypesUnderInequality(t1); // t1Eq assertTypeEquals(t1Eq, p12.typeA); assertTypeEquals(t1Eq, p21.typeB); // t2Eq assertTypeEquals(t2Eq, p12.typeB); assertTypeEquals(t2Eq, p21.typeA); } /** * Tests the factory method {@link JSTypeRegistry#createOptionalType(JSType)}. */ public void testCreateOptionalType() throws Exception { // number UnionType optNumber = (UnionType) registry.createOptionalType(NUMBER_TYPE); assertUnionContains(optNumber, NUMBER_TYPE); assertUnionContains(optNumber, VOID_TYPE); // union UnionType optUnion = (UnionType) registry.createOptionalType( createUnionType(STRING_OBJECT_TYPE, DATE_TYPE)); assertUnionContains(optUnion, DATE_TYPE); assertUnionContains(optUnion, STRING_OBJECT_TYPE); assertUnionContains(optUnion, VOID_TYPE); } public void assertUnionContains(UnionType union, JSType type) { assertTrue(union + " should contain " + type, union.contains(type)); } /** * Tests the factory method * {@link JSTypeRegistry#createAnonymousObjectType}}. */ public void testCreateAnonymousObjectType() throws Exception { // anonymous ObjectType anonymous = registry.createAnonymousObjectType(null); assertTypeEquals(OBJECT_TYPE, anonymous.getImplicitPrototype()); assertNull(anonymous.getReferenceName()); assertEquals("{}", anonymous.toString()); } /** * Tests the factory method * {@link JSTypeRegistry#createAnonymousObjectType}} and adds * some properties to it. */ public void testCreateAnonymousObjectType2() throws Exception { // anonymous ObjectType anonymous = registry.createAnonymousObjectType(null); anonymous.defineDeclaredProperty( "a", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "b", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "c", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "d", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "e", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "f", NUMBER_TYPE, null); assertEquals( LINE_JOINER.join( "{", " a: number,", " b: number,", " c: number,", " d: number,", " e: number,", " f: number", "}"), anonymous.toString()); } /** * Tests the factory method * {@link JSTypeRegistry#createObjectType(String, ObjectType)}}. */ public void testCreateObjectType() throws Exception { // simple ObjectType subDate = registry.createObjectType(null, DATE_TYPE.getImplicitPrototype()); assertTypeEquals(DATE_TYPE.getImplicitPrototype(), subDate.getImplicitPrototype()); assertNull(subDate.getReferenceName()); assertEquals("{...}", subDate.toString()); // name, node, prototype ObjectType subError = registry.createObjectType("Foo", ERROR_TYPE.getImplicitPrototype()); assertTypeEquals(ERROR_TYPE.getImplicitPrototype(), subError.getImplicitPrototype()); assertEquals("Foo", subError.getReferenceName()); } /** * Tests {@code (U2U_CONSTRUCTOR,undefined) <: (U2U_CONSTRUCTOR,undefined)}. */ @SuppressWarnings("checked") public void testBug903110() throws Exception { UnionType union = (UnionType) createUnionType(U2U_CONSTRUCTOR_TYPE, VOID_TYPE); assertTrue(VOID_TYPE.isSubtype(union)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(union)); assertTrue(union.isSubtype(union)); } /** * Tests {@code U2U_FUNCTION_TYPE <: U2U_CONSTRUCTOR} and * {@code U2U_FUNCTION_TYPE <: (U2U_CONSTRUCTOR,undefined)}. */ public void testBug904123() throws Exception { assertTrue(U2U_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_FUNCTION_TYPE. isSubtype(createOptionalType(U2U_CONSTRUCTOR_TYPE))); } /** * Assert that a type can assign to itself. */ private void assertTypeCanAssignToItself(JSType type) { assertTrue(type.isSubtype(type)); } /** * Tests that hasOwnProperty returns true when a property is defined directly * on a class and false if the property is defined on the supertype or not at * all. */ public void testHasOwnProperty() throws Exception { ObjectType sup = registry.createObjectType(null, registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(null, sup); sup.defineProperty("base", null, false, null); sub.defineProperty("sub", null, false, null); assertTrue(sup.hasProperty("base")); assertFalse(sup.hasProperty("sub")); assertTrue(sup.hasOwnProperty("base")); assertFalse(sup.hasOwnProperty("sub")); assertFalse(sup.hasOwnProperty("none")); assertTrue(sub.hasProperty("base")); assertTrue(sub.hasProperty("sub")); assertFalse(sub.hasOwnProperty("base")); assertTrue(sub.hasOwnProperty("sub")); assertFalse(sub.hasOwnProperty("none")); } public void testNamedTypeHasOwnProperty() throws Exception { namedGoogBar.getImplicitPrototype().defineProperty("base", null, false, null); namedGoogBar.defineProperty("sub", null, false, null); assertFalse(namedGoogBar.hasOwnProperty("base")); assertTrue(namedGoogBar.hasProperty("base")); assertTrue(namedGoogBar.hasOwnProperty("sub")); assertTrue(namedGoogBar.hasProperty("sub")); } public void testInterfaceHasOwnProperty() throws Exception { interfaceInstType.defineProperty("base", null, false, null); subInterfaceInstType.defineProperty("sub", null, false, null); assertTrue(interfaceInstType.hasProperty("base")); assertFalse(interfaceInstType.hasProperty("sub")); assertTrue(interfaceInstType.hasOwnProperty("base")); assertFalse(interfaceInstType.hasOwnProperty("sub")); assertFalse(interfaceInstType.hasOwnProperty("none")); assertTrue(subInterfaceInstType.hasProperty("base")); assertTrue(subInterfaceInstType.hasProperty("sub")); assertFalse(subInterfaceInstType.hasOwnProperty("base")); assertTrue(subInterfaceInstType.hasOwnProperty("sub")); assertFalse(subInterfaceInstType.hasOwnProperty("none")); } public void testGetPropertyNames() throws Exception { ObjectType sup = registry.createObjectType(null, registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(null, sup); sup.defineProperty("base", null, false, null); sub.defineProperty("sub", null, false, null); assertEquals(ImmutableSet.of("isPrototypeOf", "toLocaleString", "propertyIsEnumerable", "toString", "valueOf", "hasOwnProperty", "constructor", "base", "sub"), sub.getPropertyNames()); assertEquals(ImmutableSet.of("isPrototypeOf", "toLocaleString", "propertyIsEnumerable", "toString", "valueOf", "hasOwnProperty", "constructor", "base"), sup.getPropertyNames()); assertEquals(new HashSet<>(), NO_OBJECT_TYPE.getPropertyNames()); } public void testGetAndSetJSDocInfoWithNamedType() throws Exception { JSDocInfoBuilder builder = new JSDocInfoBuilder(false); builder.recordDeprecated(); JSDocInfo info = builder.build(); assertNull(namedGoogBar.getOwnPropertyJSDocInfo("X")); namedGoogBar.setPropertyJSDocInfo("X", info); assertTrue(namedGoogBar.getOwnPropertyJSDocInfo("X").isDeprecated()); assertPropertyTypeInferred(namedGoogBar, "X"); assertTypeEquals(UNKNOWN_TYPE, namedGoogBar.getPropertyType("X")); } public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception { ObjectType sup = registry.createObjectType(null, registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(null, sup); JSDocInfoBuilder builder = new JSDocInfoBuilder(false); builder.recordDeprecated(); JSDocInfo deprecated = builder.build(); builder = new JSDocInfoBuilder(false); builder.recordVisibility(Visibility.PRIVATE); JSDocInfo privateInfo = builder.build(); sup.defineProperty("X", NUMBER_TYPE, true, null); sup.setPropertyJSDocInfo("X", privateInfo); sub.defineProperty("X", NUMBER_TYPE, true, null); sub.setPropertyJSDocInfo("X", deprecated); assertFalse(sup.getOwnPropertyJSDocInfo("X").isDeprecated()); assertEquals(Visibility.PRIVATE, sup.getOwnPropertyJSDocInfo("X").getVisibility()); assertTypeEquals(NUMBER_TYPE, sup.getPropertyType("X")); assertTrue(sub.getOwnPropertyJSDocInfo("X").isDeprecated()); assertEquals(Visibility.INHERITED, sub.getOwnPropertyJSDocInfo("X").getVisibility()); assertTypeEquals(NUMBER_TYPE, sub.getPropertyType("X")); } public void testGetAndSetJSDocInfoWithNoType() throws Exception { JSDocInfoBuilder builder = new JSDocInfoBuilder(false); builder.recordDeprecated(); JSDocInfo deprecated = builder.build(); NO_TYPE.setPropertyJSDocInfo("X", deprecated); assertNull(NO_TYPE.getOwnPropertyJSDocInfo("X")); } public void testObjectGetSubTypes() throws Exception { assertTrue( containsType( OBJECT_FUNCTION_TYPE.getDirectSubTypes(), googBar)); assertTrue( containsType( googBar.getDirectSubTypes(), googSubBar)); assertFalse( containsType( googBar.getDirectSubTypes(), googSubSubBar)); assertFalse( containsType( googSubBar.getDirectSubTypes(), googSubBar)); assertTrue( containsType( googSubBar.getDirectSubTypes(), googSubSubBar)); } public void testImplementingType() throws Exception { assertTrue( containsType( registry.getDirectImplementors( interfaceType.getInstanceType()), googBar)); } public void testIsTemplatedType() throws Exception { assertTrue( new TemplateType(registry, "T") .hasAnyTemplateTypes()); assertFalse(ARRAY_TYPE.hasAnyTemplateTypes()); assertTrue( createTemplatizedType(ARRAY_TYPE, new TemplateType(registry, "T")) .hasAnyTemplateTypes()); assertFalse( createTemplatizedType(ARRAY_TYPE, STRING_TYPE).hasAnyTemplateTypes()); assertTrue( new FunctionBuilder(registry) .withReturnType(new TemplateType(registry, "T")) .build() .hasAnyTemplateTypes()); assertTrue( new FunctionBuilder(registry) .withTypeOfThis(new TemplateType(registry, "T")) .build() .hasAnyTemplateTypes()); assertFalse( new FunctionBuilder(registry) .withReturnType(STRING_TYPE) .build() .hasAnyTemplateTypes()); assertTrue( registry.createUnionType( NULL_TYPE, new TemplateType(registry, "T"), STRING_TYPE) .hasAnyTemplateTypes()); assertFalse( registry.createUnionType( NULL_TYPE, ARRAY_TYPE, STRING_TYPE) .hasAnyTemplateTypes()); } public void testTemplatizedType() throws Exception { FunctionType templatizedCtor = registry.createConstructorType( "TestingType", null, null, UNKNOWN_TYPE, ImmutableList.of(registry.createTemplateType("A"), registry.createTemplateType("B")), false); JSType templatizedInstance = registry.createTemplatizedType( templatizedCtor.getInstanceType(), ImmutableList.of(NUMBER_TYPE, STRING_TYPE)); TemplateTypeMap ctrTypeMap = templatizedCtor.getTemplateTypeMap(); TemplateType keyA = ctrTypeMap.getTemplateTypeKeyByName("A"); assertNotNull(keyA); TemplateType keyB = ctrTypeMap.getTemplateTypeKeyByName("B"); assertNotNull(keyB); TemplateType keyC = ctrTypeMap.getTemplateTypeKeyByName("C"); assertNull(keyC); TemplateType unknownKey = registry.createTemplateType("C"); TemplateTypeMap templateTypeMap = templatizedInstance.getTemplateTypeMap(); assertTrue(templateTypeMap.hasTemplateKey(keyA)); assertTrue(templateTypeMap.hasTemplateKey(keyB)); assertFalse(templateTypeMap.hasTemplateKey(unknownKey)); assertEquals(NUMBER_TYPE, templateTypeMap.getResolvedTemplateType(keyA)); assertEquals(STRING_TYPE, templateTypeMap.getResolvedTemplateType(keyB)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getResolvedTemplateType(unknownKey)); assertEquals("TestingType<number,string>", templatizedInstance.toString()); } public void testPartiallyTemplatizedType() throws Exception { FunctionType templatizedCtor = registry.createConstructorType( "TestingType", null, null, UNKNOWN_TYPE, ImmutableList.of(registry.createTemplateType("A"), registry.createTemplateType("B")), false); JSType templatizedInstance = registry.createTemplatizedType( templatizedCtor.getInstanceType(), ImmutableList.of(NUMBER_TYPE)); TemplateTypeMap ctrTypeMap = templatizedCtor.getTemplateTypeMap(); TemplateType keyA = ctrTypeMap.getTemplateTypeKeyByName("A"); assertNotNull(keyA); TemplateType keyB = ctrTypeMap.getTemplateTypeKeyByName("B"); assertNotNull(keyB); TemplateType keyC = ctrTypeMap.getTemplateTypeKeyByName("C"); assertNull(keyC); TemplateType unknownKey = registry.createTemplateType("C"); TemplateTypeMap templateTypeMap = templatizedInstance.getTemplateTypeMap(); assertTrue(templateTypeMap.hasTemplateKey(keyA)); assertTrue(templateTypeMap.hasTemplateKey(keyB)); assertFalse(templateTypeMap.hasTemplateKey(unknownKey)); assertEquals(NUMBER_TYPE, templateTypeMap.getResolvedTemplateType(keyA)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getResolvedTemplateType(keyB)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getResolvedTemplateType(unknownKey)); assertEquals("TestingType<number,?>", templatizedInstance.toString()); } public void testCanCastTo() { assertTrue(ALL_TYPE.canCastTo(NULL_TYPE)); assertTrue(ALL_TYPE.canCastTo(VOID_TYPE)); assertTrue(ALL_TYPE.canCastTo(STRING_TYPE)); assertTrue(ALL_TYPE.canCastTo(NUMBER_TYPE)); assertTrue(ALL_TYPE.canCastTo(BOOLEAN_TYPE)); assertTrue(ALL_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(NULL_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(VOID_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(STRING_TYPE)); assertTrue(NUMBER_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(STRING_TYPE.canCastTo(NULL_TYPE)); assertFalse(STRING_TYPE.canCastTo(VOID_TYPE)); assertTrue(STRING_TYPE.canCastTo(STRING_TYPE)); assertFalse(STRING_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(STRING_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(STRING_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(VOID_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(NUMBER_TYPE)); assertTrue(BOOLEAN_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(NULL_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(VOID_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(STRING_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(BOOLEAN_TYPE)); assertTrue(OBJECT_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(OBJECT_NUMBER_STRING)); assertFalse(OBJECT_NUMBER_STRING.canCastTo(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.canCastTo(U2U_FUNCTION_TYPE)); assertFalse(U2U_FUNCTION_TYPE.canCastTo(ARRAY_TYPE)); assertFalse(NULL_VOID.canCastTo(ARRAY_TYPE)); assertTrue(NULL_VOID.canCastTo(createUnionType(ARRAY_TYPE, NULL_TYPE))); // We currently allow any function to be cast to any other function type assertTrue(ARRAY_FUNCTION_TYPE.canCastTo(BOOLEAN_OBJECT_FUNCTION_TYPE)); } private static boolean containsType( Iterable<? extends TypeI> types, JSType type) { for (TypeI alt : types) { if (alt.equals(type)) { return true; } } return false; } private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB) { for (JSType alt : typeListA) { assertTrue( "List : " + typeListA + "\n" + "does not contain: " + alt, containsType(typeListA, alt)); } for (JSType alt : typeListB) { assertTrue( "List : " + typeListB + "\n" + "does not contain: " + alt, containsType(typeListB, alt)); } return false; } private ArrowType createArrowType(Node params) { return registry.createArrowType(params); } }
3e0069d7ae3801d0c02a1b6ec73e9da2006505ac
14,009
java
Java
enhanced/java/classlib/modules/swing/src/test/api/java.injected/javax/swing/border/MatteBorderTest.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
5
2017-03-08T20:32:39.000Z
2021-07-10T10:12:38.000Z
enhanced/java/classlib/modules/swing/src/test/api/java.injected/javax/swing/border/MatteBorderTest.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
1
2021-10-17T13:03:49.000Z
2021-10-17T13:03:49.000Z
enhanced/java/classlib/modules/swing/src/test/api/java.injected/javax/swing/border/MatteBorderTest.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
4
2015-07-07T07:06:59.000Z
2018-06-19T22:38:04.000Z
43.778125
95
0.62674
176
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Alexander T. Simbirtsev * Created on 03.12.2004 */ package javax.swing.border; import java.awt.Color; import java.awt.Insets; import java.awt.image.BufferedImage; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.SwingTestCase; public class MatteBorderTest extends SwingTestCase { public static void main(final String[] args) { junit.textui.TestRunner.run(MatteBorderTest.class); } /* * Class under test for void MatteBorder(Insets, Icon) */ public void testMatteBorderInsetsIcon() { Icon icon = new ImageIcon(new BufferedImage(20, 20, BufferedImage.TYPE_BYTE_GRAY)); int top = 100; int left = 200; int right = 300; int bottom = 400; MatteBorder border = new MatteBorder(new Insets(top, left, bottom, right), icon); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("icon value coinsides", icon, border.getTileIcon()); icon = new ImageIcon(new BufferedImage(30, 40, BufferedImage.TYPE_4BYTE_ABGR)); top = 200; left = 300; right = 200; bottom = 300; border = new MatteBorder(new Insets(top, left, bottom, right), icon); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("icon value coinsides", icon, border.getTileIcon()); } /* * Class under test for void MatteBorder(Insets, Color) */ public void testMatteBorderInsetsColor() { Color color = Color.RED; int top = 100; int left = 200; int right = 300; int bottom = 400; MatteBorder border = new MatteBorder(new Insets(top, left, bottom, right), color); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("color value coinsides", color, border.getMatteColor()); color = Color.YELLOW; top = 200; left = 300; right = 200; bottom = 300; border = new MatteBorder(new Insets(top, left, bottom, right), color); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("color value coinsides", color, border.getMatteColor()); } /* * Class under test for void MatteBorder(Icon) */ public void testMatteBorderIcon() { Icon icon = new ImageIcon(new BufferedImage(20, 20, BufferedImage.TYPE_BYTE_GRAY)); MatteBorder border = new MatteBorder(icon); Insets insets; assertEquals("icon value coinsides", icon, border.getTileIcon()); icon = new ImageIcon(new BufferedImage(30, 40, BufferedImage.TYPE_4BYTE_ABGR)); border = new MatteBorder(icon); assertEquals("icon value coinsides", icon, border.getTileIcon()); //Regression test for HARMONY-2589 border = new MatteBorder(null); insets = border.getBorderInsets(); assertEquals(-1, insets.top); assertEquals(-1, insets.bottom); assertEquals(-1, insets.left); assertEquals(-1, insets.right); } /* * Class under test for void MatteBorder(int, int, int, int, Icon) */ public void testMatteBorderintintintintIcon() { Icon icon = new ImageIcon(new BufferedImage(20, 20, BufferedImage.TYPE_BYTE_GRAY)); int top = 100; int left = 200; int right = 300; int bottom = 400; MatteBorder border = new MatteBorder(top, left, bottom, right, icon); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("icon value coinsides", icon, border.getTileIcon()); icon = new ImageIcon(new BufferedImage(30, 40, BufferedImage.TYPE_4BYTE_ABGR)); top = 200; left = 300; right = 200; bottom = 300; border = new MatteBorder(top, left, bottom, right, icon); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("icon value coinsides", icon, border.getTileIcon()); } /* * Class under test for void MatteBorder(int, int, int, int, Color) */ public void testMatteBorderintintintintColor() { Color color = Color.RED; int top = 100; int left = 200; int right = 300; int bottom = 400; MatteBorder border = new MatteBorder(top, left, bottom, right, color); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("color value coinsides", color, border.getMatteColor()); color = Color.YELLOW; top = 200; left = 300; right = 200; bottom = 300; border = new MatteBorder(top, left, bottom, right, color); assertEquals(border.getBorderInsets(), new Insets(top, left, bottom, right)); assertEquals("color value coinsides", color, border.getMatteColor()); } public void testPaintBorder() { // JPanel panel1 = new JPanel(); // JPanel panel2 = new JPanel(); // JPanel panel3 = new JPanel(); // // Color color1 = Color.GREEN; // Icon icon = null; // icon = new ImageIcon(DefaultMetalTheme.class.getResource("icons/Error.gif")); // Color shadowOuterColor = Color.BLACK; // Color highlightedInnerColor = Color.RED; // Color highlightedOuterColor = Color.BLUE; // // Border border1 = new MatteBorder(10, 20, 30, 50, color1); // Border border2 = new MatteBorder(10, 20, 30, 50, icon); // panel2.setBorder(border1); // panel3.setBorder(border2); // panel2.setPreferredSize(new Dimension(200, 150)); // panel3.setPreferredSize(new Dimension(200, 150)); // // panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS)); // panel1.add(panel2); // panel1.add(panel3); // // JFrame frame = new JFrame(); // frame.getContentPane().add(panel1); // frame.pack(); // frame.show(); // while(!frame.isActive()); // while(frame.isActive()); } public void testIsBorderOpaque() { int top = 100; int left = 200; int right = 300; int bottom = 400; Color color = Color.RED; MatteBorder border = new MatteBorder(top, left, bottom, right, color); assertTrue("MatteBorder without tiles is opaque", border.isBorderOpaque()); Icon icon = new ImageIcon(new BufferedImage(20, 20, BufferedImage.TYPE_BYTE_GRAY)); border = new MatteBorder(top, left, bottom, right, icon); assertFalse("MatteBorder with tiles is not opaque", border.isBorderOpaque()); } /* * Class under test for Insets getBorderInsets(Component, Insets) */ public void testGetBorderInsetsComponentInsets() { int top = 10; int left = 20; int right = 30; int bottom = 40; Icon icon = new ImageIcon(new BufferedImage(200, 200, BufferedImage.TYPE_BYTE_GRAY)); MatteBorder border = new MatteBorder(top, left, bottom, right, icon); Insets insets = new Insets(1, 1, 1, 1); JPanel panel = new JPanel(); border.getBorderInsets(panel, insets); assertEquals("insets values coinside", top, insets.top); assertEquals("insets values coinside", left, insets.left); assertEquals("insets values coinside", right, insets.right); assertEquals("insets values coinside", bottom, insets.bottom); panel.setBorder(new LineBorder(Color.black, 100)); border.getBorderInsets(panel, insets); assertEquals("insets values coinside", top, insets.top); assertEquals("insets values coinside", left, insets.left); assertEquals("insets values coinside", right, insets.right); assertEquals("insets values coinside", bottom, insets.bottom); insets = new Insets(2 * top, 2 * left, 2 * bottom, 2 * right); panel.setBorder(new BevelBorder(BevelBorder.LOWERED)); Insets newInsets = border.getBorderInsets(panel, insets); assertEquals("insets values coinside", top, newInsets.top); assertEquals("insets values coinside", left, newInsets.left); assertEquals("insets values coinside", right, newInsets.right); assertEquals("insets values coinside", bottom, newInsets.bottom); assertEquals("insets values coinside", top, insets.top); assertEquals("insets values coinside", left, insets.left); assertEquals("insets values coinside", right, insets.right); assertEquals("insets values coinside", bottom, insets.bottom); } /* * Class under test for Insets getBorderInsets(Component) */ public void testGetBorderInsetsComponent() { int top = 10; int left = 20; int right = 30; int bottom = 40; Icon icon = new ImageIcon(new BufferedImage(200, 200, BufferedImage.TYPE_BYTE_GRAY)); MatteBorder border = new MatteBorder(top, left, bottom, right, icon); Insets insets = new Insets(1, 1, 1, 1); JPanel panel = new JPanel(); border.getBorderInsets(panel, insets); assertEquals("insets values coinside", top, insets.top); assertEquals("insets values coinside", left, insets.left); assertEquals("insets values coinside", right, insets.right); assertEquals("insets values coinside", bottom, insets.bottom); panel.setBorder(new LineBorder(Color.black, 100)); insets = border.getBorderInsets(panel); assertEquals("insets values coinside", top, insets.top); assertEquals("insets values coinside", left, insets.left); assertEquals("insets values coinside", right, insets.right); assertEquals("insets values coinside", bottom, insets.bottom); insets = new Insets(2 * top, 2 * left, 2 * bottom, 2 * right); panel.setBorder(new EmptyBorder(insets)); insets = border.getBorderInsets(panel); assertEquals("insets values coinside", top, insets.top); assertEquals("insets values coinside", left, insets.left); assertEquals("insets values coinside", right, insets.right); assertEquals("insets values coinside", bottom, insets.bottom); } /* * Class under test for Insets getBorderInsets() */ public void testGetBorderInsets() { int top = 10; int left = 20; int right = 30; int bottom = 40; int tileHeight = 30; int tileWidth = 40; Color color = Color.RED; MatteBorder border = new MatteBorder(top, left, bottom, right, color); Icon icon = new ImageIcon(new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_BYTE_GRAY)); top = left = bottom = right = 30; border = new MatteBorder(top, left, bottom, right, icon); assertEquals("Insets coinside ", new Insets(top, left, bottom, right), border .getBorderInsets()); top = left = bottom = right = 10; border = new MatteBorder(top, left, bottom, right, icon); assertEquals("Insets coinside ", new Insets(top, left, bottom, right), border .getBorderInsets()); border = new MatteBorder(icon); assertEquals("Insets coinside ", new Insets(tileHeight, tileWidth, tileHeight, tileWidth), border.getBorderInsets()); top = left = bottom = right = 1; border = new MatteBorder(top, left, bottom, right, icon); assertEquals("Insets coinside ", new Insets(top, left, bottom, right), border .getBorderInsets()); top = left = bottom = right = 0; border = new MatteBorder(top, left, bottom, right, icon); assertEquals("Insets coinside ", new Insets(top, left, bottom, right), border .getBorderInsets()); } public void testGetTileIcon() { int top = 100; int left = 200; int right = 300; int bottom = 400; Color color = Color.RED; Icon icon = null; MatteBorder border = new MatteBorder(top, left, bottom, right, color); assertEquals("Icon coinsides", icon, border.getTileIcon()); icon = new ImageIcon(new BufferedImage(20, 20, BufferedImage.TYPE_BYTE_GRAY)); border = new MatteBorder(top, left, bottom, right, icon); assertEquals("Icon coinsides", icon, border.getTileIcon()); } public void testGetMatteColor() { int top = 100; int left = 200; int right = 300; int bottom = 400; Color color = Color.RED; MatteBorder border = new MatteBorder(top, left, bottom, right, color); assertEquals("Colors coinside ", color, border.getMatteColor()); color = Color.YELLOW; border = new MatteBorder(top, left, bottom, right, color); assertEquals("Colors coinside ", color, border.getMatteColor()); } }
3e006a4621f850eb653e4c2f22ac87bf96db03fa
1,709
java
Java
service/src/main/java/com/trihydro/cvpt/controller/MailController.java
Trihydro/cvrm
3446b3206fd0e9c21922201ec4fd7b18427a5b1c
[ "Apache-2.0" ]
3
2018-07-23T14:30:31.000Z
2019-03-25T22:39:58.000Z
service/src/main/java/com/trihydro/cvpt/controller/MailController.java
Trihydro/cvrm
3446b3206fd0e9c21922201ec4fd7b18427a5b1c
[ "Apache-2.0" ]
null
null
null
service/src/main/java/com/trihydro/cvpt/controller/MailController.java
Trihydro/cvrm
3446b3206fd0e9c21922201ec4fd7b18427a5b1c
[ "Apache-2.0" ]
1
2018-08-21T06:28:32.000Z
2018-08-21T06:28:32.000Z
40.690476
89
0.729081
177
/******************************************************************** * Copyright 2016 Trihydro * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************/ package com.trihydro.cvpt.controller; import org.springframework.web.bind.annotation.RestController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import javax.mail.MessagingException; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestBody; import com.trihydro.cvpt.model.Email; import com.trihydro.cvpt.model.service.EmailService; @CrossOrigin @RestController @RequestMapping("/cvpt") public class MailController{ @Autowired private EmailService emailService; @RequestMapping(method = RequestMethod.POST, value = "/sendEmail") public void sendMail(@RequestBody Email input) throws MessagingException { emailService.send(input.getTo(), input.getFrom(), input.getSubject(), input.getBody()); } }
3e006aa7e192c72aeabee24d10ee7df0e88d97fe
2,209
java
Java
src/main/java/com/jme3/shader/glsl/parser/ast/declaration/ExternalFieldDeclarationAstNode.java
JavaSaBr/ss-editor-shader-nodes
c11b5de260898057e5f5615c9ab54901635ab389
[ "Apache-2.0" ]
5
2018-04-24T07:14:45.000Z
2021-02-01T23:11:14.000Z
src/main/java/com/jme3/shader/glsl/parser/ast/declaration/ExternalFieldDeclarationAstNode.java
JavaSaBr/ss-editor-shader-nodes
c11b5de260898057e5f5615c9ab54901635ab389
[ "Apache-2.0" ]
null
null
null
src/main/java/com/jme3/shader/glsl/parser/ast/declaration/ExternalFieldDeclarationAstNode.java
JavaSaBr/ss-editor-shader-nodes
c11b5de260898057e5f5615c9ab54901635ab389
[ "Apache-2.0" ]
3
2018-04-24T07:14:48.000Z
2021-02-27T04:21:53.000Z
25.988235
89
0.60344
178
package com.jme3.shader.glsl.parser.ast.declaration; import static java.util.Arrays.asList; import java.util.HashSet; import java.util.Set; /** * The node to present an external field declaration in the code. * * @author JavaSaBr */ public class ExternalFieldDeclarationAstNode extends FieldDeclarationAstNode { public enum ExternalFieldType { UNIFORM("uniform"), ATTRIBUTE("attribute", "in"), VARYING("varying", "out"); private static final ExternalFieldType[] VALUES = values(); public static ExternalFieldType forKeyWord(final String keyword) { for (final ExternalFieldType fieldType : VALUES) { if (fieldType.keywords.contains(keyword)) { return fieldType; } } return null; } private Set<String> keywords; ExternalFieldType(final String... keywords) { this.keywords = new HashSet<>(asList(keywords)); } } /** * The field type. */ private ExternalFieldType fieldType; /** * Gets the field type. * * @return the field type. */ public ExternalFieldType getFieldType() { return fieldType; } /** * Sets the field type. * * @param fieldType the field type. */ public void setFieldType(final ExternalFieldType fieldType) { this.fieldType = fieldType; } @Override protected String getStringAttributes() { return getFieldType().name(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ExternalFieldDeclarationAstNode that = (ExternalFieldDeclarationAstNode) o; if (getFieldType() != that.getFieldType()) return false; if (!getType().equals(that.getType())) return false; return getName().equals(that.getName()); } @Override public int hashCode() { int result = getFieldType().hashCode(); result = 31 * result + getType().hashCode(); result = 31 * result + getName().hashCode(); return result; } }
3e006b66b1c95ef9ed7b6703dd04849961c62b7e
778
java
Java
Socket/SocketCDI11/src/fr/imie/LaucherClient.java
imie-source/CDI-N-11-SHARE
d13a7f86d511af1d83d93e7f4243ad9844ce891d
[ "MIT" ]
3
2015-11-03T13:32:51.000Z
2017-09-19T17:25:51.000Z
Socket/SocketCDI11/src/fr/imie/LaucherClient.java
imie-source/CDI-N-11-SHARE
d13a7f86d511af1d83d93e7f4243ad9844ce891d
[ "MIT" ]
null
null
null
Socket/SocketCDI11/src/fr/imie/LaucherClient.java
imie-source/CDI-N-11-SHARE
d13a7f86d511af1d83d93e7f4243ad9844ce891d
[ "MIT" ]
null
null
null
16.553191
63
0.602828
179
/** * */ package fr.imie; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; /** * @author imie * */ public class LaucherClient { /** * */ public LaucherClient() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { try (Socket socket = new Socket("192.168.1.97", 2042)) { String s = ""; PrintWriter out = new PrintWriter(socket.getOutputStream(), false); while (s.compareTo("STOP") != 0) { s= scanner.nextLine(); out.println(s); out.flush(); } System.out.println("fin saisie"); } } catch (IOException e) { e.printStackTrace(); } } }
3e006b690621e6fde3b2133c6c557797314612c6
2,179
java
Java
src/test/java/com/yunfeng/tools/phoneproxy/socket/Cert.java
liang47009/gameserver
b27e962bd1d0c8f70ca4802c16226fd2360d74a2
[ "MIT" ]
null
null
null
src/test/java/com/yunfeng/tools/phoneproxy/socket/Cert.java
liang47009/gameserver
b27e962bd1d0c8f70ca4802c16226fd2360d74a2
[ "MIT" ]
null
null
null
src/test/java/com/yunfeng/tools/phoneproxy/socket/Cert.java
liang47009/gameserver
b27e962bd1d0c8f70ca4802c16226fd2360d74a2
[ "MIT" ]
null
null
null
35.145161
99
0.61542
180
package com.yunfeng.tools.phoneproxy.socket; import com.yunfeng.CertTool; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.io.InputStream; import java.security.*; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; public class Cert { private static Map<String, X509Certificate> certCache = new HashMap<String, X509Certificate>(); private static String issuer = null; private static PrivateKey caPriKey = null; public static PrivateKey serverPriKey = null; private static PublicKey serverPubKey = null; static { try { Security.addProvider(new BouncyCastleProvider()); ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); // 读取CA证书使用者信息 issuer = CertUtil.getSubject(classLoader .getResourceAsStream("server.cer")); // CA私钥用于给动态生成的网站SSL证书签证 // caPriKey = CertUtil.loadPriKey(classLoader // .getResourceAsStream("server.bks")); KeyStore keystore = KeyStore.getInstance("BKS", "BC"); InputStream in = classLoader.getResourceAsStream("server.bks"); keystore.load(in, "a123456".toCharArray()); KeyPair caKeyPair = CertTool.getKeyPair(keystore, "server", "a123456".toCharArray()); caPriKey = caKeyPair.getPrivate(); // 生产一对随机公私钥用于网站SSL证书动态创建 KeyPair keyPair = CertUtil.genKeyPair(); serverPriKey = keyPair.getPrivate(); serverPubKey = keyPair.getPublic(); } catch (Exception e) { e.printStackTrace(); } } public static X509Certificate getCert(String host) throws Exception { X509Certificate cert = null; if (host != null) { String key = host.trim().toLowerCase(); if (certCache.containsKey(key)) { return certCache.get(key); } else { cert = CertUtil.genCert(issuer, serverPubKey, caPriKey, key); certCache.put(key, cert); } } return cert; } }
3e006c64c38121922e244c733df6a4d9b54283e6
890
java
Java
cache2k-core/src/main/java/org/cache2k/core/util/ScheduledClock.java
GiuseppeValente/MMQS
0635e68e3c994309d4df5ec5ac0fb48bd13a271c
[ "Apache-2.0" ]
null
null
null
cache2k-core/src/main/java/org/cache2k/core/util/ScheduledClock.java
GiuseppeValente/MMQS
0635e68e3c994309d4df5ec5ac0fb48bd13a271c
[ "Apache-2.0" ]
2
2020-12-24T01:32:59.000Z
2022-03-31T20:58:46.000Z
cache2k-core/src/main/java/org/cache2k/core/util/ScheduledClock.java
DonnySpace/AndiVirus
0635e68e3c994309d4df5ec5ac0fb48bd13a271c
[ "Apache-2.0" ]
null
null
null
24.054054
75
0.705618
181
package org.cache2k.core.util; /* * #%L * cache2k implementation * %% * Copyright (C) 2000 - 2019 headissue GmbH, Munich * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * @author Jens Wilke */ public interface ScheduledClock { boolean isJobSchedulable(); Job createJob(Runnable r); void schedule(Job j, long _millis); interface Job { } }
3e006d224305817322ba09e24e6f6c9cc9c439fa
1,952
java
Java
app/src/main/java/cn/msxf0/note/MarkDown.java
msxfXF/AndroidNote
57c51516393eb6677bf37f49745ca6fddd3e66d1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/msxf0/note/MarkDown.java
msxfXF/AndroidNote
57c51516393eb6677bf37f49745ca6fddd3e66d1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/msxf0/note/MarkDown.java
msxfXF/AndroidNote
57c51516393eb6677bf37f49745ca6fddd3e66d1
[ "Apache-2.0" ]
null
null
null
22.964706
142
0.625512
182
package cn.msxf0.note; import java.util.Date; /** *  * @author XiaoFei *  * @SchoolNum:B17070714  *  * @description:  *  * @date :19-10-26 上午10:38 *   */ public class MarkDown { private String author; private String author_face; private String background; private String content; private Date date; private String title; public MarkDown(String paramString1, String paramString2) { this.title = paramString1; this.content = paramString2; this.background = ""; this.date = new Date(); this.author = "匿名用户"; this.author_face = ""; } public MarkDown(String paramString1, String paramString2, String paramString3, Date paramDate, String paramString4, String paramString5) { this.title = paramString1; this.content = paramString2; this.background = paramString3; this.date = paramDate; this.author = paramString4; this.author_face = paramString5; } public String getAuthor() { return this.author; } public String getAuthor_face() { return this.author_face; } public String getBackground() { return this.background; } public String getContent() { return this.content; } public Date getDate() { return this.date; } public String getTitle() { return this.title; } public void setAuthor(String paramString) { this.author = paramString; } public void setAuthor_face(String paramString) { this.author_face = paramString; } public void setBackground(String paramString) { this.background = paramString; } public void setContent(String paramString) { this.content = paramString; } public void setDate(Date paramDate) { this.date = paramDate; } public void setTitle(String paramString) { this.title = paramString; } }
3e006d53cf017dceb89c9e6e790fe47c32f74f9a
4,206
java
Java
common/src/main/java/com/alchemiasoft/common/sync/BooksSyncService.java
SimoneCasagranda/android-wear-tutorial
aa35a8658d12c7ee1ddf12abfdcfab954dba839b
[ "Apache-2.0" ]
16
2015-02-01T13:43:28.000Z
2017-09-28T16:12:10.000Z
common/src/main/java/com/alchemiasoft/common/sync/BooksSyncService.java
SimoneCasagranda/android-wear-tutorial
aa35a8658d12c7ee1ddf12abfdcfab954dba839b
[ "Apache-2.0" ]
1
2015-02-20T09:39:18.000Z
2015-02-20T09:39:18.000Z
common/src/main/java/com/alchemiasoft/common/sync/BooksSyncService.java
SimoneCasagranda/android-wear-tutorial
aa35a8658d12c7ee1ddf12abfdcfab954dba839b
[ "Apache-2.0" ]
7
2015-01-29T01:40:50.000Z
2019-11-28T10:21:31.000Z
40.834951
125
0.655017
183
/* * Copyright 2015 Simone Casagranda. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alchemiasoft.common.sync; import android.text.TextUtils; import android.util.Log; import com.alchemiasoft.common.content.BookDB; import com.alchemiasoft.common.util.ArraysUtil; import com.alchemiasoft.common.util.WearableUtil; import com.google.android.gms.common.data.FreezableUtils; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Node; import com.google.android.gms.wearable.WearableListenerService; import java.util.List; /** * Service that allows the Google Play Services to bind to our application. * In this way it's possible to synchronize data between the handheld and wearable devices. * <p/> * Created by Simone Casagranda on 08/02/15. */ public class BooksSyncService extends WearableListenerService { /** * Tag used for logging. */ private static final String TAG_LOG = BooksSyncService.class.getSimpleName(); /** * The update has always to be performed if the content is old. */ private static final String WHERE_BEFORE = BookDB.Book.UPDATED_AT + " < ?"; @Override public void onDataChanged(DataEventBuffer dataEvents) { super.onDataChanged(dataEvents); Log.d(TAG_LOG, "onDataChanged(" + dataEvents + ")"); // Extracting the DataEvent(s). final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents); // Running through all the events for (DataEvent event : events) { if (event.getType() == DataEvent.TYPE_CHANGED) { // Checking if it's the same node that has fired the event final String node = event.getDataItem().getUri().getHost(); final String localNode = WearableUtil.getLocalNode(this).getId(); if (node.equals(localNode)) { Log.d(TAG_LOG, "Skipping Event because fired from the same receiver."); continue; } final Event.DataApi.Item item = Event.DataApi.Item.from(event.getDataItem()); String where = item.where(); String[] whereArgs = item.whereArgs(); // In a real application case you can create a builder for these kind of operations, // it definitely keeps the code cleaner, more readable and maintainable. if (TextUtils.isEmpty(where)) { where = WHERE_BEFORE; whereArgs = new String[]{String.valueOf(item.time())}; } else { where = "(" + where + ") AND " + WHERE_BEFORE; whereArgs = ArraysUtil.concatenate(whereArgs, new String[]{String.valueOf(item.time())}); } getContentResolver().update(item.uri(), item.values(), where, whereArgs); } } } @Override public void onMessageReceived(MessageEvent messageEvent) { super.onMessageReceived(messageEvent); Log.d(TAG_LOG, "onMessageReceived(id=" + messageEvent.getSourceNodeId() + " & path=" + messageEvent.getPath() + ")"); } @Override public void onPeerConnected(Node peer) { super.onPeerConnected(peer); Log.d(TAG_LOG, "onPeerConnected(peer=" + peer.getId() + "|" + peer.getDisplayName() + ")"); } @Override public void onPeerDisconnected(Node peer) { super.onPeerDisconnected(peer); Log.d(TAG_LOG, "onPeerDisconnected(peer=" + peer.getId() + "|" + peer.getDisplayName() + ")"); } }
3e006ef0702d069dfa787e297028982f3b568bf8
652
java
Java
src/main/java/svenhjol/charm/base/module/Debug.java
BardinTheDwarf/Charm
85b319f0cbea86efacf0d2c89e4d51b45eb063a5
[ "MIT" ]
null
null
null
src/main/java/svenhjol/charm/base/module/Debug.java
BardinTheDwarf/Charm
85b319f0cbea86efacf0d2c89e4d51b45eb063a5
[ "MIT" ]
null
null
null
src/main/java/svenhjol/charm/base/module/Debug.java
BardinTheDwarf/Charm
85b319f0cbea86efacf0d2c89e4d51b45eb063a5
[ "MIT" ]
null
null
null
38.352941
113
0.76227
184
package svenhjol.charm.base.module; import svenhjol.charm.Charm; import svenhjol.charm.base.CharmCategories; import svenhjol.meson.MesonModule; import svenhjol.meson.iface.Config; import svenhjol.meson.iface.Module; @Module(mod = Charm.MOD_ID, category = CharmCategories.CORE, hasSubscriptions = true, description = "Internal debugging tests for Charm.") public class Debug extends MesonModule { @Config(name = "Show debug messages", description = "If true, shows debug messages in the Minecraft log.\n" + "This applies to all Meson-based mods, e.g. Charm, Strange, Covalent.") public static boolean showDebugMessages = false; }
3e00712d2d001b71e0a8b85705e961f475e206d1
6,840
java
Java
waggle-dance-core/src/test/java/com/hotels/bdp/waggledance/client/CloseableThriftHiveMetastoreIfaceClientFactoryTest.java
groobyming/waggle-dance
2afb9d3843e23f247376101e22c31794bdd2af1d
[ "Apache-2.0" ]
null
null
null
waggle-dance-core/src/test/java/com/hotels/bdp/waggledance/client/CloseableThriftHiveMetastoreIfaceClientFactoryTest.java
groobyming/waggle-dance
2afb9d3843e23f247376101e22c31794bdd2af1d
[ "Apache-2.0" ]
null
null
null
waggle-dance-core/src/test/java/com/hotels/bdp/waggledance/client/CloseableThriftHiveMetastoreIfaceClientFactoryTest.java
groobyming/waggle-dance
2afb9d3843e23f247376101e22c31794bdd2af1d
[ "Apache-2.0" ]
null
null
null
49.565217
112
0.806579
185
/** * Copyright (C) 2016-2022 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hotels.bdp.waggledance.client; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.isA; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static com.hotels.bdp.waggledance.api.model.AbstractMetaStore.newFederatedInstance; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.amazonaws.glue.catalog.metastore.AWSCatalogMetastoreClient; import com.hotels.bdp.waggledance.api.model.AbstractMetaStore; import com.hotels.bdp.waggledance.api.model.FederatedMetaStore; import com.hotels.bdp.waggledance.api.model.GlueConfig; import com.hotels.bdp.waggledance.client.adapter.MetastoreIfaceAdapter; import com.hotels.bdp.waggledance.client.tunnelling.TunnelingMetaStoreClientFactory; import com.hotels.bdp.waggledance.conf.WaggleDanceConfiguration; import com.hotels.hcommon.hive.metastore.client.tunnelling.MetastoreTunnel; @RunWith(MockitoJUnitRunner.class) public class CloseableThriftHiveMetastoreIfaceClientFactoryTest { private static final String THRIFT_URI = "thrift://host:port"; private CloseableThriftHiveMetastoreIfaceClientFactory factory; private @Mock TunnelingMetaStoreClientFactory tunnelingMetaStoreClientFactory; private @Mock DefaultMetaStoreClientFactory defaultMetaStoreClientFactory; private @Mock GlueClientFactory glueClientFactory; private @Mock WaggleDanceConfiguration waggleDanceConfiguration; private final Map<String, String> configurationProperties = new HashMap<>(); private @Mock AWSCatalogMetastoreClient glueClient; @Before public void setUp() { configurationProperties.put(ConfVars.METASTORETHRIFTCONNECTIONRETRIES.varname, "5"); configurationProperties.put(ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT.varname, "6"); configurationProperties.put(ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY.varname, "5"); configurationProperties.put(ConfVars.METASTORE_USE_THRIFT_FRAMED_TRANSPORT.varname, "true"); configurationProperties.put(ConfVars.METASTORE_USE_THRIFT_COMPACT_PROTOCOL.varname, "false"); when(waggleDanceConfiguration.getConfigurationProperties()).thenReturn(configurationProperties); factory = new CloseableThriftHiveMetastoreIfaceClientFactory(tunnelingMetaStoreClientFactory, defaultMetaStoreClientFactory, glueClientFactory, waggleDanceConfiguration); } @Test public void defaultFactory() { ArgumentCaptor<HiveConf> hiveConfCaptor = ArgumentCaptor.forClass(HiveConf.class); factory.newInstance(newFederatedInstance("fed1", THRIFT_URI)); verify(defaultMetaStoreClientFactory) .newInstance(hiveConfCaptor.capture(), eq("waggledance-fed1"), eq(3), eq(2000)); verifyNoInteractions(tunnelingMetaStoreClientFactory); HiveConf hiveConf = hiveConfCaptor.getValue(); assertThat(hiveConf.getVar(ConfVars.METASTOREURIS), is(THRIFT_URI)); assertThat(hiveConf.getIntVar(ConfVars.METASTORETHRIFTCONNECTIONRETRIES), is(5)); assertThat(hiveConf.getTimeVar(ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS), is(6000L)); assertThat(hiveConf.getTimeVar(ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY, TimeUnit.SECONDS), is(5L)); assertThat(hiveConf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_FRAMED_TRANSPORT), is(true)); assertThat(hiveConf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_COMPACT_PROTOCOL), is(false)); } @Test public void tunnelingFactory() { MetastoreTunnel metastoreTunnel = new MetastoreTunnel(); metastoreTunnel.setLocalhost("local-machine"); metastoreTunnel.setPort(2222); metastoreTunnel.setRoute("a -> b -> c"); metastoreTunnel.setKnownHosts("knownHosts"); metastoreTunnel.setPrivateKeys("privateKeys"); metastoreTunnel.setTimeout(123); AbstractMetaStore federatedMetaStore = newFederatedInstance("fed1", THRIFT_URI); federatedMetaStore.setMetastoreTunnel(metastoreTunnel); factory.newInstance(federatedMetaStore); verify(tunnelingMetaStoreClientFactory) .newInstance(THRIFT_URI, metastoreTunnel, "fed1", 3, 2000, configurationProperties); verifyNoInteractions(defaultMetaStoreClientFactory); } @Test public void glueFactory() throws Exception { ArgumentCaptor<HiveConf> hiveConfCaptor = ArgumentCaptor.forClass(HiveConf.class); FederatedMetaStore federatedMetaStore = new FederatedMetaStore("fedGlue", null); GlueConfig glueConfig = new GlueConfig(); String glueAccountId = "123456789012"; glueConfig.setGlueAccountId(glueAccountId); String glueEndpoint = "glue.us-east-1.amazonaws.com"; glueConfig.setGlueEndpoint(glueEndpoint); federatedMetaStore.setGlueConfig(glueConfig); when(glueClientFactory.newInstance(hiveConfCaptor.capture(), eq(null))).thenReturn(glueClient); CloseableThriftHiveMetastoreIface newInstance = factory.newInstance(federatedMetaStore); assertThat(newInstance, isA(MetastoreIfaceAdapter.class)); verifyNoInteractions(tunnelingMetaStoreClientFactory, defaultMetaStoreClientFactory); HiveConf hiveConf = hiveConfCaptor.getValue(); assertThat(hiveConf.get("hive.metastore.glue.catalogid"), is(glueAccountId)); assertThat(hiveConf.get("aws.glue.endpoint"), is(glueEndpoint)); assertThat(hiveConf.getVar(ConfVars.METASTOREURIS), is("")); assertThat(hiveConf.getIntVar(ConfVars.METASTORETHRIFTCONNECTIONRETRIES), is(5)); assertThat(hiveConf.getTimeVar(ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS), is(6000L)); assertThat(hiveConf.getTimeVar(ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY, TimeUnit.SECONDS), is(5L)); assertThat(hiveConf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_FRAMED_TRANSPORT), is(true)); assertThat(hiveConf.getBoolVar(ConfVars.METASTORE_USE_THRIFT_COMPACT_PROTOCOL), is(false)); } }
3e00722558cda524dd5ee2d6e81a13d25063a63a
489
java
Java
src/headfirst/factory/simplefactory/PepperoniPizza.java
4amup/head-first-design-pattern
a8b745c8250a236a2d59b9e83138a5965b413c84
[ "MIT" ]
null
null
null
src/headfirst/factory/simplefactory/PepperoniPizza.java
4amup/head-first-design-pattern
a8b745c8250a236a2d59b9e83138a5965b413c84
[ "MIT" ]
null
null
null
src/headfirst/factory/simplefactory/PepperoniPizza.java
4amup/head-first-design-pattern
a8b745c8250a236a2d59b9e83138a5965b413c84
[ "MIT" ]
null
null
null
13.971429
43
0.697342
186
package headfirst.factory.simplefactory; public class PepperoniPizza extends Pizza { public PepperoniPizza(String name) { super(name); // TODO Auto-generated constructor stub } @Override public void prepare() { // TODO Auto-generated method stub } @Override public void bake() { // TODO Auto-generated method stub } @Override public void cut() { // TODO Auto-generated method stub } @Override public void box() { // TODO Auto-generated method stub } }
3e00729eda22b6a44e32273283e163bca9f6f8cc
1,091
java
Java
tests/DataOutputStream/Test.java
FloflisPull/js2me
134398dd2782540c98cd427e49ed02b6828b817d
[ "MIT" ]
64
2015-01-16T17:56:30.000Z
2022-03-26T20:21:52.000Z
tests/DataOutputStream/Test.java
FloflisPull/js2me
134398dd2782540c98cd427e49ed02b6828b817d
[ "MIT" ]
11
2017-09-26T20:31:24.000Z
2022-03-31T19:57:28.000Z
tests/DataOutputStream/Test.java
FloflisPull/js2me
134398dd2782540c98cd427e49ed02b6828b817d
[ "MIT" ]
17
2015-01-16T17:57:32.000Z
2022-03-26T20:22:37.000Z
26.609756
111
0.571036
187
import java.io.*; public class Test extends TestMidlet { public void startApp() { try { byte[] input = {-2, 54, -2, -2, 1, 0, -128, 1, 91, -64, 0x0C, 0x7A, -31, 0x47, -82, 0x14, 0x7B, 0x41, 0x09, 0x1d, 0x25, 122, 121, 0, 120, -1, -7, 0x51, 0x54, -1, -1, -1, -1, -1, -7, 0x51, 0x54, -14, 0x16, 0, 10, -59, -101, 99, 105, -61, -77, -59, -126, 107, 97}; ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream s = new DataOutputStream(out); s.write(254); byte[] bb = {54, -2}; s.write(bb); s.write(bb, 1, 1); s.writeBoolean(true); s.writeBoolean(false); s.writeByte(-128); s.writeChar('ś'); s.writeDouble(-3.56); s.writeFloat(8.569615f); s.writeChars("穹x"); s.writeInt(-437932); s.writeLong(-437932l); s.writeShort(-3562); s.writeUTF("ściółka"); s.flush(); bb = out.toByteArray(); compare(bb.length, input.length); for (int i = 0; i < bb.length; i++) { compare(bb[i], input[i]); } s.close(); } catch (Exception e) { e.printStackTrace(); check(false); } finish(); } }
3e0072c22d700cda6d9cf12a13b2eff6e598b287
9,031
java
Java
store/count-db/src/main/java/sn/analytics/data/store/UniqueUsersDbStoreV2.java
sumanthn/rocks-db-ops
a0383f331f3ae15e25d1f64610d7d63dfbc3bb73
[ "Apache-2.0" ]
1
2021-09-09T14:08:30.000Z
2021-09-09T14:08:30.000Z
store/count-db/src/main/java/sn/analytics/data/store/UniqueUsersDbStoreV2.java
sumanthn/rocks-db-ops
a0383f331f3ae15e25d1f64610d7d63dfbc3bb73
[ "Apache-2.0" ]
null
null
null
store/count-db/src/main/java/sn/analytics/data/store/UniqueUsersDbStoreV2.java
sumanthn/rocks-db-ops
a0383f331f3ae15e25d1f64610d7d63dfbc3bb73
[ "Apache-2.0" ]
null
null
null
33.080586
129
0.565386
188
package sn.analytics.data.store; import com.clearspring.analytics.stream.cardinality.HyperLogLog; import com.clearspring.analytics.stream.cardinality.ICardinality; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.hash.Hashing; import com.sangupta.murmur.Murmur3; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.nio.charset.StandardCharsets; import java.util.*; /** * Store unique users per day * Class Db.class has all RocksDB ops, this manages sharding & HLL ops * Data model: * K=day V=HLL, * each batch of records are not updated once written instead they are merged upon reading * So K is suffixed with randomId * Sharded by K */ public class UniqueUsersDbStoreV2 { private static final Logger logger = LogManager.getLogger(UniqueUsersDbStoreV2.class); private static final UniqueUsersDbStoreV2 _instance = new UniqueUsersDbStoreV2(); private UniqueUsersDbStoreV2(){} public static UniqueUsersDbStoreV2 getInstance(){return _instance;} private String dbPath="/tmp"; private int maxInstances=8; private boolean isReadOnly=false; private Map<Integer,Db> dbShardColl; private static final int _seed=299_792_458; private static final int _hllBits = 16; static final String recSep = "~"; /** init with base path & max instances*/ public synchronized void init(final String dbPath, final int maxInstances){ init(dbPath,maxInstances,false); } /** init read-only instance*/ public synchronized void init(final String dbPath, final int maxInstances,final boolean readOnly){ this.dbPath=dbPath; this.maxInstances=maxInstances; this.isReadOnly=readOnly; initDbShards(); } public void initDbShards(){ Map<Integer,Db> dbshards= new HashMap<>(maxInstances); for(int i =0;i < maxInstances;i++){ try{ Db db = new Db(dbPath,i,isReadOnly); dbshards.put(i,db); }catch (Exception e){ logger.error("Error in initializing Db shards {}",i); throw new RuntimeException("Error in initializing DB shard {}"); } } dbShardColl = ImmutableMap.copyOf(dbshards); logger.info("initialized db shards {} DB path {}", dbPath,maxInstances); } //shard based on hashing public int getInstanceSlot(final String str){ return Hashing.consistentHash( Murmur3.hash_x64_128(str.getBytes(), str.getBytes().length, _seed)[0] >>> 1,maxInstances); } public int getInstanceSlot(final byte [] b){ return Hashing.consistentHash( Murmur3.hash_x64_128(b, b.length, _seed)[0] >>> 1,maxInstances); } private final String getRandomSuffix(){ return UUID.randomUUID().toString().replaceAll("-",""); } //DB ops public void addRecord(final String k, final String v) { int instanceSlot = getInstanceSlot(k); Db db = dbShardColl.get(instanceSlot); if (db!=null){ String key = k+recSep+getRandomSuffix(); try { db.addRecord(key, v); }catch (Exception e){ logger.error("Exception in adding record {} {}",k,e); } } } public void addRecord(final String k, final byte[] v) { int instanceSlot = getInstanceSlot(k); Db db = dbShardColl.get(instanceSlot); if (db!=null){ String key = k+recSep+getRandomSuffix(); try { db.addRecord(key.getBytes(StandardCharsets.UTF_8), v); }catch (Exception e){ e.printStackTrace(); logger.error("Exception in adding record {} ,{}",k,e); } } } public byte[] getRecord(final String k){ int instanceSlot = getInstanceSlot(k); Db db = dbShardColl.get(instanceSlot); if (db!=null){ try { return db.getRecord(k); }catch (Exception e){ logger.error("Exception in fetching record {} ,{}",k,e); e.printStackTrace(); } } return null; } public Set<byte[]> getRecordPrefixed(final String k){ int instanceSlot = getInstanceSlot(k); Db db = dbShardColl.get(instanceSlot); if (db!=null){ try { return db.fetchRecordsBulk(k); }catch (Exception e){ logger.error("Exception in fetching record {} ,{}",k,e); e.printStackTrace(); } } return null; } public byte[] getRecord(final String prefix, final String k){ int instanceSlot = getInstanceSlot(prefix); Db db = dbShardColl.get(instanceSlot); if (db!=null){ try { return db.getRecord(k); }catch (Exception e){ e.printStackTrace(); } } return null; } public void addRecord(final String prefix, final String key , final byte [] v){ int instanceSlot = getInstanceSlot(prefix); //find the db and insert into right DB Db db = dbShardColl.get(instanceSlot); if (db!=null) { db.addRecord(key.getBytes(StandardCharsets.UTF_8), v); } } public void close(){ try { dbShardColl.values().forEach(Db::close); }catch (Exception e){ logger.error("error in closing instances ",e); } } //HLL Ops /** Add users set day format yyyyMMdd with a suffix.can add multiple batches without overwriting keys*/ public void addUniqueUsers(final String day, Set<Long> usersSet){ Preconditions.checkArgument(day!=null,"Day cannot be null"); Preconditions.checkArgument(usersSet!=null,"users set cannot be null"); //Preconditions.checkArgument(!usersSet.isEmpty(),"Users set empty"); //make it HLL and persist based on key try { HyperLogLog hll = HyperLogLog.Builder.withLog2m(_hllBits).build(); //offer would hash the data as required usersSet.forEach(hll::offer); if (logger.isDebugEnabled()) logger.debug("insert hll {} set size {}, hll cardinality {} ",day,usersSet.size(),hll.cardinality()); addRecord(day,hll.getBytes()); }catch (Exception e){ logger.error("error in insert record {} day",day,e); } } public Long getUniqueUserCount(final String day){ Preconditions.checkArgument(day!=null,"Day cannot be null"); try{ Set<byte[]> userRecords = getRecordPrefixed(day); if (userRecords!=null){ if (!userRecords.isEmpty()) { HyperLogLog hllSrc = HyperLogLog.Builder.withLog2m(16).build(); HyperLogLog[] hllArr = new HyperLogLog[userRecords.size()]; int i=0; for(byte [] b: userRecords){ hllArr[i++] =HyperLogLog.Builder.build(b); } ICardinality hllMerged = hllSrc.merge(hllArr); return hllMerged.cardinality(); } } }catch (Exception e){ logger.error("error in fetching HLL records from store ",e); } return 0L; } public Long getUniqueUserCount(final String ... days){ Preconditions.checkArgument(days!=null,"Day cannot be null"); List<HyperLogLog> hllColl = new ArrayList<>(); try{ for(String day : days) { Set<byte[]> userRecords = getRecordPrefixed(day); if (userRecords != null) { userRecords.forEach(hllPart->{ try { HyperLogLog hll = HyperLogLog.Builder.build(hllPart); if (logger.isDebugEnabled()) { logger.debug("fetched {} cardinality {} ", day, hll.cardinality()); } if (hll != null) { hllColl.add(hll); } }catch (Exception e){ logger.error("error in adding HLL ",e); } }); } } if (!hllColl.isEmpty()) { HyperLogLog hllSrc = HyperLogLog.Builder.withLog2m(16).build(); HyperLogLog[] hllArr = new HyperLogLog[hllColl.size()]; hllColl.toArray(hllArr); ICardinality hllMerged = hllSrc.merge(hllArr); return hllMerged.cardinality(); } }catch (Exception e){ logger.error("error in fetching HLL / merging ",e); } return 0L; } }
3e0073beccdfec60fff580463d390558d6afdee0
1,316
java
Java
vespajlib/src/main/java/com/yahoo/slime/ObjectInserter.java
t1707/vespa
9f4859e9996ac9913ce80ed9b209f683507fe157
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
vespajlib/src/main/java/com/yahoo/slime/ObjectInserter.java
t1707/vespa
9f4859e9996ac9913ce80ed9b209f683507fe157
[ "Apache-2.0" ]
1
2021-03-31T22:27:25.000Z
2021-03-31T22:27:25.000Z
vespajlib/src/main/java/com/yahoo/slime/ObjectInserter.java
t1707/vespa
9f4859e9996ac9913ce80ed9b209f683507fe157
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
50.615385
118
0.699088
189
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.slime; /** * Helper class for inserting values into an ObjectValue. * For justification read Inserter documentation. **/ final class ObjectInserter implements Inserter { private Cursor target; private int symbol; public final ObjectInserter adjust(Cursor c, int sym) { target = c; symbol = sym; return this; } public final Cursor insertNIX() { return target.setNix(symbol); } public final Cursor insertBOOL(boolean value) { return target.setBool(symbol, value); } public final Cursor insertLONG(long value) { return target.setLong(symbol, value); } public final Cursor insertDOUBLE(double value) { return target.setDouble(symbol, value); } public final Cursor insertSTRING(String value) { return target.setString(symbol, value); } public final Cursor insertSTRING(byte[] utf8) { return target.setString(symbol, utf8); } public final Cursor insertDATA(byte[] value) { return target.setData(symbol, value); } public final Cursor insertARRAY() { return target.setArray(symbol); } public final Cursor insertOBJECT() { return target.setObject(symbol); } }
3e0073d5ed047118ee6bfa624a76fe0df325ddcd
1,032
java
Java
src/main/java/com/stackify/metric/aop/Counter.java
stackify/stackify-metrics-aspectj
ee338355de5e7a70b7e3a4a845b366e5b4919659
[ "Apache-2.0" ]
1
2017-07-06T15:07:55.000Z
2017-07-06T15:07:55.000Z
src/main/java/com/stackify/metric/aop/Counter.java
stackify/stackify-metrics-aspectj
ee338355de5e7a70b7e3a4a845b366e5b4919659
[ "Apache-2.0" ]
null
null
null
src/main/java/com/stackify/metric/aop/Counter.java
stackify/stackify-metrics-aspectj
ee338355de5e7a70b7e3a4a845b366e5b4919659
[ "Apache-2.0" ]
1
2021-01-31T04:31:44.000Z
2021-01-31T04:31:44.000Z
25.170732
75
0.736434
190
/* * Copyright 2014 Stackify * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stackify.metric.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Counter * @author Eric Martin */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Counter { /** * @return Metric category */ String category(); /** * @return Metric name */ String name(); }
3e007423468b11aef9cd0b6018a3153342863721
3,495
java
Java
adaptor/sources/cis-adaptor-connector-rest-template/src/impl/java/com/frequentis/cis/connector/rest/CoreRESTSender.java
DRIVER-EU/CommonInformationSpace
dad119c57c03fe0872bcb20e6602d1623fc8b06f
[ "MIT" ]
1
2017-11-08T09:09:42.000Z
2017-11-08T09:09:42.000Z
adaptor/sources/cis-adaptor-connector-rest-template/src/impl/java/com/frequentis/cis/connector/rest/CoreRESTSender.java
DRIVER-EU/CommonInformationSpace
dad119c57c03fe0872bcb20e6602d1623fc8b06f
[ "MIT" ]
null
null
null
adaptor/sources/cis-adaptor-connector-rest-template/src/impl/java/com/frequentis/cis/connector/rest/CoreRESTSender.java
DRIVER-EU/CommonInformationSpace
dad119c57c03fe0872bcb20e6602d1623fc8b06f
[ "MIT" ]
null
null
null
36.40625
170
0.726466
191
package com.frequentis.cis.connector.rest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import org.apache.log4j.Logger; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.frequentis.cis.core.edxlde.parameters.DEParameters; import com.frequentis.cis.core.payload.CISPayload; import com.frequentis.cis.core.payload.objects.CISOtherContent; import com.frequentis.cis.core.payload.objects.CISXMLContent; import com.frequentis.cis.core.properties.PropertiesReader; import com.frequentis.cis.core.rest.OtherContentNotify; import com.frequentis.cis.core.rest.XMLContentNotify; import com.frequentis.cis.exception.communication.CISCommunicationException; import com.frequentis.cis.exception.invalid.xml.CISInvalidXMLObject; public class CoreRESTSender { private Logger log = Logger.getLogger(this.getClass()); private String coreEndpointUrl = PropertiesReader.getInstance().getPropertie("core.rest.endpoint"); public CoreRESTSender() { log.info("--> CoreRESTSender"); } public void notify(String msgType, CISPayload msg, Map<DEParameters, String> deParameters, boolean dontEnvelope) throws CISInvalidXMLObject, CISCommunicationException { log.info("--> notify"); ObjectMapper mapper = new ObjectMapper(); String response = null; try { if (msg instanceof CISXMLContent) { CISXMLContent xmlPayload = (CISXMLContent)msg; XMLContentNotify xmlNotify = new XMLContentNotify(msgType, xmlPayload, deParameters, dontEnvelope); response = postHTTPRequest(coreEndpointUrl + "/CISCore/sendXMLMessage","application/json",mapper.writeValueAsString(xmlNotify)); } else if (msg instanceof CISOtherContent) { CISOtherContent otherPayload = (CISOtherContent)msg; OtherContentNotify otherNotify = new OtherContentNotify(msgType, otherPayload, deParameters, dontEnvelope); response = postHTTPRequest(coreEndpointUrl + "/CISCore/sendOtherMessage","application/json",mapper.writeValueAsString(otherNotify)); } } catch (JsonProcessingException e1) { log.error("Error parsing Notify Information!", e1); } log.info("notify -->"); } private String postHTTPRequest(String url, String contentType, String msgParam) { log.info("--> postHTTPRequest"); log.debug("url: " + url + ", contentType: " + contentType + ", msgParam: " + msgParam); String response = null; try { HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", contentType); if (msgParam != null) { byte[] postDataBytes = msgParam.getBytes("UTF-8"); connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); connection.getOutputStream().write(postDataBytes); } String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = ""; while ((line = reader.readLine()) != null) { response += line; } reader.close(); log.debug("sendMessage: " + response); } catch (Exception e) { log.error("Error distributing the Message!", e); response = null; } return response; } }
3e007444d34da2ef6f3d078a5a22fd97d4ea14f1
6,202
java
Java
ah_database/app/src/main/java/ese/database/MainActivity.java
eggeral/android-examples
87e788a338627a5a22b6eaf7e09423887c4dc344
[ "Apache-2.0" ]
null
null
null
ah_database/app/src/main/java/ese/database/MainActivity.java
eggeral/android-examples
87e788a338627a5a22b6eaf7e09423887c4dc344
[ "Apache-2.0" ]
null
null
null
ah_database/app/src/main/java/ese/database/MainActivity.java
eggeral/android-examples
87e788a338627a5a22b6eaf7e09423887c4dc344
[ "Apache-2.0" ]
null
null
null
41.905405
119
0.614318
192
package ese.database; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import ese.database.BookStoreContract.BookTable; public class MainActivity extends AppCompatActivity { private static String TAG = "ese.database"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // == 01 create contract class BookStoreContract // == 02 create SqlOpenHelper BookStoreDbOpenHelper dbHelper = new BookStoreDbOpenHelper(this); // == 03 write some data // This is long running and should be done in the background SQLiteDatabase dbWriter = dbHelper.getWritableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(BookTable.COLUMN_NAME_TITLE, "Lord of the Rings - The Fellowship of the Ring"); values.put(BookTable.COLUMN_NAME_AUTHOR, "J. R. R. Tolkien"); values.put(BookTable.COLUMN_NAME_ISBN, "12345678"); // Insert the new row, returning the primary key value of the new row long newRowId = dbWriter.insert(BookTable.TABLE_NAME, null, values); values = new ContentValues(); values.put(BookTable.COLUMN_NAME_TITLE, "The Hitchhiker's Guide to the Galaxy"); values.put(BookTable.COLUMN_NAME_AUTHOR, "Douglas Adams"); values.put(BookTable.COLUMN_NAME_ISBN, "0909090909"); newRowId = dbWriter.insert(BookTable.TABLE_NAME, null, values); dbWriter.close(); // Keep around the dbWriter instance as long as possible. Do this in onDestroy() // == 04 read the data again SQLiteDatabase dbReader = dbHelper.getReadableDatabase(); String[] projection = { BookTable._ID, BookTable.COLUMN_NAME_TITLE, BookTable.COLUMN_NAME_AUTHOR, BookTable.COLUMN_NAME_ISBN }; String selection = BookTable.COLUMN_NAME_TITLE + " = ?"; String[] selectionArgs = {"The Hitchhiker's Guide to the Galaxy"}; // How you want the results sorted in the resulting Cursor String sortOrder = BookTable.COLUMN_NAME_TITLE + " DESC"; Cursor cursor = dbReader.query( BookTable.TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder // The sort order ); final List<Map<String, Object>> books = new ArrayList<>(); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndexOrThrow(BookTable._ID)); String title = cursor.getString(cursor.getColumnIndexOrThrow(BookTable.COLUMN_NAME_TITLE)); String author = cursor.getString(cursor.getColumnIndexOrThrow(BookTable.COLUMN_NAME_AUTHOR)); String isbn = cursor.getString(cursor.getColumnIndexOrThrow(BookTable.COLUMN_NAME_ISBN)); Map<String, Object> data = new HashMap<>(); data.put(BookTable._ID, id); data.put(BookTable.COLUMN_NAME_TITLE, title); data.put(BookTable.COLUMN_NAME_AUTHOR, author); data.put(BookTable.COLUMN_NAME_ISBN, isbn); books.add(data); Log.i(TAG, "onCreate: " + title); } cursor.close(); dbReader.close(); // == 05 delete entries // dbWriter = dbHelper.getWritableDatabase(); // selection = BookTable.COLUMN_NAME_TITLE + " LIKE ?"; // selectionArgs = new String[]{"The%"}; // dbWriter.delete(BookTable.TABLE_NAME, selection, selectionArgs); // // // == 06 update entries // dbWriter = dbHelper.getWritableDatabase(); // // values = new ContentValues(); // values.put(BookTable.COLUMN_NAME_TITLE, "Updated Title"); // // selection = BookTable.COLUMN_NAME_TITLE + " LIKE ?"; // selectionArgs = new String[]{"Lord%"}; // // int count = dbWriter.update( // BookTable.TABLE_NAME, // values, // selection, // selectionArgs); // Log.i(TAG, "onCreate: Updated items:" + count); // == 07 show items in a list // add list to layout String[] fromColumns = {BookTable.COLUMN_NAME_TITLE, BookTable.COLUMN_NAME_AUTHOR, BookTable.COLUMN_NAME_ISBN}; int[] toViews = {android.R.id.text1, android.R.id.text2, android.R.id.text2}; ListView bookList = (ListView) findViewById(R.id.bookList); ListAdapter adapter = new SimpleAdapter( this, books, android.R.layout.simple_list_item_1, fromColumns, toViews ); bookList.setAdapter(adapter); bookList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i(TAG, "onItemClick: position: " + position + ", id: " + id); Log.i(TAG, "onItemClick: book selected has database id: " + books.get(position).get(BookTable._ID)); } }); // Example: Create a simple shopping list (special task; add images to the items) } }
3e0074adf5fb95d312b63f3d85e14867d13d38f2
618
java
Java
exs/mundo_1/java/024.java
Coding-in-community/exercicios-CeV
282e76d202342eb988de89d665ca80d43c9f0e1f
[ "MIT" ]
45
2021-01-02T18:36:01.000Z
2022-03-26T19:46:47.000Z
exs/mundo_1/java/024.java
LeonardoCruzx/exercicios-CeV
5afb8778bb25a234e211fca061c6a7aee4cba5cc
[ "MIT" ]
24
2020-12-31T17:23:16.000Z
2021-03-11T19:44:36.000Z
exs/mundo_1/java/024.java
LeonardoCruzx/exercicios-CeV
5afb8778bb25a234e211fca061c6a7aee4cba5cc
[ "MIT" ]
28
2020-12-30T15:57:16.000Z
2022-03-26T19:46:49.000Z
21.310345
100
0.567961
193
/* ### 024 - Verificando as primeiras letras de um texto Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com a palavra "Santo" */ import java.util.Scanner; public class Main { public static void main(String[] args) { String nome; Scanner scanner = new Scanner(System.in); System.out.println("Digite o nome de uma cidade: "); nome = scanner.nextLine(); if (nome.startsWith("Santo")) { System.out.println("Começa"); } else { System.out.println("Não começa"); } } }
3e0074e6d24cfa5d9abf469d32de7bd0e2af9a77
7,056
java
Java
ihmc-quadruped/src/footstep-planning/java/us/ihmc/quadrupedFootstepPlanning/pawPlanning/graphSearch/visualization/AStarPawPlannerVisualizer.java
ihmcrobotics/ihmc-open-robotics-software
129b261de850e85e1dc78a12e9c075f53c6019a0
[ "Apache-2.0" ]
170
2016-02-01T18:58:50.000Z
2022-03-17T05:28:01.000Z
ihmc-quadruped/src/footstep-planning/java/us/ihmc/quadrupedFootstepPlanning/pawPlanning/graphSearch/visualization/AStarPawPlannerVisualizer.java
ihmcrobotics/ihmc-open-robotics-software
129b261de850e85e1dc78a12e9c075f53c6019a0
[ "Apache-2.0" ]
162
2016-01-29T17:04:29.000Z
2022-02-10T16:25:37.000Z
ihmc-quadruped/src/footstep-planning/java/us/ihmc/quadrupedFootstepPlanning/pawPlanning/graphSearch/visualization/AStarPawPlannerVisualizer.java
ihmcrobotics/ihmc-open-robotics-software
129b261de850e85e1dc78a12e9c075f53c6019a0
[ "Apache-2.0" ]
83
2016-01-28T22:49:01.000Z
2022-03-28T03:11:24.000Z
38.140541
187
0.741638
194
package us.ihmc.quadrupedFootstepPlanning.pawPlanning.graphSearch.visualization; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import us.ihmc.commons.thread.ThreadTools; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.graphicsDescription.Graphics3DObject; import us.ihmc.graphicsDescription.appearance.YoAppearance; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicPosition; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicReferenceFrame; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry; import us.ihmc.quadrupedFootstepPlanning.pawPlanning.graphSearch.PawStepPlannerNodeRejectionReason; import us.ihmc.quadrupedFootstepPlanning.pawPlanning.graphSearch.graph.PawNode; import us.ihmc.quadrupedFootstepPlanning.pawPlanning.graphSearch.listeners.PawStepPlannerListener; import us.ihmc.robotics.geometry.PlanarRegionsList; import us.ihmc.robotics.graphics.Graphics3DObjectTools; import us.ihmc.robotics.robotSide.RobotQuadrant; import us.ihmc.simulationconstructionset.Robot; import us.ihmc.simulationconstructionset.SimulationConstructionSet; import us.ihmc.yoVariables.euclid.referenceFrame.YoFramePoint2D; import us.ihmc.yoVariables.registry.YoRegistry; import us.ihmc.yoVariables.variable.YoDouble; public class AStarPawPlannerVisualizer implements PawStepPlannerListener { private static final int maxNumberOfChildNodes = 500; private static final double childNodeSize = 0.005; private static final double nodeSize = 0.007; private final YoGraphicsListRegistry graphicsListRegistry = new YoGraphicsListRegistry(); private final YoRegistry registry = new YoRegistry(getClass().getSimpleName()); private final SimulationConstructionSet scs = new SimulationConstructionSet(new Robot("Dummy")); private final YoDouble time = new YoDouble("time", registry); private final HashMap<PawNode, List<PawNode>> validChildNodeMap = new HashMap<>(); private final HashMap<PawNode, List<PawNode>> invalidChildNodeMap = new HashMap<>(); private final List<YoFramePoint2D> yoValidChildNodes = new ArrayList<>(); private final List<YoFramePoint2D> yoInValidChildNodes = new ArrayList<>(); private final YoPawNode currentPawNode = new YoPawNode(registry); public AStarPawPlannerVisualizer(PlanarRegionsList regions) { this(0.1, regions); } public AStarPawPlannerVisualizer(double playbackRate, PlanarRegionsList regions) { for (int i = 0; i < maxNumberOfChildNodes; i++) { YoFramePoint2D validChildNode = new YoFramePoint2D("validChildNode" + i, ReferenceFrame.getWorldFrame(), registry); YoGraphicPosition validChildNodeVis = new YoGraphicPosition("validChildNode" + i, validChildNode, childNodeSize, YoAppearance.Green()); yoValidChildNodes.add(validChildNode); graphicsListRegistry.registerYoGraphic("plannerListener", validChildNodeVis); YoFramePoint2D invalidChildNode = new YoFramePoint2D("invalidChildNode" + i, ReferenceFrame.getWorldFrame(), registry); YoGraphicPosition invalidChildNodeVis = new YoGraphicPosition("invalidChildNode" + i, invalidChildNode, childNodeSize, YoAppearance.Red()); yoInValidChildNodes.add(invalidChildNode); graphicsListRegistry.registerYoGraphic("plannerListener", invalidChildNodeVis); } for (RobotQuadrant robotQuadrant : RobotQuadrant.values) { YoGraphicPosition otherPaws = new YoGraphicPosition(robotQuadrant.getShortName() + "activeNodePaw", currentPawNode.getYoPosition(robotQuadrant), nodeSize, YoAppearance.Orange()); graphicsListRegistry.registerYoGraphic("plannerListener", otherPaws); } YoGraphicPosition nodeVis = new YoGraphicPosition("activeNode", currentPawNode.getMovingYoPosition(), nodeSize, YoAppearance.White()); graphicsListRegistry.registerYoGraphic("plannerListener", nodeVis); YoGraphicReferenceFrame worldViz = new YoGraphicReferenceFrame(ReferenceFrame.getWorldFrame(), registry, false, 0.5); graphicsListRegistry.registerYoGraphic("plannerListener", worldViz); Graphics3DObject graphics3DObject = new Graphics3DObject(); if (regions != null) Graphics3DObjectTools.addPlanarRegionsList(graphics3DObject, regions); scs.addStaticLinkGraphics(graphics3DObject); scs.addYoRegistry(registry); scs.addYoGraphicsListRegistry(graphicsListRegistry); scs.setPlaybackRealTimeRate(playbackRate); scs.setCameraFix(0.0, 0.0, 0.0); scs.setCameraPosition(-0.001, 0.0, 15.0); scs.setGroundVisible(false); scs.tickAndUpdate(); } @Override public void addNode(PawNode node, PawNode previousNode) { if (previousNode == null) return; if (!validChildNodeMap.containsKey(previousNode)) validChildNodeMap.put(previousNode, new ArrayList<>()); validChildNodeMap.get(previousNode).add(node); currentPawNode.set(previousNode); } @Override public void rejectNode(PawNode rejectedNode, PawNode parentNode, PawStepPlannerNodeRejectionReason reason) { if(validChildNodeMap.containsKey(parentNode)) validChildNodeMap.get(parentNode).remove(rejectedNode); if (!invalidChildNodeMap.containsKey(parentNode)) invalidChildNodeMap.put(parentNode, new ArrayList<>()); invalidChildNodeMap.get(parentNode).add(rejectedNode); } @Override public void rejectNode(PawNode rejectedNode, PawStepPlannerNodeRejectionReason reason) { // TODO } @Override public void plannerFinished(List<PawNode> plan) { } @Override public void reportLowestCostNodeList(List<PawNode> plan) { } @Override public void tickAndUpdate() { yoValidChildNodes.forEach(YoFramePoint2D::setToNaN); PawNode currentNode = currentPawNode.getEquivalentNode(); if (currentNode == null) return; List<PawNode> validChildNodes = validChildNodeMap.get(currentNode); if (validChildNodes != null) { for (int i = 0; i < validChildNodes.size(); i++) { PawNode childNode = validChildNodes.get(i); RobotQuadrant quadrant = childNode.getMovingQuadrant(); yoValidChildNodes.get(i).set(childNode.getX(quadrant), childNode.getY(quadrant)); } } List<PawNode> invalidChildNodes = invalidChildNodeMap.get(currentNode); if (invalidChildNodes != null) { for (int i = 0; i < invalidChildNodes.size(); i++) { PawNode childNode = invalidChildNodes.get(i); RobotQuadrant quadrant = childNode.getMovingQuadrant(); yoInValidChildNodes.get(i).set(childNode.getX(quadrant), childNode.getY(quadrant)); } } scs.setTime(time.getDoubleValue()); scs.tickAndUpdate(); time.add(1.0); } public void showAndSleep(boolean autoplay) { if (autoplay) scs.play(); scs.startOnAThread(); ThreadTools.sleepForever(); } }
3e0075857402d2de0eb709d3136deef987bd21d3
9,673
java
Java
android-31/src/android/window/SplashScreen.java
Pixelated-Project/aosp-android-jar
72ae25d4fc6414e071fc1f52dd78080b84d524f8
[ "MIT" ]
93
2020-10-11T04:37:16.000Z
2022-03-24T13:18:49.000Z
android-31/src/android/window/SplashScreen.java
huangjxdev/aosp-android-jar
e22b61576b05ff7483180cb4d245921d66c26ee4
[ "MIT" ]
3
2020-10-11T04:27:44.000Z
2022-01-19T01:31:52.000Z
android-31/src/android/window/SplashScreen.java
huangjxdev/aosp-android-jar
e22b61576b05ff7483180cb4d245921d66c26ee4
[ "MIT" ]
10
2020-11-23T02:41:58.000Z
2022-03-06T00:56:52.000Z
35.30292
100
0.611082
195
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.window; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.StyleRes; import android.annotation.SuppressLint; import android.annotation.UiThread; import android.app.Activity; import android.app.ActivityThread; import android.app.AppGlobals; import android.content.Context; import android.content.res.Resources; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.util.Singleton; import android.util.Slog; import java.util.ArrayList; /** * The interface that apps use to talk to the splash screen. * <p> * Each splash screen instance is bound to a particular {@link Activity}. * To obtain a {@link SplashScreen} for an Activity, use * <code>Activity.getSplashScreen()</code> to get the SplashScreen.</p> */ public interface SplashScreen { /** * Force splash screen to be empty. * @hide */ int SPLASH_SCREEN_STYLE_EMPTY = 0; /** * Force splash screen to show icon. * @hide */ int SPLASH_SCREEN_STYLE_ICON = 1; /** @hide */ @IntDef(prefix = { "SPLASH_SCREEN_STYLE_" }, value = { SPLASH_SCREEN_STYLE_EMPTY, SPLASH_SCREEN_STYLE_ICON }) @interface SplashScreenStyle {} /** * <p>Specifies whether an {@link Activity} wants to handle the splash screen animation on its * own. Normally the splash screen will show on screen before the content of the activity has * been drawn, and disappear when the activity is showing on the screen. With this listener set, * the activity will receive {@link OnExitAnimationListener#onSplashScreenExit} callback if * splash screen is showed, then the activity can create its own exit animation based on the * SplashScreenView.</p> * * <p> Note that this method must be called before splash screen leave, so it only takes effect * during or before {@link Activity#onResume}.</p> * * @param listener the listener for receive the splash screen with * * @see OnExitAnimationListener#onSplashScreenExit(SplashScreenView) */ @SuppressLint("ExecutorRegistration") void setOnExitAnimationListener(@NonNull SplashScreen.OnExitAnimationListener listener); /** * Clear exist listener * @see #setOnExitAnimationListener */ void clearOnExitAnimationListener(); /** * Overrides the theme used for the {@link SplashScreen}s of this application. * <p> * By default, the {@link SplashScreen} uses the theme set in the manifest. This method * overrides and persists the theme used for the {@link SplashScreen} of this application. * <p> * To reset to the default theme, set this the themeId to {@link Resources#ID_NULL}. */ void setSplashScreenTheme(@StyleRes int themeId); /** * Listens for the splash screen exit event. */ interface OnExitAnimationListener { /** * When receiving this callback, the {@link SplashScreenView} object will be drawing on top * of the activity. The {@link SplashScreenView} represents the splash screen view * object, developer can make an exit animation based on this view.</p> * * <p>This method is never invoked if your activity clear the listener by * {@link #clearOnExitAnimationListener}. * * @param view The view object which on top of this Activity. * @see #setOnExitAnimationListener * @see #clearOnExitAnimationListener */ @UiThread void onSplashScreenExit(@NonNull SplashScreenView view); } /** * @hide */ class SplashScreenImpl implements SplashScreen { private static final String TAG = "SplashScreenImpl"; private OnExitAnimationListener mExitAnimationListener; private final IBinder mActivityToken; private final SplashScreenManagerGlobal mGlobal; public SplashScreenImpl(Context context) { mActivityToken = context.getActivityToken(); mGlobal = SplashScreenManagerGlobal.getInstance(); } @Override public void setOnExitAnimationListener( @NonNull SplashScreen.OnExitAnimationListener listener) { if (mActivityToken == null) { // This is not an activity. return; } synchronized (mGlobal.mGlobalLock) { if (listener != null) { mExitAnimationListener = listener; mGlobal.addImpl(this); } } } @Override public void clearOnExitAnimationListener() { if (mActivityToken == null) { // This is not an activity. return; } synchronized (mGlobal.mGlobalLock) { mExitAnimationListener = null; mGlobal.removeImpl(this); } } public void setSplashScreenTheme(@StyleRes int themeId) { if (mActivityToken == null) { Log.w(TAG, "Couldn't persist the starting theme. This instance is not an Activity"); return; } Activity activity = ActivityThread.currentActivityThread().getActivity( mActivityToken); if (activity == null) { return; } String themeName = themeId != Resources.ID_NULL ? activity.getResources().getResourceName(themeId) : null; try { AppGlobals.getPackageManager().setSplashScreenTheme( activity.getComponentName().getPackageName(), themeName, activity.getUserId()); } catch (RemoteException e) { Log.w(TAG, "Couldn't persist the starting theme", e); } } } /** * This class is only used internally to manage the activities for this process. * * @hide */ class SplashScreenManagerGlobal { private static final String TAG = SplashScreen.class.getSimpleName(); private final Object mGlobalLock = new Object(); private final ArrayList<SplashScreenImpl> mImpls = new ArrayList<>(); private SplashScreenManagerGlobal() { ActivityThread.currentActivityThread().registerSplashScreenManager(this); } public static SplashScreenManagerGlobal getInstance() { return sInstance.get(); } private static final Singleton<SplashScreenManagerGlobal> sInstance = new Singleton<SplashScreenManagerGlobal>() { @Override protected SplashScreenManagerGlobal create() { return new SplashScreenManagerGlobal(); } }; private void addImpl(SplashScreenImpl impl) { synchronized (mGlobalLock) { mImpls.add(impl); } } private void removeImpl(SplashScreenImpl impl) { synchronized (mGlobalLock) { mImpls.remove(impl); } } private SplashScreenImpl findImpl(IBinder token) { synchronized (mGlobalLock) { for (SplashScreenImpl impl : mImpls) { if (impl.mActivityToken == token) { return impl; } } } return null; } public void tokenDestroyed(IBinder token) { synchronized (mGlobalLock) { final SplashScreenImpl impl = findImpl(token); if (impl != null) { removeImpl(impl); } } } public void handOverSplashScreenView(@NonNull IBinder token, @NonNull SplashScreenView splashScreenView) { transferSurface(splashScreenView); dispatchOnExitAnimation(token, splashScreenView); } private void dispatchOnExitAnimation(IBinder token, SplashScreenView view) { synchronized (mGlobalLock) { final SplashScreenImpl impl = findImpl(token); if (impl == null) { return; } if (impl.mExitAnimationListener == null) { Slog.e(TAG, "cannot dispatch onExitAnimation to listener " + token); return; } impl.mExitAnimationListener.onSplashScreenExit(view); } } public boolean containsExitListener(IBinder token) { synchronized (mGlobalLock) { final SplashScreenImpl impl = findImpl(token); return impl != null && impl.mExitAnimationListener != null; } } private void transferSurface(@NonNull SplashScreenView splashScreenView) { splashScreenView.transferSurface(); } } }
3e0075ac5ab7aeb29575ef7196ca7a0cb54143f5
6,211
java
Java
src/main/java/com/oracle/truffle/js/nodes/access/JSGuardDisconnectedArgumentRead.java
pitbox46/graaljs-forge
369d305ed531f66653b4bf2ce881483639401707
[ "UPL-1.0" ]
null
null
null
src/main/java/com/oracle/truffle/js/nodes/access/JSGuardDisconnectedArgumentRead.java
pitbox46/graaljs-forge
369d305ed531f66653b4bf2ce881483639401707
[ "UPL-1.0" ]
null
null
null
src/main/java/com/oracle/truffle/js/nodes/access/JSGuardDisconnectedArgumentRead.java
pitbox46/graaljs-forge
369d305ed531f66653b4bf2ce881483639401707
[ "UPL-1.0" ]
null
null
null
47.412214
187
0.751087
196
/* * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.js.nodes.access; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Cached.Shared; import com.oracle.truffle.api.dsl.Executed; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.instrumentation.StandardTags; import com.oracle.truffle.api.instrumentation.Tag; import com.oracle.truffle.api.object.DynamicObject; import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.js.nodes.JavaScriptNode; import com.oracle.truffle.js.nodes.ReadNode; import com.oracle.truffle.js.nodes.RepeatableNode; import com.oracle.truffle.js.nodes.instrumentation.JSTags; import com.oracle.truffle.js.nodes.instrumentation.JSTags.ReadVariableTag; import com.oracle.truffle.js.nodes.instrumentation.NodeObjectDescriptor; import com.oracle.truffle.js.runtime.builtins.JSArgumentsArray; import com.oracle.truffle.js.runtime.objects.Undefined; import java.util.Set; public abstract class JSGuardDisconnectedArgumentRead extends JavaScriptNode implements RepeatableNode, ReadNode { private final int index; @Child @Executed JavaScriptNode argumentsArrayNode; @Child private ReadElementNode readElementNode; private final FrameSlot slot; JSGuardDisconnectedArgumentRead(int index, ReadElementNode readElementNode, JavaScriptNode argumentsArray, FrameSlot slot) { this.index = index; this.argumentsArrayNode = argumentsArray; this.readElementNode = readElementNode; this.slot = slot; } public static JSGuardDisconnectedArgumentRead create(int index, ReadElementNode readElementNode, JavaScriptNode argumentsArray, FrameSlot slot) { return JSGuardDisconnectedArgumentReadNodeGen.create(index, readElementNode, argumentsArray, slot); } @Override public boolean hasTag(Class<? extends Tag> tag) { if ((tag == ReadVariableTag.class || tag == StandardTags.ReadVariableTag.class)) { return true; } else { return super.hasTag(tag); } } @Override public Object getNodeObject() { NodeObjectDescriptor descriptor = JSTags.createNodeObjectDescriptor("name", slot.getIdentifier()); descriptor.addProperty(StandardTags.ReadVariableTag.NAME, slot.getIdentifier()); return descriptor; } @Specialization(guards = "!isArgumentsDisconnected(argumentsArray)") public Object doObject(DynamicObject argumentsArray, @Cached("createBinaryProfile()") @Shared("unconnected") ConditionProfile unconnected) { assert JSArgumentsArray.isJSArgumentsObject(argumentsArray); if (unconnected.profile(index >= JSArgumentsArray.getConnectedArgumentCount(argumentsArray))) { return Undefined.instance; } else { return readElementNode.executeWithTargetAndIndex(argumentsArray, index); } } public final int getIndex() { return index; } @Specialization(guards = "isArgumentsDisconnected(argumentsArray)") public Object doObjectDisconnected(DynamicObject argumentsArray, @Cached("createBinaryProfile()") ConditionProfile wasDisconnected, @Cached("createBinaryProfile()") @Shared("unconnected") ConditionProfile unconnected) { assert JSArgumentsArray.isJSArgumentsObject(argumentsArray); if (wasDisconnected.profile(JSArgumentsArray.wasIndexDisconnected(argumentsArray, index))) { return JSArgumentsArray.getDisconnectedIndexValue(argumentsArray, index); } else if (unconnected.profile(index >= JSArgumentsArray.getConnectedArgumentCount(argumentsArray))) { return Undefined.instance; } else { return readElementNode.executeWithTargetAndIndex(argumentsArray, index); } } @Override protected JavaScriptNode copyUninitialized(Set<Class<? extends Tag>> materializedTags) { return JSGuardDisconnectedArgumentReadNodeGen.create(index, cloneUninitialized(readElementNode, materializedTags), cloneUninitialized(argumentsArrayNode, materializedTags), slot); } }
3e0075b62b5dc402fb33378d52ec6fb534062a37
1,036
java
Java
Final Project OOP src/Calculos_Salariais/Vendedor.java
SauloCav/POO-Experiments-
f6ce30c2e64bfa26adde6edab259fd0b464ca1e4
[ "MIT" ]
null
null
null
Final Project OOP src/Calculos_Salariais/Vendedor.java
SauloCav/POO-Experiments-
f6ce30c2e64bfa26adde6edab259fd0b464ca1e4
[ "MIT" ]
null
null
null
Final Project OOP src/Calculos_Salariais/Vendedor.java
SauloCav/POO-Experiments-
f6ce30c2e64bfa26adde6edab259fd0b464ca1e4
[ "MIT" ]
null
null
null
18.836364
95
0.739382
197
package Calculos_Salariais; public abstract class Vendedor { private String nome = ""; private double salBase; private double totalVendas; private double numeroDeDependentes; public Vendedor() { super(); } public Vendedor(String nome, double salBase, double totalVendas, double numeroDeDependentes) { super(); this.nome = nome; this.salBase = salBase; this.totalVendas = totalVendas; this.numeroDeDependentes = numeroDeDependentes; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public double isSalBase() { return salBase; } public void setSalBase(double salBase) { this.salBase = salBase; } public double isTotalVendas() { return totalVendas; } public void setTotalVendas(double totalVendas) { this.totalVendas = totalVendas; } public double getNumeroDeDependentes() { return numeroDeDependentes; } public void setNumeroDeDependentes(double numeroDeDependentes) { this.numeroDeDependentes = numeroDeDependentes; } }
3e007603f9696e8eceb663660688f48d348b0f42
2,411
java
Java
gen/com/intellij/plugins/haxe/lang/psi/impl/HaxeTypedefDeclarationImpl.java
JetBrains/intellij-haxe
bd307e10a832854716b932a612f368d8d7ed1925
[ "Apache-2.0" ]
48
2015-01-01T06:32:10.000Z
2022-01-13T11:05:25.000Z
gen/com/intellij/plugins/haxe/lang/psi/impl/HaxeTypedefDeclarationImpl.java
JetBrains/intellij-haxe
bd307e10a832854716b932a612f368d8d7ed1925
[ "Apache-2.0" ]
14
2015-04-14T20:35:21.000Z
2017-08-05T01:49:03.000Z
gen/com/intellij/plugins/haxe/lang/psi/impl/HaxeTypedefDeclarationImpl.java
JetBrains/intellij-haxe
bd307e10a832854716b932a612f368d8d7ed1925
[ "Apache-2.0" ]
25
2015-01-08T10:35:06.000Z
2021-11-10T07:17:12.000Z
28.364706
107
0.767316
198
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2016 AS3Boyan * Copyright 2014-2014 Elias Ku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This is a generated file. Not intended for manual editing. package com.intellij.plugins.haxe.lang.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*; import com.intellij.plugins.haxe.lang.psi.*; public class HaxeTypedefDeclarationImpl extends AbstractHaxeTypeDefImpl implements HaxeTypedefDeclaration { public HaxeTypedefDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof HaxeVisitor) ((HaxeVisitor)visitor).visitTypedefDeclaration(this); else super.accept(visitor); } @Override @NotNull public HaxeComponentName getComponentName() { return findNotNullChildByClass(HaxeComponentName.class); } @Override @Nullable public HaxeExternKeyWord getExternKeyWord() { return findChildByClass(HaxeExternKeyWord.class); } @Override @Nullable public HaxeFunctionType getFunctionType() { return findChildByClass(HaxeFunctionType.class); } @Override @Nullable public HaxeGenericParam getGenericParam() { return findChildByClass(HaxeGenericParam.class); } @Override @Nullable public HaxeMacroClassList getMacroClassList() { return findChildByClass(HaxeMacroClassList.class); } @Override @Nullable public HaxePrivateKeyWord getPrivateKeyWord() { return findChildByClass(HaxePrivateKeyWord.class); } @Override @Nullable public HaxeTypeOrAnonymous getTypeOrAnonymous() { return findChildByClass(HaxeTypeOrAnonymous.class); } }
3e00786c5824fc2c7b213ada530abe596975742f
2,102
java
Java
src/StockIT-v2-release_source_from_JADX/sources/kotlin/sequences/TakeSequence$iterator$1.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-11-23T10:12:35.000Z
2021-11-23T10:12:35.000Z
src/StockIT-v1-release_source_from_JADX/sources/kotlin/sequences/TakeSequence$iterator$1.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
null
null
null
src/StockIT-v1-release_source_from_JADX/sources/kotlin/sequences/TakeSequence$iterator$1.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-10-01T13:14:19.000Z
2021-10-01T13:14:19.000Z
42.04
851
0.671265
199
package kotlin.sequences; import java.util.Iterator; import java.util.NoSuchElementException; import kotlin.Metadata; import kotlin.jvm.internal.markers.KMappedMarker; @Metadata(mo40251bv = {1, 0, 3}, mo40252d1 = {"\u0000\u001d\n\u0000\n\u0002\u0010(\n\u0002\b\u0004\n\u0002\u0010\b\n\u0002\b\u0005\n\u0002\u0010\u000b\n\u0002\b\u0003*\u0001\u0000\b\n\u0018\u00002\b\u0012\u0004\u0012\u00028\u00000\u0001J\t\u0010\u000b\u001a\u00020\fH–\u0002J\u000e\u0010\r\u001a\u00028\u0000H–\u0002¢\u0006\u0002\u0010\u000eR\u0017\u0010\u0002\u001a\b\u0012\u0004\u0012\u00028\u00000\u0001¢\u0006\b\n\u0000\u001a\u0004\b\u0003\u0010\u0004R\u001a\u0010\u0005\u001a\u00020\u0006X†\u000e¢\u0006\u000e\n\u0000\u001a\u0004\b\u0007\u0010\b\"\u0004\b\t\u0010\n¨\u0006\u000f"}, mo40253d2 = {"kotlin/sequences/TakeSequence$iterator$1", "", "iterator", "getIterator", "()Ljava/util/Iterator;", "left", "", "getLeft", "()I", "setLeft", "(I)V", "hasNext", "", "next", "()Ljava/lang/Object;", "kotlin-stdlib"}, mo40254k = 1, mo40255mv = {1, 4, 1}) /* compiled from: Sequences.kt */ public final class TakeSequence$iterator$1 implements Iterator<T>, KMappedMarker { private final Iterator<T> iterator; private int left; final /* synthetic */ TakeSequence this$0; public void remove() { throw new UnsupportedOperationException("Operation is not supported for read-only collection"); } TakeSequence$iterator$1(TakeSequence takeSequence) { this.this$0 = takeSequence; this.left = takeSequence.count; this.iterator = takeSequence.sequence.iterator(); } public final int getLeft() { return this.left; } public final void setLeft(int i) { this.left = i; } public final Iterator<T> getIterator() { return this.iterator; } public T next() { int i = this.left; if (i != 0) { this.left = i - 1; return this.iterator.next(); } throw new NoSuchElementException(); } public boolean hasNext() { return this.left > 0 && this.iterator.hasNext(); } }
3e00792e4d1beeb29a044f1b4f11f10519836d7d
1,116
java
Java
shop/src/main/java/ro/msg/learning/shop/configuration/ChosenStrategy.java
ro-msg-spring-training/online-shop-ptruta
ccc2becab6db06e1d3df7d07f26bb761a8d4cc7f
[ "MIT" ]
null
null
null
shop/src/main/java/ro/msg/learning/shop/configuration/ChosenStrategy.java
ro-msg-spring-training/online-shop-ptruta
ccc2becab6db06e1d3df7d07f26bb761a8d4cc7f
[ "MIT" ]
null
null
null
shop/src/main/java/ro/msg/learning/shop/configuration/ChosenStrategy.java
ro-msg-spring-training/online-shop-ptruta
ccc2becab6db06e1d3df7d07f26bb761a8d4cc7f
[ "MIT" ]
null
null
null
36
99
0.793011
200
package ro.msg.learning.shop.configuration; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ro.msg.learning.shop.service.implementation.LocationService; import ro.msg.learning.shop.service.implementation.StockService; import ro.msg.learning.shop.service.strategies.IWhichStrategy; import ro.msg.learning.shop.service.strategies.MostAbundantStrategy; import ro.msg.learning.shop.service.strategies.SingleLocationStrategy; @Configuration @RequiredArgsConstructor public class ChosenStrategy { @Value("${choose_strategy}") private String chooseStrategy; @Bean public IWhichStrategy getStrategy(StockService stockService, LocationService locationService) { if (chooseStrategy.equals("MostAbundant")) { return new MostAbundantStrategy(stockService); } else if (chooseStrategy.equals("Single")) return new SingleLocationStrategy(stockService, locationService); return null; } }